diff options
233 files changed, 44960 insertions, 22451 deletions
diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000000..30d80990a6 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,37 @@ +# Lines starting with '#' are comments. +# Each line is a file pattern followed by one or more owners. +# Owners can be @users, @org/teams or emails + +core/* @reduz + +doc/* @godotengine/documentation + +drivers/gles2/* @karroffel +drivers/gles3/* @reduz + +editor/icons/* @djrm + +main/* @reduz + +misc/* @akien-mga + +modules/bullet/* @AndreaCatania +modules/enet/* @godotengine/network +modules/gnative/* @karroffel +modules/gdscript/* @reduz @vnen @bojidar-bg +modules/mbedtls/* @godotengine/network +modules/mobile_vr/* @BastiaanOlij +modules/mono/* @neikeq +modules/regex/* @LeeZH +modules/upnp/* @godotengine/network +modules/websocket/* @godotengine/network + +platform/javascript/* @eska014 +platform/uwp/* @vnen + +scene/main/* @reduz + +server/physics* @reduz @AndreaCatania +server/visual* @reduz @karroffel + +thirdparty/* @akien-mga diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt index 6b6ee4c509..f4340719dc 100644 --- a/COPYRIGHT.txt +++ b/COPYRIGHT.txt @@ -218,11 +218,21 @@ Comment: WebP codec Copyright: 2010, Google Inc. License: BSD-3-clause +Files: ./thirdparty/libwebsockets/ +Comment: libwebsockets +Copyright: 2010-2017, Andy Green +License: LGPL-2.1+SLE (libwebsockets) + Files: ./thirdparty/mbedtls/ Comment: Mbed TLS Copyright: 2006-2015, ARM Limited License: Apache-2.0 +Files: ./thirdparty/miniupnpc/ +Comment: MiniUPnPc +Copyright: 2005-2016, Thomas Bernard +License: BSD-3-clause + Files: ./thirdparty/minizip/ Comment: MiniZip Copyright: 1998-2010, Gilles Vollant @@ -244,6 +254,12 @@ Comment: BASE64 conversion methods Copyright: Ari Edelkind License: public-domain +Files: ./thirdparty/misc/clipper.cpp + ./thirdparty/misc/clipper.hpp +Comment: Clipper +Copyright: 2010-2017, Angus Johnson +License: BSL-1.0 + Files: ./thirdparty/misc/curl_hostcheck.c ./thirdparty/misc/curl_hostcheck.h Comment: curl @@ -378,30 +394,6 @@ License: Apache-2.0 See the License for the specific language governing permissions and limitations under the License. -License: BSD-2-clause - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - . - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - . - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. Neither the name of the author - nor the names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - . - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - License: Bitstream Vera Fonts Copyright Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. @@ -444,6 +436,28 @@ License: Bitstream Vera Fonts Copyright authorization from the GNOME Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. +License: BSD-2-clause + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + . + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + . + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + . + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + License: BSD-3-clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions @@ -472,6 +486,31 @@ License: BSD-3-clause OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License: BSL-1.0 + Boost Software License - Version 1.0 - August 17th, 2003 + . + Permission is hereby granted, free of charge, to any person or organization + obtaining a copy of the software and accompanying documentation covered by + this license (the "Software") to use, reproduce, display, distribute, + execute, and transmit the Software, and to prepare derivative works of the + Software, and to permit third-parties to whom the Software is furnished to + do so, all subject to the following: + . + The copyright notices in the Software and this entire statement, including + the above license grant, this restriction and the following disclaimer, + must be included in all copies of the Software, in whole or in part, and + all derivative works of the Software, unless such copies or derivative + works are solely in the form of machine-executable object code generated by + a source language processor. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + License: CC-BY-3.0 Creative Commons Attribution 3.0 Unported . @@ -1022,6 +1061,564 @@ License: ISC ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +License: LGPL-2.1+SLE (libwebsockets) + Libwebsockets and included programs are provided under the terms of the GNU + Library General Public License (LGPL) 2.1, with the following exceptions: + . + 1) Any reference, whether in these modifications or in the GNU + Library General Public License 2.1, to this License, these terms, the + GNU Lesser Public License, GNU Library General Public License, LGPL, or + any similar reference shall refer to the GNU Library General Public + License 2.1 as modified by these paragraphs 1) through 4). + . + 2) Static linking of programs with the libwebsockets library does not + constitute a derivative work and does not require the author to provide + source code for the program, use the shared libwebsockets libraries, or + link their program against a user-supplied version of libwebsockets. + . + If you link the program to a modified version of libwebsockets, then the + changes to libwebsockets must be provided under the terms of the LGPL in + sections 1, 2, and 4. + . + 3) You do not have to provide a copy of the libwebsockets license with + programs that are linked to the libwebsockets library, nor do you have to + identify the libwebsockets license in your program or documentation as + required by section 6 of the LGPL. + . + However, programs must still identify their use of libwebsockets. The + following example statement can be included in user documentation to + satisfy this requirement: + . + "[program] is based in part on the work of the libwebsockets project + (https://libwebsockets.org)" + . + 4) Some sources included have their own, more liberal licenses, or options + to get original sources with the liberal terms. + . + Original liberal license retained + . + - lib/misc/sha-1.c - 3-clause BSD license retained, link to original + - win32port/zlib - ZLIB license (see zlib.h) + - lib/tls/mbedtls/wrapper - Apache 2.0 (only built if linked against mbedtls) + . + Relicensed to libwebsocket license + . + - lib/misc/base64-decode.c - relicensed to LGPL2.1+SLE, link to original + - lib/misc/daemonize.c - relicensed from Public Domain to LGPL2.1+SLE, + link to original Public Domain version + . + Public Domain (CC-zero) to simplify reuse + . + - test-apps/*.c + - test-apps/*.h + - minimal-examples/* + - lwsws/* + . + ------ end of exceptions + . + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + . + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + . + [This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + . + Preamble + . + The licenses for most software are designed to take away your + freedom to share and change it. By contrast, the GNU General Public + Licenses are intended to guarantee your freedom to share and change + free software--to make sure the software is free for all its users. + . + This license, the Lesser General Public License, applies to some + specially designated software packages--typically libraries--of the + Free Software Foundation and other authors who decide to use it. You + can use it too, but we suggest you first think carefully about whether + this license or the ordinary General Public License is the better + strategy to use in any particular case, based on the explanations below. + . + When we speak of free software, we are referring to freedom of use, + not price. Our General Public Licenses are designed to make sure that + you have the freedom to distribute copies of free software (and charge + for this service if you wish); that you receive source code or can get + it if you want it; that you can change the software and use pieces of + it in new free programs; and that you are informed that you can do + these things. + . + To protect your rights, we need to make restrictions that forbid + distributors to deny you these rights or to ask you to surrender these + rights. These restrictions translate to certain responsibilities for + you if you distribute copies of the library or if you modify it. + . + For example, if you distribute copies of the library, whether gratis + or for a fee, you must give the recipients all the rights that we gave + you. You must make sure that they, too, receive or can get the source + code. If you link other code with the library, you must provide + complete object files to the recipients, so that they can relink them + with the library after making changes to the library and recompiling + it. And you must show them these terms so they know their rights. + . + We protect your rights with a two-step method: (1) we copyright the + library, and (2) we offer you this license, which gives you legal + permission to copy, distribute and/or modify the library. + . + To protect each distributor, we want to make it very clear that + there is no warranty for the free library. Also, if the library is + modified by someone else and passed on, the recipients should know + that what they have is not the original version, so that the original + author's reputation will not be affected by problems that might be + introduced by others. + . + Finally, software patents pose a constant threat to the existence of + any free program. We wish to make sure that a company cannot + effectively restrict the users of a free program by obtaining a + restrictive license from a patent holder. Therefore, we insist that + any patent license obtained for a version of the library must be + consistent with the full freedom of use specified in this license. + . + Most GNU software, including some libraries, is covered by the + ordinary GNU General Public License. This license, the GNU Lesser + General Public License, applies to certain designated libraries, and + is quite different from the ordinary General Public License. We use + this license for certain libraries in order to permit linking those + libraries into non-free programs. + . + When a program is linked with a library, whether statically or using + a shared library, the combination of the two is legally speaking a + combined work, a derivative of the original library. The ordinary + General Public License therefore permits such linking only if the + entire combination fits its criteria of freedom. The Lesser General + Public License permits more lax criteria for linking other code with + the library. + . + We call this license the "Lesser" General Public License because it + does Less to protect the user's freedom than the ordinary General + Public License. It also provides other free software developers Less + of an advantage over competing non-free programs. These disadvantages + are the reason we use the ordinary General Public License for many + libraries. However, the Lesser license provides advantages in certain + special circumstances. + . + For example, on rare occasions, there may be a special need to + encourage the widest possible use of a certain library, so that it becomes + a de-facto standard. To achieve this, non-free programs must be + allowed to use the library. A more frequent case is that a free + library does the same job as widely used non-free libraries. In this + case, there is little to gain by limiting the free library to free + software only, so we use the Lesser General Public License. + . + In other cases, permission to use a particular library in non-free + programs enables a greater number of people to use a large body of + free software. For example, permission to use the GNU C Library in + non-free programs enables many more people to use the whole GNU + operating system, as well as its variant, the GNU/Linux operating + system. + . + Although the Lesser General Public License is Less protective of the + users' freedom, it does ensure that the user of a program that is + linked with the Library has the freedom and the wherewithal to run + that program using a modified version of the Library. + . + The precise terms and conditions for copying, distribution and + modification follow. Pay close attention to the difference between a + "work based on the library" and a "work that uses the library". The + former contains code derived from the library, whereas the latter must + be combined with the library in order to run. + . + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + . + 0. This License Agreement applies to any software library or other + program which contains a notice placed by the copyright holder or + other authorized party saying it may be distributed under the terms of + this Lesser General Public License (also called "this License"). + Each licensee is addressed as "you". + . + A "library" means a collection of software functions and/or data + prepared so as to be conveniently linked with application programs + (which use some of those functions and data) to form executables. + . + The "Library", below, refers to any such software library or work + which has been distributed under these terms. A "work based on the + Library" means either the Library or any derivative work under + copyright law: that is to say, a work containing the Library or a + portion of it, either verbatim or with modifications and/or translated + straightforwardly into another language. (Hereinafter, translation is + included without limitation in the term "modification".) + . + "Source code" for a work means the preferred form of the work for + making modifications to it. For a library, complete source code means + all the source code for all modules it contains, plus any associated + interface definition files, plus the scripts used to control compilation + and installation of the library. + . + Activities other than copying, distribution and modification are not + covered by this License; they are outside its scope. The act of + running a program using the Library is not restricted, and output from + such a program is covered only if its contents constitute a work based + on the Library (independent of the use of the Library in a tool for + writing it). Whether that is true depends on what the Library does + and what the program that uses the Library does. + . + 1. You may copy and distribute verbatim copies of the Library's + complete source code as you receive it, in any medium, provided that + you conspicuously and appropriately publish on each copy an + appropriate copyright notice and disclaimer of warranty; keep intact + all the notices that refer to this License and to the absence of any + warranty; and distribute a copy of this License along with the + Library. + . + You may charge a fee for the physical act of transferring a copy, + and you may at your option offer warranty protection in exchange for a + fee. + . + 2. You may modify your copy or copies of the Library or any portion + of it, thus forming a work based on the Library, and copy and + distribute such modifications or work under the terms of Section 1 + above, provided that you also meet all of these conditions: + . + a) The modified work must itself be a software library. + . + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + . + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + . + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + . + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + . + These requirements apply to the modified work as a whole. If + identifiable sections of that work are not derived from the Library, + and can be reasonably considered independent and separate works in + themselves, then this License, and its terms, do not apply to those + sections when you distribute them as separate works. But when you + distribute the same sections as part of a whole which is a work based + on the Library, the distribution of the whole must be on the terms of + this License, whose permissions for other licensees extend to the + entire whole, and thus to each and every part regardless of who wrote + it. + . + Thus, it is not the intent of this section to claim rights or contest + your rights to work written entirely by you; rather, the intent is to + exercise the right to control the distribution of derivative or + collective works based on the Library. + . + In addition, mere aggregation of another work not based on the Library + with the Library (or with a work based on the Library) on a volume of + a storage or distribution medium does not bring the other work under + the scope of this License. + . + 3. You may opt to apply the terms of the ordinary GNU General Public + License instead of this License to a given copy of the Library. To do + this, you must alter all the notices that refer to this License, so + that they refer to the ordinary GNU General Public License, version 2, + instead of to this License. (If a newer version than version 2 of the + ordinary GNU General Public License has appeared, then you can specify + that version instead if you wish.) Do not make any other change in + these notices. + . + Once this change is made in a given copy, it is irreversible for + that copy, so the ordinary GNU General Public License applies to all + subsequent copies and derivative works made from that copy. + . + This option is useful when you wish to copy part of the code of + the Library into a program that is not a library. + . + 4. You may copy and distribute the Library (or a portion or + derivative of it, under Section 2) in object code or executable form + under the terms of Sections 1 and 2 above provided that you accompany + it with the complete corresponding machine-readable source code, which + must be distributed under the terms of Sections 1 and 2 above on a + medium customarily used for software interchange. + . + If distribution of object code is made by offering access to copy + from a designated place, then offering equivalent access to copy the + source code from the same place satisfies the requirement to + distribute the source code, even though third parties are not + compelled to copy the source along with the object code. + . + 5. A program that contains no derivative of any portion of the + Library, but is designed to work with the Library by being compiled or + linked with it, is called a "work that uses the Library". Such a + work, in isolation, is not a derivative work of the Library, and + therefore falls outside the scope of this License. + . + However, linking a "work that uses the Library" with the Library + creates an executable that is a derivative of the Library (because it + contains portions of the Library), rather than a "work that uses the + library". The executable is therefore covered by this License. + Section 6 states terms for distribution of such executables. + . + When a "work that uses the Library" uses material from a header file + that is part of the Library, the object code for the work may be a + derivative work of the Library even though the source code is not. + Whether this is true is especially significant if the work can be + linked without the Library, or if the work is itself a library. The + threshold for this to be true is not precisely defined by law. + . + If such an object file uses only numerical parameters, data + structure layouts and accessors, and small macros and small inline + functions (ten lines or less in length), then the use of the object + file is unrestricted, regardless of whether it is legally a derivative + work. (Executables containing this object code plus portions of the + Library will still fall under Section 6.) + . + Otherwise, if the work is a derivative of the Library, you may + distribute the object code for the work under the terms of Section 6. + Any executables containing that work also fall under Section 6, + whether or not they are linked directly with the Library itself. + . + 6. As an exception to the Sections above, you may also combine or + link a "work that uses the Library" with the Library to produce a + work containing portions of the Library, and distribute that work + under terms of your choice, provided that the terms permit + modification of the work for the customer's own use and reverse + engineering for debugging such modifications. + . + You must give prominent notice with each copy of the work that the + Library is used in it and that the Library and its use are covered by + this License. You must supply a copy of this License. If the work + during execution displays copyright notices, you must include the + copyright notice for the Library among them, as well as a reference + directing the user to the copy of this License. Also, you must do one + of these things: + . + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + . + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + . + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + . + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + . + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + . + For an executable, the required form of the "work that uses the + Library" must include any data and utility programs needed for + reproducing the executable from it. However, as a special exception, + the materials to be distributed need not include anything that is + normally distributed (in either source or binary form) with the major + components (compiler, kernel, and so on) of the operating system on + which the executable runs, unless that component itself accompanies + the executable. + . + It may happen that this requirement contradicts the license + restrictions of other proprietary libraries that do not normally + accompany the operating system. Such a contradiction means you cannot + use both them and the Library together in an executable that you + distribute. + . + 7. You may place library facilities that are a work based on the + Library side-by-side in a single library together with other library + facilities not covered by this License, and distribute such a combined + library, provided that the separate distribution of the work based on + the Library and of the other library facilities is otherwise + permitted, and provided that you do these two things: + . + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + . + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + . + 8. You may not copy, modify, sublicense, link with, or distribute + the Library except as expressly provided under this License. Any + attempt otherwise to copy, modify, sublicense, link with, or + distribute the Library is void, and will automatically terminate your + rights under this License. However, parties who have received copies, + or rights, from you under this License will not have their licenses + terminated so long as such parties remain in full compliance. + . + 9. You are not required to accept this License, since you have not + signed it. However, nothing else grants you permission to modify or + distribute the Library or its derivative works. These actions are + prohibited by law if you do not accept this License. Therefore, by + modifying or distributing the Library (or any work based on the + Library), you indicate your acceptance of this License to do so, and + all its terms and conditions for copying, distributing or modifying + the Library or works based on it. + . + 10. Each time you redistribute the Library (or any work based on the + Library), the recipient automatically receives a license from the + original licensor to copy, distribute, link with or modify the Library + subject to these terms and conditions. You may not impose any further + restrictions on the recipients' exercise of the rights granted herein. + You are not responsible for enforcing compliance by third parties with + this License. + . + 11. If, as a consequence of a court judgment or allegation of patent + infringement or for any other reason (not limited to patent issues), + conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot + distribute so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you + may not distribute the Library at all. For example, if a patent + license would not permit royalty-free redistribution of the Library by + all those who receive copies directly or indirectly through you, then + the only way you could satisfy both it and this License would be to + refrain entirely from distribution of the Library. + . + If any portion of this section is held invalid or unenforceable under any + particular circumstance, the balance of the section is intended to apply, + and the section as a whole is intended to apply in other circumstances. + . + It is not the purpose of this section to induce you to infringe any + patents or other property right claims or to contest validity of any + such claims; this section has the sole purpose of protecting the + integrity of the free software distribution system which is + implemented by public license practices. Many people have made + generous contributions to the wide range of software distributed + through that system in reliance on consistent application of that + system; it is up to the author/donor to decide if he or she is willing + to distribute software through any other system and a licensee cannot + impose that choice. + . + This section is intended to make thoroughly clear what is believed to + be a consequence of the rest of this License. + . + 12. If the distribution and/or use of the Library is restricted in + certain countries either by patents or by copyrighted interfaces, the + original copyright holder who places the Library under this License may add + an explicit geographical distribution limitation excluding those countries, + so that distribution is permitted only in or among countries not thus + excluded. In such case, this License incorporates the limitation as if + written in the body of this License. + . + 13. The Free Software Foundation may publish revised and/or new + versions of the Lesser General Public License from time to time. + Such new versions will be similar in spirit to the present version, + but may differ in detail to address new problems or concerns. + . + Each version is given a distinguishing version number. If the Library + specifies a version number of this License which applies to it and + "any later version", you have the option of following the terms and + conditions either of that version or of any later version published by + the Free Software Foundation. If the Library does not specify a + license version number, you may choose any version ever published by + the Free Software Foundation. + . + 14. If you wish to incorporate parts of the Library into other free + programs whose distribution conditions are incompatible with these, + write to the author to ask for permission. For software which is + copyrighted by the Free Software Foundation, write to the Free + Software Foundation; we sometimes make exceptions for this. Our + decision will be guided by the two goals of preserving the free status + of all derivatives of our free software and of promoting the sharing + and reuse of software generally. + . + NO WARRANTY + . + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO + WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. + EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR + OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY + KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE + LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME + THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + . + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN + WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY + AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU + FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE + LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING + RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A + FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF + SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + DAMAGES. + . + END OF TERMS AND CONDITIONS + . + How to Apply These Terms to Your New Libraries + . + If you develop a new library, and you want it to be of the greatest + possible use to the public, we recommend making it free software that + everyone can redistribute and change. You can do so by permitting + redistribution under these terms (or, alternatively, under the terms of the + ordinary General Public License). + . + To apply these terms, attach the following notices to the library. It is + safest to attach them to the start of each source file to most effectively + convey the exclusion of warranty; and each file should have at least the + "copyright" line and a pointer to where the full notice is found. + . + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + . + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + . + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + . + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + . + Also add information on how to contact you by electronic and paper mail. + . + You should also get your employer (if you work as a programmer) or your + school, if any, to sign a "copyright disclaimer" for the library, if + necessary. Here is a sample; alter the names: + . + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + . + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + . + That's all there is to it! + License: MPL-2.0 Mozilla Public License Version 2.0 ================================== diff --git a/SConstruct b/SConstruct index 3056e03d48..df0e40381f 100644 --- a/SConstruct +++ b/SConstruct @@ -2,7 +2,6 @@ EnsureSConsVersion(0, 98, 1) - import string import os import os.path @@ -10,9 +9,6 @@ import glob import sys import methods -# moved below to compensate with module version string -# methods.update_version() - # scan possible build platforms platform_list = [] # list of platforms @@ -53,9 +49,6 @@ for x in glob.glob("platform/*"): module_list = methods.detect_modules() - -# print "Detected Platforms: "+str(platform_list) - methods.save_active_platforms(active_platforms, active_platform_ids) custom_tools = ['default'] @@ -101,7 +94,6 @@ env_base.Decider('MD5-timestamp') # http://scons.org/doc/production/HTML/scons-user/ch06s04.html env_base.SetOption('implicit_cache', 1) - env_base.__class__.android_add_maven_repository = methods.android_add_maven_repository env_base.__class__.android_add_flat_dir = methods.android_add_flat_dir env_base.__class__.android_add_dependency = methods.android_add_dependency @@ -145,52 +137,53 @@ if profile: opts = Variables(customs, ARGUMENTS) # Target build options -opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/etc)", '') +opts.Add('arch', "Platform-dependent architecture (arm/arm64/x86/x64/mips/...)", '') opts.Add(EnumVariable('bits', "Target platform bits", 'default', ('default', '32', '64'))) opts.Add('p', "Platform (alias for 'platform')", '') opts.Add('platform', "Target platform (%s)" % ('|'.join(platform_list), ), '') opts.Add(EnumVariable('target', "Compilation target", 'debug', ('debug', 'release_debug', 'release'))) -opts.Add(BoolVariable('tools', "Build the tools a.k.a. the Godot editor", True)) -opts.Add(BoolVariable('use_lto', 'Use linking time optimization', False)) +opts.Add(BoolVariable('tools', "Build the tools (a.k.a. the Godot editor)", True)) +opts.Add(BoolVariable('use_lto', 'Use link-time optimization', False)) # Components opts.Add(BoolVariable('deprecated', "Enable deprecated features", True)) -opts.Add(BoolVariable('gdscript', "Build GDSCript support", True)) -opts.Add(BoolVariable('minizip', "Build minizip archive support", True)) -opts.Add(BoolVariable('xaudio2', "XAudio2 audio driver", False)) -opts.Add(BoolVariable('xml', "XML format support for resources", True)) +opts.Add(BoolVariable('gdscript', "Enable GDScript support", True)) +opts.Add(BoolVariable('minizip', "Enable ZIP archive support using minizip", True)) +opts.Add(BoolVariable('xaudio2', "Enable the XAudio2 audio driver", False)) +opts.Add(BoolVariable('xml', "Enable XML format support for resources", True)) # Advanced options -opts.Add(BoolVariable('disable_3d', "Disable 3D nodes for smaller executable", False)) -opts.Add(BoolVariable('disable_advanced_gui', "Disable advanced 3D gui nodes and behaviors", False)) +opts.Add(BoolVariable('disable_3d', "Disable 3D nodes for a smaller executable", False)) +opts.Add(BoolVariable('disable_advanced_gui', "Disable advanced 3D GUI nodes and behaviors", False)) opts.Add('extra_suffix', "Custom extra suffix added to the base filename of all generated binary files", '') -opts.Add('unix_global_settings_path', "UNIX-specific path to system-wide settings. Currently only used for templates", '') opts.Add(BoolVariable('verbose', "Enable verbose output for the compilation", False)) -opts.Add(BoolVariable('vsproj', "Generate Visual Studio Project", False)) +opts.Add(BoolVariable('vsproj', "Generate a Visual Studio solution", False)) opts.Add(EnumVariable('warnings', "Set the level of warnings emitted during compilation", 'no', ('extra', 'all', 'moderate', 'no'))) -opts.Add(BoolVariable('progress', "Show a progress indicator during build", True)) +opts.Add(BoolVariable('progress', "Show a progress indicator during compilation", True)) opts.Add(BoolVariable('dev', "If yes, alias for verbose=yes warnings=all", False)) -opts.Add(EnumVariable('macports_clang', "Build using clang from MacPorts", 'no', ('no', '5.0', 'devel'))) +opts.Add(EnumVariable('macports_clang', "Build using Clang from MacPorts", 'no', ('no', '5.0', 'devel'))) +opts.Add(BoolVariable('no_editor_splash', "Don't use the custom splash screen for the editor", False)) # Thirdparty libraries -opts.Add(BoolVariable('builtin_bullet', "Use the builtin bullet library", True)) -opts.Add(BoolVariable('builtin_enet', "Use the builtin enet library", True)) -opts.Add(BoolVariable('builtin_freetype', "Use the builtin freetype library", True)) -opts.Add(BoolVariable('builtin_libogg', "Use the builtin libogg library", True)) -opts.Add(BoolVariable('builtin_libpng', "Use the builtin libpng library", True)) -opts.Add(BoolVariable('builtin_libtheora', "Use the builtin libtheora library", True)) -opts.Add(BoolVariable('builtin_libvorbis', "Use the builtin libvorbis library", True)) -opts.Add(BoolVariable('builtin_libvpx', "Use the builtin libvpx library", True)) -opts.Add(BoolVariable('builtin_libwebp', "Use the builtin libwebp library", True)) -opts.Add(BoolVariable('builtin_mbedtls', "Use the builtin mbedTLS library", True)) -opts.Add(BoolVariable('builtin_opus', "Use the builtin opus library", True)) -opts.Add(BoolVariable('builtin_pcre2', "Use the builtin pcre2 library)", True)) -opts.Add(BoolVariable('builtin_recast', "Use the builtin recast library", True)) -opts.Add(BoolVariable('builtin_squish', "Use the builtin squish library", True)) -opts.Add(BoolVariable('builtin_thekla_atlas', "Use the builtin thekla_altas library", True)) -opts.Add(BoolVariable('builtin_zlib', "Use the builtin zlib library", True)) -opts.Add(BoolVariable('builtin_zstd', "Use the builtin zstd library", True)) -opts.Add(BoolVariable('no_editor_splash', "Don't use the custom splash screen for the editor", False)) +opts.Add(BoolVariable('builtin_bullet', "Use the built-in Bullet library", True)) +opts.Add(BoolVariable('builtin_enet', "Use the built-in ENet library", True)) +opts.Add(BoolVariable('builtin_freetype', "Use the built-in FreeType library", True)) +opts.Add(BoolVariable('builtin_libogg', "Use the built-in libogg library", True)) +opts.Add(BoolVariable('builtin_libpng', "Use the built-in libpng library", True)) +opts.Add(BoolVariable('builtin_libtheora', "Use the built-in libtheora library", True)) +opts.Add(BoolVariable('builtin_libvorbis', "Use the built-in libvorbis library", True)) +opts.Add(BoolVariable('builtin_libvpx', "Use the built-in libvpx library", True)) +opts.Add(BoolVariable('builtin_libwebp', "Use the built-in libwebp library", True)) +opts.Add(BoolVariable('builtin_libwebsockets', "Use the built-in libwebsockets library", True)) +opts.Add(BoolVariable('builtin_mbedtls', "Use the built-in mbedTLS library", True)) +opts.Add(BoolVariable('builtin_miniupnpc', "Use the built-in miniupnpc library", True)) +opts.Add(BoolVariable('builtin_opus', "Use the built-in Opus library", True)) +opts.Add(BoolVariable('builtin_pcre2', "Use the built-in PCRE2 library)", True)) +opts.Add(BoolVariable('builtin_recast', "Use the built-in Recast library", True)) +opts.Add(BoolVariable('builtin_squish', "Use the built-in squish library", True)) +opts.Add(BoolVariable('builtin_thekla_atlas', "Use the built-in thekla_altas library", True)) +opts.Add(BoolVariable('builtin_zlib', "Use the built-in zlib library", True)) +opts.Add(BoolVariable('builtin_zstd', "Use the built-in Zstd library", True)) # Compilation environment setup opts.Add("CXX", "C++ compiler") @@ -201,7 +194,6 @@ opts.Add("CXXFLAGS", "Custom flags for the C++ compiler") opts.Add("CFLAGS", "Custom flags for the C compiler") opts.Add("LINKFLAGS", "Custom flags for the linker") - # add platform specific options for k in platform_opts.keys(): @@ -232,14 +224,6 @@ env_base.Append(CPPPATH=['#core', '#core/math', '#editor', '#drivers', '#']) env_base.platform_exporters = platform_exporters env_base.platform_apis = platform_apis -""" -sys.path.append("./platform/"+env_base["platform"]) -import detect -detect.configure(env_base) -sys.path.remove("./platform/"+env_base["platform"]) -sys.modules.pop('detect') -""" - if (env_base['target'] == 'debug'): env_base.Append(CPPDEFINES=['DEBUG_MEMORY_ALLOC', 'SCI_NAMESPACE']) @@ -251,7 +235,6 @@ if not env_base['deprecated']: env_base.platforms = {} - selected_platform = "" if env_base['platform'] != "": @@ -260,7 +243,6 @@ elif env_base['p'] != "": selected_platform = env_base['p'] env_base["platform"] = selected_platform - if selected_platform in platform_list: sys.path.append("./platform/" + selected_platform) @@ -352,7 +334,6 @@ if selected_platform in platform_list: else: # 'no' env.Append(CCFLAGS=['-w']) env.Append(CCFLAGS=['-Werror=return-type']) - #env['platform_libsuffix'] = env['LIBSUFFIX'] suffix = "." + selected_platform @@ -429,10 +410,6 @@ if selected_platform in platform_list: if (env.use_ptrcall): env.Append(CPPDEFINES=['PTRCALL_ENABLED']) - - # to test 64 bits compiltion - # env.Append(CPPFLAGS=['-m64']) - if env['tools']: env.Append(CPPDEFINES=['TOOLS_ENABLED']) if env['disable_3d']: @@ -441,10 +418,8 @@ if selected_platform in platform_list: env.Append(CPPDEFINES=['GDSCRIPT_ENABLED']) if env['disable_advanced_gui']: env.Append(CPPDEFINES=['ADVANCED_GUI_DISABLED']) - if env['minizip']: env.Append(CPPDEFINES=['MINIZIP_ENABLED']) - if env['xml']: env.Append(CPPDEFINES=['XML_ENABLED']) @@ -492,11 +467,10 @@ if selected_platform in platform_list: else: print("No valid target platform selected.") - print("The following were detected:") + print("The following platforms were detected:") for x in platform_list: print("\t" + x) - print("\nPlease run scons again with argument: platform=<string>") - + print("\nPlease run SCons again with the argument: platform=<string>") # The following only makes sense when the env is defined, and assumes it is if 'env' in locals(): diff --git a/core/math/triangle_mesh.cpp b/core/math/triangle_mesh.cpp index edd4ad3441..0dd1cbf1c3 100644 --- a/core/math/triangle_mesh.cpp +++ b/core/math/triangle_mesh.cpp @@ -88,6 +88,26 @@ int TriangleMesh::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, in return index; } +void TriangleMesh::get_indices(PoolVector<int> *r_triangles_indices) const { + + if (!valid) + return; + + const int triangles_num = triangles.size(); + + // Parse vertices indices + PoolVector<Triangle>::Read triangles_read = triangles.read(); + + r_triangles_indices->resize(triangles_num * 3); + PoolVector<int>::Write r_indices_write = r_triangles_indices->write(); + + for (int i = 0; i < triangles_num; ++i) { + r_indices_write[3 * i + 0] = triangles_read[i].indices[0]; + r_indices_write[3 * i + 1] = triangles_read[i].indices[1]; + r_indices_write[3 * i + 2] = triangles_read[i].indices[2]; + } +} + void TriangleMesh::create(const PoolVector<Vector3> &p_faces) { valid = false; diff --git a/core/math/triangle_mesh.h b/core/math/triangle_mesh.h index 9f145f2afb..78de7ae7ee 100644 --- a/core/math/triangle_mesh.h +++ b/core/math/triangle_mesh.h @@ -92,6 +92,10 @@ public: Vector3 get_area_normal(const AABB &p_aabb) const; PoolVector<Face3> get_faces() const; + PoolVector<Triangle> get_triangles() const { return triangles; } + PoolVector<Vector3> get_vertices() const { return vertices; } + void get_indices(PoolVector<int> *p_triangles_indices) const; + void create(const PoolVector<Vector3> &p_faces); TriangleMesh(); }; diff --git a/doc/classes/Particles.xml b/doc/classes/Particles.xml index 04177aca25..b03cf6cadb 100644 --- a/doc/classes/Particles.xml +++ b/doc/classes/Particles.xml @@ -22,6 +22,7 @@ <return type="void"> </return> <description> + Restarts the particle emmission, clearing existing particles. </description> </method> </methods> @@ -33,14 +34,19 @@ Particle draw order. Uses [code]DRAW_ORDER_*[/code] values. Default value: [code]DRAW_ORDER_INDEX[/code]. </member> <member name="draw_pass_1" type="Mesh" setter="set_draw_pass_mesh" getter="get_draw_pass_mesh"> + [Mesh] that is drawn for the first draw pass. </member> <member name="draw_pass_2" type="Mesh" setter="set_draw_pass_mesh" getter="get_draw_pass_mesh"> + [Mesh] that is drawn for the second draw pass. </member> <member name="draw_pass_3" type="Mesh" setter="set_draw_pass_mesh" getter="get_draw_pass_mesh"> + [Mesh] that is drawn for the third draw pass. </member> <member name="draw_pass_4" type="Mesh" setter="set_draw_pass_mesh" getter="get_draw_pass_mesh"> + [Mesh] that is drawn for the fourth draw pass. </member> <member name="draw_passes" type="int" setter="set_draw_passes" getter="get_draw_passes"> + The number of draw passes when rendering particles. </member> <member name="emitting" type="bool" setter="set_emitting" getter="is_emitting"> If [code]true[/code] particles are being emitted. Default value: [code]true[/code]. @@ -62,6 +68,7 @@ If [code]true[/code] only [code]amount[/code] particles will be emitted. Default value: [code]false[/code]. </member> <member name="preprocess" type="float" setter="set_pre_process_time" getter="get_pre_process_time"> + Amount of time to preprocess the particles before animation starts. Lets you start the animation some time after particles have started emitting. </member> <member name="process_material" type="Material" setter="set_process_material" getter="get_process_material"> [Material] for processing particles. Can be a [ParticlesMaterial] or a [ShaderMaterial]. @@ -73,6 +80,7 @@ Speed scaling ratio. Default value: [code]1[/code]. </member> <member name="visibility_aabb" type="AABB" setter="set_visibility_aabb" getter="get_visibility_aabb"> + The [AABB] that determines the area of the world part of which needs to be visible on screen for the particle system to be active. </member> </members> <constants> @@ -86,6 +94,7 @@ Particles are drawn in order of depth. </constant> <constant name="MAX_DRAW_PASSES" value="4"> + Maximum number of draw passes supported. </constant> </constants> </class> diff --git a/editor/animation_bezier_editor.cpp b/editor/animation_bezier_editor.cpp new file mode 100644 index 0000000000..197599442b --- /dev/null +++ b/editor/animation_bezier_editor.cpp @@ -0,0 +1,1183 @@ +#include "animation_bezier_editor.h" + +float AnimationBezierTrackEdit::_bezier_h_to_pixel(float p_h) { + float h = p_h; + h = (h - v_scroll) / v_zoom; + h = (get_size().height / 2) - h; + return h; +} + +static _FORCE_INLINE_ Vector2 _bezier_interp(real_t t, const Vector2 &start, const Vector2 &control_1, const Vector2 &control_2, const Vector2 &end) { + /* Formula from Wikipedia article on Bezier curves. */ + real_t omt = (1.0 - t); + real_t omt2 = omt * omt; + real_t omt3 = omt2 * omt; + real_t t2 = t * t; + real_t t3 = t2 * t; + + return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3; +} + +void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) { + + float scale = timeline->get_zoom_scale(); + int limit = timeline->get_name_limit(); + int right_limit = get_size().width - timeline->get_buttons_width(); + + //selection may have altered the order of keys + Map<float, int> key_order; + + for (int i = 0; i < animation->track_get_key_count(p_track); i++) { + float ofs = animation->track_get_key_time(p_track, i); + if (moving_selection && track == p_track && selection.has(i)) { + ofs += moving_selection_offset.x; + } + + key_order[ofs] = i; + } + + for (Map<float, int>::Element *E = key_order.front(); E; E = E->next()) { + + int i = E->get(); + + if (!E->next()) + break; + + int i_n = E->next()->get(); + + float offset = animation->track_get_key_time(p_track, i); + float height = animation->bezier_track_get_key_value(p_track, i); + Vector2 out_handle = animation->bezier_track_get_key_out_handle(p_track, i); + if (track == p_track && moving_handle != 0 && moving_handle_key == i) { + out_handle = moving_handle_right; + } + + if (moving_selection && track == p_track && selection.has(i)) { + offset += moving_selection_offset.x; + height += moving_selection_offset.y; + } + + out_handle += Vector2(offset, height); + + float offset_n = animation->track_get_key_time(p_track, i_n); + float height_n = animation->bezier_track_get_key_value(p_track, i_n); + Vector2 in_handle = animation->bezier_track_get_key_in_handle(p_track, i_n); + if (track == p_track && moving_handle != 0 && moving_handle_key == i_n) { + in_handle = moving_handle_left; + } + + if (moving_selection && track == p_track && selection.has(i_n)) { + offset_n += moving_selection_offset.x; + height_n += moving_selection_offset.y; + } + + in_handle += Vector2(offset_n, height_n); + + Vector2 start(offset, height); + Vector2 end(offset_n, height_n); + + int from_x = (offset - timeline->get_value()) * scale + limit; + int point_start = from_x; + int to_x = (offset_n - timeline->get_value()) * scale + limit; + int point_end = to_x; + + if (from_x > right_limit) //not visible + continue; + + if (to_x < limit) //not visible + continue; + + from_x = MAX(from_x, limit); + to_x = MIN(to_x, right_limit); + + Vector<Vector2> lines; + + Vector2 prev_pos; + + for (int j = from_x; j <= to_x; j++) { + + float t = (j - limit) / scale + timeline->get_value(); + + float h; + + if (j == point_end) { + h = end.y; //make sure it always connects + } else if (j == point_start) { + h = start.y; //make sure it always connects + } else { //custom interpolation, used because it needs to show paths affected by moving the selection or handles + int iterations = 10; + float low = 0; + float high = 1; + float middle; + + //narrow high and low as much as possible + for (int k = 0; k < iterations; k++) { + + middle = (low + high) / 2; + + Vector2 interp = _bezier_interp(middle, start, out_handle, in_handle, end); + + if (interp.x < t) { + low = middle; + } else { + high = middle; + } + } + + //interpolate the result: + Vector2 low_pos = _bezier_interp(low, start, out_handle, in_handle, end); + Vector2 high_pos = _bezier_interp(high, start, out_handle, in_handle, end); + + float c = (t - low_pos.x) / (high_pos.x - low_pos.x); + + h = low_pos.linear_interpolate(high_pos, c).y; + } + + h = _bezier_h_to_pixel(h); + + Vector2 pos(j, h); + + if (j > from_x) { + lines.push_back(prev_pos); + lines.push_back(pos); + } + prev_pos = pos; + } + + if (lines.size() >= 2) { + draw_multiline(lines, p_color); + } + } +} + +void AnimationBezierTrackEdit::_draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right) { + + Vector2 from = p_from; + Vector2 to = p_to; + + if (from.x == to.x) + return; + if (to.x < from.x) { + SWAP(to, from); + } + + if (to.x < p_clip_left) + return; + + if (from.x > p_clip_right) + return; + + if (to.x > p_clip_right) { + float c = (p_clip_right - from.x) / (to.x - from.x); + to = from.linear_interpolate(to, c); + } + + if (from.x < p_clip_left) { + float c = (p_clip_left - from.x) / (to.x - from.x); + from = from.linear_interpolate(to, c); + } + + draw_line(from, to, p_color); +} + +void AnimationBezierTrackEdit::_notification(int p_what) { + + if (p_what == NOTIFICATION_THEME_CHANGED || p_what == NOTIFICATION_ENTER_TREE) { + bezier_icon = get_icon("KeyBezierPoint", "EditorIcons"); + bezier_handle_icon = get_icon("KeyBezierHandle", "EditorIcons"); + selected_icon = get_icon("KeyBezierSelected", "EditorIcons"); + if (handle_mode_option->get_item_count() == 0) { + handle_mode_option->add_icon_item(get_icon("BezierHandlesFree", "EditorIcons"), TTR("Free"), HANDLE_MODE_FREE); + handle_mode_option->add_icon_item(get_icon("BezierHandlesBalanced", "EditorIcons"), TTR("Balanced"), HANDLE_MODE_BALANCED); + handle_mode_option->add_icon_item(get_icon("BezierHandlesMirror", "EditorIcons"), TTR("Mirror"), HANDLE_MODE_MIRROR); + } + } + if (p_what == NOTIFICATION_RESIZED) { + + int right_limit = get_size().width - timeline->get_buttons_width(); + int hsep = get_constant("hseparation", "ItemList"); + int vsep = get_constant("vseparation", "ItemList"); + + handle_mode_option->set_position(Vector2(right_limit + hsep, get_size().height - handle_mode_option->get_combined_minimum_size().height - vsep)); + handle_mode_option->set_size(Vector2(timeline->get_buttons_width() - hsep * 2, handle_mode_option->get_combined_minimum_size().height)); + } + if (p_what == NOTIFICATION_DRAW) { + if (animation.is_null()) + return; + + int limit = timeline->get_name_limit(); + + if (has_focus()) { + Color accent = get_color("accent_color", "Editor"); + accent.a *= 0.7; + draw_rect(Rect2(Point2(), get_size()), accent, false); + } + + Ref<Font> font = get_font("font", "Label"); + Color color = get_color("font_color", "Label"); + int hsep = get_constant("hseparation", "ItemList"); + int vsep = get_constant("vseparation", "ItemList"); + Color linecolor = color; + linecolor.a = 0.2; + + draw_line(Point2(limit, 0), Point2(limit, get_size().height), linecolor); + + int right_limit = get_size().width - timeline->get_buttons_width(); + + draw_line(Point2(right_limit, 0), Point2(right_limit, get_size().height), linecolor); + + Ref<Texture> close_icon = get_icon("Close", "EditorIcons"); + + close_icon_rect.position = Vector2(get_size().width - close_icon->get_width() - hsep, hsep); + close_icon_rect.size = close_icon->get_size(); + draw_texture(close_icon, close_icon_rect.position); + + String base_path = animation->track_get_path(track); + int end = base_path.find(":"); + if (end != -1) { + base_path = base_path.substr(0, end + 1); + } + + // NAMES AND ICON + int vofs = vsep; + int margin = 0; + + { + int ofs = 0; + + NodePath path = animation->track_get_path(track); + + Node *node = NULL; + + if (root && root->has_node(path)) { + node = root->get_node(path); + } + + String text; + + int h = font->get_height(); + + if (node) { + Ref<Texture> icon; + if (has_icon(node->get_class(), "EditorIcons")) { + icon = get_icon(node->get_class(), "EditorIcons"); + } else { + icon = get_icon("Node", "EditorIcons"); + } + + h = MAX(h, icon->get_height()); + + draw_texture(icon, Point2(ofs, vofs + int(h - icon->get_height()) / 2)); + + margin = icon->get_width(); + + text = node->get_name(); + ofs += hsep; + ofs += icon->get_width(); + + Vector2 string_pos = Point2(ofs, vofs + (h - font->get_height()) / 2 + font->get_ascent()); + string_pos = string_pos.floor(); + draw_string(font, string_pos, text, color, limit - ofs - hsep); + + vofs += h + vsep; + } + } + + // RELATED TRACKS TITLES + + Map<int, Color> subtrack_colors; + subtracks.clear(); + + for (int i = 0; i < animation->get_track_count(); i++) { + if (animation->track_get_type(i) != Animation::TYPE_BEZIER) + continue; + String path = animation->track_get_path(i); + if (!path.begins_with(base_path)) + continue; //another node + path = path.replace_first(base_path, ""); + + Color cc = color; + Rect2 rect = Rect2(margin, vofs, limit - margin - hsep, font->get_height() + vsep); + if (i != track) { + cc.a *= 0.7; + uint32_t hash = path.hash(); + hash = ((hash >> 16) ^ hash) * 0x45d9f3b; + hash = ((hash >> 16) ^ hash) * 0x45d9f3b; + hash = (hash >> 16) ^ hash; + float h = (hash % 65535) / 65536.0; + Color subcolor; + subcolor.set_hsv(h, 0.2, 0.8); + subcolor.a = 0.5; + draw_rect(Rect2(0, vofs + font->get_height() * 0.1, margin - hsep, font->get_height() * 0.8), subcolor); + subtrack_colors[i] = subcolor; + + subtracks[i] = rect; + } else { + Color ac = get_color("accent_color", "Editor"); + ac.a = 0.5; + draw_rect(rect, ac); + } + draw_string(font, Point2(margin, vofs + font->get_ascent()), path, cc, limit - margin - hsep); + + vofs += font->get_height() + vsep; + } + + Color accent = get_color("accent_color", "Editor"); + + { //guides + float min_left_scale = font->get_height() + vsep; + + float scale = 1; + + while (scale / v_zoom < min_left_scale * 2) { + scale *= 5; + } + + bool first = true; + int prev_iv = 0; + for (int i = font->get_height(); i < get_size().height; i++) { + + float ofs = get_size().height / 2 - i; + ofs *= v_zoom; + ofs += v_scroll; + + int iv = int(ofs / scale); + if (ofs < 0) + iv -= 1; + if (!first && iv != prev_iv) { + + Color lc = linecolor; + lc.a *= 0.5; + draw_line(Point2(limit, i), Point2(right_limit, i), lc); + Color c = color; + c.a *= 0.5; + draw_string(font, Point2(limit + 8, i - 2), itos((iv + 1) * scale), c); + } + + first = false; + prev_iv = iv; + } + } + + { //draw OTHER curves + + float scale = timeline->get_zoom_scale(); + Ref<Texture> point = get_icon("KeyValue", "EditorIcons"); + for (Map<int, Color>::Element *E = subtrack_colors.front(); E; E = E->next()) { + + _draw_track(E->key(), E->get()); + + for (int i = 0; i < animation->track_get_key_count(E->key()); i++) { + + float offset = animation->track_get_key_time(E->key(), i); + float value = animation->bezier_track_get_key_value(E->key(), i); + + Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value)); + + if (pos.x >= limit && pos.x <= right_limit) { + draw_texture(point, pos - point->get_size() / 2, E->get()); + } + } + } + + //draw edited curve + _draw_track(track, accent); + } + + //draw editor handles + { + + float scale = timeline->get_zoom_scale(); + edit_points.clear(); + + for (int i = 0; i < animation->track_get_key_count(track); i++) { + + float offset = animation->track_get_key_time(track, i); + float value = animation->bezier_track_get_key_value(track, i); + + if (moving_selection && selection.has(i)) { + offset += moving_selection_offset.x; + value += moving_selection_offset.y; + } + + Vector2 pos((offset - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value)); + + Vector2 in_vec = animation->bezier_track_get_key_in_handle(track, i); + if (moving_handle != 0 && moving_handle_key == i) { + in_vec = moving_handle_left; + } + Vector2 pos_in = Vector2(((offset + in_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + in_vec.y)); + + Vector2 out_vec = animation->bezier_track_get_key_out_handle(track, i); + + if (moving_handle != 0 && moving_handle_key == i) { + out_vec = moving_handle_right; + } + + Vector2 pos_out = Vector2(((offset + out_vec.x) - timeline->get_value()) * scale + limit, _bezier_h_to_pixel(value + out_vec.y)); + + _draw_line_clipped(pos, pos_in, accent, limit, right_limit); + _draw_line_clipped(pos, pos_out, accent, limit, right_limit); + + EditPoint ep; + if (pos.x >= limit && pos.x <= right_limit) { + ep.point_rect.position = (pos - bezier_icon->get_size() / 2).floor(); + ep.point_rect.size = bezier_icon->get_size(); + if (selection.has(i)) { + draw_texture(selected_icon, ep.point_rect.position); + } else { + draw_texture(bezier_icon, ep.point_rect.position); + } + ep.point_rect = ep.point_rect.grow(ep.point_rect.size.width * 0.5); + } + if (pos_in.x >= limit && pos_in.x <= right_limit) { + ep.in_rect.position = (pos_in - bezier_handle_icon->get_size() / 2).floor(); + ep.in_rect.size = bezier_handle_icon->get_size(); + draw_texture(bezier_handle_icon, ep.in_rect.position); + ep.in_rect = ep.in_rect.grow(ep.in_rect.size.width * 0.5); + } + if (pos_out.x >= limit && pos_out.x <= right_limit) { + ep.out_rect.position = (pos_out - bezier_handle_icon->get_size() / 2).floor(); + ep.out_rect.size = bezier_handle_icon->get_size(); + draw_texture(bezier_handle_icon, ep.out_rect.position); + ep.out_rect = ep.out_rect.grow(ep.out_rect.size.width * 0.5); + } + edit_points.push_back(ep); + } + } + + if (box_selecting) { + Color bs = accent; + bs.a *= 0.5; + Vector2 bs_from = box_selection_from; + Vector2 bs_to = box_selection_to; + if (bs_from.x > bs_to.x) { + SWAP(bs_from.x, bs_to.x); + } + if (bs_from.y > bs_to.y) { + SWAP(bs_from.y, bs_to.y); + } + draw_rect(Rect2(bs_from, bs_to - bs_from), bs); + } + +#if 0 + // KEYFAMES // + + { + + float scale = timeline->get_zoom_scale(); + int limit_end = get_size().width - timeline->get_buttons_width(); + + for (int i = 0; i < animation->track_get_key_count(track); i++) { + + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + if (editor->is_key_selected(track, i) && editor->is_moving_selection()) { + offset += editor->get_moving_selection_offset(); + } + offset = offset * scale + limit; + draw_key(i, scale, int(offset), editor->is_key_selected(track, i), limit, limit_end); + } + } +#endif + } +} + +Ref<Animation> AnimationBezierTrackEdit::get_animation() const { + return animation; +} + +void AnimationBezierTrackEdit::set_animation_and_track(const Ref<Animation> &p_animation, int p_track) { + + animation = p_animation; + track = p_track; + update(); +} + +Size2 AnimationBezierTrackEdit::get_minimum_size() const { + + return Vector2(1, 1); +} + +void AnimationBezierTrackEdit::set_undo_redo(UndoRedo *p_undo_redo) { + undo_redo = p_undo_redo; +} + +void AnimationBezierTrackEdit::set_timeline(AnimationTimelineEdit *p_timeline) { + timeline = p_timeline; + timeline->connect("zoom_changed", this, "_zoom_changed"); +} +void AnimationBezierTrackEdit::set_editor(AnimationTrackEditor *p_editor) { + editor = p_editor; +} + +void AnimationBezierTrackEdit::_play_position_draw() { + + if (!animation.is_valid() || play_position_pos < 0) + return; + + float scale = timeline->get_zoom_scale(); + int h = get_size().height; + + int px = (-timeline->get_value() + play_position_pos) * scale + timeline->get_name_limit(); + + if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) { + Color color = get_color("accent_color", "Editor"); + play_position->draw_line(Point2(px, 0), Point2(px, h), color); + } +} + +void AnimationBezierTrackEdit::set_play_position(float p_pos) { + + play_position_pos = p_pos; + play_position->update(); +} + +void AnimationBezierTrackEdit::update_play_position() { + play_position->update(); +} + +void AnimationBezierTrackEdit::set_root(Node *p_root) { + root = p_root; +} +void AnimationBezierTrackEdit::_zoom_changed() { + update(); +} + +String AnimationBezierTrackEdit::get_tooltip(const Point2 &p_pos) const { + + return Control::get_tooltip(p_pos); +} + +void AnimationBezierTrackEdit::_clear_selection() { + selection.clear(); + update(); +} + +void AnimationBezierTrackEdit::_clear_selection_for_anim(const Ref<Animation> &p_anim) { + + if (!(animation == p_anim)) + return; + //selection.clear(); + _clear_selection(); +} + +void AnimationBezierTrackEdit::_select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos) { + + if (!(animation == p_anim)) + return; + + int idx = animation->track_find_key(p_track, p_pos, true); + ERR_FAIL_COND(idx < 0); + + selection.insert(idx); + update(); +} + +void AnimationBezierTrackEdit::_gui_input(const Ref<InputEvent> &p_event) { + + if (p_event->is_pressed()) { + if (ED_GET_SHORTCUT("animation_editor/duplicate_selection")->is_shortcut(p_event)) { + duplicate_selection(); + accept_event(); + } + + if (ED_GET_SHORTCUT("animation_editor/delete_selection")->is_shortcut(p_event)) { + delete_selection(); + accept_event(); + } + } + + Ref<InputEventMouseButton> mb = p_event; + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { + if (mb->get_command()) { + timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() * 1.05); + } else { + if (v_zoom < 1000) { + v_zoom *= 1.2; + } + } + update(); + } + + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) { + if (mb->get_command()) { + timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() / 1.05); + } else { + if (v_zoom > 0.01) { + v_zoom /= 1.2; + } + } + update(); + } + + if (mb.is_valid() && mb->get_button_index() == BUTTON_MIDDLE) { + + if (mb->is_pressed()) { + int x = mb->get_position().x - timeline->get_name_limit(); + panning_timeline_from = x / timeline->get_zoom_scale(); + panning_timeline = true; + panning_timeline_at = timeline->get_value(); + } else { + panning_timeline = false; + } + } + + if (mb.is_valid() && mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) { + + menu_insert_key = mb->get_position(); + Vector2 popup_pos = get_global_transform().xform(mb->get_position()); + + menu->clear(); + menu->add_icon_item(bezier_icon, TTR("Insert Key Here"), MENU_KEY_INSERT); + if (selection.size()) { + menu->add_separator(); + menu->add_icon_item(get_icon("Duplicate", "EditorIcons"), TTR("Duplicate Selected Key(s)"), MENU_KEY_DUPLICATE); + menu->add_separator(); + menu->add_icon_item(get_icon("Remove", "EditorIcons"), TTR("Delete Selected Key(s)"), MENU_KEY_DELETE); + } + + menu->set_as_minsize(); + menu->set_position(popup_pos); + menu->popup(); + } + + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + if (close_icon_rect.has_point(mb->get_position())) { + emit_signal("close_request"); + return; + } + for (Map<int, Rect2>::Element *E = subtracks.front(); E; E = E->next()) { + if (E->get().has_point(mb->get_position())) { + set_animation_and_track(animation, E->key()); + return; + } + } + + for (int i = 0; i < edit_points.size(); i++) { + + //first check point + //command makes it ignore the main point, so control point editors can be force-edited + //path 2D editing in the 3D and 2D editors works the same way + if (!mb->get_command()) { + if (edit_points[i].point_rect.has_point(mb->get_position())) { + if (mb->get_shift()) { + //add to selection + if (selection.has(i)) { + selection.erase(i); + } else { + selection.insert(i); + } + update(); + select_single_attempt = -1; + } else if (selection.has(i)) { + moving_selection_attempt = true; + moving_selection = false; + moving_selection_from_key = i; + moving_selection_offset = Vector2(); + select_single_attempt = i; + update(); + } else { + + moving_selection_attempt = true; + moving_selection = true; + moving_selection_from_key = i; + moving_selection_offset = Vector2(); + selection.clear(); + selection.insert(i); + update(); + } + return; + } + } + + if (edit_points[i].in_rect.has_point(mb->get_position())) { + moving_handle = -1; + moving_handle_key = i; + moving_handle_left = animation->bezier_track_get_key_in_handle(track, i); + moving_handle_right = animation->bezier_track_get_key_out_handle(track, i); + update(); + return; + } + + if (edit_points[i].out_rect.has_point(mb->get_position())) { + moving_handle = 1; + moving_handle_key = i; + moving_handle_left = animation->bezier_track_get_key_in_handle(track, i); + moving_handle_right = animation->bezier_track_get_key_out_handle(track, i); + update(); + return; + ; + } + } + + //insert new point + if (mb->get_command() && mb->get_position().x >= timeline->get_name_limit() && mb->get_position().x < get_size().width - timeline->get_buttons_width()) { + + Array new_point; + new_point.resize(5); + + float h = (get_size().height / 2 - mb->get_position().y) * v_zoom + v_scroll; + + new_point[0] = h; + new_point[1] = -0.25; + new_point[2] = 0; + new_point[3] = 0.25; + new_point[4] = 0; + + float time = ((mb->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale()) + timeline->get_value(); + while (animation->track_find_key(track, time, true) != -1) { + time += 0.001; + } + + undo_redo->create_action("Add Bezier Point"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, time, new_point); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, time); + undo_redo->commit_action(); + + //then attempt to move + int index = animation->track_find_key(track, time, true); + ERR_FAIL_COND(index == -1); + _clear_selection(); + selection.insert(index); + + moving_selection_attempt = true; + moving_selection = false; + moving_selection_from_key = index; + moving_selection_offset = Vector2(); + select_single_attempt = -1; + update(); + + return; + } + + //box select + if (mb->get_position().x >= timeline->get_name_limit() && mb->get_position().x < get_size().width - timeline->get_buttons_width()) { + box_selecting_attempt = true; + box_selecting = false; + box_selecting_add = false; + box_selection_from = mb->get_position(); + return; + } + } + + if (box_selecting_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + if (box_selecting) { + //do actual select + if (!box_selecting_add) { + _clear_selection(); + } + + Vector2 bs_from = box_selection_from; + Vector2 bs_to = box_selection_to; + if (bs_from.x > bs_to.x) { + SWAP(bs_from.x, bs_to.x); + } + if (bs_from.y > bs_to.y) { + SWAP(bs_from.y, bs_to.y); + } + Rect2 selection_rect(bs_from, bs_to - bs_from); + + for (int i = 0; i < edit_points.size(); i++) { + + if (edit_points[i].point_rect.intersects(selection_rect)) { + selection.insert(i); + } + } + } else { + _clear_selection(); //clicked and nothing happened, so clear the selection + } + box_selecting_attempt = false; + box_selecting = false; + update(); + } + + if (moving_handle != 0 && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + undo_redo->create_action("Move Bezier Points"); + undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_in_handle", track, moving_handle_key, moving_handle_left); + undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_out_handle", track, moving_handle_key, moving_handle_right); + undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_in_handle", track, moving_handle_key, animation->bezier_track_get_key_in_handle(track, moving_handle_key)); + undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_out_handle", track, moving_handle_key, animation->bezier_track_get_key_out_handle(track, moving_handle_key)); + undo_redo->commit_action(); + + moving_handle = 0; + update(); + } + + if (moving_selection_attempt && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + if (moving_selection) { + //combit it + + undo_redo->create_action("Move Bezier Points"); + + List<AnimMoveRestore> to_restore; + // 1-remove the keys + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", track, E->get()); + } + // 2- remove overlapped keys + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float newtime = animation->track_get_key_time(track, E->get()) + moving_selection_offset.x; + + int idx = animation->track_find_key(track, newtime, true); + if (idx == -1) + continue; + + if (selection.has(idx)) + continue; //already in selection, don't save + + undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_position", track, newtime); + AnimMoveRestore amr; + + amr.key = animation->track_get_key_value(track, idx); + amr.track = track; + amr.time = newtime; + + to_restore.push_back(amr); + } + + // 3-move the keys (re insert them) + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = animation->track_get_key_time(track, E->get()) + moving_selection_offset.x; + /* + if (newpos<0) + continue; //no add at the beginning + */ + Array key = animation->track_get_key_value(track, E->get()); + float h = key[0]; + h += moving_selection_offset.y; + key[0] = h; + undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, newpos, key, 1); + } + + // 4-(undo) remove inserted keys + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = animation->track_get_key_time(track, E->get()) + moving_selection_offset.x; + /* + if (newpos<0) + continue; //no remove what no inserted + */ + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, newpos); + } + + // 5-(undo) reinsert keys + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float oldpos = animation->track_get_key_time(track, E->get()); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, oldpos, animation->track_get_key_value(track, E->get()), 1); + } + + // 6-(undo) reinsert overlapped keys + for (List<AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1); + } + + // 6-(undo) reinsert overlapped keys + for (List<AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, 1); + } + + undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); + undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); + + // 7-reselect + + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float oldpos = animation->track_get_key_time(track, E->get()); + float newpos = oldpos + moving_selection_offset.x; + + undo_redo->add_do_method(this, "_select_at_anim", animation, track, newpos); + undo_redo->add_undo_method(this, "_select_at_anim", animation, track, oldpos); + } + + undo_redo->commit_action(); + + moving_selection = false; + } else if (select_single_attempt != -1) { + selection.clear(); + selection.insert(select_single_attempt); + } + + moving_selection_attempt = false; + update(); + } + + Ref<InputEventMouseMotion> mm = p_event; + if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_MIDDLE) { + v_scroll += mm->get_relative().y * v_zoom; + if (v_scroll > 100000) + v_scroll = 100000; + if (v_scroll < -100000) + v_scroll = -100000; + + int x = mm->get_position().x - timeline->get_name_limit(); + float ofs = x / timeline->get_zoom_scale(); + float diff = ofs - panning_timeline_from; + timeline->set_value(panning_timeline_at - diff); + + update(); + } + if (moving_selection_attempt && mm.is_valid()) { + + if (!moving_selection) { + moving_selection = true; + select_single_attempt = -1; + } + + float y = (get_size().height / 2 - mm->get_position().y) * v_zoom + v_scroll; + float x = ((mm->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale()) + timeline->get_value(); + + moving_selection_offset = Vector2(x - animation->track_get_key_time(track, moving_selection_from_key), y - animation->bezier_track_get_key_value(track, moving_selection_from_key)); + update(); + } + + if (box_selecting_attempt && mm.is_valid()) { + + if (!box_selecting) { + box_selecting = true; + box_selecting_add = mm->get_shift(); + } + + box_selection_to = mm->get_position(); + + if (get_local_mouse_position().y < 0) { + //avoid cursor from going too above, so it does not lose focus with viewport + warp_mouse(Vector2(get_local_mouse_position().x, 0)); + } + update(); + } + + if (moving_handle != 0 && mm.is_valid()) { + + float y = (get_size().height / 2 - mm->get_position().y) * v_zoom + v_scroll; + float x = ((mm->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale()) + timeline->get_value(); + + Vector2 key_pos = Vector2(animation->track_get_key_time(track, moving_handle_key), animation->bezier_track_get_key_value(track, moving_handle_key)); + + Vector2 moving_handle_value = Vector2(x, y) - key_pos; + + moving_handle_left = animation->bezier_track_get_key_in_handle(track, moving_handle_key); + moving_handle_right = animation->bezier_track_get_key_out_handle(track, moving_handle_key); + + if (moving_handle == -1) { + moving_handle_left = moving_handle_value; + if (moving_handle_left.x > 0) { + moving_handle_left.x = 0; + } + + if (handle_mode_option->get_selected() == HANDLE_MODE_BALANCED) { + Vector2 scale = Vector2(timeline->get_zoom_scale(), v_zoom); + moving_handle_right = (-(moving_handle_left * scale).normalized() * (moving_handle_right * scale).length()) / scale; + + } else if (handle_mode_option->get_selected() == HANDLE_MODE_MIRROR) { + moving_handle_right = -moving_handle_left; + } + } + + if (moving_handle == 1) { + moving_handle_right = moving_handle_value; + if (moving_handle_right.x < 0) { + moving_handle_right.x = 0; + } + + if (handle_mode_option->get_selected() == HANDLE_MODE_BALANCED) { + Vector2 scale = Vector2(timeline->get_zoom_scale(), v_zoom); + moving_handle_left = (-(moving_handle_right * scale).normalized() * (moving_handle_left * scale).length()) / scale; + } else if (handle_mode_option->get_selected() == HANDLE_MODE_MIRROR) { + moving_handle_left = -moving_handle_right; + } + } + + update(); + } +} + +void AnimationBezierTrackEdit::_menu_selected(int p_index) { + + switch (p_index) { + case MENU_KEY_INSERT: { + + Array new_point; + new_point.resize(5); + + float h = (get_size().height / 2 - menu_insert_key.y) * v_zoom + v_scroll; + + new_point[0] = h; + new_point[1] = -0.25; + new_point[2] = 0; + new_point[3] = 0.25; + new_point[4] = 0; + + float time = ((menu_insert_key.x - timeline->get_name_limit()) / timeline->get_zoom_scale()) + timeline->get_value(); + while (animation->track_find_key(track, time, true) != -1) { + time += 0.001; + } + + undo_redo->create_action("Add Bezier Point"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, time, new_point); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, time); + undo_redo->commit_action(); + + } break; + case MENU_KEY_DUPLICATE: { + duplicate_selection(); + } break; + case MENU_KEY_DELETE: { + delete_selection(); + } break; + } +} + +void AnimationBezierTrackEdit::duplicate_selection() { + + if (selection.size() == 0) + return; + + float top_time = 1e10; + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float t = animation->track_get_key_time(track, E->get()); + if (t < top_time) + top_time = t; + } + + undo_redo->create_action(TTR("Anim Duplicate Keys")); + + List<Pair<int, float> > new_selection_values; + + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + float t = animation->track_get_key_time(track, E->get()); + float dst_time = t + (timeline->get_play_position() - top_time); + int existing_idx = animation->track_find_key(track, dst_time, true); + + undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, dst_time, animation->track_get_key_value(track, E->get()), animation->track_get_key_transition(track, E->get())); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, dst_time); + + Pair<int, float> p; + p.first = track; + p.second = dst_time; + new_selection_values.push_back(p); + + if (existing_idx != -1) { + + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, dst_time, animation->track_get_key_value(track, existing_idx), animation->track_get_key_transition(track, existing_idx)); + } + } + + undo_redo->commit_action(); + + //reselect duplicated + + selection.clear(); + for (List<Pair<int, float> >::Element *E = new_selection_values.front(); E; E = E->next()) { + + int track = E->get().first; + float time = E->get().second; + + int existing_idx = animation->track_find_key(track, time, true); + + if (existing_idx == -1) + continue; + + selection.insert(existing_idx); + } + + update(); +} + +void AnimationBezierTrackEdit::delete_selection() { + if (selection.size()) { + undo_redo->create_action(TTR("Anim Delete Keys")); + + for (Set<int>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", track, E->get()); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, animation->track_get_key_time(track, E->get()), animation->track_get_key_value(track, E->get()), 1); + } + undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); + undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); + undo_redo->commit_action(); + //selection.clear(); + } +} + +void AnimationBezierTrackEdit::set_block_animation_update_ptr(bool *p_block_ptr) { + block_animation_update_ptr = p_block_ptr; +} + +void AnimationBezierTrackEdit::_bind_methods() { + + ClassDB::bind_method("_zoom_changed", &AnimationBezierTrackEdit::_zoom_changed); + ClassDB::bind_method("_menu_selected", &AnimationBezierTrackEdit::_menu_selected); + ClassDB::bind_method("_gui_input", &AnimationBezierTrackEdit::_gui_input); + ClassDB::bind_method("_play_position_draw", &AnimationBezierTrackEdit::_play_position_draw); + + ClassDB::bind_method("_clear_selection", &AnimationBezierTrackEdit::_clear_selection); + ClassDB::bind_method("_clear_selection_for_anim", &AnimationBezierTrackEdit::_clear_selection); + ClassDB::bind_method("_select_at_anim", &AnimationBezierTrackEdit::_clear_selection); + + ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag"))); + ADD_SIGNAL(MethodInfo("remove_request", PropertyInfo(Variant::INT, "track"))); + ADD_SIGNAL(MethodInfo("insert_key", PropertyInfo(Variant::REAL, "ofs"))); + ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"))); + ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"))); + ADD_SIGNAL(MethodInfo("clear_selection")); + ADD_SIGNAL(MethodInfo("close_request")); + + ADD_SIGNAL(MethodInfo("move_selection_begin")); + ADD_SIGNAL(MethodInfo("move_selection", PropertyInfo(Variant::REAL, "ofs"))); + ADD_SIGNAL(MethodInfo("move_selection_commit")); + ADD_SIGNAL(MethodInfo("move_selection_cancel")); +} + +AnimationBezierTrackEdit::AnimationBezierTrackEdit() { + undo_redo = NULL; + timeline = NULL; + root = NULL; + menu = NULL; + block_animation_update_ptr = NULL; + + moving_selection_attempt = false; + moving_selection = false; + select_single_attempt = -1; + box_selecting = false; + box_selecting_attempt = false; + + moving_handle = 0; + + play_position_pos = 0; + play_position = memnew(Control); + play_position->set_mouse_filter(MOUSE_FILTER_PASS); + add_child(play_position); + play_position->set_anchors_and_margins_preset(PRESET_WIDE); + play_position->connect("draw", this, "_play_position_draw"); + set_focus_mode(FOCUS_CLICK); + + v_scroll = 0; + v_zoom = 1; + + panning_timeline = false; + set_clip_contents(true); + handle_mode = HANDLE_MODE_FREE; + handle_mode_option = memnew(OptionButton); + add_child(handle_mode_option); + + menu = memnew(PopupMenu); + add_child(menu); + menu->connect("id_pressed", this, "_menu_selected"); + + //set_mouse_filter(MOUSE_FILTER_PASS); //scroll has to work too for selection +} diff --git a/editor/animation_bezier_editor.h b/editor/animation_bezier_editor.h new file mode 100644 index 0000000000..544690844a --- /dev/null +++ b/editor/animation_bezier_editor.h @@ -0,0 +1,141 @@ +#ifndef ANIMATION_BEZIER_EDITOR_H +#define ANIMATION_BEZIER_EDITOR_H + +#include "animation_track_editor.h" + +class AnimationBezierTrackEdit : public Control { + + GDCLASS(AnimationBezierTrackEdit, Control) + + enum HandleMode { + HANDLE_MODE_FREE, + HANDLE_MODE_BALANCED, + HANDLE_MODE_MIRROR + }; + + enum { + MENU_KEY_INSERT, + MENU_KEY_DUPLICATE, + MENU_KEY_DELETE + }; + + HandleMode handle_mode; + OptionButton *handle_mode_option; + + AnimationTimelineEdit *timeline; + UndoRedo *undo_redo; + Node *root; + Control *play_position; //separate control used to draw so updates for only position changed are much faster + float play_position_pos; + + Ref<Animation> animation; + int track; + + Vector<Rect2> view_rects; + + Ref<Texture> bezier_icon; + Ref<Texture> bezier_handle_icon; + Ref<Texture> selected_icon; + + Rect2 close_icon_rect; + + Map<int, Rect2> subtracks; + + float v_scroll; + float v_zoom; + + PopupMenu *menu; + + void _zoom_changed(); + + void _gui_input(const Ref<InputEvent> &p_event); + void _menu_selected(int p_index); + + bool *block_animation_update_ptr; //used to block all tracks re-gen (speed up) + + void _play_position_draw(); + + Vector2 insert_at_pos; + + bool moving_selection_attempt; + int select_single_attempt; + bool moving_selection; + int moving_selection_from_key; + + Vector2 moving_selection_offset; + + bool box_selecting_attempt; + bool box_selecting; + bool box_selecting_add; + Vector2 box_selection_from; + Vector2 box_selection_to; + + int moving_handle; //0 no move -1 or +1 out + int moving_handle_key; + Vector2 moving_handle_left; + Vector2 moving_handle_right; + + void _clear_selection(); + void _clear_selection_for_anim(const Ref<Animation> &p_anim); + void _select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos); + + Vector2 menu_insert_key; + + struct AnimMoveRestore { + + int track; + float time; + Variant key; + float transition; + }; + + AnimationTrackEditor *editor; + + struct EditPoint { + Rect2 point_rect; + Rect2 in_rect; + Rect2 out_rect; + }; + + Vector<EditPoint> edit_points; + + Set<int> selection; + + bool panning_timeline; + float panning_timeline_from; + float panning_timeline_at; + + void _draw_line_clipped(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, int p_clip_left, int p_clip_right); + void _draw_track(int p_track, const Color &p_color); + + float _bezier_h_to_pixel(float p_h); + +protected: + static void _bind_methods(); + void _notification(int p_what); + +public: + virtual String get_tooltip(const Point2 &p_pos) const; + + Ref<Animation> get_animation() const; + + void set_animation_and_track(const Ref<Animation> &p_animation, int p_track); + virtual Size2 get_minimum_size() const; + + void set_undo_redo(UndoRedo *p_undo_redo); + void set_timeline(AnimationTimelineEdit *p_timeline); + void set_editor(AnimationTrackEditor *p_editor); + void set_root(Node *p_root); + + void set_block_animation_update_ptr(bool *p_block_ptr); + + void set_play_position(float p_pos); + void update_play_position(); + + void duplicate_selection(); + void delete_selection(); + + AnimationBezierTrackEdit(); +}; + +#endif // ANIMATION_BEZIER_EDITOR_H diff --git a/editor/animation_editor.cpp b/editor/animation_editor.cpp deleted file mode 100644 index a03bf76d1b..0000000000 --- a/editor/animation_editor.cpp +++ /dev/null @@ -1,4146 +0,0 @@ -/*************************************************************************/ -/* animation_editor.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "animation_editor.h" - -#include "editor/plugins/animation_player_editor_plugin.h" -#include "editor_node.h" -#include "editor_settings.h" -#include "io/resource_saver.h" -#include "os/keyboard.h" -#include "os/os.h" -#include "pair.h" -#include "scene/gui/separator.h" -#include "scene/main/viewport.h" - -/* Missing to fix: - - *Set - *Find better source for hint for edited value keys - * + button on track to add a key - * when clicked for first time, erase selection of not selected at first - * automatically create discrete/continuous tracks!! - *when create track do undo/redo -*/ - -class AnimationCurveEdit : public Control { - GDCLASS(AnimationCurveEdit, Control); - -public: - enum Mode { - MODE_DISABLED, - MODE_SINGLE, - MODE_MULTIPLE - }; - -private: - Set<float> multiples; - float transition; - Mode mode; - - LineEdit *value_edit; - - void _notification(int p_what) { - - if (p_what == NOTIFICATION_DRAW) { - - RID ci = get_canvas_item(); - - Size2 s = get_size(); - Rect2 r(Point2(), s); - - //r=r.grow(3); - Ref<StyleBox> sb = get_stylebox("normal", "LineEdit"); - sb->draw(ci, r); - r.size -= sb->get_minimum_size(); - r.position += sb->get_offset(); - //VisualServer::get_singleton()->canvas_item_add - - Ref<Font> f = get_font("font", "Label"); - r = r.grow(-2); - Color color = get_color("font_color", "Label"); - - int points = 48; - if (mode == MODE_MULTIPLE) { - - Color mcolor = color; - mcolor.a *= 0.3; - - Set<float>::Element *E = multiples.front(); - for (int j = 0; j < 16; j++) { - - if (!E) - break; - - float prev = 1.0; - float exp = E->get(); - bool flip = false; //hint_text=="attenuation"; - - for (int i = 1; i <= points; i++) { - - float ifl = i / float(points); - float iflp = (i - 1) / float(points); - - float h = 1.0 - Math::ease(ifl, exp); - - if (flip) { - ifl = 1.0 - ifl; - iflp = 1.0 - iflp; - } - - VisualServer::get_singleton()->canvas_item_add_line(ci, r.position + Point2(iflp * r.size.width, prev * r.size.height), r.position + Point2(ifl * r.size.width, h * r.size.height), mcolor); - prev = h; - } - - E = E->next(); - } - } - - float exp = transition; - if (mode != MODE_DISABLED) { - - float prev = 1.0; - - bool flip = false; //hint_text=="attenuation"; - - for (int i = 1; i <= points; i++) { - - float ifl = i / float(points); - float iflp = (i - 1) / float(points); - - float h = 1.0 - Math::ease(ifl, exp); - - if (flip) { - ifl = 1.0 - ifl; - iflp = 1.0 - iflp; - } - - VisualServer::get_singleton()->canvas_item_add_line(ci, r.position + Point2(iflp * r.size.width, prev * r.size.height), r.position + Point2(ifl * r.size.width, h * r.size.height), color); - prev = h; - } - } - - if (mode == MODE_DISABLED) { - f->draw(ci, Point2(5, 5 + f->get_ascent()), TTR("Disabled"), color); - } else if (mode == MODE_MULTIPLE) { - f->draw(ci, Point2(5, 5 + f->get_ascent() + value_edit->get_size().height), TTR("All Selection"), color); - } - } - } - - void _gui_input(const Ref<InputEvent> &p_ev) { - - Ref<InputEventMouseMotion> mm = p_ev; - if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT) { - - if (mode == MODE_DISABLED) - return; - - value_edit->release_focus(); - - float rel = mm->get_relative().x; - if (rel == 0) - return; - - bool flip = false; - - if (flip) - rel = -rel; - - float val = transition; - if (val == 0) - return; - bool sg = val < 0; - val = Math::absf(val); - - val = Math::log(val) / Math::log((float)2.0); - //logspace - val += rel * 0.05; - // - - val = Math::pow((float)2.0, val); - if (sg) - val = -val; - - force_transition(val); - } - } - - void _edit_value_changed(const String &p_value_str) { - - force_transition(p_value_str.to_float()); - } - -public: - static void _bind_methods() { - - //ClassDB::bind_method("_update_obj",&AnimationKeyEdit::_update_obj); - ClassDB::bind_method("_gui_input", &AnimationCurveEdit::_gui_input); - ClassDB::bind_method("_edit_value_changed", &AnimationCurveEdit::_edit_value_changed); - ADD_SIGNAL(MethodInfo("transition_changed")); - } - - void set_mode(Mode p_mode) { - - mode = p_mode; - value_edit->set_visible(mode != MODE_DISABLED); - update(); - } - - void clear_multiples() { - multiples.clear(); - update(); - } - void set_multiple(float p_transition) { - - multiples.insert(p_transition); - } - - void set_transition(float p_transition) { - transition = Math::stepify(p_transition, 0.01); - value_edit->set_text(String::num(transition)); - update(); - } - - float get_transition() const { - return transition; - } - - void force_transition(float p_value) { - if (mode == MODE_DISABLED) - return; - set_transition(p_value); - emit_signal("transition_changed", p_value); - } - - AnimationCurveEdit() { - - transition = 1.0; - set_default_cursor_shape(CURSOR_HSPLIT); - mode = MODE_DISABLED; - - value_edit = memnew(LineEdit); - value_edit->hide(); - value_edit->connect("text_entered", this, "_edit_value_changed"); - add_child(value_edit); - } -}; - -class AnimationKeyEdit : public Object { - - GDCLASS(AnimationKeyEdit, Object); - -public: - bool setting; - bool hidden; - - static void _bind_methods() { - - ClassDB::bind_method("_update_obj", &AnimationKeyEdit::_update_obj); - ClassDB::bind_method("_key_ofs_changed", &AnimationKeyEdit::_key_ofs_changed); - } - - //PopupDialog *ke_dialog; - - void _fix_node_path(Variant &value) { - - NodePath np = value; - - if (np == NodePath()) - return; - - Node *root = EditorNode::get_singleton()->get_tree()->get_root(); - - Node *np_node = root->get_node(np); - ERR_FAIL_COND(!np_node); - - Node *edited_node = root->get_node(base); - ERR_FAIL_COND(!edited_node); - - value = edited_node->get_path_to(np_node); - } - - void _update_obj(const Ref<Animation> &p_anim) { - if (setting) - return; - if (hidden) - return; - if (!(animation == p_anim)) - return; - notify_change(); - } - - void _key_ofs_changed(const Ref<Animation> &p_anim, float from, float to) { - if (hidden) - return; - if (!(animation == p_anim)) - return; - if (from != key_ofs) - return; - key_ofs = to; - if (setting) - return; - notify_change(); - } - - bool _set(const StringName &p_name, const Variant &p_value) { - - int key = animation->track_find_key(track, key_ofs, true); - ERR_FAIL_COND_V(key == -1, false); - - String name = p_name; - if (name == "time") { - - float new_time = p_value; - if (new_time == key_ofs) - return true; - - int existing = animation->track_find_key(track, new_time, true); - - setting = true; - undo_redo->create_action(TTR("Anim Change Keyframe Time"), UndoRedo::MERGE_ENDS); - - Variant val = animation->track_get_key_value(track, key); - float trans = animation->track_get_key_transition(track, key); - - undo_redo->add_do_method(animation.ptr(), "track_remove_key", track, key); - undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, new_time, val, trans); - undo_redo->add_do_method(this, "_key_ofs_changed", animation, key_ofs, new_time); - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, new_time); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, key_ofs, val, trans); - undo_redo->add_undo_method(this, "_key_ofs_changed", animation, new_time, key_ofs); - - if (existing != -1) { - Variant v = animation->track_get_key_value(track, existing); - float trans = animation->track_get_key_transition(track, existing); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, new_time, v, trans); - } - - undo_redo->commit_action(); - setting = false; - - return true; - } else if (name == "easing") { - - float val = p_value; - float prev_val = animation->track_get_key_transition(track, key); - setting = true; - undo_redo->create_action(TTR("Anim Change Transition"), UndoRedo::MERGE_ENDS); - undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", track, key, val); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", track, key, prev_val); - undo_redo->add_do_method(this, "_update_obj", animation); - undo_redo->add_undo_method(this, "_update_obj", animation); - undo_redo->commit_action(); - setting = false; - return true; - } - - switch (animation->track_get_type(track)) { - - case Animation::TYPE_TRANSFORM: { - - Dictionary d_old = animation->track_get_key_value(track, key); - Dictionary d_new = d_old; - d_new[p_name] = p_value; - setting = true; - undo_redo->create_action(TTR("Anim Change Transform")); - undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old); - undo_redo->add_do_method(this, "_update_obj", animation); - undo_redo->add_undo_method(this, "_update_obj", animation); - undo_redo->commit_action(); - setting = false; - return true; - - } break; - case Animation::TYPE_VALUE: { - - if (name == "value") { - - Variant value = p_value; - - if (value.get_type() == Variant::NODE_PATH) { - - _fix_node_path(value); - } - - setting = true; - undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); - Variant prev = animation->track_get_key_value(track, key); - undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, value); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, prev); - undo_redo->add_do_method(this, "_update_obj", animation); - undo_redo->add_undo_method(this, "_update_obj", animation); - undo_redo->commit_action(); - setting = false; - return true; - } - - } break; - case Animation::TYPE_METHOD: { - - Dictionary d_old = animation->track_get_key_value(track, key); - Dictionary d_new = d_old; - - bool change_notify_deserved = false; - bool mergeable = false; - - if (name == "name") { - - d_new["method"] = p_value; - } - - if (name == "arg_count") { - - Vector<Variant> args = d_old["args"]; - args.resize(p_value); - d_new["args"] = args; - change_notify_deserved = true; - } - - if (name.begins_with("args/")) { - - Vector<Variant> args = d_old["args"]; - int idx = name.get_slice("/", 1).to_int(); - ERR_FAIL_INDEX_V(idx, args.size(), false); - - String what = name.get_slice("/", 2); - if (what == "type") { - Variant::Type t = Variant::Type(int(p_value)); - - if (t != args[idx].get_type()) { - Variant::CallError err; - if (Variant::can_convert(args[idx].get_type(), t)) { - Variant old = args[idx]; - Variant *ptrs[1] = { &old }; - args[idx] = Variant::construct(t, (const Variant **)ptrs, 1, err); - } else { - - args[idx] = Variant::construct(t, NULL, 0, err); - } - change_notify_deserved = true; - d_new["args"] = args; - } - } - if (what == "value") { - - Variant value = p_value; - if (value.get_type() == Variant::NODE_PATH) { - - _fix_node_path(value); - } - - args[idx] = value; - d_new["args"] = args; - mergeable = true; - } - } - - if (mergeable) - undo_redo->create_action(TTR("Anim Change Call"), UndoRedo::MERGE_ENDS); - else - undo_redo->create_action(TTR("Anim Change Call")); - - Variant prev = animation->track_get_key_value(track, key); - setting = true; - undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old); - undo_redo->add_do_method(this, "_update_obj", animation); - undo_redo->add_undo_method(this, "_update_obj", animation); - undo_redo->commit_action(); - setting = false; - if (change_notify_deserved) - notify_change(); - return true; - } break; - } - - return false; - } - - bool _get(const StringName &p_name, Variant &r_ret) const { - - int key = animation->track_find_key(track, key_ofs, true); - ERR_FAIL_COND_V(key == -1, false); - - String name = p_name; - if (name == "time") { - r_ret = key_ofs; - return true; - } else if (name == "easing") { - r_ret = animation->track_get_key_transition(track, key); - return true; - } - - switch (animation->track_get_type(track)) { - - case Animation::TYPE_TRANSFORM: { - - Dictionary d = animation->track_get_key_value(track, key); - ERR_FAIL_COND_V(!d.has(name), false); - r_ret = d[p_name]; - return true; - - } break; - case Animation::TYPE_VALUE: { - - if (name == "value") { - r_ret = animation->track_get_key_value(track, key); - return true; - } - - } break; - case Animation::TYPE_METHOD: { - - Dictionary d = animation->track_get_key_value(track, key); - - if (name == "name") { - - ERR_FAIL_COND_V(!d.has("method"), false); - r_ret = d["method"]; - return true; - } - - ERR_FAIL_COND_V(!d.has("args"), false); - - Vector<Variant> args = d["args"]; - - if (name == "arg_count") { - - r_ret = args.size(); - return true; - } - - if (name.begins_with("args/")) { - - int idx = name.get_slice("/", 1).to_int(); - ERR_FAIL_INDEX_V(idx, args.size(), false); - - String what = name.get_slice("/", 2); - if (what == "type") { - r_ret = args[idx].get_type(); - return true; - } - if (what == "value") { - r_ret = args[idx]; - return true; - } - } - - } break; - } - - return false; - } - void _get_property_list(List<PropertyInfo> *p_list) const { - - if (animation.is_null()) - return; - - ERR_FAIL_INDEX(track, animation->get_track_count()); - int key = animation->track_find_key(track, key_ofs, true); - ERR_FAIL_COND(key == -1); - - p_list->push_back(PropertyInfo(Variant::REAL, "time", PROPERTY_HINT_RANGE, "0," + rtos(animation->get_length()) + ",0.01")); - - switch (animation->track_get_type(track)) { - - case Animation::TYPE_TRANSFORM: { - - p_list->push_back(PropertyInfo(Variant::VECTOR3, "location")); - p_list->push_back(PropertyInfo(Variant::QUAT, "rotation")); - p_list->push_back(PropertyInfo(Variant::VECTOR3, "scale")); - - } break; - case Animation::TYPE_VALUE: { - - Variant v = animation->track_get_key_value(track, key); - - if (hint.type != Variant::NIL) { - - PropertyInfo pi = hint; - pi.name = "value"; - p_list->push_back(pi); - } else { - - PropertyHint hint = PROPERTY_HINT_NONE; - String hint_string; - - if (v.get_type() == Variant::OBJECT) { - //could actually check the object property if exists..? yes i will! - Ref<Resource> res = v; - if (res.is_valid()) { - - hint = PROPERTY_HINT_RESOURCE_TYPE; - hint_string = res->get_class(); - } - } - - if (v.get_type() != Variant::NIL) - p_list->push_back(PropertyInfo(v.get_type(), "value", hint, hint_string)); - } - - } break; - case Animation::TYPE_METHOD: { - - p_list->push_back(PropertyInfo(Variant::STRING, "name")); - p_list->push_back(PropertyInfo(Variant::INT, "arg_count", PROPERTY_HINT_RANGE, "0,5,1")); - - Dictionary d = animation->track_get_key_value(track, key); - ERR_FAIL_COND(!d.has("args")); - Vector<Variant> args = d["args"]; - String vtypes; - for (int i = 0; i < Variant::VARIANT_MAX; i++) { - - if (i > 0) - vtypes += ","; - vtypes += Variant::get_type_name(Variant::Type(i)); - } - - for (int i = 0; i < args.size(); i++) { - - p_list->push_back(PropertyInfo(Variant::INT, "args/" + itos(i) + "/type", PROPERTY_HINT_ENUM, vtypes)); - if (args[i].get_type() != Variant::NIL) - p_list->push_back(PropertyInfo(args[i].get_type(), "args/" + itos(i) + "/value")); - } - - } break; - } - - /* - if (animation->track_get_type(track)!=Animation::TYPE_METHOD) - p_list->push_back( PropertyInfo( Variant::REAL, "easing", PROPERTY_HINT_EXP_EASING)); - */ - } - - UndoRedo *undo_redo; - Ref<Animation> animation; - int track; - float key_ofs; - - PropertyInfo hint; - NodePath base; - - void notify_change() { - - _change_notify(); - } - - AnimationKeyEdit() { - hidden = true; - key_ofs = 0; - track = -1; - setting = false; - } -}; - -void AnimationKeyEditor::_menu_add_track(int p_type) { - - ERR_FAIL_COND(!animation.is_valid()); - - switch (p_type) { - - case ADD_TRACK_MENU_ADD_CALL_TRACK: { - if (root) { - call_select->popup_centered_ratio(); - break; - } - } break; - case ADD_TRACK_MENU_ADD_VALUE_TRACK: - case ADD_TRACK_MENU_ADD_TRANSFORM_TRACK: { - - undo_redo->create_action(TTR("Anim Add Track")); - undo_redo->add_do_method(animation.ptr(), "add_track", p_type); - undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), "."); - undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); - undo_redo->commit_action(); - - } break; - } -} - -void AnimationKeyEditor::_anim_duplicate_keys(bool transpose) { - //duplicait! - if (selection.size() && animation.is_valid() && selected_track >= 0 && selected_track < animation->get_track_count()) { - - int top_track = 0x7FFFFFFF; - float top_time = 1e10; - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - const SelectedKey &sk = E->key(); - - float t = animation->track_get_key_time(sk.track, sk.key); - if (t < top_time) - top_time = t; - if (sk.track < top_track) - top_track = sk.track; - } - ERR_FAIL_COND(top_track == 0x7FFFFFFF || top_time == 1e10); - - // - - int start_track = transpose ? selected_track : top_track; - - undo_redo->create_action(TTR("Anim Duplicate Keys")); - - List<Pair<int, float> > new_selection_values; - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - const SelectedKey &sk = E->key(); - - float t = animation->track_get_key_time(sk.track, sk.key); - - float dst_time = t + (timeline_pos - top_time); - int dst_track = sk.track + (start_track - top_track); - - if (dst_track < 0 || dst_track >= animation->get_track_count()) - continue; - - if (animation->track_get_type(dst_track) != animation->track_get_type(sk.track)) - continue; - - int existing_idx = animation->track_find_key(dst_track, dst_time, true); - - undo_redo->add_do_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", dst_track, dst_time); - - Pair<int, float> p; - p.first = dst_track; - p.second = dst_time; - new_selection_values.push_back(p); - - if (existing_idx != -1) { - - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(dst_track, existing_idx), animation->track_get_key_transition(dst_track, existing_idx)); - } - } - - undo_redo->commit_action(); - - //reselect duplicated - - Map<SelectedKey, KeyInfo> new_selection; - for (List<Pair<int, float> >::Element *E = new_selection_values.front(); E; E = E->next()) { - - int track = E->get().first; - float time = E->get().second; - - int existing_idx = animation->track_find_key(track, time, true); - - if (existing_idx == -1) - continue; - SelectedKey sk2; - sk2.track = track; - sk2.key = existing_idx; - - KeyInfo ki; - ki.pos = time; - - new_selection[sk2] = ki; - } - - selection = new_selection; - track_editor->update(); - _edit_if_single_selection(); - } -} - -void AnimationKeyEditor::_menu_track(int p_type) { - - ERR_FAIL_COND(!animation.is_valid()); - - last_menu_track_opt = p_type; - switch (p_type) { - - case TRACK_MENU_SCALE: - case TRACK_MENU_SCALE_PIVOT: { - - scale_dialog->popup_centered(Size2(200, 100)); - } break; - case TRACK_MENU_MOVE_UP: { - - int idx = selected_track; - if (idx > 0 && idx < animation->get_track_count()) { - undo_redo->create_action(TTR("Move Anim Track Up")); - undo_redo->add_do_method(animation.ptr(), "track_move_down", idx); - undo_redo->add_undo_method(animation.ptr(), "track_move_up", idx - 1); - undo_redo->commit_action(); - selected_track = idx - 1; - } - - } break; - case TRACK_MENU_MOVE_DOWN: { - - int idx = selected_track; - if (idx >= 0 && idx < animation->get_track_count() - 1) { - undo_redo->create_action(TTR("Move Anim Track Down")); - undo_redo->add_do_method(animation.ptr(), "track_move_up", idx); - undo_redo->add_undo_method(animation.ptr(), "track_move_down", idx + 1); - undo_redo->commit_action(); - selected_track = idx + 1; - } - - } break; - case TRACK_MENU_REMOVE: { - - int idx = selected_track; - if (idx >= 0 && idx < animation->get_track_count()) { - undo_redo->create_action(TTR("Remove Anim Track")); - undo_redo->add_do_method(animation.ptr(), "remove_track", idx); - undo_redo->add_undo_method(animation.ptr(), "add_track", animation->track_get_type(idx), idx); - undo_redo->add_undo_method(animation.ptr(), "track_set_path", idx, animation->track_get_path(idx)); - //todo interpolation - for (int i = 0; i < animation->track_get_key_count(idx); i++) { - - Variant v = animation->track_get_key_value(idx, i); - float time = animation->track_get_key_time(idx, i); - float trans = animation->track_get_key_transition(idx, i); - - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, time, v); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", idx, i, trans); - } - - undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", idx, animation->track_get_interpolation_type(idx)); - if (animation->track_get_type(idx) == Animation::TYPE_VALUE) { - undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", idx, animation->value_track_get_update_mode(idx)); - } - - undo_redo->commit_action(); - } - - } break; - case TRACK_MENU_DUPLICATE: - case TRACK_MENU_DUPLICATE_TRANSPOSE: { - - _anim_duplicate_keys(p_type == TRACK_MENU_DUPLICATE_TRANSPOSE); - } break; - case TRACK_MENU_SET_ALL_TRANS_LINEAR: - case TRACK_MENU_SET_ALL_TRANS_CONSTANT: - case TRACK_MENU_SET_ALL_TRANS_OUT: - case TRACK_MENU_SET_ALL_TRANS_IN: - case TRACK_MENU_SET_ALL_TRANS_INOUT: - case TRACK_MENU_SET_ALL_TRANS_OUTIN: { - - if (!selection.size() || !animation.is_valid()) - break; - - float t = 0; - switch (p_type) { - case TRACK_MENU_SET_ALL_TRANS_LINEAR: t = 1.0; break; - case TRACK_MENU_SET_ALL_TRANS_CONSTANT: t = 0.0; break; - case TRACK_MENU_SET_ALL_TRANS_OUT: t = 0.5; break; - case TRACK_MENU_SET_ALL_TRANS_IN: t = 2.0; break; - case TRACK_MENU_SET_ALL_TRANS_INOUT: t = -0.5; break; - case TRACK_MENU_SET_ALL_TRANS_OUTIN: t = -2.0; break; - } - - undo_redo->create_action(TTR("Set Transitions to:") + " " + rtos(t)); - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - const SelectedKey &sk = E->key(); - - undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", sk.track, sk.key, t); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", sk.track, sk.key, animation->track_get_key_transition(sk.track, sk.key)); - } - - undo_redo->commit_action(); - - } break; - case TRACK_MENU_NEXT_STEP: { - - if (animation.is_null()) - break; - float step = animation->get_step(); - if (step == 0) - step = 1; - - float pos = timeline_pos; - - pos = Math::stepify(pos + step, step); - if (pos > animation->get_length()) - pos = animation->get_length(); - timeline_pos = pos; - track_pos->update(); - emit_signal("timeline_changed", pos, true); - - } break; - case TRACK_MENU_PREV_STEP: { - if (animation.is_null()) - break; - float step = animation->get_step(); - if (step == 0) - step = 1; - - float pos = timeline_pos; - pos = Math::stepify(pos - step, step); - if (pos < 0) - pos = 0; - timeline_pos = pos; - track_pos->update(); - emit_signal("timeline_changed", pos, true); - - } break; - - case TRACK_MENU_OPTIMIZE: { - - optimize_dialog->popup_centered(Size2(250, 180)); - } break; - case TRACK_MENU_CLEAN_UP: { - - cleanup_dialog->popup_centered_minsize(Size2(300, 0)); - } break; - case TRACK_MENU_CLEAN_UP_CONFIRM: { - - if (cleanup_all->is_pressed()) { - List<StringName> names; - AnimationPlayerEditor::singleton->get_player()->get_animation_list(&names); - for (List<StringName>::Element *E = names.front(); E; E = E->next()) { - _cleanup_animation(AnimationPlayerEditor::singleton->get_player()->get_animation(E->get())); - } - } else { - _cleanup_animation(animation); - } - } break; - case CURVE_SET_LINEAR: { - curve_edit->force_transition(1.0); - - } break; - case CURVE_SET_IN: { - - curve_edit->force_transition(4.0); - - } break; - case CURVE_SET_OUT: { - - curve_edit->force_transition(0.25); - } break; - case CURVE_SET_INOUT: { - curve_edit->force_transition(-4); - - } break; - case CURVE_SET_OUTIN: { - - curve_edit->force_transition(-0.25); - } break; - case CURVE_SET_CONSTANT: { - - curve_edit->force_transition(0); - } break; - } -} - -void AnimationKeyEditor::_cleanup_animation(Ref<Animation> p_animation) { - - for (int i = 0; i < p_animation->get_track_count(); i++) { - - bool prop_exists = false; - Variant::Type valid_type = Variant::NIL; - Object *obj = NULL; - - RES res; - Vector<StringName> leftover_path; - - Node *node = root->get_node_and_resource(p_animation->track_get_path(i), res, leftover_path); - - if (res.is_valid()) { - obj = res.ptr(); - } else if (node) { - obj = node; - } - - if (obj && p_animation->track_get_type(i) == Animation::TYPE_VALUE) { - valid_type = obj->get_static_property_type_indexed(leftover_path, &prop_exists); - } - - if (!obj && cleanup_tracks->is_pressed()) { - - p_animation->remove_track(i); - i--; - continue; - } - - if (!prop_exists || p_animation->track_get_type(i) != Animation::TYPE_VALUE || cleanup_keys->is_pressed() == false) - continue; - - for (int j = 0; j < p_animation->track_get_key_count(i); j++) { - - Variant v = p_animation->track_get_key_value(i, j); - - if (!Variant::can_convert(v.get_type(), valid_type)) { - p_animation->track_remove_key(i, j); - j--; - } - } - - if (p_animation->track_get_key_count(i) == 0 && cleanup_tracks->is_pressed()) { - p_animation->remove_track(i); - i--; - } - } - - undo_redo->clear_history(); - _update_paths(); -} - -void AnimationKeyEditor::_animation_optimize() { - - animation->optimize(optimize_linear_error->get_value(), optimize_angular_error->get_value(), optimize_max_angle->get_value()); - track_editor->update(); - undo_redo->clear_history(); -} - -float AnimationKeyEditor::_get_zoom_scale() const { - - float zv = zoom->get_value(); - if (zv < 1) { - zv = 1.0 - zv; - return Math::pow(1.0f + zv, 8.0f) * 100; - } else { - return 1.0 / Math::pow(zv, 8.0f) * 100; - } -} - -void AnimationKeyEditor::_track_position_draw() { - - if (!animation.is_valid()) { - return; - } - - Ref<StyleBox> style = get_stylebox("normal", "TextEdit"); - Size2 size = track_editor->get_size() - style->get_minimum_size(); - Size2 ofs = style->get_offset(); - - int settings_limit = size.width - right_data_size_cache; - int name_limit = settings_limit * name_column_ratio; - - float keys_from = h_scroll->get_value(); - float zoom_scale = _get_zoom_scale(); - float keys_to = keys_from + (settings_limit - name_limit) / zoom_scale; - - //will move to separate control! (for speedup) - if (timeline_pos >= keys_from && timeline_pos < keys_to) { - //draw position - int pixel = (timeline_pos - h_scroll->get_value()) * zoom_scale; - pixel += name_limit; - track_pos->draw_line(ofs + Point2(pixel, 0), ofs + Point2(pixel, size.height), get_color("accent_color", "Editor")); - } -} - -void AnimationKeyEditor::_track_editor_draw() { - - if (animation.is_valid() && animation->get_track_count()) { - if (selected_track < 0) - selected_track = 0; - else if (selected_track >= animation->get_track_count()) - selected_track = animation->get_track_count() - 1; - } - - track_pos->update(); - Control *te = track_editor; - Ref<StyleBox> style = get_stylebox("normal", "TextEdit"); - te->draw_style_box(style, Rect2(Point2(), track_editor->get_size())); - - if (te->has_focus()) { - te->draw_style_box(get_stylebox("bg_focus", "Tree"), Rect2(Point2(), track_editor->get_size())); - } - - if (!animation.is_valid()) { - v_scroll->hide(); - h_scroll->hide(); - length->set_editable(false); - step->set_editable(false); - loop->set_disabled(true); - menu_add_track->set_disabled(true); - menu_track->set_disabled(true); - edit_button->set_disabled(true); - key_editor_tab->hide(); - move_up_button->set_disabled(true); - move_down_button->set_disabled(true); - remove_button->set_disabled(true); - - return; - } - - length->set_editable(true); - step->set_editable(true); - loop->set_disabled(false); - menu_add_track->set_disabled(false); - menu_track->set_disabled(false); - edit_button->set_disabled(false); - move_up_button->set_disabled(false); - move_down_button->set_disabled(false); - remove_button->set_disabled(false); - if (edit_button->is_pressed()) - key_editor_tab->show(); - - te_drawing = true; - - Size2 size = te->get_size() - style->get_minimum_size(); - Size2 ofs = style->get_offset(); - - Ref<Font> font = te->get_font("font", "Tree"); - int sep = get_constant("vseparation", "Tree"); - int hsep = get_constant("hseparation", "Tree"); - Color color = get_color("font_color", "Tree"); - Color sepcolor = color; - sepcolor.a = 0.2; - Color timecolor = color; - timecolor.a = 0.2; - Color hover_color = color; - hover_color.a = 0.05; - Color select_color = color; - select_color.a = 0.1; - Color invalid_path_color = get_color("error_color", "Editor"); - Color track_select_color = get_color("highlighted_font_color", "Editor"); - - Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons"); - Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons"); - Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons"); - Ref<Texture> remove_icon_hl = get_icon("RemoveHl", "EditorIcons"); - Ref<Texture> move_up_icon_hl = get_icon("MoveUpHl", "EditorIcons"); - Ref<Texture> move_down_icon_hl = get_icon("MoveDownHl", "EditorIcons"); - Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons"); - Ref<Texture> add_key_icon_hl = get_icon("TrackAddKeyHl", "EditorIcons"); - Ref<Texture> down_icon = get_icon("select_arrow", "Tree"); - Ref<Texture> checked = get_icon("checked", "Tree"); - Ref<Texture> unchecked = get_icon("unchecked", "Tree"); - - Ref<Texture> wrap_icon[2] = { - get_icon("InterpWrapClamp", "EditorIcons"), - get_icon("InterpWrapLoop", "EditorIcons"), - }; - - Ref<Texture> interp_icon[3] = { - get_icon("InterpRaw", "EditorIcons"), - get_icon("InterpLinear", "EditorIcons"), - get_icon("InterpCubic", "EditorIcons") - }; - Ref<Texture> cont_icon[3] = { - get_icon("TrackContinuous", "EditorIcons"), - get_icon("TrackDiscrete", "EditorIcons"), - get_icon("TrackTrigger", "EditorIcons") - }; - Ref<Texture> type_icon[3] = { - get_icon("KeyValue", "EditorIcons"), - get_icon("KeyXform", "EditorIcons"), - get_icon("KeyCall", "EditorIcons") - }; - - Ref<Texture> valid_icon = get_icon("KeyValid", "EditorIcons"); - Ref<Texture> invalid_icon = get_icon("KeyInvalid", "EditorIcons"); - const Color modulate_selected = Color(0x84 / 255.0, 0xc2 / 255.0, 0xff / 255.0); - - Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons"); - - int right_separator_ofs = right_data_size_cache; - - int h = font->get_height() + sep; - - int fit = (size.height / h) - 1; - int total = animation->get_track_count(); - if (total < fit) { - v_scroll->hide(); - v_scroll->set_max(total); - v_scroll->set_page(fit); - } else { - v_scroll->show(); - v_scroll->set_max(total); - v_scroll->set_page(fit); - } - - int left_check_ofs = checked->get_width(); - int settings_limit = size.width - right_separator_ofs; - int name_limit = settings_limit * name_column_ratio; - - Color linecolor = color; - linecolor.a = 0.2; - te->draw_line(ofs + Point2(name_limit, 0), ofs + Point2(name_limit, size.height), linecolor); - te->draw_line(ofs + Point2(settings_limit, 0), ofs + Point2(settings_limit, size.height), linecolor); - te->draw_texture(hsize_icon, ofs + Point2(name_limit - hsize_icon->get_width() - hsep, (h - hsize_icon->get_height()) / 2)); - - te->draw_line(ofs + Point2(0, h), ofs + Point2(size.width, h), linecolor); - // draw time - - float keys_from; - float keys_to; - float zoom_scale; - - { - - int zoomw = settings_limit - name_limit; - - float scale = _get_zoom_scale(); - zoom_scale = scale; - - float l = animation->get_length(); - if (l <= 0) - l = 0.001; //avoid crashor - - int end_px = (l - h_scroll->get_value()) * scale; - int begin_px = -h_scroll->get_value() * scale; - Color notimecol = get_color("dark_color_2", "Editor"); - - { - - te->draw_rect(Rect2(ofs + Point2(name_limit, 0), Point2(zoomw - 1, h)), notimecol); - - if (begin_px < zoomw && end_px > 0) { - - if (begin_px < 0) - begin_px = 0; - if (end_px > zoomw) - end_px = zoomw; - - te->draw_rect(Rect2(ofs + Point2(name_limit + begin_px, 0), Point2(end_px - begin_px - 1, h)), timecolor); - } - } - - keys_from = h_scroll->get_value(); - keys_to = keys_from + zoomw / scale; - - { - float time_min = 0; - float time_max = animation->get_length(); - for (int i = 0; i < animation->get_track_count(); i++) { - - if (animation->track_get_key_count(i) > 0) { - - float beg = animation->track_get_key_time(i, 0); - if (beg < time_min) - time_min = beg; - float end = animation->track_get_key_time(i, animation->track_get_key_count(i) - 1); - if (end > time_max) - time_max = end; - } - } - - float extra = (zoomw / scale) * 0.5; - - if (time_min < -0.001) - time_min -= extra; - time_max += extra; - h_scroll->set_min(time_min); - h_scroll->set_max(time_max); - - if (zoomw / scale < (time_max - time_min)) { - h_scroll->show(); - - } else { - - h_scroll->hide(); - } - } - - h_scroll->set_page(zoomw / scale); - - Color color_time_sec = color; - Color color_time_dec = color; - color_time_dec.a *= 0.5; -#define SC_ADJ 100 - int min = 30; - int dec = 1; - int step = 1; - int decimals = 2; - bool step_found = false; - - const int period_width = font->get_char_size('.').width; - int max_digit_width = font->get_char_size('0').width; - for (int i = 1; i <= 9; i++) { - const int digit_width = font->get_char_size('0' + i).width; - max_digit_width = MAX(digit_width, max_digit_width); - } - const int max_sc = int(Math::ceil(zoomw / scale)); - const int max_sc_width = String::num(max_sc).length() * max_digit_width; - - while (!step_found) { - - min = max_sc_width; - if (decimals > 0) - min += period_width + max_digit_width * decimals; - - static const int _multp[3] = { 1, 2, 5 }; - for (int i = 0; i < 3; i++) { - - step = (_multp[i] * dec); - if (step * scale / SC_ADJ > min) { - step_found = true; - break; - } - } - if (step_found) - break; - dec *= 10; - decimals--; - if (decimals < 0) - decimals = 0; - } - - for (int i = 0; i < zoomw; i++) { - - float pos = h_scroll->get_value() + double(i) / scale; - float prev = h_scroll->get_value() + (double(i) - 1.0) / scale; - - int sc = int(Math::floor(pos * SC_ADJ)); - int prev_sc = int(Math::floor(prev * SC_ADJ)); - bool sub = (sc % SC_ADJ); - - if ((sc / step) != (prev_sc / step) || (prev_sc < 0 && sc >= 0)) { - - int scd = sc < 0 ? prev_sc : sc; - te->draw_line(ofs + Point2(name_limit + i, 0), ofs + Point2(name_limit + i, h), linecolor); - te->draw_string(font, ofs + Point2(name_limit + i + 3, (h - font->get_height()) / 2 + font->get_ascent()).floor(), String::num((scd - (scd % step)) / double(SC_ADJ), decimals), sub ? color_time_dec : color_time_sec, zoomw - i); - } - } - } - - color.a *= 0.5; - - for (int i = 0; i < fit; i++) { - - //this code sucks, i always forget how it works - - int idx = v_scroll->get_value() + i; - if (idx >= animation->get_track_count()) - break; - int y = h + i * h + sep; - - bool prop_exists = false; - Variant::Type valid_type = Variant::NIL; - Object *obj = NULL; - - RES res; - Vector<StringName> leftover_path; - - Node *node = root ? root->get_node_and_resource(animation->track_get_path(idx), res, leftover_path) : (Node *)NULL; - - if (res.is_valid()) { - obj = res.ptr(); - } else if (node) { - obj = node; - } - - if (obj && animation->track_get_type(idx) == Animation::TYPE_VALUE) { - // While leftover_path might be still empty, we wouldn't be able to get here anyway - valid_type = obj->get_static_property_type_indexed(leftover_path, &prop_exists); - } - - // Draw background color of the whole track - if (/*mouse_over.over!=MouseOver::OVER_NONE &&*/ idx == mouse_over.track) { - Color sepc = hover_color; - te->draw_rect(Rect2(ofs + Point2(0, y), Size2(size.width, h - 1)), sepc); - } - - if (selected_track == idx) { - Color tc = select_color; - //tc.a*=0.7; - te->draw_rect(Rect2(ofs + Point2(0, y), Size2(size.width - 1, h - 1)), tc); - } - - // Draw track enabled state check box - Ref<Texture> check_box = animation->track_is_enabled(idx) ? checked : unchecked; - te->draw_texture(check_box, ofs + Point2(0, y + (h - checked->get_height()) / 2).floor()); - - // Draw track type glyph and node path - te->draw_texture(type_icon[animation->track_get_type(idx)], ofs + Point2(left_check_ofs + sep, y + (h - type_icon[0]->get_height()) / 2).floor()); - NodePath np = animation->track_get_path(idx); - Node *n = root ? root->get_node(np) : (Node *)NULL; - Color ncol = color; - if (n && editor_selection->is_selected(n)) - ncol = track_select_color; - te->draw_string(font, Point2(ofs + Point2(left_check_ofs + sep + type_icon[0]->get_width() + sep, y + font->get_ascent() + (sep / 2))).floor(), np, ncol, name_limit - (left_check_ofs + sep) - (type_icon[0]->get_width() + sep) - 5); - - // Draw separator line below track area - if (!obj) - te->draw_line(ofs + Point2(0, y + h / 2), ofs + Point2(name_limit, y + h / 2), invalid_path_color); - - te->draw_line(ofs + Point2(0, y + h), ofs + Point2(size.width, y + h), sepcolor); - - Point2 icon_ofs = ofs + Point2(size.width, y + (h - remove_icon->get_height()) / 2).floor(); - icon_ofs.y += 4 * EDSCALE; - - /* icon_ofs.x-=remove_icon->get_width(); - - te->draw_texture((mouse_over.over==MouseOver::OVER_REMOVE && mouse_over.track==idx)?remove_icon_hl:remove_icon,icon_ofs); - icon_ofs.x-=hsep; - icon_ofs.x-=move_down_icon->get_width(); - te->draw_texture((mouse_over.over==MouseOver::OVER_DOWN && mouse_over.track==idx)?move_down_icon_hl:move_down_icon,icon_ofs); - icon_ofs.x-=hsep; - icon_ofs.x-=move_up_icon->get_width(); - te->draw_texture((mouse_over.over==MouseOver::OVER_UP && mouse_over.track==idx)?move_up_icon_hl:move_up_icon,icon_ofs); - icon_ofs.x-=hsep; - te->draw_line(Point2(icon_ofs.x,ofs.y+y),Point2(icon_ofs.x,ofs.y+y+h),sepcolor); - - icon_ofs.x-=hsep; - */ - track_ofs[0] = size.width - icon_ofs.x + ofs.x; - icon_ofs.x -= down_icon->get_width(); - te->draw_texture(down_icon, icon_ofs - Size2(0, 4 * EDSCALE)); - - int wrap_type = animation->track_get_interpolation_loop_wrap(idx) ? 1 : 0; - icon_ofs.x -= hsep; - icon_ofs.x -= wrap_icon[wrap_type]->get_width(); - te->draw_texture(wrap_icon[wrap_type], icon_ofs); - - icon_ofs.x -= hsep; - te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor); - - track_ofs[1] = size.width - icon_ofs.x + ofs.x; - - icon_ofs.x -= down_icon->get_width(); - te->draw_texture(down_icon, icon_ofs - Size2(0, 4 * EDSCALE)); - - int interp_type = animation->track_get_interpolation_type(idx); - ERR_CONTINUE(interp_type < 0 || interp_type >= 3); - icon_ofs.x -= hsep; - icon_ofs.x -= interp_icon[interp_type]->get_width(); - te->draw_texture(interp_icon[interp_type], icon_ofs); - - icon_ofs.x -= hsep; - te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor); - - track_ofs[2] = size.width - icon_ofs.x + ofs.x; - - if (animation->track_get_type(idx) == Animation::TYPE_VALUE) { - - int umode = animation->value_track_get_update_mode(idx); - - icon_ofs.x -= hsep; - icon_ofs.x -= down_icon->get_width(); - te->draw_texture(down_icon, icon_ofs - Size2(0, 4 * EDSCALE)); - - icon_ofs.x -= hsep; - icon_ofs.x -= cont_icon[umode]->get_width(); - te->draw_texture(cont_icon[umode], icon_ofs); - } else { - - icon_ofs.x -= hsep * 2 + cont_icon[0]->get_width() + down_icon->get_width(); - } - - icon_ofs.x -= hsep; - te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor); - - track_ofs[3] = size.width - icon_ofs.x + ofs.x; - - icon_ofs.x -= hsep; - icon_ofs.x -= add_key_icon->get_width(); - te->draw_texture((mouse_over.over == MouseOver::OVER_ADD_KEY && mouse_over.track == idx) ? add_key_icon_hl : add_key_icon, icon_ofs); - track_ofs[4] = size.width - icon_ofs.x + ofs.x; - - //draw the keys; - int tt = animation->track_get_type(idx); - float key_vofs = Math::floor((float)(h - type_icon[tt]->get_height()) / 2); - float key_hofs = -Math::floor((float)type_icon[tt]->get_height() / 2); - - int kc = animation->track_get_key_count(idx); - bool first = true; - - for (int i = 0; i < kc; i++) { - - float time = animation->track_get_key_time(idx, i); - if (time < keys_from) - continue; - if (time > keys_to) { - - if (first && i > 0 && animation->track_get_key_value(idx, i) == animation->track_get_key_value(idx, i - 1)) { - //draw whole line - te->draw_line(ofs + Vector2(name_limit, y + h / 2), ofs + Point2(settings_limit, y + h / 2), color); - } - - break; - } - - float x = key_hofs + name_limit + (time - keys_from) * zoom_scale; - - Ref<Texture> tex = type_icon[tt]; - Color modulate = Color(1, 1, 1); - - bool is_hover = false; - bool is_selected = false; - - SelectedKey sk; - sk.key = i; - sk.track = idx; - if (selection.has(sk)) { - - if (click.click == ClickOver::CLICK_MOVE_KEYS) - continue; - is_selected = true; - } - - if (mouse_over.over == MouseOver::OVER_KEY && mouse_over.track == idx && mouse_over.over_key == i) - is_hover = true; - - Variant value = animation->track_get_key_value(idx, i); - - if (prop_exists && !Variant::can_convert(value.get_type(), valid_type)) { - - tex = invalid_icon; - if (is_hover) - modulate = Color(1.5, 1.5, 1.5); - else - modulate = Color(1, 1, 1); - } else if (is_selected) { - - tex = valid_icon; - modulate = modulate_selected; - if (is_hover) - modulate = modulate.lightened(0.2); - } else if (is_hover) { - - tex = valid_icon; - modulate = Color(1, 1, 1); - } - - if (first && i > 0 && value == animation->track_get_key_value(idx, i - 1)) { - - te->draw_line(ofs + Vector2(name_limit, y + h / 2), ofs + Point2(x, y + h / 2), color); - } - - if (i < kc - 1 && value == animation->track_get_key_value(idx, i + 1)) { - float x_n = key_hofs + name_limit + (animation->track_get_key_time(idx, i + 1) - keys_from) * zoom_scale; - - x_n = MIN(x_n, settings_limit); - te->draw_line(ofs + Point2(x_n, y + h / 2), ofs + Point2(x, y + h / 2), color); - } - - te->draw_texture(tex, ofs + Point2(x, y + key_vofs).floor(), modulate); - - first = false; - } - } - - switch (click.click) { - case ClickOver::CLICK_SELECT_KEYS: { - - Color box_color = get_color("accent_color", "Editor"); - box_color.a = 0.35; - te->draw_rect(Rect2(click.at, click.to - click.at), box_color); - - } break; - case ClickOver::CLICK_MOVE_KEYS: { - - float from_t = 1e20; - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - float t = animation->track_get_key_time(E->key().track, E->key().key); - if (t < from_t) - from_t = t; - } - - float motion = from_t + (click.to.x - click.at.x) / zoom_scale; - if (step->get_value()) - motion = Math::stepify(motion, step->get_value()); - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - - int idx = E->key().track; - int i = idx - (int)v_scroll->get_value(); - if (i < 0 || i >= fit) - continue; - int y = h + i * h + sep; - - float key_vofs = Math::floor((float)(h - valid_icon->get_height()) / 2); - float key_hofs = -Math::floor((float)valid_icon->get_height() / 2); - - float time = animation->track_get_key_time(idx, E->key().key); - float diff = time - from_t; - - float t = motion + diff; - - float x = (t - keys_from) * zoom_scale; - //x+=click.to.x - click.at.x; - if (x < 0 || x >= (settings_limit - name_limit)) - continue; - - x += name_limit; - - te->draw_texture(valid_icon, ofs + Point2(x + key_hofs, y + key_vofs).floor(), modulate_selected); - } - } break; - default: {}; - } - - te_drawing = false; -} - -void AnimationKeyEditor::_track_name_changed(const String &p_name) { - - ERR_FAIL_COND(!animation.is_valid()); - undo_redo->create_action(TTR("Anim Track Rename")); - undo_redo->add_do_method(animation.ptr(), "track_set_path", track_name_editing, p_name); - undo_redo->add_undo_method(animation.ptr(), "track_set_path", track_name_editing, animation->track_get_path(track_name_editing)); - undo_redo->commit_action(); - track_name->hide(); -} - -void AnimationKeyEditor::_track_menu_selected(int p_idx) { - - ERR_FAIL_COND(!animation.is_valid()); - - if (interp_editing != -1) { - - ERR_FAIL_INDEX(interp_editing, animation->get_track_count()); - undo_redo->create_action(TTR("Anim Track Change Interpolation")); - undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", interp_editing, p_idx); - undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", interp_editing, animation->track_get_interpolation_type(interp_editing)); - undo_redo->commit_action(); - } else if (cont_editing != -1) { - - ERR_FAIL_INDEX(cont_editing, animation->get_track_count()); - - undo_redo->create_action(TTR("Anim Track Change Value Mode")); - undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", cont_editing, p_idx); - undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", cont_editing, animation->value_track_get_update_mode(cont_editing)); - undo_redo->commit_action(); - } else if (wrap_editing != -1) { - - ERR_FAIL_INDEX(wrap_editing, animation->get_track_count()); - - undo_redo->create_action(TTR("Anim Track Change Wrap Mode")); - undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_loop_wrap", wrap_editing, p_idx ? true : false); - undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_loop_wrap", wrap_editing, animation->track_get_interpolation_loop_wrap(wrap_editing)); - undo_redo->commit_action(); - } else { - switch (p_idx) { - - case RIGHT_MENU_DUPLICATE: - _anim_duplicate_keys(); - break; - case RIGHT_MENU_DUPLICATE_TRANSPOSE: - _anim_duplicate_keys(true); - break; - case RIGHT_MENU_REMOVE: - _anim_delete_keys(); - break; - } - } -} - -struct _AnimMoveRestore { - - int track; - float time; - Variant key; - float transition; -}; - -void AnimationKeyEditor::_clear_selection_for_anim(const Ref<Animation> &p_anim) { - - if (!(animation == p_anim)) - return; - //selection.clear(); - _clear_selection(); -} - -void AnimationKeyEditor::_select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos) { - - if (!(animation == p_anim)) - return; - - int idx = animation->track_find_key(p_track, p_pos, true); - ERR_FAIL_COND(idx < 0); - - SelectedKey sk; - sk.track = p_track; - sk.key = idx; - KeyInfo ki; - ki.pos = p_pos; - - selection.insert(sk, ki); -} - -PropertyInfo AnimationKeyEditor::_find_hint_for_track(int p_idx, NodePath &r_base_path) { - - r_base_path = NodePath(); - ERR_FAIL_COND_V(!animation.is_valid(), PropertyInfo()); - ERR_FAIL_INDEX_V(p_idx, animation->get_track_count(), PropertyInfo()); - - if (!root) - return PropertyInfo(); - - NodePath path = animation->track_get_path(p_idx); - - if (!root->has_node_and_resource(path)) - return PropertyInfo(); - - RES res; - Vector<StringName> leftover_path; - Node *node = root->get_node_and_resource(path, res, leftover_path, true); - - if (node) { - r_base_path = node->get_path(); - } - - if (leftover_path.empty()) - return PropertyInfo(); - - Variant property_info_base; - if (res.is_valid()) - property_info_base = res; - else if (node) - property_info_base = node; - - for (int i = 0; i < leftover_path.size() - 1; i++) { - property_info_base = property_info_base.get_named(leftover_path[i]); - } - - List<PropertyInfo> pinfo; - property_info_base.get_property_list(&pinfo); - - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - - if (E->get().name == leftover_path[leftover_path.size() - 1]) { - return E->get(); - } - } - - return PropertyInfo(); -} - -void AnimationKeyEditor::_curve_transition_changed(float p_what) { - - if (selection.size() == 0) - return; - if (selection.size() == 1) - undo_redo->create_action(TTR("Edit Node Curve"), UndoRedo::MERGE_ENDS); - else - undo_redo->create_action(TTR("Edit Selection Curve"), UndoRedo::MERGE_ENDS); - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - - int track = E->key().track; - int key = E->key().key; - float prev_val = animation->track_get_key_transition(track, key); - undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", track, key, p_what); - undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", track, key, prev_val); - } - - undo_redo->commit_action(); -} - -void AnimationKeyEditor::_toggle_edit_curves() { - - if (edit_button->is_pressed()) - key_editor_tab->show(); - else - key_editor_tab->hide(); -} - -bool AnimationKeyEditor::_edit_if_single_selection() { - - if (selection.size() != 1) { - - if (selection.size() == 0) { - curve_edit->set_mode(AnimationCurveEdit::MODE_DISABLED); - //print_line("disable"); - } else { - - curve_edit->set_mode(AnimationCurveEdit::MODE_MULTIPLE); - curve_edit->set_transition(1.0); - curve_edit->clear_multiples(); - //add all - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - - curve_edit->set_multiple(animation->track_get_key_transition(E->key().track, E->key().key)); - } - //print_line("multiple"); - } - return false; - } - curve_edit->set_mode(AnimationCurveEdit::MODE_SINGLE); - //print_line("regular"); - - int idx = selection.front()->key().track; - int key = selection.front()->key().key; - { - - key_edit->animation = animation; - key_edit->track = idx; - key_edit->key_ofs = animation->track_get_key_time(idx, key); - key_edit->hint = _find_hint_for_track(idx, key_edit->base); - key_edit->notify_change(); - - curve_edit->set_transition(animation->track_get_key_transition(idx, key)); - - /*key_edit_dialog->set_size( Size2( 200,200) ); - key_edit_dialog->set_position( track_editor->get_global_position() + ofs + mpos +Point2(-100,20)); - key_edit_dialog->popup();*/ - } - - return true; -} - -void AnimationKeyEditor::_anim_delete_keys() { - if (selection.size()) { - undo_redo->create_action(TTR("Anim Delete Keys")); - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - } - undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); - undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); - undo_redo->commit_action(); - //selection.clear(); - accept_event(); - _edit_if_single_selection(); - } -} - -void AnimationKeyEditor::_track_editor_gui_input(const Ref<InputEvent> &p_input) { - - Control *te = track_editor; - Ref<StyleBox> style = get_stylebox("normal", "TextEdit"); - - if (!animation.is_valid()) { - return; - } - - Size2 size = te->get_size() - style->get_minimum_size(); - Size2 ofs = style->get_offset(); - - Ref<Font> font = te->get_font("font", "Tree"); - int sep = get_constant("vseparation", "Tree"); - int hsep = get_constant("hseparation", "Tree"); - Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons"); - Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons"); - Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons"); - Ref<Texture> down_icon = get_icon("select_arrow", "Tree"); - Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons"); - Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons"); - Ref<Texture> check_icon = get_icon("checked", "Tree"); - - Ref<Texture> wrap_icon[2] = { - get_icon("InterpWrapClamp", "EditorIcons"), - get_icon("InterpWrapLoop", "EditorIcons"), - }; - Ref<Texture> interp_icon[3] = { - get_icon("InterpRaw", "EditorIcons"), - get_icon("InterpLinear", "EditorIcons"), - get_icon("InterpCubic", "EditorIcons") - }; - Ref<Texture> cont_icon[3] = { - get_icon("TrackContinuous", "EditorIcons"), - get_icon("TrackDiscrete", "EditorIcons"), - get_icon("TrackTrigger", "EditorIcons") - }; - Ref<Texture> type_icon[3] = { - get_icon("KeyValue", "EditorIcons"), - get_icon("KeyXform", "EditorIcons"), - get_icon("KeyCall", "EditorIcons") - }; - int right_separator_ofs = right_data_size_cache; - - int h = font->get_height() + sep; - - int fit = (size.height / h) - 1; - int total = animation->get_track_count(); - if (total < fit) { - v_scroll->hide(); - } else { - v_scroll->show(); - v_scroll->set_max(total); - v_scroll->set_page(fit); - } - - int left_check_ofs = check_icon->get_width(); - int settings_limit = size.width - right_separator_ofs; - int name_limit = settings_limit * name_column_ratio; - - Ref<InputEventKey> key = p_input; - if (key.is_valid()) { - - if (key->get_scancode() == KEY_D && key->is_pressed() && key->get_command()) { - - if (key->get_shift()) - _menu_track(TRACK_MENU_DUPLICATE_TRANSPOSE); - else - _menu_track(TRACK_MENU_DUPLICATE); - - accept_event(); - - } else if (key->get_scancode() == KEY_DELETE && key->is_pressed() && click.click == ClickOver::CLICK_NONE) { - - _anim_delete_keys(); - } else if (animation.is_valid() && animation->get_track_count() > 0) { - - if (key->is_pressed() && (key->is_action("ui_up") || key->is_action("ui_page_up"))) { - - if (key->is_action("ui_up")) - selected_track--; - if (v_scroll->is_visible_in_tree() && key->is_action("ui_page_up")) - selected_track--; - - if (selected_track < 0) - selected_track = 0; - - if (v_scroll->is_visible_in_tree()) { - if (v_scroll->get_value() > selected_track) - v_scroll->set_value(selected_track); - } - - track_editor->update(); - accept_event(); - } - - if (key->is_pressed() && (key->is_action("ui_down") || key->is_action("ui_page_down"))) { - - if (key->is_action("ui_down")) - selected_track++; - else if (v_scroll->is_visible_in_tree() && key->is_action("ui_page_down")) - selected_track += v_scroll->get_page(); - - if (selected_track >= animation->get_track_count()) - selected_track = animation->get_track_count() - 1; - - if (v_scroll->is_visible_in_tree() && v_scroll->get_page() + v_scroll->get_value() < selected_track + 1) { - v_scroll->set_value(selected_track - v_scroll->get_page() + 1); - } - - track_editor->update(); - accept_event(); - } - } - } - - Ref<InputEventMouseButton> mb = p_input; - - if (mb.is_valid()) { - - if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed()) { - - if (mb->get_command()) { - - zoom->set_value(zoom->get_value() + zoom->get_step()); - } else { - - v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() * mb->get_factor() / 8); - } - } - - if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed()) { - - if (mb->get_command()) { - - zoom->set_value(zoom->get_value() - zoom->get_step()); - } else { - - v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() * mb->get_factor() / 8); - } - } - - if (mb->get_button_index() == BUTTON_WHEEL_RIGHT && mb->is_pressed()) { - - h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() * mb->get_factor() / 8); - } - - if (mb->get_button_index() == BUTTON_WHEEL_LEFT && mb->is_pressed()) { - - v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() * mb->get_factor() / 8); - } - - if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) { - - Point2 mpos = mb->get_position() - ofs; - - if (selection.size() == 0) { - // Auto-select on right-click if nothing is selected - // Note: This code is pretty much duplicated from the left click code, - // both codes could be moved into a function to avoid the duplicated code. - Point2 mpos = mb->get_position() - ofs; - - if (mpos.y < h) { - return; - } - - mpos.y -= h; - - int idx = mpos.y / h; - idx += v_scroll->get_value(); - if (idx < 0 || idx >= animation->get_track_count()) - return; - - if (mpos.x < name_limit) { - } else if (mpos.x < settings_limit) { - float pos = mpos.x - name_limit; - pos /= _get_zoom_scale(); - pos += h_scroll->get_value(); - float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0; - - int kidx = animation->track_find_key(idx, pos); - int kidx_n = kidx + 1; - int key = -1; - - if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx); - if (ABS(pos - kpos) <= w_time) { - - key = kidx; - } - } - - if (key == -1 && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx_n); - if (ABS(pos - kpos) <= w_time) { - - key = kidx_n; - } - } - - if (key == -1) { - - click.click = ClickOver::CLICK_SELECT_KEYS; - click.at = mb->get_position(); - click.to = click.at; - click.shift = mb->get_shift(); - selected_track = idx; - track_editor->update(); - //drag select region - return; - } - - SelectedKey sk; - sk.track = idx; - sk.key = key; - KeyInfo ki; - ki.pos = animation->track_get_key_time(idx, key); - click.shift = mb->get_shift(); - click.selk = sk; - - if (!mb->get_shift() && !selection.has(sk)) - _clear_selection(); - - selection.insert(sk, ki); - - click.click = ClickOver::CLICK_MOVE_KEYS; - click.at = mb->get_position(); - click.to = click.at; - update(); - selected_track = idx; - track_editor->update(); - - if (_edit_if_single_selection() && mb->get_command()) { - edit_button->set_pressed(true); - key_editor_tab->show(); - } - } - } - - if (selection.size()) { - // User has right clicked and we have a selection, show a popup menu with options - track_menu->clear(); - track_menu->set_size(Point2(1, 1)); - track_menu->add_item(TTR("Duplicate Selection"), RIGHT_MENU_DUPLICATE); - track_menu->add_item(TTR("Duplicate Transposed"), RIGHT_MENU_DUPLICATE_TRANSPOSE); - track_menu->add_item(TTR("Remove Selection"), RIGHT_MENU_REMOVE); - - track_menu->set_position(te->get_global_position() + mpos); - - interp_editing = -1; - cont_editing = -1; - wrap_editing = -1; - - track_menu->popup(); - } - } - - if (mb->get_button_index() == BUTTON_LEFT && !(mb->get_button_mask() & ~BUTTON_MASK_LEFT)) { - - if (mb->is_pressed()) { - - Point2 mpos = mb->get_position() - ofs; - - if (mpos.y < h) { - - if (mpos.x < name_limit && mpos.x > (name_limit - hsep - hsize_icon->get_width())) { - - click.click = ClickOver::CLICK_RESIZE_NAMES; - click.at = mb->get_position(); - click.to = click.at; - click.at.y = name_limit; - } - - if (mpos.x >= name_limit && mpos.x < settings_limit) { - //seek - //int zoomw = settings_limit-name_limit; - float scale = _get_zoom_scale(); - float pos = h_scroll->get_value() + (mpos.x - name_limit) / scale; - if (animation->get_step()) - pos = Math::stepify(pos, animation->get_step()); - - if (pos < 0) - pos = 0; - if (pos >= animation->get_length()) - pos = animation->get_length(); - timeline_pos = pos; - click.click = ClickOver::CLICK_DRAG_TIMELINE; - click.at = mb->get_position(); - click.to = click.at; - emit_signal("timeline_changed", pos, false); - } - - return; - } - - mpos.y -= h; - - int idx = mpos.y / h; - idx += v_scroll->get_value(); - if (idx < 0) - return; - - if (idx >= animation->get_track_count()) { - - if (mpos.x >= name_limit && mpos.x < settings_limit) { - - click.click = ClickOver::CLICK_SELECT_KEYS; - click.at = mb->get_position(); - click.to = click.at; - //drag select region - } - - return; - } - - if (mpos.x < left_check_ofs) { - // Checkbox on the very left to enable/disable tracks. - - animation->track_set_enabled(idx, !animation->track_is_enabled(idx)); - - } else if (mpos.x < name_limit - (type_icon[0]->get_width() / 2.0)) { - //name column - - // area - if (idx != selected_track) { - - selected_track = idx; - track_editor->update(); - return; - } - - Rect2 area(ofs.x + left_check_ofs + sep, ofs.y + ((int(mpos.y) / h) + 1) * h, name_limit - left_check_ofs - sep, h); - track_name->set_text(animation->track_get_path(idx)); - track_name->set_position(te->get_global_position() + area.position); - track_name->set_size(area.size); - track_name->show_modal(); - track_name->grab_focus(); - track_name->select_all(); - track_name_editing = idx; - - } else if (mpos.x < settings_limit) { - - float pos = mpos.x - name_limit; - pos /= _get_zoom_scale(); - pos += h_scroll->get_value(); - float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0; - - int kidx = animation->track_find_key(idx, pos); - int kidx_n = kidx + 1; - int key = -1; - - if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx); - if (ABS(pos - kpos) <= w_time) { - - key = kidx; - } - } - - if (key == -1 && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx_n); - if (ABS(pos - kpos) <= w_time) { - - key = kidx_n; - } - } - - if (key == -1) { - - click.click = ClickOver::CLICK_SELECT_KEYS; - click.at = mb->get_position(); - click.to = click.at; - click.shift = mb->get_shift(); - selected_track = idx; - track_editor->update(); - //drag select region - return; - } - - SelectedKey sk; - sk.track = idx; - sk.key = key; - KeyInfo ki; - ki.pos = animation->track_get_key_time(idx, key); - click.shift = mb->get_shift(); - click.selk = sk; - - if (!mb->get_shift() && !selection.has(sk)) - _clear_selection(); - - selection.insert(sk, ki); - - click.click = ClickOver::CLICK_MOVE_KEYS; - click.at = mb->get_position(); - click.to = click.at; - update(); - selected_track = idx; - track_editor->update(); - - if (_edit_if_single_selection() && mb->get_command()) { - edit_button->set_pressed(true); - key_editor_tab->show(); - } - } else { - //button column - int ofsx = size.width - mpos.x; - if (ofsx < 0) - return; - /* - if (ofsx < remove_icon->get_width()) { - - undo_redo->create_action("Remove Anim Track"); - undo_redo->add_do_method(animation.ptr(),"remove_track",idx); - undo_redo->add_undo_method(animation.ptr(),"add_track",animation->track_get_type(idx),idx); - undo_redo->add_undo_method(animation.ptr(),"track_set_path",idx,animation->track_get_path(idx)); - //todo interpolation - for(int i=0;i<animation->track_get_key_count(idx);i++) { - - Variant v = animation->track_get_key_value(idx,i); - float time = animation->track_get_key_time(idx,i); - float trans = animation->track_get_key_transition(idx,i); - - undo_redo->add_undo_method(animation.ptr(),"track_insert_key",idx,time,v); - undo_redo->add_undo_method(animation.ptr(),"track_set_key_transition",idx,i,trans); - - } - - undo_redo->add_undo_method(animation.ptr(),"track_set_interpolation_type",idx,animation->track_get_interpolation_type(idx)); - if (animation->track_get_type(idx)==Animation::TYPE_VALUE) { - undo_redo->add_undo_method(animation.ptr(),"value_track_set_continuous",idx,animation->value_track_is_continuous(idx)); - - } - - undo_redo->commit_action(); - - - return; - } - - ofsx-=hsep+remove_icon->get_width(); - - if (ofsx < move_down_icon->get_width()) { - - if (idx < animation->get_track_count() -1) { - undo_redo->create_action("Move Anim Track Down"); - undo_redo->add_do_method(animation.ptr(),"track_move_up",idx); - undo_redo->add_undo_method(animation.ptr(),"track_move_down",idx+1); - undo_redo->commit_action(); - } - return; - } - - ofsx-=hsep+move_down_icon->get_width(); - - if (ofsx < move_up_icon->get_width()) { - - if (idx >0) { - undo_redo->create_action("Move Anim Track Up"); - undo_redo->add_do_method(animation.ptr(),"track_move_down",idx); - undo_redo->add_undo_method(animation.ptr(),"track_move_up",idx-1); - undo_redo->commit_action(); - } - return; - } - - - ofsx-=hsep*3+move_up_icon->get_width(); - */ - - if (ofsx < track_ofs[1]) { - - track_menu->clear(); - track_menu->set_size(Point2(1, 1)); - static const char *interp_name[2] = { "Clamp Loop Interp", "Wrap Loop Interp" }; - for (int i = 0; i < 2; i++) { - track_menu->add_icon_item(wrap_icon[i], interp_name[i]); - } - - int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h; - int popup_x = size.width - track_ofs[1]; - - track_menu->set_position(te->get_global_position() + Point2(popup_x, popup_y)); - - wrap_editing = idx; - interp_editing = -1; - cont_editing = -1; - - track_menu->popup(); - - return; - } - - if (ofsx < track_ofs[2]) { - - track_menu->clear(); - track_menu->set_size(Point2(1, 1)); - static const char *interp_name[3] = { "Nearest", "Linear", "Cubic" }; - for (int i = 0; i < 3; i++) { - track_menu->add_icon_item(interp_icon[i], interp_name[i]); - } - - int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h; - int popup_x = size.width - track_ofs[2]; - - track_menu->set_position(te->get_global_position() + Point2(popup_x, popup_y)); - - interp_editing = idx; - cont_editing = -1; - wrap_editing = -1; - - track_menu->popup(); - - return; - } - - if (ofsx < track_ofs[3]) { - - track_menu->clear(); - track_menu->set_size(Point2(1, 1)); - String cont_name[3] = { TTR("Continuous"), TTR("Discrete"), TTR("Trigger") }; - for (int i = 0; i < 3; i++) { - track_menu->add_icon_item(cont_icon[i], cont_name[i]); - } - - int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h; - int popup_x = size.width - track_ofs[3]; - - track_menu->set_position(te->get_global_position() + Point2(popup_x, popup_y)); - - interp_editing = -1; - wrap_editing = -1; - cont_editing = idx; - - track_menu->popup(); - - return; - } - - if (ofsx < track_ofs[4]) { - - Animation::TrackType tt = animation->track_get_type(idx); - - float pos = timeline_pos; - int existing = animation->track_find_key(idx, pos, true); - - Variant newval; - - if (tt == Animation::TYPE_TRANSFORM) { - Dictionary d; - d["location"] = Vector3(); - d["rotation"] = Quat(); - d["scale"] = Vector3(); - newval = d; - - } else if (tt == Animation::TYPE_METHOD) { - - Dictionary d; - d["method"] = ""; - d["args"] = Vector<Variant>(); - - newval = d; - } else if (tt == Animation::TYPE_VALUE) { - - NodePath np; - PropertyInfo inf = _find_hint_for_track(idx, np); - if (inf.type != Variant::NIL) { - - Variant::CallError err; - newval = Variant::construct(inf.type, NULL, 0, err); - } - - if (newval.get_type() == Variant::NIL) { - //popup a new type - cvi_track = idx; - cvi_pos = pos; - - type_menu->set_position(get_global_position() + mpos + ofs); - type_menu->popup(); - return; - } - } - - undo_redo->create_action(TTR("Anim Add Key")); - - undo_redo->add_do_method(animation.ptr(), "track_insert_key", idx, pos, newval, 1); - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", idx, pos); - - if (existing != -1) { - Variant v = animation->track_get_key_value(idx, existing); - float trans = animation->track_get_key_transition(idx, existing); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, pos, v, trans); - } - - undo_redo->commit_action(); - - return; - } - } - - } else { - - switch (click.click) { - case ClickOver::CLICK_SELECT_KEYS: { - - float zoom_scale = _get_zoom_scale(); - float keys_from = h_scroll->get_value(); - float keys_to = keys_from + (settings_limit - name_limit) / zoom_scale; - - float from_time = keys_from + (click.at.x - (name_limit + ofs.x)) / zoom_scale; - float to_time = keys_from + (click.to.x - (name_limit + ofs.x)) / zoom_scale; - - if (to_time < from_time) - SWAP(from_time, to_time); - - if (from_time > keys_to || to_time < keys_from) - break; - - if (from_time < keys_from) - from_time = keys_from; - - if (to_time >= keys_to) - to_time = keys_to; - - int from_track = int(click.at.y - ofs.y - h - sep) / h + v_scroll->get_value(); - int to_track = int(click.to.y - ofs.y - h - sep) / h + v_scroll->get_value(); - int from_mod = int(click.at.y - ofs.y - sep) % h; - int to_mod = int(click.to.y - ofs.y - sep) % h; - - if (to_track < from_track) { - - SWAP(from_track, to_track); - SWAP(from_mod, to_mod); - } - - if ((from_mod > (h / 2)) && ((click.at.y - ofs.y) >= (h + sep))) { - from_track++; - } - - if (to_mod < h / 2) { - to_track--; - } - - if (from_track > to_track) { - if (!click.shift) - _clear_selection(); - _edit_if_single_selection(); - break; - } - - int tracks_from = v_scroll->get_value(); - int tracks_to = v_scroll->get_value() + fit - 1; - if (tracks_to >= animation->get_track_count()) - tracks_to = animation->get_track_count() - 1; - - tracks_from = 0; - tracks_to = animation->get_track_count() - 1; - if (to_track > tracks_to) - to_track = tracks_to; - if (from_track < tracks_from) - from_track = tracks_from; - - if (from_track > tracks_to || to_track < tracks_from) { - if (!click.shift) - _clear_selection(); - _edit_if_single_selection(); - break; - } - - if (!click.shift) - _clear_selection(); - - int higher_track = 0x7FFFFFFF; - for (int i = from_track; i <= to_track; i++) { - - int kc = animation->track_get_key_count(i); - for (int j = 0; j < kc; j++) { - - float t = animation->track_get_key_time(i, j); - if (t < from_time) - continue; - if (t > to_time) - break; - - if (i < higher_track) - higher_track = i; - - SelectedKey sk; - sk.track = i; - sk.key = j; - KeyInfo ki; - ki.pos = t; - selection[sk] = ki; - } - } - - if (higher_track != 0x7FFFFFFF) { - selected_track = higher_track; - track_editor->update(); - } - - _edit_if_single_selection(); - - } break; - case ClickOver::CLICK_MOVE_KEYS: { - - if (selection.empty()) - break; - if (click.at == click.to) { - - if (!click.shift) { - - KeyInfo ki = selection[click.selk]; - _clear_selection(); - selection[click.selk] = ki; - _edit_if_single_selection(); - } - - break; - } - - float from_t = 1e20; - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - float t = animation->track_get_key_time(E->key().track, E->key().key); - if (t < from_t) - from_t = t; - } - - float motion = from_t + (click.to.x - click.at.x) / _get_zoom_scale(); - if (step->get_value()) - motion = Math::stepify(motion, step->get_value()); - - undo_redo->create_action(TTR("Anim Move Keys")); - - List<_AnimMoveRestore> to_restore; - - // 1-remove the keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); - } - // 2- remove overlapped keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newtime = E->get().pos - from_t + motion; - int idx = animation->track_find_key(E->key().track, newtime, true); - if (idx == -1) - continue; - SelectedKey sk; - sk.key = idx; - sk.track = E->key().track; - if (selection.has(sk)) - continue; //already in selection, don't save - - undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newtime); - _AnimMoveRestore amr; - - amr.key = animation->track_get_key_value(E->key().track, idx); - amr.track = E->key().track; - amr.time = newtime; - amr.transition = animation->track_get_key_transition(E->key().track, idx); - - to_restore.push_back(amr); - } - - // 3-move the keys (re insert them) - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newpos = E->get().pos - from_t + motion; - /* - if (newpos<0) - continue; //no add at the beginning - */ - undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - } - - // 4-(undo) remove inserted keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newpos = E->get().pos + -from_t + motion; - /* - if (newpos<0) - continue; //no remove what no inserted - */ - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newpos); - } - - // 5-(undo) reinsert keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - } - - // 6-(undo) reinsert overlapped keys - for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { - - _AnimMoveRestore &amr = E->get(); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); - } - - // 6-(undo) reinsert overlapped keys - for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { - - _AnimMoveRestore &amr = E->get(); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); - } - - undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); - undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); - - // 7-reselect - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float oldpos = E->get().pos; - float newpos = oldpos - from_t + motion; - //if (newpos>=0) - undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos); - undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos); - } - - undo_redo->commit_action(); - _edit_if_single_selection(); - - } break; - default: {} - } - - //button released - click.click = ClickOver::CLICK_NONE; - track_editor->update(); - } - } - } - - Ref<InputEventMouseMotion> mm = p_input; - - if (mm.is_valid()) { - - mouse_over.over = MouseOver::OVER_NONE; - mouse_over.track = -1; - te->update(); - track_editor->set_tooltip(""); - - if (!track_editor->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field())) - track_editor->call_deferred("grab_focus"); - - if (click.click != ClickOver::CLICK_NONE) { - - switch (click.click) { - case ClickOver::CLICK_RESIZE_NAMES: { - - float base = click.at.y; - float clickp = click.at.x - ofs.x; - float dif = base - clickp; - - float target = mm->get_position().x + dif - ofs.x; - - float ratio = target / settings_limit; - - if (ratio > 0.9) - ratio = 0.9; - else if (ratio < 0.2) - ratio = 0.2; - - name_column_ratio = ratio; - - } break; - case ClickOver::CLICK_DRAG_TIMELINE: { - - Point2 mpos = mm->get_position() - ofs; - /* - if (mpos.x<name_limit) - mpos.x=name_limit; - if (mpos.x>settings_limit) - mpos.x=settings_limit; - */ - - //int zoomw = settings_limit-name_limit; - float scale = _get_zoom_scale(); - float pos = h_scroll->get_value() + (mpos.x - name_limit) / scale; - if (animation->get_step()) { - pos = Math::stepify(pos, animation->get_step()); - } - if (pos < 0) - pos = 0; - if (pos >= animation->get_length()) - pos = animation->get_length(); - - if (pos < h_scroll->get_value()) { - h_scroll->set_value(pos); - } else if (pos > h_scroll->get_value() + (settings_limit - name_limit) / scale) { - h_scroll->set_value(pos - (settings_limit - name_limit) / scale); - } - - timeline_pos = pos; - emit_signal("timeline_changed", pos, true); - - } break; - case ClickOver::CLICK_SELECT_KEYS: { - - click.to = mm->get_position(); - if (click.to.y < h && click.at.y > h && mm->get_relative().y < 0) { - - float prev = v_scroll->get_value(); - v_scroll->set_value(v_scroll->get_value() - 1); - if (prev != v_scroll->get_value()) - click.at.y += h; - } - if (click.to.y > size.height && click.at.y < size.height && mm->get_relative().y > 0) { - - float prev = v_scroll->get_value(); - v_scroll->set_value(v_scroll->get_value() + 1); - if (prev != v_scroll->get_value()) - click.at.y -= h; - } - - } break; - case ClickOver::CLICK_MOVE_KEYS: { - - click.to = mm->get_position(); - } break; - default: {} - } - - return; - } else if (mm->get_button_mask() & BUTTON_MASK_MIDDLE) { - - int rel = mm->get_relative().x; - float relf = rel / _get_zoom_scale(); - h_scroll->set_value(h_scroll->get_value() - relf); - } - - if (mm->get_button_mask() == 0) { - - Point2 mpos = mm->get_position() - ofs; - - if (mpos.y < h) { - return; - } - - mpos.y -= h; - - int idx = mpos.y / h; - idx += v_scroll->get_value(); - if (idx < 0 || idx >= animation->get_track_count()) - return; - - mouse_over.track = idx; - - if (mpos.x < name_limit) { - //name column - - mouse_over.over = MouseOver::OVER_NAME; - - } else if (mpos.x < settings_limit) { - - float pos = mpos.x - name_limit; - pos /= _get_zoom_scale(); - pos += h_scroll->get_value(); - float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0; - - int kidx = animation->track_find_key(idx, pos); - int kidx_n = kidx + 1; - - bool found = false; - - if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx); - if (ABS(pos - kpos) <= w_time) { - - mouse_over.over = MouseOver::OVER_KEY; - mouse_over.track = idx; - mouse_over.over_key = kidx; - found = true; - } - } - - if (!found && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) { - - float kpos = animation->track_get_key_time(idx, kidx_n); - if (ABS(pos - kpos) <= w_time) { - - mouse_over.over = MouseOver::OVER_KEY; - mouse_over.track = idx; - mouse_over.over_key = kidx_n; - found = true; - } - } - - if (found) { - - String text; - text = "time: " + rtos(animation->track_get_key_time(idx, mouse_over.over_key)) + "\n"; - - switch (animation->track_get_type(idx)) { - - case Animation::TYPE_TRANSFORM: { - - Dictionary d = animation->track_get_key_value(idx, mouse_over.over_key); - if (d.has("location")) - text += "location: " + String(d["location"]) + "\n"; - if (d.has("rotation")) - text += "rot: " + String(d["rotation"]) + "\n"; - if (d.has("scale")) - text += "scale: " + String(d["scale"]) + "\n"; - } break; - case Animation::TYPE_VALUE: { - - Variant v = animation->track_get_key_value(idx, mouse_over.over_key); - //text+="value: "+String(v)+"\n"; - - bool prop_exists = false; - Variant::Type valid_type = Variant::NIL; - Object *obj = NULL; - - RES res; - Vector<StringName> leftover_path; - Node *node = root->get_node_and_resource(animation->track_get_path(idx), res, leftover_path); - - if (res.is_valid()) { - obj = res.ptr(); - } else if (node) { - obj = node; - } - - if (obj) { - valid_type = obj->get_static_property_type_indexed(leftover_path, &prop_exists); - } - - text += "type: " + Variant::get_type_name(v.get_type()) + "\n"; - if (prop_exists && !Variant::can_convert(v.get_type(), valid_type)) { - text += "value: " + String(v) + " (Invalid, expected type: " + Variant::get_type_name(valid_type) + ")\n"; - } else { - text += "value: " + String(v) + "\n"; - } - - } break; - case Animation::TYPE_METHOD: { - - Dictionary d = animation->track_get_key_value(idx, mouse_over.over_key); - if (d.has("method")) - text += String(d["method"]); - text += "("; - Vector<Variant> args; - if (d.has("args")) - args = d["args"]; - for (int i = 0; i < args.size(); i++) { - - if (i > 0) - text += ", "; - text += String(args[i]); - } - text += ")\n"; - - } break; - } - text += "easing: " + rtos(animation->track_get_key_transition(idx, mouse_over.over_key)); - - track_editor->set_tooltip(text); - return; - } - - } else { - //button column - int ofsx = size.width - mpos.x; - if (ofsx < 0) - return; - /* - if (ofsx < remove_icon->get_width()) { - - mouse_over.over=MouseOver::OVER_REMOVE; - - return; - } - - ofsx-=hsep+remove_icon->get_width(); - - if (ofsx < move_down_icon->get_width()) { - - mouse_over.over=MouseOver::OVER_DOWN; - return; - } - - ofsx-=hsep+move_down_icon->get_width(); - - if (ofsx < move_up_icon->get_width()) { - - mouse_over.over=MouseOver::OVER_UP; - return; - } - - ofsx-=hsep*3+move_up_icon->get_width(); - -*/ - - if (ofsx < down_icon->get_width() + wrap_icon[0]->get_width() + hsep * 3) { - - mouse_over.over = MouseOver::OVER_WRAP; - return; - } - - ofsx -= hsep * 3 + wrap_icon[0]->get_width() + down_icon->get_width(); - - if (ofsx < down_icon->get_width() + interp_icon[0]->get_width() + hsep * 3) { - - mouse_over.over = MouseOver::OVER_INTERP; - return; - } - - ofsx -= hsep * 2 + interp_icon[0]->get_width() + down_icon->get_width(); - - if (ofsx < down_icon->get_width() + cont_icon[0]->get_width() + hsep * 3) { - - mouse_over.over = MouseOver::OVER_VALUE; - return; - } - - ofsx -= hsep * 3 + cont_icon[0]->get_width() + down_icon->get_width(); - - if (ofsx < add_key_icon->get_width()) { - - mouse_over.over = MouseOver::OVER_ADD_KEY; - return; - } - } - } - } - - Ref<InputEventMagnifyGesture> magnify_gesture = p_input; - if (magnify_gesture.is_valid()) { - zoom->set_value(zoom->get_value() * magnify_gesture->get_factor()); - } - - Ref<InputEventPanGesture> pan_gesture = p_input; - if (pan_gesture.is_valid()) { - - h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() * pan_gesture->get_delta().x / 8); - v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() * pan_gesture->get_delta().y / 8); - } -} - -void AnimationKeyEditor::_notification(int p_what) { - - switch (p_what) { - case NOTIFICATION_VISIBILITY_CHANGED: { - - update_keying(); - EditorNode::get_singleton()->update_keying(); - emit_signal("keying_changed"); - } break; - - case NOTIFICATION_ENTER_TREE: { - - key_editor->edit(key_edit); - - zoomicon->set_custom_minimum_size(Size2(24 * EDSCALE, 0)); - zoomicon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); - - menu_track->set_icon(get_icon("Tools", "EditorIcons")); - menu_track->get_popup()->add_item(TTR("Scale Selection"), TRACK_MENU_SCALE); - menu_track->get_popup()->add_item(TTR("Scale From Cursor"), TRACK_MENU_SCALE_PIVOT); - menu_track->get_popup()->add_separator(); - menu_track->get_popup()->add_item(TTR("Duplicate Selection"), TRACK_MENU_DUPLICATE); - menu_track->get_popup()->add_item(TTR("Duplicate Transposed"), TRACK_MENU_DUPLICATE_TRANSPOSE); - menu_track->get_popup()->add_separator(); - menu_track->get_popup()->add_item(TTR("Goto Next Step"), TRACK_MENU_NEXT_STEP, KEY_MASK_CMD | KEY_RIGHT); - menu_track->get_popup()->add_item(TTR("Goto Prev Step"), TRACK_MENU_PREV_STEP, KEY_MASK_CMD | KEY_LEFT); - menu_track->get_popup()->add_separator(); - PopupMenu *tpp = memnew(PopupMenu); - tpp->add_item(TTR("Linear"), TRACK_MENU_SET_ALL_TRANS_LINEAR); - tpp->add_item(TTR("Constant"), TRACK_MENU_SET_ALL_TRANS_CONSTANT); - tpp->add_item(TTR("In"), TRACK_MENU_SET_ALL_TRANS_IN); - tpp->add_item(TTR("Out"), TRACK_MENU_SET_ALL_TRANS_OUT); - tpp->add_item(TTR("In-Out"), TRACK_MENU_SET_ALL_TRANS_INOUT); - tpp->add_item(TTR("Out-In"), TRACK_MENU_SET_ALL_TRANS_OUTIN); - tpp->set_name(TTR("Transitions")); - tpp->connect("id_pressed", this, "_menu_track"); - optimize_dialog->connect("confirmed", this, "_animation_optimize"); - - menu_track->get_popup()->add_child(tpp); - - menu_track->get_popup()->add_item(TTR("Optimize Animation"), TRACK_MENU_OPTIMIZE); - menu_track->get_popup()->add_item(TTR("Clean-Up Animation"), TRACK_MENU_CLEAN_UP); - - curve_linear->connect("pressed", this, "_menu_track", varray(CURVE_SET_LINEAR)); - curve_in->connect("pressed", this, "_menu_track", varray(CURVE_SET_IN)); - curve_out->connect("pressed", this, "_menu_track", varray(CURVE_SET_OUT)); - curve_inout->connect("pressed", this, "_menu_track", varray(CURVE_SET_INOUT)); - curve_outin->connect("pressed", this, "_menu_track", varray(CURVE_SET_OUTIN)); - curve_constant->connect("pressed", this, "_menu_track", varray(CURVE_SET_CONSTANT)); - - edit_button->connect("pressed", this, "_toggle_edit_curves"); - - curve_edit->connect("transition_changed", this, "_curve_transition_changed"); - call_select->connect("selected", this, "_add_call_track"); - - _update_menu(); - - } break; - - case NOTIFICATION_THEME_CHANGED: { - zoomicon->set_texture(get_icon("Zoom", "EditorIcons")); - - menu_add_track->set_icon(get_icon("Add", "EditorIcons")); - - menu_track->set_icon(get_icon("Tools", "EditorIcons")); - - menu_add_track->get_popup()->set_item_icon(ADD_TRACK_MENU_ADD_VALUE_TRACK, get_icon("KeyValue", "EditorIcons")); - menu_add_track->get_popup()->set_item_icon(ADD_TRACK_MENU_ADD_TRANSFORM_TRACK, get_icon("KeyXform", "EditorIcons")); - menu_add_track->get_popup()->set_item_icon(ADD_TRACK_MENU_ADD_CALL_TRACK, get_icon("KeyCall", "EditorIcons")); - - curve_linear->set_icon(get_icon("CurveLinear", "EditorIcons")); - curve_in->set_icon(get_icon("CurveIn", "EditorIcons")); - curve_out->set_icon(get_icon("CurveOut", "EditorIcons")); - curve_inout->set_icon(get_icon("CurveInOut", "EditorIcons")); - curve_outin->set_icon(get_icon("CurveOutIn", "EditorIcons")); - curve_constant->set_icon(get_icon("CurveConstant", "EditorIcons")); - - move_up_button->set_icon(get_icon("MoveUp", "EditorIcons")); - move_down_button->set_icon(get_icon("MoveDown", "EditorIcons")); - remove_button->set_icon(get_icon("Remove", "EditorIcons")); - edit_button->set_icon(get_icon("EditKey", "EditorIcons")); - - loop->set_icon(get_icon("Loop", "EditorIcons")); - - { - - right_data_size_cache = 0; - int hsep = get_constant("hseparation", "Tree"); - Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons"); - Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons"); - Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons"); - Ref<Texture> down_icon = get_icon("select_arrow", "Tree"); - Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons"); - Ref<Texture> interp_icon[3] = { - get_icon("InterpRaw", "EditorIcons"), - get_icon("InterpLinear", "EditorIcons"), - get_icon("InterpCubic", "EditorIcons") - }; - Ref<Texture> cont_icon[3] = { - get_icon("TrackContinuous", "EditorIcons"), - get_icon("TrackDiscrete", "EditorIcons"), - get_icon("TrackTrigger", "EditorIcons") - }; - - Ref<Texture> wrap_icon[2] = { - get_icon("InterpWrapClamp", "EditorIcons"), - get_icon("InterpWrapLoop", "EditorIcons"), - }; - right_data_size_cache = down_icon->get_width() * 3 + add_key_icon->get_width() + interp_icon[0]->get_width() + cont_icon[0]->get_width() + wrap_icon[0]->get_width() + hsep * 9; - } - } break; - } -} - -void AnimationKeyEditor::_scroll_changed(double) { - - if (te_drawing) - return; - - track_editor->update(); -} - -void AnimationKeyEditor::_update_paths() { - - if (animation.is_valid()) { - //timeline->set_max(animation->get_length()); - //timeline->set_step(0.01); - track_editor->update(); - length->set_value(animation->get_length()); - step->set_value(animation->get_step()); - } -} - -void AnimationKeyEditor::_root_removed() { - - root = NULL; -} - -void AnimationKeyEditor::_update_menu() { - - updating = true; - - if (animation.is_valid()) { - - length->set_value(animation->get_length()); - loop->set_pressed(animation->has_loop()); - step->set_value(animation->get_step()); - } - - track_editor->update(); - updating = false; -} -void AnimationKeyEditor::_clear_selection() { - - selection.clear(); - key_edit->animation = Ref<Animation>(); - key_edit->track = 0; - key_edit->key_ofs = 0; - key_edit->hint = PropertyInfo(); - key_edit->base = NodePath(); - key_edit->notify_change(); -} - -void AnimationKeyEditor::set_animation(const Ref<Animation> &p_anim) { - - if (animation.is_valid()) - animation->disconnect("changed", this, "_update_paths"); - animation = p_anim; - if (animation.is_valid()) - animation->connect("changed", this, "_update_paths"); - - timeline_pos = 0; - _clear_selection(); - - _update_menu(); - selected_track = -1; - _edit_if_single_selection(); - - EditorNode::get_singleton()->update_keying(); -} - -void AnimationKeyEditor::set_root(Node *p_root) { - - if (root) - root->disconnect("tree_exiting", this, "_root_removed"); - - root = p_root; - - if (root) - root->connect("tree_exiting", this, "_root_removed", make_binds(), CONNECT_ONESHOT); -} - -Node *AnimationKeyEditor::get_root() const { - - return root; -} - -void AnimationKeyEditor::update_keying() { - - bool keying_enabled = is_visible_in_tree() && animation.is_valid(); - - if (keying_enabled == keying) - return; - - keying = keying_enabled; - _update_menu(); - emit_signal("keying_changed"); -} - -bool AnimationKeyEditor::has_keying() const { - - return keying; -} - -void AnimationKeyEditor::_query_insert(const InsertData &p_id) { - - if (insert_frame != Engine::get_singleton()->get_frames_drawn()) { - //clear insert list for the frame if frame changed - if (insert_confirm->is_visible_in_tree()) - return; //do nothing - insert_data.clear(); - insert_query = false; - } - insert_frame = Engine::get_singleton()->get_frames_drawn(); - - for (List<InsertData>::Element *E = insert_data.front(); E; E = E->next()) { - //prevent insertion of multiple tracks - if (E->get().path == p_id.path) - return; //already inserted a track for this on this frame - } - - insert_data.push_back(p_id); - - if (p_id.track_idx == -1) { - if (bool(EDITOR_DEF("editors/animation/confirm_insert_track", true))) { - //potential new key, does not exist - if (insert_data.size() == 1) - insert_confirm->set_text(vformat(TTR("Create NEW track for %s and insert key?"), p_id.query)); - else - insert_confirm->set_text(vformat(TTR("Create %d NEW tracks and insert keys?"), insert_data.size())); - - insert_confirm->get_ok()->set_text(TTR("Create")); - insert_confirm->popup_centered_minsize(); - insert_query = true; - } else { - call_deferred("_insert_delay"); - insert_queue = true; - } - - } else { - if (!insert_query && !insert_queue) { - call_deferred("_insert_delay"); - insert_queue = true; - } - } -} - -void AnimationKeyEditor::insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform) { - - if (!keying) - return; - if (!animation.is_valid()) - return; - - ERR_FAIL_COND(!root); - //let's build a node path - String path = root->get_path_to(p_node); - if (p_sub != "") - path += ":" + p_sub; - - NodePath np = path; - - int track_idx = -1; - - for (int i = 0; i < animation->get_track_count(); i++) { - - if (animation->track_get_type(i) != Animation::TYPE_TRANSFORM) - continue; - if (animation->track_get_path(i) != np) - continue; - - track_idx = i; - break; - } - - InsertData id; - Dictionary val; - - id.path = np; - id.track_idx = track_idx; - id.value = p_xform; - id.type = Animation::TYPE_TRANSFORM; - id.query = "node '" + p_node->get_name() + "'"; - id.advance = false; - - //dialog insert - - _query_insert(id); -} - -void AnimationKeyEditor::insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists) { - - ERR_FAIL_COND(!root); - //let's build a node path - - Node *node = p_node; - - String path = root->get_path_to(node); - - for (int i = 1; i < history->get_path_size(); i++) { - - String prop = history->get_path_property(i); - ERR_FAIL_COND(prop == ""); - path += ":" + prop; - } - - path += ":" + p_property; - - NodePath np = path; - - //locate track - - int track_idx = -1; - - for (int i = 0; i < animation->get_track_count(); i++) { - - if (animation->track_get_type(i) != Animation::TYPE_VALUE) - continue; - if (animation->track_get_path(i) != np) - continue; - - track_idx = i; - break; - } - - if (p_only_if_exists && track_idx == -1) - return; - InsertData id; - id.path = np; - id.track_idx = track_idx; - id.value = p_value; - id.type = Animation::TYPE_VALUE; - id.query = "property '" + p_property + "'"; - id.advance = false; - //dialog insert - _query_insert(id); -} - -void AnimationKeyEditor::insert_value_key(const String &p_property, const Variant &p_value, bool p_advance) { - - ERR_FAIL_COND(!root); - //let's build a node path - ERR_FAIL_COND(history->get_path_size() == 0); - Object *obj = ObjectDB::get_instance(history->get_path_object(0)); - ERR_FAIL_COND(!Object::cast_to<Node>(obj)); - - Node *node = Object::cast_to<Node>(obj); - - String path = root->get_path_to(node); - - for (int i = 1; i < history->get_path_size(); i++) { - - String prop = history->get_path_property(i); - ERR_FAIL_COND(prop == ""); - path += ":" + prop; - } - - path += ":" + p_property; - - NodePath np = path; - - //locate track - - int track_idx = -1; - - for (int i = 0; i < animation->get_track_count(); i++) { - - if (animation->track_get_type(i) != Animation::TYPE_VALUE) - continue; - if (animation->track_get_path(i) != np) - continue; - - track_idx = i; - break; - } - - InsertData id; - id.path = np; - id.track_idx = track_idx; - id.value = p_value; - id.type = Animation::TYPE_VALUE; - id.query = "property '" + p_property + "'"; - id.advance = p_advance; - //dialog insert - _query_insert(id); -} - -void AnimationKeyEditor::_confirm_insert_list() { - - undo_redo->create_action(TTR("Anim Create & Insert")); - - int last_track = animation->get_track_count(); - while (insert_data.size()) { - - last_track = _confirm_insert(insert_data.front()->get(), last_track); - insert_data.pop_front(); - } - - undo_redo->commit_action(); -} - -int AnimationKeyEditor::_confirm_insert(InsertData p_id, int p_last_track) { - - if (p_last_track == -1) - p_last_track = animation->get_track_count(); - - bool created = false; - if (p_id.track_idx < 0) { - - created = true; - undo_redo->create_action(TTR("Anim Insert Track & Key")); - Animation::UpdateMode update_mode = Animation::UPDATE_DISCRETE; - - if (p_id.type == Animation::TYPE_VALUE) { - //wants a new tack - - { - //hack - NodePath np; - animation->add_track(p_id.type); - animation->track_set_path(animation->get_track_count() - 1, p_id.path); - PropertyInfo h = _find_hint_for_track(animation->get_track_count() - 1, np); - animation->remove_track(animation->get_track_count() - 1); //hack - - if (h.type == Variant::REAL || - h.type == Variant::VECTOR2 || - h.type == Variant::RECT2 || - h.type == Variant::VECTOR3 || - h.type == Variant::AABB || - h.type == Variant::QUAT || - h.type == Variant::COLOR || - h.type == Variant::TRANSFORM) { - - update_mode = Animation::UPDATE_CONTINUOUS; - } - - if (h.usage & PROPERTY_USAGE_ANIMATE_AS_TRIGGER) { - update_mode = Animation::UPDATE_TRIGGER; - } - } - } - - p_id.track_idx = p_last_track; - - undo_redo->add_do_method(animation.ptr(), "add_track", p_id.type); - undo_redo->add_do_method(animation.ptr(), "track_set_path", p_id.track_idx, p_id.path); - if (p_id.type == Animation::TYPE_VALUE) - undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", p_id.track_idx, update_mode); - - } else { - undo_redo->create_action(TTR("Anim Insert Key")); - } - - float time = timeline_pos; - Variant value; - - switch (p_id.type) { - - case Animation::TYPE_VALUE: { - - value = p_id.value; - - } break; - case Animation::TYPE_TRANSFORM: { - - Transform tr = p_id.value; - Dictionary d; - d["location"] = tr.origin; - d["scale"] = tr.basis.get_scale(); - d["rotation"] = Quat(tr.basis); //.orthonormalized(); - value = d; - } break; - default: {} - } - - undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, value); - - if (created) { - - //just remove the track - undo_redo->add_undo_method(animation.ptr(), "remove_track", p_last_track); - p_last_track++; - } else { - - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_id.track_idx, time); - int existing = animation->track_find_key(p_id.track_idx, time, true); - if (existing != -1) { - Variant v = animation->track_get_key_value(p_id.track_idx, existing); - float trans = animation->track_get_key_transition(p_id.track_idx, existing); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, v, trans); - } - } - - undo_redo->add_do_method(this, "update"); - undo_redo->add_undo_method(this, "update"); - undo_redo->add_do_method(track_editor, "update"); - undo_redo->add_undo_method(track_editor, "update"); - undo_redo->add_do_method(track_pos, "update"); - undo_redo->add_undo_method(track_pos, "update"); - - undo_redo->commit_action(); - - return p_last_track; -} - -Ref<Animation> AnimationKeyEditor::get_current_animation() const { - - return animation; -} - -void AnimationKeyEditor::_animation_len_changed(float p_len) { - - if (updating) - return; - - if (!animation.is_null()) { - - undo_redo->create_action(TTR("Change Anim Len")); - undo_redo->add_do_method(animation.ptr(), "set_length", p_len); - undo_redo->add_undo_method(animation.ptr(), "set_length", animation->get_length()); - undo_redo->add_do_method(this, "_animation_len_update"); - undo_redo->add_undo_method(this, "_animation_len_update"); - undo_redo->commit_action(); - } -} - -void AnimationKeyEditor::_animation_len_update() { - - if (!animation.is_null()) - emit_signal(alc, animation->get_length()); -} - -void AnimationKeyEditor::_animation_changed() { - if (updating) - return; - _update_menu(); -} - -void AnimationKeyEditor::_animation_loop_changed() { - - if (updating) - return; - - if (!animation.is_null()) { - - undo_redo->create_action(TTR("Change Anim Loop")); - undo_redo->add_do_method(animation.ptr(), "set_loop", loop->is_pressed()); - undo_redo->add_undo_method(animation.ptr(), "set_loop", !loop->is_pressed()); - undo_redo->commit_action(); - } -} - -void AnimationKeyEditor::_create_value_item(int p_type) { - - undo_redo->create_action(TTR("Anim Create Typed Value Key")); - - Variant::CallError ce; - Variant v = Variant::construct(Variant::Type(p_type), NULL, 0, ce); - undo_redo->add_do_method(animation.ptr(), "track_insert_key", cvi_track, cvi_pos, v); - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", cvi_track, cvi_pos); - - int existing = animation->track_find_key(cvi_track, cvi_pos, true); - - if (existing != -1) { - Variant v = animation->track_get_key_value(cvi_track, existing); - float trans = animation->track_get_key_transition(cvi_track, existing); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", cvi_track, cvi_pos, v, trans); - } - - undo_redo->commit_action(); -} - -void AnimationKeyEditor::set_anim_pos(float p_pos) { - - if (animation.is_null()) - return; - timeline_pos = p_pos; - update(); - track_pos->update(); - track_editor->update(); -} - -void AnimationKeyEditor::_pane_drag(const Point2 &p_delta) { - - Size2 ecs = ec->get_custom_minimum_size(); - ecs.y -= p_delta.y; - if (ecs.y < 100) - ecs.y = 100; - ec->set_custom_minimum_size(ecs); -} - -void AnimationKeyEditor::_insert_delay() { - - if (insert_query) { - //discard since it's entered into query mode - insert_queue = false; - return; - } - - undo_redo->create_action(TTR("Anim Insert")); - - int last_track = animation->get_track_count(); - bool advance = false; - while (insert_data.size()) { - - if (insert_data.front()->get().advance) - advance = true; - last_track = _confirm_insert(insert_data.front()->get(), last_track); - insert_data.pop_front(); - } - - undo_redo->commit_action(); - - if (advance) { - float step = animation->get_step(); - if (step == 0) - step = 1; - - float pos = timeline_pos; - - pos = Math::stepify(pos + step, step); - if (pos > animation->get_length()) - pos = animation->get_length(); - timeline_pos = pos; - track_pos->update(); - emit_signal("timeline_changed", pos, true); - } - insert_queue = false; -} - -void AnimationKeyEditor::_step_changed(float p_len) { - - updating = true; - if (!animation.is_null()) { - animation->set_step(p_len); - emit_signal("animation_step_changed", animation->get_step()); - } - updating = false; -} - -void AnimationKeyEditor::_scale() { - - if (selection.empty()) - return; - - float from_t = 1e20; - float to_t = -1e20; - float len = -1e20; - float pivot = 0; - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { - float t = animation->track_get_key_time(E->key().track, E->key().key); - if (t < from_t) - from_t = t; - if (t > to_t) - to_t = t; - } - - len = to_t - from_t; - if (last_menu_track_opt == TRACK_MENU_SCALE_PIVOT) { - pivot = timeline_pos; - - } else { - - pivot = from_t; - } - - float s = scale->get_value(); - if (s == 0) { - ERR_PRINT("Can't scale to 0"); - } - - undo_redo->create_action(TTR("Anim Scale Keys")); - - List<_AnimMoveRestore> to_restore; - - // 1-remove the keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); - } - // 2- remove overlapped keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newtime = (E->get().pos - from_t) * s + from_t; - int idx = animation->track_find_key(E->key().track, newtime, true); - if (idx == -1) - continue; - SelectedKey sk; - sk.key = idx; - sk.track = E->key().track; - if (selection.has(sk)) - continue; //already in selection, don't save - - undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newtime); - _AnimMoveRestore amr; - - amr.key = animation->track_get_key_value(E->key().track, idx); - amr.track = E->key().track; - amr.time = newtime; - amr.transition = animation->track_get_key_transition(E->key().track, idx); - - to_restore.push_back(amr); - } - -#define _NEW_POS(m_ofs) (((s > 0) ? m_ofs : from_t + (len - (m_ofs - from_t))) - pivot) * ABS(s) + from_t - // 3-move the keys (re insert them) - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newpos = _NEW_POS(E->get().pos); - undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - } - - // 4-(undo) remove inserted keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float newpos = _NEW_POS(E->get().pos); - undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newpos); - } - - // 5-(undo) reinsert keys - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); - } - - // 6-(undo) reinsert overlapped keys - for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { - - _AnimMoveRestore &amr = E->get(); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); - } - - // 6-(undo) reinsert overlapped keys - for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { - - _AnimMoveRestore &amr = E->get(); - undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); - } - - undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); - undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); - - // 7-reselect - - for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { - - float oldpos = E->get().pos; - float newpos = _NEW_POS(oldpos); - if (newpos >= 0) - undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos); - undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos); - } -#undef _NEW_POS - undo_redo->commit_action(); -} - -void AnimationKeyEditor::_add_call_track(const NodePath &p_base) { - - Node *base = EditorNode::get_singleton()->get_edited_scene(); - if (!base) - return; - Node *from = base->get_node(p_base); - if (!from || !root) - return; - - NodePath path = root->get_path_to(from); - - //print_line("root: "+String(root->get_path())); - //print_line("path: "+String(path)); - - undo_redo->create_action(TTR("Anim Add Call Track")); - undo_redo->add_do_method(animation.ptr(), "add_track", Animation::TYPE_METHOD); - undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), path); - undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); - undo_redo->commit_action(); -} - -void AnimationKeyEditor::cleanup() { - - set_animation(Ref<Animation>()); -} - -void AnimationKeyEditor::_bind_methods() { - - ClassDB::bind_method(D_METHOD("_root_removed"), &AnimationKeyEditor::_root_removed); - ClassDB::bind_method(D_METHOD("_scale"), &AnimationKeyEditor::_scale); - ClassDB::bind_method(D_METHOD("set_root"), &AnimationKeyEditor::set_root); - - //ClassDB::bind_method(D_METHOD("_confirm_insert"),&AnimationKeyEditor::_confirm_insert); - ClassDB::bind_method(D_METHOD("_confirm_insert_list"), &AnimationKeyEditor::_confirm_insert_list); - - ClassDB::bind_method(D_METHOD("_update_paths"), &AnimationKeyEditor::_update_paths); - ClassDB::bind_method(D_METHOD("_track_editor_draw"), &AnimationKeyEditor::_track_editor_draw); - - ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationKeyEditor::_animation_changed); - ClassDB::bind_method(D_METHOD("_scroll_changed"), &AnimationKeyEditor::_scroll_changed); - ClassDB::bind_method(D_METHOD("_track_editor_gui_input"), &AnimationKeyEditor::_track_editor_gui_input); - ClassDB::bind_method(D_METHOD("_track_name_changed"), &AnimationKeyEditor::_track_name_changed); - ClassDB::bind_method(D_METHOD("_track_menu_selected"), &AnimationKeyEditor::_track_menu_selected); - ClassDB::bind_method(D_METHOD("_menu_add_track"), &AnimationKeyEditor::_menu_add_track); - ClassDB::bind_method(D_METHOD("_menu_track"), &AnimationKeyEditor::_menu_track); - ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationKeyEditor::_clear_selection_for_anim); - ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationKeyEditor::_select_at_anim); - ClassDB::bind_method(D_METHOD("_track_position_draw"), &AnimationKeyEditor::_track_position_draw); - ClassDB::bind_method(D_METHOD("_insert_delay"), &AnimationKeyEditor::_insert_delay); - ClassDB::bind_method(D_METHOD("_step_changed"), &AnimationKeyEditor::_step_changed); - - ClassDB::bind_method(D_METHOD("_animation_loop_changed"), &AnimationKeyEditor::_animation_loop_changed); - ClassDB::bind_method(D_METHOD("_animation_len_changed"), &AnimationKeyEditor::_animation_len_changed); - ClassDB::bind_method(D_METHOD("_create_value_item"), &AnimationKeyEditor::_create_value_item); - ClassDB::bind_method(D_METHOD("_pane_drag"), &AnimationKeyEditor::_pane_drag); - - ClassDB::bind_method(D_METHOD("_animation_len_update"), &AnimationKeyEditor::_animation_len_update); - - ClassDB::bind_method(D_METHOD("set_animation"), &AnimationKeyEditor::set_animation); - ClassDB::bind_method(D_METHOD("_animation_optimize"), &AnimationKeyEditor::_animation_optimize); - ClassDB::bind_method(D_METHOD("_curve_transition_changed"), &AnimationKeyEditor::_curve_transition_changed); - ClassDB::bind_method(D_METHOD("_toggle_edit_curves"), &AnimationKeyEditor::_toggle_edit_curves); - ClassDB::bind_method(D_METHOD("_add_call_track"), &AnimationKeyEditor::_add_call_track); - - ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "res"), PropertyInfo(Variant::STRING, "prop"))); - ADD_SIGNAL(MethodInfo("keying_changed")); - ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag"))); - ADD_SIGNAL(MethodInfo("animation_len_changed", PropertyInfo(Variant::REAL, "len"))); - ADD_SIGNAL(MethodInfo("animation_step_changed", PropertyInfo(Variant::REAL, "step"))); - ADD_SIGNAL(MethodInfo("key_edited", PropertyInfo(Variant::INT, "track"), PropertyInfo(Variant::INT, "key"))); -} - -AnimationKeyEditor::AnimationKeyEditor() { - - alc = "animation_len_changed"; - editor_selection = EditorNode::get_singleton()->get_editor_selection(); - - selected_track = -1; - updating = false; - te_drawing = false; - undo_redo = EditorNode::get_singleton()->get_undo_redo(); - history = EditorNode::get_singleton()->get_editor_history(); - - ec = memnew(Control); - ec->set_custom_minimum_size(Size2(0, 150) * EDSCALE); - add_child(ec); - ec->set_v_size_flags(SIZE_EXPAND_FILL); - - h_scroll = memnew(HScrollBar); - h_scroll->connect("value_changed", this, "_scroll_changed"); - add_child(h_scroll); - h_scroll->set_value(0); - - HBoxContainer *hb = memnew(HBoxContainer); - add_child(hb); - - root = NULL; - //menu = memnew( MenuButton ); - //menu->set_flat(true); - //menu->set_position(Point2()); - //add_child(menu); - - zoomicon = memnew(TextureRect); - hb->add_child(zoomicon); - zoomicon->set_tooltip(TTR("Animation zoom.")); - - zoom = memnew(HSlider); - //hb->add_child(zoom); - zoom->set_step(0.01); - zoom->set_min(0.0); - zoom->set_max(2.0); - zoom->set_value(1.0); - zoom->set_h_size_flags(SIZE_EXPAND_FILL); - zoom->set_v_size_flags(SIZE_EXPAND_FILL); - zoom->set_stretch_ratio(2); - hb->add_child(zoom); - zoom->connect("value_changed", this, "_scroll_changed"); - zoom->set_tooltip(TTR("Animation zoom.")); - - hb->add_child(memnew(VSeparator)); - - Label *l = memnew(Label); - l->set_text(TTR("Length (s):")); - hb->add_child(l); - - length = memnew(SpinBox); - length->set_min(0.01); - length->set_max(10000); - length->set_step(0.01); - length->set_h_size_flags(SIZE_EXPAND_FILL); - length->set_stretch_ratio(1); - length->set_tooltip(TTR("Animation length (in seconds).")); - length->set_editable(false); - - hb->add_child(length); - length->connect("value_changed", this, "_animation_len_changed"); - - l = memnew(Label); - l->set_text(TTR("Step (s):")); - hb->add_child(l); - - step = memnew(SpinBox); - step->set_min(0.00); - step->set_max(128); - step->set_step(0.01); - step->set_value(0.0); - step->set_h_size_flags(SIZE_EXPAND_FILL); - step->set_stretch_ratio(1); - step->set_tooltip(TTR("Cursor step snap (in seconds).")); - step->set_editable(false); - - hb->add_child(step); - step->connect("value_changed", this, "_step_changed"); - - loop = memnew(ToolButton); - loop->set_toggle_mode(true); - loop->connect("pressed", this, "_animation_loop_changed"); - hb->add_child(loop); - loop->set_tooltip(TTR("Enable/Disable looping in animation.")); - loop->set_disabled(true); - - hb->add_child(memnew(VSeparator)); - - menu_add_track = memnew(MenuButton); - hb->add_child(menu_add_track); - menu_add_track->get_popup()->connect("id_pressed", this, "_menu_add_track"); - menu_add_track->set_tooltip(TTR("Add new tracks.")); - menu_add_track->get_popup()->add_icon_item(get_icon("KeyValue", "EditorIcons"), "Add Normal Track", ADD_TRACK_MENU_ADD_VALUE_TRACK); - menu_add_track->get_popup()->add_icon_item(get_icon("KeyXform", "EditorIcons"), "Add Transform Track", ADD_TRACK_MENU_ADD_TRANSFORM_TRACK); - menu_add_track->get_popup()->add_icon_item(get_icon("KeyCall", "EditorIcons"), "Add Call Func Track", ADD_TRACK_MENU_ADD_CALL_TRACK); - - move_up_button = memnew(ToolButton); - hb->add_child(move_up_button); - move_up_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_MOVE_UP)); - move_up_button->set_focus_mode(FOCUS_NONE); - move_up_button->set_disabled(true); - move_up_button->set_tooltip(TTR("Move current track up.")); - - move_down_button = memnew(ToolButton); - hb->add_child(move_down_button); - move_down_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_MOVE_DOWN)); - move_down_button->set_focus_mode(FOCUS_NONE); - move_down_button->set_disabled(true); - move_down_button->set_tooltip(TTR("Move current track down.")); - - remove_button = memnew(ToolButton); - hb->add_child(remove_button); - remove_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_REMOVE)); - remove_button->set_focus_mode(FOCUS_NONE); - remove_button->set_disabled(true); - remove_button->set_tooltip(TTR("Remove selected track.")); - - hb->add_child(memnew(VSeparator)); - - menu_track = memnew(MenuButton); - hb->add_child(menu_track); - menu_track->get_popup()->connect("id_pressed", this, "_menu_track"); - menu_track->set_tooltip(TTR("Track Tools")); - - edit_button = memnew(ToolButton); - edit_button->set_toggle_mode(true); - edit_button->set_focus_mode(FOCUS_NONE); - edit_button->set_disabled(true); - - hb->add_child(edit_button); - edit_button->set_tooltip(TTR("Enable editing of individual keys by clicking them.")); - - optimize_dialog = memnew(ConfirmationDialog); - add_child(optimize_dialog); - optimize_dialog->set_title(TTR("Anim. Optimizer")); - VBoxContainer *optimize_vb = memnew(VBoxContainer); - optimize_dialog->add_child(optimize_vb); - - optimize_linear_error = memnew(SpinBox); - optimize_linear_error->set_max(1.0); - optimize_linear_error->set_min(0.001); - optimize_linear_error->set_step(0.001); - optimize_linear_error->set_value(0.05); - optimize_vb->add_margin_child(TTR("Max. Linear Error:"), optimize_linear_error); - optimize_angular_error = memnew(SpinBox); - optimize_angular_error->set_max(1.0); - optimize_angular_error->set_min(0.001); - optimize_angular_error->set_step(0.001); - optimize_angular_error->set_value(0.01); - - optimize_vb->add_margin_child(TTR("Max. Angular Error:"), optimize_angular_error); - optimize_max_angle = memnew(SpinBox); - optimize_vb->add_margin_child(TTR("Max Optimizable Angle:"), optimize_max_angle); - optimize_max_angle->set_max(360.0); - optimize_max_angle->set_min(0.0); - optimize_max_angle->set_step(0.1); - optimize_max_angle->set_value(22); - - optimize_dialog->get_ok()->set_text(TTR("Optimize")); - - /*keying = memnew( Button ); - keying->set_toggle_mode(true); - //keying->set_text("Keys"); - keying->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,60); - keying->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,10); - keying->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,55); - keying->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,10); - //add_child(keying); - keying->connect("pressed",this,"_keying_toggled"); - */ - - /* l = memnew( Label ); - l->set_text("Base: "); - l->set_position(Point2(0,3)); - //dr_panel->add_child(l);*/ - - //menu->get_popup()->connect("id_pressed",this,"_menu_callback"); - - hb = memnew(HBoxContainer); - hb->set_anchors_and_margins_preset(Control::PRESET_WIDE); - ec->add_child(hb); - hb->set_v_size_flags(SIZE_EXPAND_FILL); - - track_editor = memnew(Control); - track_editor->connect("draw", this, "_track_editor_draw"); - hb->add_child(track_editor); - track_editor->connect("gui_input", this, "_track_editor_gui_input"); - track_editor->set_focus_mode(Control::FOCUS_ALL); - track_editor->set_h_size_flags(SIZE_EXPAND_FILL); - - track_pos = memnew(Control); - track_pos->set_anchors_and_margins_preset(Control::PRESET_WIDE); - track_pos->set_mouse_filter(MOUSE_FILTER_IGNORE); - track_editor->add_child(track_pos); - track_pos->connect("draw", this, "_track_position_draw"); - - select_anim_warning = memnew(Label); - track_editor->add_child(select_anim_warning); - select_anim_warning->set_anchors_and_margins_preset(Control::PRESET_WIDE); - select_anim_warning->set_text(TTR("Select an AnimationPlayer from the Scene Tree to edit animations.")); - select_anim_warning->set_autowrap(true); - select_anim_warning->set_align(Label::ALIGN_CENTER); - select_anim_warning->set_valign(Label::VALIGN_CENTER); - - v_scroll = memnew(VScrollBar); - hb->add_child(v_scroll); - v_scroll->connect("value_changed", this, "_scroll_changed"); - v_scroll->set_value(0); - - key_editor_tab = memnew(TabContainer); - key_editor_tab->set_tab_align(TabContainer::ALIGN_LEFT); - hb->add_child(key_editor_tab); - key_editor_tab->set_custom_minimum_size(Size2(200, 0) * EDSCALE); - - key_editor = memnew(PropertyEditor); - key_editor->hide_top_label(); - key_editor->set_name(TTR("Key")); - key_editor_tab->add_child(key_editor); - - key_edit = memnew(AnimationKeyEdit); - key_edit->undo_redo = undo_redo; - //key_edit->ke_dialog=key_edit_dialog; - - type_menu = memnew(PopupMenu); - type_menu->set_pass_on_modal_close_click(false); - add_child(type_menu); - for (int i = 0; i < Variant::VARIANT_MAX; i++) - type_menu->add_item(Variant::get_type_name(Variant::Type(i)), i); - type_menu->connect("id_pressed", this, "_create_value_item"); - - VBoxContainer *curve_vb = memnew(VBoxContainer); - curve_vb->set_name(TTR("Transition")); - HBoxContainer *curve_hb = memnew(HBoxContainer); - curve_vb->add_child(curve_hb); - - curve_linear = memnew(ToolButton); - curve_linear->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_linear); - curve_in = memnew(ToolButton); - curve_in->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_in); - curve_out = memnew(ToolButton); - curve_out->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_out); - curve_inout = memnew(ToolButton); - curve_inout->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_inout); - curve_outin = memnew(ToolButton); - curve_outin->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_outin); - curve_constant = memnew(ToolButton); - curve_constant->set_focus_mode(FOCUS_NONE); - curve_hb->add_child(curve_constant); - - curve_edit = memnew(AnimationCurveEdit); - curve_vb->add_child(curve_edit); - curve_edit->set_v_size_flags(SIZE_EXPAND_FILL); - key_editor_tab->add_child(curve_vb); - - track_name = memnew(LineEdit); - track_name->set_as_toplevel(true); - track_name->hide(); - add_child(track_name); - track_name->connect("text_entered", this, "_track_name_changed"); - track_menu = memnew(PopupMenu); - track_menu->set_pass_on_modal_close_click(false); - add_child(track_menu); - track_menu->connect("id_pressed", this, "_track_menu_selected"); - - key_editor_tab->hide(); - - last_idx = 1; - - _update_menu(); - - insert_confirm = memnew(ConfirmationDialog); - add_child(insert_confirm); - insert_confirm->connect("confirmed", this, "_confirm_insert_list"); - - click.click = ClickOver::CLICK_NONE; - - name_column_ratio = 0.3; - timeline_pos = 0; - - keying = false; - insert_frame = 0; - insert_query = false; - insert_queue = false; - - editor_selection->connect("selection_changed", track_editor, "update"); - - scale_dialog = memnew(ConfirmationDialog); - VBoxContainer *vbc = memnew(VBoxContainer); - scale_dialog->add_child(vbc); - - scale = memnew(SpinBox); - scale->set_min(-99999); - scale->set_max(99999); - scale->set_step(0.001); - vbc->add_margin_child(TTR("Scale Ratio:"), scale); - scale_dialog->connect("confirmed", this, "_scale"); - add_child(scale_dialog); - - call_select = memnew(SceneTreeDialog); - add_child(call_select); - call_select->set_title(TTR("Call Functions in Which Node?")); - - cleanup_dialog = memnew(ConfirmationDialog); - add_child(cleanup_dialog); - VBoxContainer *cleanup_vb = memnew(VBoxContainer); - cleanup_dialog->add_child(cleanup_vb); - - cleanup_keys = memnew(CheckButton); - cleanup_keys->set_text(TTR("Remove invalid keys")); - cleanup_keys->set_pressed(true); - cleanup_vb->add_child(cleanup_keys); - - cleanup_tracks = memnew(CheckButton); - cleanup_tracks->set_text(TTR("Remove unresolved and empty tracks")); - cleanup_tracks->set_pressed(true); - cleanup_vb->add_child(cleanup_tracks); - - cleanup_all = memnew(CheckButton); - cleanup_all->set_text(TTR("Clean-up all animations")); - cleanup_vb->add_child(cleanup_all); - - cleanup_dialog->set_title(TTR("Clean-Up Animation(s) (NO UNDO!)")); - cleanup_dialog->get_ok()->set_text(TTR("Clean-Up")); - - cleanup_dialog->connect("confirmed", this, "_menu_track", varray(TRACK_MENU_CLEAN_UP_CONFIRM)); - - track_editor->set_clip_contents(true); -} - -AnimationKeyEditor::~AnimationKeyEditor() { - - memdelete(key_edit); -} diff --git a/editor/animation_editor.h b/editor/animation_editor.h deleted file mode 100644 index 1e593f237c..0000000000 --- a/editor/animation_editor.h +++ /dev/null @@ -1,348 +0,0 @@ -/*************************************************************************/ -/* animation_editor.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef ANIMATION_EDITOR_H -#define ANIMATION_EDITOR_H - -#include "scene/gui/control.h" -#include "scene/gui/file_dialog.h" -#include "scene/gui/menu_button.h" -#include "scene/gui/scroll_bar.h" -#include "scene/gui/slider.h" -#include "scene/gui/spin_box.h" -#include "scene/gui/tab_container.h" -#include "scene/gui/texture_rect.h" -#include "scene/gui/tool_button.h" - -#include "editor_data.h" -#include "property_editor.h" -#include "scene/animation/animation_cache.h" -#include "scene/resources/animation.h" -#include "scene_tree_editor.h" - -class AnimationKeyEdit; -class AnimationCurveEdit; - -class AnimationKeyEditor : public VBoxContainer { - - GDCLASS(AnimationKeyEditor, VBoxContainer); - - /* - enum { - - MENU_NEW_ANIMATION, - MENU_OPEN_ANIMATION, - MENU_EDIT_ANIMATION, - MENU_CLOSE_ANIMATION, - MENU_KEYING_ACTIVE, - MENU_SET_ROOT_NODE, - MENU_SYNC_TO_PLAYER, - MENU_ANIM_BASE=100, - }; - -*/ - - enum { - - ADD_TRACK_MENU_ADD_VALUE_TRACK, - ADD_TRACK_MENU_ADD_TRANSFORM_TRACK, - ADD_TRACK_MENU_ADD_CALL_TRACK, - TRACK_MENU_SCALE, - TRACK_MENU_SCALE_PIVOT, - TRACK_MENU_MOVE_UP, - TRACK_MENU_MOVE_DOWN, - TRACK_MENU_REMOVE, - TRACK_MENU_DUPLICATE, - TRACK_MENU_DUPLICATE_TRANSPOSE, - TRACK_MENU_SET_ALL_TRANS_LINEAR, - TRACK_MENU_SET_ALL_TRANS_CONSTANT, - TRACK_MENU_SET_ALL_TRANS_OUT, - TRACK_MENU_SET_ALL_TRANS_IN, - TRACK_MENU_SET_ALL_TRANS_INOUT, - TRACK_MENU_SET_ALL_TRANS_OUTIN, - TRACK_MENU_NEXT_STEP, - TRACK_MENU_PREV_STEP, - TRACK_MENU_OPTIMIZE, - TRACK_MENU_CLEAN_UP, - TRACK_MENU_CLEAN_UP_CONFIRM, - CURVE_SET_LINEAR, - CURVE_SET_IN, - CURVE_SET_OUT, - CURVE_SET_INOUT, - CURVE_SET_OUTIN, - CURVE_SET_CONSTANT - }; - - enum { - RIGHT_MENU_DUPLICATE, - RIGHT_MENU_DUPLICATE_TRANSPOSE, - RIGHT_MENU_REMOVE - }; - - struct MouseOver { - - enum Over { - OVER_NONE, - OVER_NAME, - OVER_KEY, - OVER_VALUE, - OVER_INTERP, - OVER_WRAP, - OVER_UP, - OVER_DOWN, - OVER_REMOVE, - OVER_ADD_KEY, - }; - - Over over; - int track; - int over_key; - - } mouse_over; - - struct SelectedKey { - - int track; - int key; - bool operator<(const SelectedKey &p_key) const { return track == p_key.track ? key < p_key.key : track < p_key.track; }; - }; - - struct KeyInfo { - - float pos; - }; - - Map<SelectedKey, KeyInfo> selection; - - struct ClickOver { - - enum Click { - - CLICK_NONE, - CLICK_RESIZE_NAMES, - CLICK_DRAG_TIMELINE, - CLICK_MOVE_KEYS, - CLICK_SELECT_KEYS - - }; - - SelectedKey selk; - bool shift; - Click click; - Point2 at; - Point2 to; - } click; - - float timeline_pos; - - float name_column_ratio; - - int track_name_editing; - int interp_editing; - int cont_editing; - int wrap_editing; - int selected_track; - int track_ofs[5]; - - int last_menu_track_opt; - LineEdit *track_name; - PopupMenu *track_menu; - PopupMenu *type_menu; - - Control *ec; - TextureRect *zoomicon; - HSlider *zoom; - //MenuButton *menu; - SpinBox *length; - Button *loop; - bool keying; - ToolButton *edit_button; - ToolButton *move_up_button; - ToolButton *move_down_button; - ToolButton *remove_button; - - ToolButton *curve_linear; - ToolButton *curve_in; - ToolButton *curve_out; - ToolButton *curve_inout; - ToolButton *curve_outin; - ToolButton *curve_constant; - - ConfirmationDialog *optimize_dialog; - SpinBox *optimize_linear_error; - SpinBox *optimize_angular_error; - SpinBox *optimize_max_angle; - - ConfirmationDialog *cleanup_dialog; - CheckButton *cleanup_keys; - CheckButton *cleanup_tracks; - CheckButton *cleanup_all; - - SpinBox *step; - - MenuButton *menu_add_track; - MenuButton *menu_track; - - HScrollBar *h_scroll; - VScrollBar *v_scroll; - - Control *track_editor; - Control *track_pos; - TabContainer *key_editor_tab; - - ConfirmationDialog *scale_dialog; - SpinBox *scale; - - PropertyEditor *key_editor; - - SceneTreeDialog *call_select; - - Ref<Animation> animation; - void _update_paths(); - - int last_idx; - - Node *root; - - UndoRedo *undo_redo; - EditorHistory *history; - ConfirmationDialog *insert_confirm; - - AnimationKeyEdit *key_edit; - AnimationCurveEdit *curve_edit; - - bool inserting; - - bool updating; - bool te_drawing; - - void _animation_len_changed(float p_len); - void _animation_loop_changed(); - void _step_changed(float p_len); - - struct InsertData { - - Animation::TrackType type; - NodePath path; - int track_idx; - Variant value; - String query; - bool advance; - }; /* insert_data;*/ - - bool insert_query; - List<InsertData> insert_data; - uint64_t insert_frame; - - int cvi_track; - float cvi_pos; - - int right_data_size_cache; - - EditorSelection *editor_selection; - - Label *select_anim_warning; - - float _get_zoom_scale() const; - - void _track_editor_draw(); - void _track_editor_gui_input(const Ref<InputEvent> &p_input); - void _track_position_draw(); - - void _track_name_changed(const String &p_name); - void _track_menu_selected(int p_idx); - void _confirm_insert_list(); - int _confirm_insert(InsertData p_id, int p_last_track = -1); - void _query_insert(const InsertData &p_id); - void _update_menu(); - bool insert_queue; - void _insert_delay(); - void _scale(); - - void _clear_selection(); - - //void _browse_path(); - - StringName alc; - - void _animation_changed(); - void _animation_optimize(); - void _cleanup_animation(Ref<Animation> p_animation); - - void _scroll_changed(double); - - void _menu_add_track(int p_type); - void _menu_track(int p_type); - - void _clear_selection_for_anim(const Ref<Animation> &p_anim); - void _select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos); - void _curve_transition_changed(float p_what); - - PropertyInfo _find_hint_for_track(int p_idx, NodePath &r_base_path); - - void _create_value_item(int p_type); - void _pane_drag(const Point2 &p_delta); - bool _edit_if_single_selection(); - - void _toggle_edit_curves(); - void _animation_len_update(); - - void _add_call_track(const NodePath &p_base); - - void _anim_duplicate_keys(bool transpose = false); - void _anim_delete_keys(); - - void _root_removed(); - -protected: - void _notification(int p_what); - static void _bind_methods(); - -public: - void set_animation(const Ref<Animation> &p_anim); - Ref<Animation> get_current_animation() const; - void set_root(Node *p_root); - Node *get_root() const; - void update_keying(); - bool has_keying() const; - - void cleanup(); - - void set_anim_pos(float p_pos); - void insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists = false); - void insert_value_key(const String &p_property, const Variant &p_value, bool p_advance); - void insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform); - - void show_select_node_warning(bool p_show) { select_anim_warning->set_visible(p_show); } - AnimationKeyEditor(); - ~AnimationKeyEditor(); -}; - -#endif // ANIMATION_EDITOR_H diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp new file mode 100644 index 0000000000..adc9821d8a --- /dev/null +++ b/editor/animation_track_editor.cpp @@ -0,0 +1,5001 @@ +#include "animation_track_editor.h" +#include "animation_track_editor_plugins.h" +#include "editor/animation_bezier_editor.h" +#include "editor/plugins/animation_player_editor_plugin.h" +#include "editor_node.h" +#include "editor_scale.h" +#include "os/keyboard.h" +#include "scene/main/viewport.h" +#include "servers/audio/audio_stream.h" + +class AnimationTrackKeyEdit : public Object { + + GDCLASS(AnimationTrackKeyEdit, Object); + +public: + bool setting; + bool hidden; + + bool _hide_script_from_inspector() { + return true; + } + + static void _bind_methods() { + + ClassDB::bind_method("_update_obj", &AnimationTrackKeyEdit::_update_obj); + ClassDB::bind_method("_key_ofs_changed", &AnimationTrackKeyEdit::_key_ofs_changed); + ClassDB::bind_method("_hide_script_from_inspector", &AnimationTrackKeyEdit::_hide_script_from_inspector); + } + + //PopupDialog *ke_dialog; + + void _fix_node_path(Variant &value) { + + NodePath np = value; + + if (np == NodePath()) + return; + + Node *root = EditorNode::get_singleton()->get_tree()->get_root(); + + Node *np_node = root->get_node(np); + ERR_FAIL_COND(!np_node); + + Node *edited_node = root->get_node(base); + ERR_FAIL_COND(!edited_node); + + value = edited_node->get_path_to(np_node); + } + + void _update_obj(const Ref<Animation> &p_anim) { + if (setting) + return; + if (hidden) + return; + if (!(animation == p_anim)) + return; + notify_change(); + } + + void _key_ofs_changed(const Ref<Animation> &p_anim, float from, float to) { + if (hidden) + return; + if (!(animation == p_anim)) + return; + if (from != key_ofs) + return; + key_ofs = to; + if (setting) + return; + notify_change(); + } + + bool _set(const StringName &p_name, const Variant &p_value) { + + int key = animation->track_find_key(track, key_ofs, true); + ERR_FAIL_COND_V(key == -1, false); + + String name = p_name; + if (name == "time") { + + float new_time = p_value; + if (new_time == key_ofs) + return true; + + int existing = animation->track_find_key(track, new_time, true); + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Time"), UndoRedo::MERGE_ENDS); + + Variant val = animation->track_get_key_value(track, key); + float trans = animation->track_get_key_transition(track, key); + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", track, key); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, new_time, val, trans); + undo_redo->add_do_method(this, "_key_ofs_changed", animation, key_ofs, new_time); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", track, new_time); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, key_ofs, val, trans); + undo_redo->add_undo_method(this, "_key_ofs_changed", animation, new_time, key_ofs); + + if (existing != -1) { + Variant v = animation->track_get_key_value(track, existing); + float trans = animation->track_get_key_transition(track, existing); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, new_time, v, trans); + } + + undo_redo->commit_action(); + setting = false; + + return true; + } else if (name == "easing") { + + float val = p_value; + float prev_val = animation->track_get_key_transition(track, key); + setting = true; + undo_redo->create_action(TTR("Anim Change Transition"), UndoRedo::MERGE_ENDS); + undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", track, key, val); + undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", track, key, prev_val); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + + switch (animation->track_get_type(track)) { + + case Animation::TYPE_TRANSFORM: { + + Dictionary d_old = animation->track_get_key_value(track, key); + Dictionary d_new = d_old; + d_new[p_name] = p_value; + setting = true; + undo_redo->create_action(TTR("Anim Change Transform")); + undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new); + undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + + } break; + case Animation::TYPE_VALUE: { + + if (name == "value") { + + Variant value = p_value; + + if (value.get_type() == Variant::NODE_PATH) { + + _fix_node_path(value); + } + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + Variant prev = animation->track_get_key_value(track, key); + undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + + } break; + case Animation::TYPE_METHOD: { + + Dictionary d_old = animation->track_get_key_value(track, key); + Dictionary d_new = d_old; + + bool change_notify_deserved = false; + bool mergeable = false; + + if (name == "name") { + + d_new["method"] = p_value; + } + + if (name == "arg_count") { + + Vector<Variant> args = d_old["args"]; + args.resize(p_value); + d_new["args"] = args; + change_notify_deserved = true; + } + + if (name.begins_with("args/")) { + + Vector<Variant> args = d_old["args"]; + int idx = name.get_slice("/", 1).to_int(); + ERR_FAIL_INDEX_V(idx, args.size(), false); + + String what = name.get_slice("/", 2); + if (what == "type") { + Variant::Type t = Variant::Type(int(p_value)); + + if (t != args[idx].get_type()) { + Variant::CallError err; + if (Variant::can_convert(args[idx].get_type(), t)) { + Variant old = args[idx]; + Variant *ptrs[1] = { &old }; + args[idx] = Variant::construct(t, (const Variant **)ptrs, 1, err); + } else { + + args[idx] = Variant::construct(t, NULL, 0, err); + } + change_notify_deserved = true; + d_new["args"] = args; + } + } + if (what == "value") { + + Variant value = p_value; + if (value.get_type() == Variant::NODE_PATH) { + + _fix_node_path(value); + } + + args[idx] = value; + d_new["args"] = args; + mergeable = true; + } + } + + if (mergeable) + undo_redo->create_action(TTR("Anim Change Call"), UndoRedo::MERGE_ENDS); + else + undo_redo->create_action(TTR("Anim Change Call")); + + Variant prev = animation->track_get_key_value(track, key); + setting = true; + undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new); + undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + if (change_notify_deserved) + notify_change(); + return true; + } break; + case Animation::TYPE_BEZIER: { + + if (name == "value") { + + Variant value = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + float prev = animation->bezier_track_get_key_value(track, key); + undo_redo->add_do_method(animation.ptr(), "bezier_track_set_key_value", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_key_value", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + if (name == "in_handle") { + + Variant value = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + Vector2 prev = animation->bezier_track_get_key_in_handle(track, key); + undo_redo->add_do_method(animation.ptr(), "bezier_track_set_in_handle", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_in_handle", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + if (name == "out_handle") { + + Variant value = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + Vector2 prev = animation->bezier_track_get_key_out_handle(track, key); + undo_redo->add_do_method(animation.ptr(), "bezier_track_set_out_handle", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "bezier_track_set_out_handle", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + + } break; + case Animation::TYPE_AUDIO: { + + if (name == "stream") { + + Ref<AudioStream> stream = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + RES prev = animation->audio_track_get_key_stream(track, key); + undo_redo->add_do_method(animation.ptr(), "audio_track_set_key_stream", track, key, stream); + undo_redo->add_undo_method(animation.ptr(), "audio_track_set_key_stream", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + if (name == "start_offset") { + + float value = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + float prev = animation->audio_track_get_key_start_offset(track, key); + undo_redo->add_do_method(animation.ptr(), "audio_track_set_key_start_offset", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "audio_track_set_key_start_offset", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + if (name == "end_offset") { + + float value = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + float prev = animation->audio_track_get_key_end_offset(track, key); + undo_redo->add_do_method(animation.ptr(), "audio_track_set_key_end_offset", track, key, value); + undo_redo->add_undo_method(animation.ptr(), "audio_track_set_key_end_offset", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + + } break; + case Animation::TYPE_ANIMATION: { + + if (name == "animation") { + + StringName name = p_value; + + setting = true; + undo_redo->create_action(TTR("Anim Change Keyframe Value"), UndoRedo::MERGE_ENDS); + StringName prev = animation->animation_track_get_key_animation(track, key); + undo_redo->add_do_method(animation.ptr(), "animation_track_set_key_animation", track, key, name); + undo_redo->add_undo_method(animation.ptr(), "animation_track_set_key_animation", track, key, prev); + undo_redo->add_do_method(this, "_update_obj", animation); + undo_redo->add_undo_method(this, "_update_obj", animation); + undo_redo->commit_action(); + setting = false; + return true; + } + + } break; + } + + return false; + } + + bool _get(const StringName &p_name, Variant &r_ret) const { + + int key = animation->track_find_key(track, key_ofs, true); + ERR_FAIL_COND_V(key == -1, false); + + String name = p_name; + if (name == "time") { + r_ret = key_ofs; + return true; + } else if (name == "easing") { + r_ret = animation->track_get_key_transition(track, key); + return true; + } + + switch (animation->track_get_type(track)) { + + case Animation::TYPE_TRANSFORM: { + + Dictionary d = animation->track_get_key_value(track, key); + ERR_FAIL_COND_V(!d.has(name), false); + r_ret = d[p_name]; + return true; + + } break; + case Animation::TYPE_VALUE: { + + if (name == "value") { + r_ret = animation->track_get_key_value(track, key); + return true; + } + + } break; + case Animation::TYPE_METHOD: { + + Dictionary d = animation->track_get_key_value(track, key); + + if (name == "name") { + + ERR_FAIL_COND_V(!d.has("method"), false); + r_ret = d["method"]; + return true; + } + + ERR_FAIL_COND_V(!d.has("args"), false); + + Vector<Variant> args = d["args"]; + + if (name == "arg_count") { + + r_ret = args.size(); + return true; + } + + if (name.begins_with("args/")) { + + int idx = name.get_slice("/", 1).to_int(); + ERR_FAIL_INDEX_V(idx, args.size(), false); + + String what = name.get_slice("/", 2); + if (what == "type") { + r_ret = args[idx].get_type(); + return true; + } + if (what == "value") { + r_ret = args[idx]; + return true; + } + } + + } break; + case Animation::TYPE_BEZIER: { + + if (name == "value") { + r_ret = animation->bezier_track_get_key_value(track, key); + return true; + } + if (name == "in_handle") { + r_ret = animation->bezier_track_get_key_in_handle(track, key); + return true; + } + if (name == "out_handle") { + r_ret = animation->bezier_track_get_key_out_handle(track, key); + return true; + } + + } break; + case Animation::TYPE_AUDIO: { + + if (name == "stream") { + r_ret = animation->audio_track_get_key_stream(track, key); + return true; + } + if (name == "start_offset") { + r_ret = animation->audio_track_get_key_start_offset(track, key); + return true; + } + if (name == "end_offset") { + r_ret = animation->audio_track_get_key_end_offset(track, key); + return true; + } + + } break; + case Animation::TYPE_ANIMATION: { + + if (name == "animation") { + r_ret = animation->animation_track_get_key_animation(track, key); + return true; + } + + } break; + } + + return false; + } + void _get_property_list(List<PropertyInfo> *p_list) const { + + if (animation.is_null()) + return; + + ERR_FAIL_INDEX(track, animation->get_track_count()); + int key = animation->track_find_key(track, key_ofs, true); + ERR_FAIL_COND(key == -1); + + p_list->push_back(PropertyInfo(Variant::REAL, "time", PROPERTY_HINT_RANGE, "0," + rtos(animation->get_length()) + ",0.01")); + + switch (animation->track_get_type(track)) { + + case Animation::TYPE_TRANSFORM: { + + p_list->push_back(PropertyInfo(Variant::VECTOR3, "location")); + p_list->push_back(PropertyInfo(Variant::QUAT, "rotation")); + p_list->push_back(PropertyInfo(Variant::VECTOR3, "scale")); + + } break; + case Animation::TYPE_VALUE: { + + Variant v = animation->track_get_key_value(track, key); + + if (hint.type != Variant::NIL) { + + PropertyInfo pi = hint; + pi.name = "value"; + p_list->push_back(pi); + } else { + + PropertyHint hint = PROPERTY_HINT_NONE; + String hint_string; + + if (v.get_type() == Variant::OBJECT) { + //could actually check the object property if exists..? yes i will! + Ref<Resource> res = v; + if (res.is_valid()) { + + hint = PROPERTY_HINT_RESOURCE_TYPE; + hint_string = res->get_class(); + } + } + + if (v.get_type() != Variant::NIL) + p_list->push_back(PropertyInfo(v.get_type(), "value", hint, hint_string)); + } + + } break; + case Animation::TYPE_METHOD: { + + p_list->push_back(PropertyInfo(Variant::STRING, "name")); + p_list->push_back(PropertyInfo(Variant::INT, "arg_count", PROPERTY_HINT_RANGE, "0,5,1")); + + Dictionary d = animation->track_get_key_value(track, key); + ERR_FAIL_COND(!d.has("args")); + Vector<Variant> args = d["args"]; + String vtypes; + for (int i = 0; i < Variant::VARIANT_MAX; i++) { + + if (i > 0) + vtypes += ","; + vtypes += Variant::get_type_name(Variant::Type(i)); + } + + for (int i = 0; i < args.size(); i++) { + + p_list->push_back(PropertyInfo(Variant::INT, "args/" + itos(i) + "/type", PROPERTY_HINT_ENUM, vtypes)); + if (args[i].get_type() != Variant::NIL) + p_list->push_back(PropertyInfo(args[i].get_type(), "args/" + itos(i) + "/value")); + } + + } break; + case Animation::TYPE_BEZIER: { + + p_list->push_back(PropertyInfo(Variant::REAL, "value")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "in_handle")); + p_list->push_back(PropertyInfo(Variant::VECTOR2, "out_handle")); + + } break; + case Animation::TYPE_AUDIO: { + + p_list->push_back(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream")); + p_list->push_back(PropertyInfo(Variant::REAL, "start_offset", PROPERTY_HINT_RANGE, "0,3600,0.01,or_greater")); + p_list->push_back(PropertyInfo(Variant::REAL, "end_offset", PROPERTY_HINT_RANGE, "0,3600,0.01,or_greater")); + + } break; + case Animation::TYPE_ANIMATION: { + + String animations; + + if (root_path && root_path->has_node(animation->track_get_path(track))) { + + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(root_path->get_node(animation->track_get_path(track))); + if (ap) { + List<StringName> anims; + ap->get_animation_list(&anims); + for (List<StringName>::Element *E = anims.front(); E; E = E->next()) { + if (animations != String()) { + animations += ","; + } + + animations += String(E->get()); + } + } + } + + if (animations != String()) { + animations += ","; + } + animations += "[stop]"; + + p_list->push_back(PropertyInfo(Variant::STRING, "animation", PROPERTY_HINT_ENUM, animations)); + + } break; + } + + if (animation->track_get_type(track) == Animation::TYPE_VALUE) { + p_list->push_back(PropertyInfo(Variant::REAL, "easing", PROPERTY_HINT_EXP_EASING)); + } + } + + UndoRedo *undo_redo; + Ref<Animation> animation; + int track; + float key_ofs; + Node *root_path; + + PropertyInfo hint; + NodePath base; + + void notify_change() { + + _change_notify(); + } + + AnimationTrackKeyEdit() { + hidden = true; + key_ofs = 0; + track = -1; + setting = false; + root_path = NULL; + } +}; + +void AnimationTimelineEdit::_zoom_changed(double) { + + update(); + emit_signal("zoom_changed"); +} + +float AnimationTimelineEdit::get_zoom_scale() const { + + float zv = zoom->get_value(); + if (zv < 1) { + zv = 1.0 - zv; + return Math::pow(1.0f + zv, 8.0f) * 100; + } else { + return 1.0 / Math::pow(zv, 8.0f) * 100; + } +} + +void AnimationTimelineEdit::_anim_length_changed(double p_new_len) { + + if (editing) + return; + + editing = true; + *block_animation_update_ptr = true; + undo_redo->create_action("Change animation length"); + undo_redo->add_do_method(animation.ptr(), "set_length", p_new_len); + undo_redo->add_undo_method(animation.ptr(), "set_length", animation->get_length()); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + editing = false; + update(); + + emit_signal("length_changed", p_new_len); +} + +void AnimationTimelineEdit::_anim_loop_pressed() { + + *block_animation_update_ptr = true; + undo_redo->create_action("Change animation loop"); + undo_redo->add_do_method(animation.ptr(), "set_loop", loop->is_pressed()); + undo_redo->add_undo_method(animation.ptr(), "set_loop", animation->has_loop()); + undo_redo->commit_action(); + *block_animation_update_ptr = false; +} + +int AnimationTimelineEdit::get_buttons_width() const { + + Ref<Texture> interp_mode = get_icon("TrackContinuous", "EditorIcons"); + Ref<Texture> interp_type = get_icon("InterpRaw", "EditorIcons"); + Ref<Texture> loop_type = get_icon("InterpWrapClamp", "EditorIcons"); + Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons"); + Ref<Texture> down_icon = get_icon("select_arrow", "Tree"); + + int total_w = interp_mode->get_width() + interp_type->get_width() + loop_type->get_width() + remove_icon->get_width(); + total_w += (down_icon->get_width() + 4 * EDSCALE) * 4; + + return total_w; +} + +int AnimationTimelineEdit::get_name_limit() const { + + Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons"); + + int limit = MAX(name_limit, add_track->get_minimum_size().width + hsize_icon->get_width()); + + limit = MIN(limit, get_size().width - get_buttons_width() - 1); + + return limit; +} + +void AnimationTimelineEdit::_notification(int p_what) { + + if (p_what == NOTIFICATION_ENTER_TREE) { + add_track->set_icon(get_icon("Add", "EditorIcons")); + loop->set_icon(get_icon("Loop", "EditorIcons")); + time_icon->set_texture(get_icon("Time", "EditorIcons")); + + add_track->get_popup()->clear(); + add_track->get_popup()->add_icon_item(get_icon("KeyValue", "EditorIcons"), TTR("Property Track")); + add_track->get_popup()->add_icon_item(get_icon("KeyXform", "EditorIcons"), TTR("3D Transform Track")); + add_track->get_popup()->add_icon_item(get_icon("KeyCall", "EditorIcons"), TTR("Call Method Track")); + add_track->get_popup()->add_icon_item(get_icon("KeyBezier", "EditorIcons"), TTR("Bezier Curve Track")); + add_track->get_popup()->add_icon_item(get_icon("KeyAudio", "EditorIcons"), TTR("Audio Playback Track")); + add_track->get_popup()->add_icon_item(get_icon("KeyAnimation", "EditorIcons"), TTR("Animation Playback Track")); + } + + if (p_what == NOTIFICATION_RESIZED) { + len_hb->set_position(Vector2(get_size().width - get_buttons_width(), 0)); + len_hb->set_size(Size2(get_buttons_width(), get_size().height)); + } + if (p_what == NOTIFICATION_DRAW) { + + int key_range = get_size().width - get_buttons_width() - get_name_limit(); + + if (!animation.is_valid()) + return; + + Ref<Font> font = get_font("font", "Label"); + Color color = get_color("font_color", "Label"); + + int zoomw = key_range; + float scale = get_zoom_scale(); + int h = get_size().height; + + float l = animation->get_length(); + if (l <= 0) + l = 0.001; //avoid crashor + + int end_px = (l - get_value()) * scale; + int begin_px = -get_value() * scale; + Color notimecol = get_color("dark_color_2", "Editor"); + Color timecolor = color; + timecolor.a = 0.2; + Color linecolor = color; + linecolor.a = 0.2; + + { + + draw_rect(Rect2(Point2(get_name_limit(), 0), Point2(zoomw - 1, h)), notimecol); + + if (begin_px < zoomw && end_px > 0) { + + if (begin_px < 0) + begin_px = 0; + if (end_px > zoomw) + end_px = zoomw; + + draw_rect(Rect2(Point2(get_name_limit() + begin_px, 0), Point2(end_px - begin_px - 1, h)), timecolor); + } + } + + Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons"); + hsize_rect = Rect2(get_name_limit() - hsize_icon->get_width() - 2 * EDSCALE, (get_size().height - hsize_icon->get_height()) / 2, hsize_icon->get_width(), hsize_icon->get_height()); + draw_texture(hsize_icon, hsize_rect.position); + + float keys_from = get_value(); + float keys_to = keys_from + zoomw / scale; + + { + float time_min = 0; + float time_max = animation->get_length(); + for (int i = 0; i < animation->get_track_count(); i++) { + + if (animation->track_get_key_count(i) > 0) { + + float beg = animation->track_get_key_time(i, 0); + if (animation->track_get_type(i) == Animation::TYPE_BEZIER) { + beg += animation->bezier_track_get_key_in_handle(i, 0).x; + } + + if (beg < time_min) + time_min = beg; + + float end = animation->track_get_key_time(i, animation->track_get_key_count(i) - 1); + if (animation->track_get_type(i) == Animation::TYPE_BEZIER) { + end += animation->bezier_track_get_key_out_handle(i, animation->track_get_key_count(i) - 1).x; + } + + if (end > time_max) + time_max = end; + } + } + + float extra = (zoomw / scale) * 0.5; + + //if (time_min < -0.001) + // time_min -= extra; + time_max += extra; + set_min(time_min); + set_max(time_max); + + if (zoomw / scale < (time_max - time_min)) { + hscroll->show(); + + } else { + + hscroll->hide(); + } + } + + set_page(zoomw / scale); + + Color color_time_sec = color; + Color color_time_dec = color; + color_time_dec.a *= 0.5; +#define SC_ADJ 100 + int min = 30; + int dec = 1; + int step = 1; + int decimals = 2; + bool step_found = false; + + const int period_width = font->get_char_size('.').width; + int max_digit_width = font->get_char_size('0').width; + for (int i = 1; i <= 9; i++) { + const int digit_width = font->get_char_size('0' + i).width; + max_digit_width = MAX(digit_width, max_digit_width); + } + const int max_sc = int(Math::ceil(zoomw / scale)); + const int max_sc_width = String::num(max_sc).length() * max_digit_width; + + while (!step_found) { + + min = max_sc_width; + if (decimals > 0) + min += period_width + max_digit_width * decimals; + + static const int _multp[3] = { 1, 2, 5 }; + for (int i = 0; i < 3; i++) { + + step = (_multp[i] * dec); + if (step * scale / SC_ADJ > min) { + step_found = true; + break; + } + } + if (step_found) + break; + dec *= 10; + decimals--; + if (decimals < 0) + decimals = 0; + } + + for (int i = 0; i < zoomw; i++) { + + float pos = get_value() + double(i) / scale; + float prev = get_value() + (double(i) - 1.0) / scale; + + int sc = int(Math::floor(pos * SC_ADJ)); + int prev_sc = int(Math::floor(prev * SC_ADJ)); + bool sub = (sc % SC_ADJ); + + if ((sc / step) != (prev_sc / step) || (prev_sc < 0 && sc >= 0)) { + + int scd = sc < 0 ? prev_sc : sc; + draw_line(Point2(get_name_limit() + i, 0), Point2(get_name_limit() + i, h), linecolor); + draw_string(font, Point2(get_name_limit() + i + 3, (h - font->get_height()) / 2 + font->get_ascent()).floor(), String::num((scd - (scd % step)) / double(SC_ADJ), decimals), sub ? color_time_dec : color_time_sec, zoomw - i); + } + } + + draw_line(Vector2(0, get_size().height), get_size(), linecolor); + } +} + +void AnimationTimelineEdit::set_animation(const Ref<Animation> &p_animation) { + animation = p_animation; + if (animation.is_valid()) { + len_hb->show(); + add_track->show(); + } else { + len_hb->hide(); + add_track->hide(); + } + update(); + update_values(); +} + +Size2 AnimationTimelineEdit::get_minimum_size() const { + + Size2 ms = add_track->get_minimum_size(); + Ref<Font> font = get_font("font", "Label"); + ms.height = MAX(ms.height, font->get_height()); + ms.width = get_buttons_width() + add_track->get_minimum_size().width + get_icon("Hsize", "EditorIcons")->get_width() + 2; + return ms; +} + +void AnimationTimelineEdit::set_block_animation_update_ptr(bool *p_block_ptr) { + block_animation_update_ptr = p_block_ptr; +} + +void AnimationTimelineEdit::set_undo_redo(UndoRedo *p_undo_redo) { + undo_redo = p_undo_redo; +} + +void AnimationTimelineEdit::set_zoom(Range *p_zoom) { + zoom = p_zoom; + zoom->connect("value_changed", this, "_zoom_changed"); +} + +void AnimationTimelineEdit::set_play_position(float p_pos) { + + play_position_pos = p_pos; + play_position->update(); +} + +float AnimationTimelineEdit::get_play_position() const { + return play_position_pos; +} + +void AnimationTimelineEdit::update_play_position() { + play_position->update(); +} + +void AnimationTimelineEdit::update_values() { + + if (!animation.is_valid() || editing) + return; + + editing = true; + length->set_value(animation->get_length()); + loop->set_pressed(animation->has_loop()); + editing = false; +} + +void AnimationTimelineEdit::_play_position_draw() { + + if (!animation.is_valid() || play_position_pos < 0) + return; + + float scale = get_zoom_scale(); + int h = play_position->get_size().height; + + int px = (-get_value() + play_position_pos) * scale + get_name_limit(); + + if (px >= get_name_limit() && px < (play_position->get_size().width - get_buttons_width())) { + Color color = get_color("accent_color", "Editor"); + play_position->draw_line(Point2(px, 0), Point2(px, h), color); + } +} + +void AnimationTimelineEdit::_gui_input(const Ref<InputEvent> &p_event) { + + Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && hsize_rect.has_point(mb->get_position())) { + + dragging_hsize = true; + dragging_hsize_from = mb->get_position().x; + dragging_hsize_at = name_limit; + } + + if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && dragging_hsize) { + dragging_hsize = false; + } + if (mb.is_valid() && mb->get_position().x > get_name_limit() && mb->get_position().x < (get_size().width - get_buttons_width())) { + + if (!panning_timeline && mb->get_button_index() == BUTTON_LEFT) { + int x = mb->get_position().x - get_name_limit(); + + float ofs = x / get_zoom_scale(); + emit_signal("timeline_changed", ofs, false); + dragging_timeline = true; + } + if (!dragging_timeline && mb->get_button_index() == BUTTON_MIDDLE) { + int x = mb->get_position().x - get_name_limit(); + panning_timeline_from = x / get_zoom_scale(); + panning_timeline = true; + panning_timeline_at = get_value(); + } + } + + if (dragging_timeline && mb.is_valid() && mb->get_button_index() == BUTTON_LEFT && !mb->is_pressed()) { + dragging_timeline = false; + } + + if (panning_timeline && mb.is_valid() && mb->get_button_index() == BUTTON_MIDDLE && !mb->is_pressed()) { + panning_timeline = false; + } + + Ref<InputEventMouseMotion> mm = p_event; + + if (mm.is_valid()) { + + if (dragging_hsize) { + int ofs = mm->get_position().x - dragging_hsize_from; + name_limit = dragging_hsize_at + ofs; + update(); + emit_signal("name_limit_changed"); + play_position->update(); + } + if (dragging_timeline) { + int x = mm->get_position().x - get_name_limit(); + float ofs = x / get_zoom_scale(); + emit_signal("timeline_changed", ofs, false); + } + if (panning_timeline) { + int x = mm->get_position().x - get_name_limit(); + float ofs = x / get_zoom_scale(); + float diff = ofs - panning_timeline_from; + set_value(panning_timeline_at - diff); + } + } +} + +void AnimationTimelineEdit::set_hscroll(HScrollBar *p_hscroll) { + + hscroll = p_hscroll; +} + +void AnimationTimelineEdit::_track_added(int p_track) { + emit_signal("track_added", p_track); +} + +void AnimationTimelineEdit::_bind_methods() { + ClassDB::bind_method("_zoom_changed", &AnimationTimelineEdit::_zoom_changed); + ClassDB::bind_method("_anim_length_changed", &AnimationTimelineEdit::_anim_length_changed); + ClassDB::bind_method("_anim_loop_pressed", &AnimationTimelineEdit::_anim_loop_pressed); + ClassDB::bind_method("_play_position_draw", &AnimationTimelineEdit::_play_position_draw); + ClassDB::bind_method("_gui_input", &AnimationTimelineEdit::_gui_input); + ClassDB::bind_method("_track_added", &AnimationTimelineEdit::_track_added); + + ADD_SIGNAL(MethodInfo("zoom_changed")); + ADD_SIGNAL(MethodInfo("name_limit_changed")); + ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag"))); + ADD_SIGNAL(MethodInfo("track_added", PropertyInfo(Variant::INT, "track"))); + ADD_SIGNAL(MethodInfo("length_changed", PropertyInfo(Variant::REAL, "size"))); +} + +AnimationTimelineEdit::AnimationTimelineEdit() { + + block_animation_update_ptr = NULL; + editing = false; + name_limit = 150; + zoom = NULL; + + play_position_pos = 0; + play_position = memnew(Control); + play_position->set_mouse_filter(MOUSE_FILTER_PASS); + add_child(play_position); + play_position->set_anchors_and_margins_preset(PRESET_WIDE); + play_position->connect("draw", this, "_play_position_draw"); + + add_track = memnew(MenuButton); + add_track->set_position(Vector2(0, 0)); + add_child(add_track); + add_track->set_text(TTR("Add Track")); + + len_hb = memnew(HBoxContainer); + + Control *expander = memnew(Control); + expander->set_h_size_flags(SIZE_EXPAND_FILL); + len_hb->add_child(expander); + time_icon = memnew(TextureRect); + time_icon->set_v_size_flags(SIZE_SHRINK_CENTER); + time_icon->set_tooltip(TTR("Animation Length Time (seconds)")); + len_hb->add_child(time_icon); + length = memnew(EditorSpinSlider); + length->set_min(0); + length->set_max(3600); + length->set_step(0.01); + length->set_allow_greater(true); + length->set_custom_minimum_size(Vector2(70 * EDSCALE, 0)); + length->set_hide_slider(true); + length->set_tooltip(TTR("Animation Length Time (seconds)")); + length->connect("value_changed", this, "_anim_length_changed"); + len_hb->add_child(length); + loop = memnew(ToolButton); + loop->set_tooltip(TTR("Animation Looping")); + loop->connect("pressed", this, "_anim_loop_pressed"); + loop->set_toggle_mode(true); + len_hb->add_child(loop); + add_child(len_hb); + + add_track->hide(); + add_track->get_popup()->connect("index_pressed", this, "_track_added"); + len_hb->hide(); + + panning_timeline = false; + dragging_timeline = false; + dragging_hsize = false; +} + +//////////////////////////////////// + +void AnimationTrackEdit::_notification(int p_what) { + if (p_what == NOTIFICATION_DRAW) { + if (animation.is_null()) + return; + ERR_FAIL_INDEX(track, animation->get_track_count()); + + int limit = timeline->get_name_limit(); + + if (has_focus()) { + Color accent = get_color("accent_color", "Editor"); + accent.a *= 0.7; + draw_rect(Rect2(Point2(), get_size()), accent, false); + } + + Ref<Font> font = get_font("font", "Label"); + Color color = get_color("font_color", "Label"); + Ref<Texture> type_icons[6] = { + get_icon("KeyValue", "EditorIcons"), + get_icon("KeyXform", "EditorIcons"), + get_icon("KeyCall", "EditorIcons"), + get_icon("KeyBezier", "EditorIcons"), + get_icon("KeyAudio", "EditorIcons"), + get_icon("KeyAnimation", "EditorIcons") + }; + int hsep = get_constant("hseparation", "ItemList"); + Color linecolor = color; + linecolor.a = 0.2; + + // NAMES AND ICONS // + + { + + Ref<Texture> check = animation->track_is_enabled(track) ? get_icon("checked", "CheckBox") : get_icon("unchecked", "CheckBox"); + + int ofs = in_group ? check->get_width() : 0; //not the best reference for margin but.. + + check_rect = Rect2(Point2(ofs, int(get_size().height - check->get_height()) / 2), check->get_size()); + + draw_texture(check, check_rect.position); + + ofs += check->get_width() + hsep; + + Ref<Texture> type_icon = type_icons[animation->track_get_type(track)]; + + draw_texture(type_icon, Point2(ofs, int(get_size().height - type_icon->get_height()) / 2)); + ofs += type_icon->get_width() + hsep; + + NodePath path = animation->track_get_path(track); + + Node *node = NULL; + + if (root && root->has_node(path)) { + node = root->get_node(path); + } + + String text; + Color text_color = color; + if (node && EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { + text_color = get_color("accent_color", "Editor"); + } + + if (in_group) { + + if (animation->track_get_type(track) == Animation::TYPE_METHOD) { + text = TTR("Functions:"); + } else if (animation->track_get_type(track) == Animation::TYPE_AUDIO) { + text = TTR("Audio Clips:"); + } else if (animation->track_get_type(track) == Animation::TYPE_ANIMATION) { + text = TTR("Anim Clips:"); + } else { + Vector<StringName> sn = path.get_subnames(); + for (int i = 0; i < sn.size(); i++) { + if (i > 0) { + text += "."; + } + text += sn[i]; + } + } + text_color.a *= 0.7; + } else if (node) { + Ref<Texture> icon; + if (has_icon(node->get_class(), "EditorIcons")) { + icon = get_icon(node->get_class(), "EditorIcons"); + } else { + icon = get_icon("Node", "EditorIcons"); + } + + draw_texture(icon, Point2(ofs, int(get_size().height - icon->get_height()) / 2)); + icon_cache = icon; + + text = node->get_name(); + ofs += hsep; + ofs += icon->get_width(); + Vector<StringName> sn = path.get_subnames(); + for (int i = 0; i < sn.size(); i++) { + text += "."; + text += sn[i]; + } + } else { + icon_cache = type_icon; + + text = path; + } + + path_cache = text; + + path_rect = Rect2(ofs, 0, limit - ofs - hsep, get_size().height); + + Vector2 string_pos = Point2(ofs, (get_size().height - font->get_height()) / 2 + font->get_ascent()); + string_pos = string_pos.floor(); + draw_string(font, string_pos, text, text_color, limit - ofs - hsep); + + draw_line(Point2(limit, 0), Point2(limit, get_size().height), linecolor); + } + + // KEYFAMES // + + draw_bg(limit, get_size().width - timeline->get_buttons_width()); + + { + + float scale = timeline->get_zoom_scale(); + int limit_end = get_size().width - timeline->get_buttons_width(); + + for (int i = 0; i < animation->track_get_key_count(track); i++) { + + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + if (editor->is_key_selected(track, i) && editor->is_moving_selection()) { + offset += editor->get_moving_selection_offset(); + } + offset = offset * scale + limit; + if (i < animation->track_get_key_count(track) - 1) { + + float offset_n = animation->track_get_key_time(track, i + 1) - timeline->get_value(); + if (editor->is_key_selected(track, i + 1) && editor->is_moving_selection()) { + offset_n += editor->get_moving_selection_offset(); + } + offset_n = offset_n * scale + limit; + + draw_key_link(i, scale, int(offset), int(offset_n), limit, limit_end); + } + + draw_key(i, scale, int(offset), editor->is_key_selected(track, i), limit, limit_end); + } + } + + draw_fg(limit, get_size().width - timeline->get_buttons_width()); + + // BUTTONS // + { + + Ref<Texture> wrap_icon[2] = { + get_icon("InterpWrapClamp", "EditorIcons"), + get_icon("InterpWrapLoop", "EditorIcons"), + }; + + Ref<Texture> interp_icon[3] = { + get_icon("InterpRaw", "EditorIcons"), + get_icon("InterpLinear", "EditorIcons"), + get_icon("InterpCubic", "EditorIcons") + }; + Ref<Texture> cont_icon[4] = { + get_icon("TrackContinuous", "EditorIcons"), + get_icon("TrackDiscrete", "EditorIcons"), + get_icon("TrackTrigger", "EditorIcons"), + get_icon("TrackCapture", "EditorIcons") + }; + + int ofs = get_size().width - timeline->get_buttons_width(); + + Ref<Texture> down_icon = get_icon("select_arrow", "Tree"); + + draw_line(Point2(ofs, 0), Point2(ofs, get_size().height), linecolor); + + ofs += hsep; + { + //callmode + + Animation::UpdateMode update_mode; + + if (animation->track_get_type(track) == Animation::TYPE_VALUE) { + update_mode = animation->value_track_get_update_mode(track); + } else { + update_mode = Animation::UPDATE_CONTINUOUS; + } + + Ref<Texture> update_icon = cont_icon[update_mode]; + + update_mode_rect.position.x = ofs; + update_mode_rect.position.y = int(get_size().height - update_icon->get_height()) / 2; + update_mode_rect.size = update_icon->get_size(); + + if (animation->track_get_type(track) == Animation::TYPE_VALUE) { + draw_texture(update_icon, update_mode_rect.position); + } + //make it easier to click + update_mode_rect.position.y = 0; + update_mode_rect.size.y = get_size().height; + + ofs += update_icon->get_width() + hsep; + update_mode_rect.size.x += hsep; + + if (animation->track_get_type(track) == Animation::TYPE_VALUE) { + draw_texture(down_icon, Vector2(ofs, int(get_size().height - down_icon->get_height()) / 2)); + update_mode_rect.size.x += down_icon->get_width(); + bezier_edit_rect = Rect2(); + } else if (animation->track_get_type(track) == Animation::TYPE_BEZIER) { + Ref<Texture> bezier_icon = get_icon("EditBezier", "EditorIcons"); + update_mode_rect.size.x += down_icon->get_width(); + bezier_edit_rect.position = update_mode_rect.position + (update_mode_rect.size - bezier_icon->get_size()) / 2; + bezier_edit_rect.size = bezier_icon->get_size(); + draw_texture(bezier_icon, bezier_edit_rect.position); + update_mode_rect = Rect2(); + } else { + update_mode_rect = Rect2(); + bezier_edit_rect = Rect2(); + } + + ofs += down_icon->get_width(); + draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor); + ofs += hsep; + } + + { + //interp + + Animation::InterpolationType interp_mode = animation->track_get_interpolation_type(track); + + Ref<Texture> icon = interp_icon[interp_mode]; + + interp_mode_rect.position.x = ofs; + interp_mode_rect.position.y = int(get_size().height - icon->get_height()) / 2; + interp_mode_rect.size = icon->get_size(); + + if (animation->track_get_type(track) == Animation::TYPE_VALUE || animation->track_get_type(track) == Animation::TYPE_TRANSFORM) { + draw_texture(icon, interp_mode_rect.position); + } + //make it easier to click + interp_mode_rect.position.y = 0; + interp_mode_rect.size.y = get_size().height; + + ofs += icon->get_width() + hsep; + interp_mode_rect.size.x += hsep; + + if (animation->track_get_type(track) == Animation::TYPE_VALUE || animation->track_get_type(track) == Animation::TYPE_TRANSFORM) { + draw_texture(down_icon, Vector2(ofs, int(get_size().height - down_icon->get_height()) / 2)); + interp_mode_rect.size.x += down_icon->get_width(); + } else { + interp_mode_rect = Rect2(); + } + + ofs += down_icon->get_width(); + draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor); + ofs += hsep; + } + + { + //loop + + bool loop_wrap = animation->track_get_interpolation_loop_wrap(track); + + Ref<Texture> icon = wrap_icon[loop_wrap ? 1 : 0]; + + loop_mode_rect.position.x = ofs; + loop_mode_rect.position.y = int(get_size().height - icon->get_height()) / 2; + loop_mode_rect.size = icon->get_size(); + + if (animation->track_get_type(track) == Animation::TYPE_VALUE || animation->track_get_type(track) == Animation::TYPE_TRANSFORM) { + draw_texture(icon, loop_mode_rect.position); + } + + loop_mode_rect.position.y = 0; + loop_mode_rect.size.y = get_size().height; + + ofs += icon->get_width() + hsep; + loop_mode_rect.size.x += hsep; + + if (animation->track_get_type(track) == Animation::TYPE_VALUE || animation->track_get_type(track) == Animation::TYPE_TRANSFORM) { + draw_texture(down_icon, Vector2(ofs, int(get_size().height - down_icon->get_height()) / 2)); + loop_mode_rect.size.x += down_icon->get_width(); + } else { + loop_mode_rect = Rect2(); + } + + ofs += down_icon->get_width(); + draw_line(Point2(ofs + hsep * 0.5, 0), Point2(ofs + hsep * 0.5, get_size().height), linecolor); + ofs += hsep; + } + + { + //erase + + Ref<Texture> icon = get_icon("Remove", "EditorIcons"); + + remove_rect.position.x = ofs + ((get_size().width - ofs) - icon->get_width()) / 2; + remove_rect.position.y = int(get_size().height - icon->get_height()) / 2; + remove_rect.size = icon->get_size(); + + draw_texture(icon, remove_rect.position); + } + } + + if (in_group) { + draw_line(Vector2(timeline->get_name_limit(), get_size().height), get_size(), linecolor); + } else { + draw_line(Vector2(0, get_size().height), get_size(), linecolor); + } + + if (dropping_at != 0) { + Color drop_color = get_color("accent_color", "Editor"); + if (dropping_at < 0) { + draw_line(Vector2(0, 0), Vector2(get_size().width, 0), drop_color); + } else { + draw_line(Vector2(0, get_size().height), get_size(), drop_color); + } + } + } + + if (p_what == NOTIFICATION_MOUSE_EXIT || p_what == NOTIFICATION_DRAG_END) { + cancel_drop(); + } +} + +int AnimationTrackEdit::get_key_height() const { + if (!animation.is_valid()) + return 0; + + return type_icon->get_height(); +} +Rect2 AnimationTrackEdit::get_key_rect(int p_index, float p_pixels_sec) { + + if (!animation.is_valid()) + return Rect2(); + Rect2 rect = Rect2(-type_icon->get_width() / 2, 0, type_icon->get_width(), get_size().height); + + //make it a big easier to click + rect.position.x -= rect.size.x * 0.5; + rect.size.x *= 2; + return rect; +} + +bool AnimationTrackEdit::is_key_selectable_by_distance() const { + return true; +} + +void AnimationTrackEdit::draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right) { + if (p_next_x < p_clip_left) + return; + if (p_x > p_clip_right) + return; + + Variant current = animation->track_get_key_value(get_track(), p_index); + Variant next = animation->track_get_key_value(get_track(), p_index + 1); + if (current != next) + return; + + Color color = get_color("font_color", "Label"); + color.a = 0.5; + + int from_x = MAX(p_x, p_clip_left); + int to_x = MIN(p_next_x, p_clip_right); + + draw_line(Point2(from_x + 1, get_size().height / 2), Point2(to_x, get_size().height / 2), color, 2); +} + +void AnimationTrackEdit::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + if (!animation.is_valid()) + return; + + if (p_x < p_clip_left || p_x > p_clip_right) + return; + + Vector2 ofs(p_x - type_icon->get_width() / 2, int(get_size().height - type_icon->get_height()) / 2); + + if (animation->track_get_type(track) == Animation::TYPE_METHOD) { + Ref<Font> font = get_font("font", "Label"); + Color color = get_color("font_color", "Label"); + color.a = 0.5; + + Dictionary d = animation->track_get_key_value(track, p_index); + String text; + + if (d.has("method")) + text += String(d["method"]); + text += "("; + Vector<Variant> args; + if (d.has("args")) + args = d["args"]; + for (int i = 0; i < args.size(); i++) { + + if (i > 0) + text += ", "; + text += String(args[i]); + } + text += ")"; + + int limit = MAX(0, p_clip_right - p_x - type_icon->get_width()); + if (limit > 0) { + draw_string(font, Vector2(p_x + type_icon->get_width(), int(get_size().height - font->get_height()) / 2 + font->get_ascent()), text, color, limit); + } + } + if (p_selected) { + draw_texture(selected_icon, ofs); + } else { + draw_texture(type_icon, ofs); + } +} + +//helper +void AnimationTrackEdit::draw_rect_clipped(const Rect2 &p_rect, const Color &p_color, bool p_filled) { + + int clip_left = timeline->get_name_limit(); + int clip_right = get_size().width - timeline->get_buttons_width(); + + if (p_rect.position.x > clip_right) + return; + if (p_rect.position.x + p_rect.size.x < clip_left) + return; + Rect2 clip = Rect2(clip_left, 0, clip_right - clip_left, get_size().height); + draw_rect(clip.clip(p_rect), p_color, p_filled); +} + +void AnimationTrackEdit::draw_bg(int p_clip_left, int p_clip_right) { +} + +void AnimationTrackEdit::draw_fg(int p_clip_left, int p_clip_right) { +} + +void AnimationTrackEdit::draw_texture_clipped(const Ref<Texture> &p_texture, const Vector2 &p_pos) { + + draw_texture_region_clipped(p_texture, Rect2(p_pos, p_texture->get_size()), Rect2(Point2(), p_texture->get_size())); +} + +void AnimationTrackEdit::draw_texture_region_clipped(const Ref<Texture> &p_texture, const Rect2 &p_rect, const Rect2 &p_region) { + + int clip_left = timeline->get_name_limit(); + int clip_right = get_size().width - timeline->get_buttons_width(); + + //clip left and right + if (clip_left > p_rect.position.x + p_rect.size.x) + return; + if (clip_right < p_rect.position.x) + return; + + Rect2 rect = p_rect; + Rect2 region = p_region; + + if (clip_left > rect.position.x) { + int rect_pixels = (clip_left - rect.position.x); + int region_pixels = rect_pixels * region.size.x / rect.size.x; + + rect.position.x += rect_pixels; + rect.size.x -= rect_pixels; + + region.position.x += region_pixels; + region.size.x -= region_pixels; + } + + if (clip_right < rect.position.x + rect.size.x) { + + int rect_pixels = rect.position.x + rect.size.x - clip_right; + int region_pixels = rect_pixels * region.size.x / rect.size.x; + + rect.size.x -= rect_pixels; + region.size.x -= region_pixels; + } + + draw_texture_rect_region(p_texture, rect, region); +} + +int AnimationTrackEdit::get_track() const { + return track; +} + +Ref<Animation> AnimationTrackEdit::get_animation() const { + return animation; +} + +void AnimationTrackEdit::set_animation_and_track(const Ref<Animation> &p_animation, int p_track) { + + animation = p_animation; + track = p_track; + update(); + + Ref<Texture> type_icons[6] = { + get_icon("KeyValue", "EditorIcons"), + get_icon("KeyXform", "EditorIcons"), + get_icon("KeyCall", "EditorIcons"), + get_icon("KeyBezier", "EditorIcons"), + get_icon("KeyAudio", "EditorIcons"), + get_icon("KeyAnimation", "EditorIcons") + }; + + ERR_FAIL_INDEX(track, animation->get_track_count()); + + type_icon = type_icons[animation->track_get_type(track)]; + selected_icon = get_icon("KeySelected", "EditorIcons"); +} + +Size2 AnimationTrackEdit::get_minimum_size() const { + + Ref<Texture> texture = get_icon("Object", "EditorIcons"); + Ref<Font> font = get_font("font", "Label"); + int separation = get_constant("vseparation", "ItemList"); + + int max_h = MAX(texture->get_height(), font->get_height()); + max_h = MAX(max_h, get_key_height()); + + return Vector2(1, max_h + separation); +} + +void AnimationTrackEdit::set_undo_redo(UndoRedo *p_undo_redo) { + undo_redo = p_undo_redo; +} + +void AnimationTrackEdit::set_timeline(AnimationTimelineEdit *p_timeline) { + timeline = p_timeline; + timeline->connect("zoom_changed", this, "_zoom_changed"); +} +void AnimationTrackEdit::set_editor(AnimationTrackEditor *p_editor) { + editor = p_editor; +} + +void AnimationTrackEdit::_play_position_draw() { + + if (!animation.is_valid() || play_position_pos < 0) + return; + + float scale = timeline->get_zoom_scale(); + int h = get_size().height; + + int px = (-timeline->get_value() + play_position_pos) * scale + timeline->get_name_limit(); + + if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) { + Color color = get_color("accent_color", "Editor"); + play_position->draw_line(Point2(px, 0), Point2(px, h), color); + } +} + +void AnimationTrackEdit::set_play_position(float p_pos) { + + play_position_pos = p_pos; + play_position->update(); +} + +void AnimationTrackEdit::update_play_position() { + play_position->update(); +} + +void AnimationTrackEdit::set_root(Node *p_root) { + root = p_root; +} +void AnimationTrackEdit::_zoom_changed() { + update(); +} + +void AnimationTrackEdit::_path_entered(const String &p_text) { + + *block_animation_update_ptr = true; + undo_redo->create_action("Change Track Path"); + undo_redo->add_do_method(animation.ptr(), "track_set_path", track, p_text); + undo_redo->add_undo_method(animation.ptr(), "track_set_path", track, animation->track_get_path(track)); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + update(); + path->hide(); +} + +String AnimationTrackEdit::get_tooltip(const Point2 &p_pos) const { + + if (check_rect.has_point(p_pos)) { + return TTR("Toggle this track on/off"); + } + + if (path_rect.has_point(p_pos)) { + return animation->track_get_path(track); + } + + if (update_mode_rect.has_point(p_pos)) { + return TTR("Update Mode (How this property is set)."); + } + + if (interp_mode_rect.has_point(p_pos)) { + return TTR("Interpolation Mode"); + } + + if (loop_mode_rect.has_point(p_pos)) { + return TTR("Loop Wrap Mode (Interpolate end with beginning on loop"); + } + + if (remove_rect.has_point(p_pos)) { + return TTR("Remove this track"); + } + + if (p_pos.x >= timeline->get_name_limit() && p_pos.x <= (get_size().width - timeline->get_buttons_width())) { + + int key_idx = -1; + float key_distance = 1e20; + + for (int i = animation->track_get_key_count(track) - 1; i >= 0; i--) { //select should happen in the opposite order of drawing for more accurate overlap select + + Rect2 rect = const_cast<AnimationTrackEdit *>(this)->get_key_rect(i, timeline->get_zoom_scale()); + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + offset = offset * timeline->get_zoom_scale() + timeline->get_name_limit(); + rect.position.x += offset; + + if (rect.has_point(p_pos)) { + + if (const_cast<AnimationTrackEdit *>(this)->is_key_selectable_by_distance()) { + float distance = ABS(offset - p_pos.x); + if (key_idx == -1 || distance < key_distance) { + key_idx = i; + key_distance = distance; + } + } else { + //first one does it + break; + } + } + } + + if (key_idx != -1) { + + String text = TTR("Time (s): ") + rtos(animation->track_get_key_time(track, key_idx)) + "\n"; + switch (animation->track_get_type(track)) { + + case Animation::TYPE_TRANSFORM: { + + Dictionary d = animation->track_get_key_value(track, key_idx); + if (d.has("location")) + text += "Pos: " + String(d["location"]) + "\n"; + if (d.has("rotation")) + text += "Rot: " + String(d["rotation"]) + "\n"; + if (d.has("scale")) + text += "Scale: " + String(d["scale"]) + "\n"; + } break; + case Animation::TYPE_VALUE: { + + Variant v = animation->track_get_key_value(track, key_idx); + //text+="value: "+String(v)+"\n"; + + bool prop_exists = false; + Variant::Type valid_type = Variant::NIL; + Object *obj = NULL; + + RES res; + Vector<StringName> leftover_path; + Node *node = root->get_node_and_resource(animation->track_get_path(track), res, leftover_path); + + if (res.is_valid()) { + obj = res.ptr(); + } else if (node) { + obj = node; + } + + if (obj) { + valid_type = obj->get_static_property_type_indexed(leftover_path, &prop_exists); + } + + text += "Type: " + Variant::get_type_name(v.get_type()) + "\n"; + if (prop_exists && !Variant::can_convert(v.get_type(), valid_type)) { + text += "Value: " + String(v) + " (Invalid, expected type: " + Variant::get_type_name(valid_type) + ")\n"; + } else { + text += "Value: " + String(v) + "\n"; + } + text += "Easing: " + rtos(animation->track_get_key_transition(track, key_idx)); + + } break; + case Animation::TYPE_METHOD: { + + Dictionary d = animation->track_get_key_value(track, key_idx); + if (d.has("method")) + text += String(d["method"]); + text += "("; + Vector<Variant> args; + if (d.has("args")) + args = d["args"]; + for (int i = 0; i < args.size(); i++) { + + if (i > 0) + text += ", "; + text += String(args[i]); + } + text += ")\n"; + + } break; + case Animation::TYPE_BEZIER: { + + float h = animation->bezier_track_get_key_value(track, key_idx); + text += "Value: " + rtos(h) + "\n"; + Vector2 ih = animation->bezier_track_get_key_in_handle(track, key_idx); + text += "In-Handle: " + ih + "\n"; + Vector2 oh = animation->bezier_track_get_key_out_handle(track, key_idx); + text += "Out-Handle: " + oh + "\n"; + } break; + case Animation::TYPE_AUDIO: { + + String stream_name = "null"; + RES stream = animation->audio_track_get_key_stream(track, key_idx); + if (stream.is_valid()) { + if (stream->get_path().is_resource_file()) { + stream_name = stream->get_path().get_file(); + } else if (stream->get_name() != "") { + stream_name = stream->get_name(); + } else { + stream_name = stream->get_class(); + } + } + + text += "Stream: " + stream_name + "\n"; + float so = animation->audio_track_get_key_start_offset(track, key_idx); + text += "Start (s): " + rtos(so) + "\n"; + float eo = animation->audio_track_get_key_end_offset(track, key_idx); + text += "End (s): " + rtos(eo) + "\n"; + } break; + case Animation::TYPE_ANIMATION: { + + String name = animation->animation_track_get_key_animation(track, key_idx); + text += "Animation Clip: " + name + "\n"; + } break; + } + return text; + } + } + + return Control::get_tooltip(p_pos); +} + +void AnimationTrackEdit::_gui_input(const Ref<InputEvent> &p_event) { + + if (p_event->is_pressed()) { + if (ED_GET_SHORTCUT("animation_editor/duplicate_selection")->is_shortcut(p_event)) { + emit_signal("duplicate_request"); + accept_event(); + } + + if (ED_GET_SHORTCUT("animation_editor/duplicate_selection_transposed")->is_shortcut(p_event)) { + emit_signal("duplicate_transpose_request"); + accept_event(); + } + + if (ED_GET_SHORTCUT("animation_editor/delete_selection")->is_shortcut(p_event)) { + emit_signal("delete_request"); + accept_event(); + } + } + + Ref<InputEventMouseButton> mb = p_event; + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + Point2 pos = mb->get_position(); + + if (check_rect.has_point(pos)) { + *block_animation_update_ptr = true; + undo_redo->create_action("Toggle track enabled"); + undo_redo->add_do_method(animation.ptr(), "track_set_enabled", track, !animation->track_is_enabled(track)); + undo_redo->add_undo_method(animation.ptr(), "track_set_enabled", track, animation->track_is_enabled(track)); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + update(); + accept_event(); + } + if (path_rect.has_point(pos)) { + + clicking_on_name = true; + accept_event(); + } + + if (update_mode_rect.has_point(pos)) { + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu); + menu->connect("id_pressed", this, "_menu_selected"); + } + menu->clear(); + menu->add_icon_item(get_icon("TrackContinuous", "EditorIcons"), TTR("Continuous"), MENU_CALL_MODE_CONTINUOUS); + menu->add_icon_item(get_icon("TrackDiscrete", "EditorIcons"), TTR("Discrete"), MENU_CALL_MODE_DISCRETE); + menu->add_icon_item(get_icon("TrackTrigger", "EditorIcons"), TTR("Trigger"), MENU_CALL_MODE_TRIGGER); + menu->add_icon_item(get_icon("TrackCapture", "EditorIcons"), TTR("Capture"), MENU_CALL_MODE_CAPTURE); + menu->set_as_minsize(); + + Vector2 popup_pos = get_global_position() + update_mode_rect.position + Vector2(0, update_mode_rect.size.height); + menu->set_global_position(popup_pos); + menu->popup(); + accept_event(); + } + + if (interp_mode_rect.has_point(pos)) { + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu); + menu->connect("id_pressed", this, "_menu_selected"); + } + menu->clear(); + menu->add_icon_item(get_icon("InterpRaw", "EditorIcons"), TTR("Nearest"), MENU_INTERPOLATION_NEAREST); + menu->add_icon_item(get_icon("InterpLinear", "EditorIcons"), TTR("Linear"), MENU_INTERPOLATION_LINEAR); + menu->add_icon_item(get_icon("InterpCubic", "EditorIcons"), TTR("Cubic"), MENU_INTERPOLATION_CUBIC); + menu->set_as_minsize(); + + Vector2 popup_pos = get_global_position() + interp_mode_rect.position + Vector2(0, interp_mode_rect.size.height); + menu->set_global_position(popup_pos); + menu->popup(); + accept_event(); + } + + if (loop_mode_rect.has_point(pos)) { + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu); + menu->connect("id_pressed", this, "_menu_selected"); + } + menu->clear(); + menu->add_icon_item(get_icon("InterpWrapClamp", "EditorIcons"), TTR("Clamp Loop Interp"), MENU_LOOP_CLAMP); + menu->add_icon_item(get_icon("InterpWrapLoop", "EditorIcons"), TTR("Wrap Loop Interp"), MENU_LOOP_WRAP); + menu->set_as_minsize(); + + Vector2 popup_pos = get_global_position() + loop_mode_rect.position + Vector2(0, loop_mode_rect.size.height); + menu->set_global_position(popup_pos); + menu->popup(); + accept_event(); + } + + if (remove_rect.has_point(pos)) { + emit_signal("remove_request", track); + accept_event(); + } + + if (bezier_edit_rect.has_point(pos)) { + emit_signal("bezier_edit"); + accept_event(); + } + + //check keyframes + + float scale = timeline->get_zoom_scale(); + int limit = timeline->get_name_limit(); + int limit_end = get_size().width - timeline->get_buttons_width(); + + if (pos.x >= limit && pos.x <= limit_end) { + + int key_idx = -1; + float key_distance = 1e20; + + for (int i = animation->track_get_key_count(track) - 1; i >= 0; i--) { //select should happen in the opposite order of drawing for more accurate overlap select + + Rect2 rect = get_key_rect(i, scale); + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + offset = offset * scale + limit; + rect.position.x += offset; + + print_line("rect: " + rect + " pos: " + pos); + if (rect.has_point(pos)) { + + if (is_key_selectable_by_distance()) { + float distance = ABS(offset - pos.x); + if (key_idx == -1 || distance < key_distance) { + key_idx = i; + key_distance = distance; + } + } else { + //first one does it + key_idx = i; + break; + } + } + } + + if (key_idx != -1) { + if (mb->get_command() || mb->get_shift()) { + if (editor->is_key_selected(track, key_idx)) { + emit_signal("deselect_key", key_idx); + + } else { + emit_signal("select_key", key_idx, false); + moving_selection_attempt = true; + select_single_attempt = -1; + moving_selection_from_ofs = (mb->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale(); + } + } else { + if (!editor->is_key_selected(track, key_idx)) { + emit_signal("select_key", key_idx, true); + select_single_attempt = -1; + } else { + select_single_attempt = key_idx; + } + + moving_selection_attempt = true; + moving_selection_from_ofs = (mb->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale(); + } + accept_event(); + } else { + emit_signal("clear_selection"); + } + } + + /*using focus instead + * if (!selected && pos.x >= timeline->get_name_limit() && pos.x < (get_size().width - timeline->get_buttons_width())) { + set_selected(true); + emit_signal("selected"); + } + */ + } + + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { + Point2 pos = mb->get_position(); + if (pos.x >= timeline->get_name_limit() && pos.x <= get_size().width - timeline->get_buttons_width()) { + //can do something with menu too! show insert key + float offset = (pos.x - timeline->get_name_limit()) / timeline->get_zoom_scale(); + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu); + menu->connect("id_pressed", this, "_menu_selected"); + } + + menu->clear(); + menu->add_icon_item(get_icon("Key", "EditorIcons"), TTR("Insert Key"), MENU_KEY_INSERT); + if (editor->is_selection_active()) { + menu->add_separator(); + menu->add_icon_item(get_icon("Duplicate", "EditorIcons"), TTR("Duplicate Key(s)"), MENU_KEY_DUPLICATE); + menu->add_separator(); + menu->add_icon_item(get_icon("Remove", "EditorIcons"), TTR("Delete Key(s)"), MENU_KEY_DELETE); + } + menu->set_as_minsize(); + + Vector2 popup_pos = get_global_transform().xform(get_local_mouse_position()); + menu->set_global_position(popup_pos); + menu->popup(); + + insert_at_pos = offset + timeline->get_value(); + accept_event(); + } + } + + if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && clicking_on_name) { + + if (!path) { + path = memnew(LineEdit); + add_child(path); + path->set_as_toplevel(true); + path->connect("text_entered", this, "_path_entered"); + } + + path->set_text(animation->track_get_path(track)); + Vector2 theme_ofs = path->get_stylebox("normal", "LineEdit")->get_offset(); + path->set_position(get_global_position() + path_rect.position - theme_ofs); + path->set_size(path_rect.size); + path->show_modal(); + path->grab_focus(); + path->set_cursor_position(path->get_text().length()); + clicking_on_name = false; + } + + if (mb.is_valid() && moving_selection_attempt) { + + if (!mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + moving_selection_attempt = false; + if (moving_selection) { + emit_signal("move_selection_commit"); + } else if (select_single_attempt != -1) { + emit_signal("select_key", select_single_attempt, true); + } + moving_selection = false; + select_single_attempt = -1; + } + + if (moving_selection && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { + + moving_selection_attempt = false; + moving_selection = false; + emit_signal("move_selection_cancel"); + } + } + + Ref<InputEventMouseMotion> mm = p_event; + if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT && moving_selection_attempt) { + + if (!moving_selection) { + moving_selection = true; + emit_signal("move_selection_begin"); + } + + float new_ofs = (mm->get_position().x - timeline->get_name_limit()) / timeline->get_zoom_scale(); + emit_signal("move_selection", new_ofs - moving_selection_from_ofs); + } +} + +Variant AnimationTrackEdit::get_drag_data(const Point2 &p_point) { + + if (!clicking_on_name) + return Variant(); + + Dictionary drag_data; + drag_data["type"] = "animation_track"; + drag_data["index"] = track; + + ToolButton *tb = memnew(ToolButton); + tb->set_text(path_cache); + tb->set_icon(icon_cache); + set_drag_preview(tb); + + clicking_on_name = false; + + return drag_data; +} + +bool AnimationTrackEdit::can_drop_data(const Point2 &p_point, const Variant &p_data) const { + + Dictionary d = p_data; + if (!d.has("type")) { + return false; + } + + String type = d["type"]; + if (type != "animation_track") + return false; + + if (p_point.y < get_size().height / 2) { + dropping_at = -1; + } else { + dropping_at = 1; + } + + const_cast<AnimationTrackEdit *>(this)->update(); + const_cast<AnimationTrackEdit *>(this)->emit_signal("drop_attempted", track); + + return true; +} +void AnimationTrackEdit::drop_data(const Point2 &p_point, const Variant &p_data) { + + Dictionary d = p_data; + if (!d.has("type")) { + return; + } + + String type = d["type"]; + if (type != "animation_track") + return; + + int from_track = d["index"]; + + if (dropping_at < 0) { + emit_signal("dropped", from_track, track); + } else { + emit_signal("dropped", from_track, track + 1); + } +} + +void AnimationTrackEdit::_menu_selected(int p_index) { + + switch (p_index) { + case MENU_CALL_MODE_CONTINUOUS: + case MENU_CALL_MODE_DISCRETE: + case MENU_CALL_MODE_TRIGGER: + case MENU_CALL_MODE_CAPTURE: { + + Animation::UpdateMode update_mode = Animation::UpdateMode(p_index); + *block_animation_update_ptr = true; + undo_redo->create_action("Change animation update mode"); + undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", track, update_mode); + undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", track, animation->value_track_get_update_mode(track)); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + update(); + + } break; + case MENU_INTERPOLATION_NEAREST: + case MENU_INTERPOLATION_LINEAR: + case MENU_INTERPOLATION_CUBIC: { + + Animation::InterpolationType interp_mode = Animation::InterpolationType(p_index - MENU_INTERPOLATION_NEAREST); + *block_animation_update_ptr = true; + undo_redo->create_action("Change animation interpolation mode"); + undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", track, interp_mode); + undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", track, animation->track_get_interpolation_type(track)); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + update(); + } break; + case MENU_LOOP_WRAP: + case MENU_LOOP_CLAMP: { + + bool loop_wrap = p_index == MENU_LOOP_WRAP; + *block_animation_update_ptr = true; + undo_redo->create_action("Change animation loop mode"); + undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_loop_wrap", track, loop_wrap); + undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_loop_wrap", track, animation->track_get_interpolation_loop_wrap(track)); + undo_redo->commit_action(); + *block_animation_update_ptr = false; + update(); + + } break; + case MENU_KEY_INSERT: { + emit_signal("insert_key", insert_at_pos); + } break; + case MENU_KEY_DUPLICATE: { + emit_signal("duplicate_request"); + + } break; + case MENU_KEY_DELETE: { + emit_signal("delete_request"); + + } break; + } +} + +void AnimationTrackEdit::set_block_animation_update_ptr(bool *p_block_ptr) { + block_animation_update_ptr = p_block_ptr; +} + +void AnimationTrackEdit::cancel_drop() { + if (dropping_at != 0) { + dropping_at = 0; + update(); + } +} +void AnimationTrackEdit::set_in_group(bool p_enable) { + in_group = p_enable; + update(); +} + +void AnimationTrackEdit::append_to_selection(const Rect2 &p_box) { + + Rect2 select_rect(timeline->get_name_limit(), 0, get_size().width - timeline->get_name_limit() - timeline->get_buttons_width(), get_size().height); + select_rect = select_rect.clip(p_box); + + for (int i = animation->track_get_key_count(track) - 1; i >= 0; i--) { //select should happen in the opposite order of drawing for more accurate overlap select + + Rect2 rect = const_cast<AnimationTrackEdit *>(this)->get_key_rect(i, timeline->get_zoom_scale()); + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + offset = offset * timeline->get_zoom_scale() + timeline->get_name_limit(); + rect.position.x += offset; + + if (select_rect.intersects(rect)) { + emit_signal("select_key", i, false); + } + } +} + +void AnimationTrackEdit::_bind_methods() { + + ClassDB::bind_method("_zoom_changed", &AnimationTrackEdit::_zoom_changed); + ClassDB::bind_method("_menu_selected", &AnimationTrackEdit::_menu_selected); + ClassDB::bind_method("_gui_input", &AnimationTrackEdit::_gui_input); + ClassDB::bind_method("_path_entered", &AnimationTrackEdit::_path_entered); + ClassDB::bind_method("_play_position_draw", &AnimationTrackEdit::_play_position_draw); + + ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag"))); + ADD_SIGNAL(MethodInfo("remove_request", PropertyInfo(Variant::INT, "track"))); + ADD_SIGNAL(MethodInfo("dropped", PropertyInfo(Variant::INT, "from_track"), PropertyInfo(Variant::INT, "to_track"))); + ADD_SIGNAL(MethodInfo("insert_key", PropertyInfo(Variant::REAL, "ofs"))); + ADD_SIGNAL(MethodInfo("select_key", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "single"))); + ADD_SIGNAL(MethodInfo("deselect_key", PropertyInfo(Variant::INT, "index"))); + ADD_SIGNAL(MethodInfo("clear_selection")); + ADD_SIGNAL(MethodInfo("bezier_edit")); + + ADD_SIGNAL(MethodInfo("move_selection_begin")); + ADD_SIGNAL(MethodInfo("move_selection", PropertyInfo(Variant::REAL, "ofs"))); + ADD_SIGNAL(MethodInfo("move_selection_commit")); + ADD_SIGNAL(MethodInfo("move_selection_cancel")); + + ADD_SIGNAL(MethodInfo("duplicate_request")); + ADD_SIGNAL(MethodInfo("duplicate_transpose_request")); + ADD_SIGNAL(MethodInfo("delete_request")); +} + +AnimationTrackEdit::AnimationTrackEdit() { + undo_redo = NULL; + timeline = NULL; + root = NULL; + path = NULL; + menu = NULL; + block_animation_update_ptr = NULL; + clicking_on_name = false; + dropping_at = 0; + + in_group = false; + + moving_selection_attempt = false; + moving_selection = false; + select_single_attempt = -1; + + play_position_pos = 0; + play_position = memnew(Control); + play_position->set_mouse_filter(MOUSE_FILTER_PASS); + add_child(play_position); + play_position->set_anchors_and_margins_preset(PRESET_WIDE); + play_position->connect("draw", this, "_play_position_draw"); + set_focus_mode(FOCUS_CLICK); + set_mouse_filter(MOUSE_FILTER_PASS); //scroll has to work too for selection +} + +////////////////////////////////////// + +AnimationTrackEdit *AnimationTrackEditPlugin::create_value_track_edit(Object *p_object, Variant::Type p_type, const String &p_property, PropertyHint p_hint, const String &p_hint_string, int p_usage) { + if (get_script_instance()) { + Variant args[6] = { + p_object, + p_type, + p_property, + p_hint, + p_hint_string, + p_usage + }; + + Variant *argptrs[6] = { + &args[0], + &args[1], + &args[2], + &args[3], + &args[4], + &args[5] + }; + + Variant::CallError ce; + return Object::cast_to<AnimationTrackEdit>(get_script_instance()->call("create_value_track_edit", (const Variant **)&argptrs, 6, ce).operator Object *()); + } + return NULL; +} + +AnimationTrackEdit *AnimationTrackEditPlugin::create_audio_track_edit() { + + if (get_script_instance()) { + return Object::cast_to<AnimationTrackEdit>(get_script_instance()->call("create_audio_track_edit").operator Object *()); + } + return NULL; +} + +AnimationTrackEdit *AnimationTrackEditPlugin::create_animation_track_edit(Object *p_object) { + if (get_script_instance()) { + return Object::cast_to<AnimationTrackEdit>(get_script_instance()->call("create_animation_track_edit", p_object).operator Object *()); + } + return NULL; +} + +/////////////////////////////////////// + +void AnimationTrackEditGroup::_notification(int p_what) { + + if (p_what == NOTIFICATION_DRAW) { + Ref<Font> font = get_font("font", "Label"); + int separation = get_constant("hseparation", "ItemList"); + Color color = get_color("font_color", "Label"); + + if (root && root->has_node(node)) { + Node *n = root->get_node(node); + if (n && EditorNode::get_singleton()->get_editor_selection()->is_selected(n)) { + color = get_color("accent_color", "Editor"); + } + } + + Color bgcol = get_color("dark_color_2", "Editor"); + bgcol.a *= 0.6; + draw_rect(Rect2(Point2(), get_size()), bgcol); + Color linecolor = color; + linecolor.a = 0.2; + + draw_line(Point2(), Point2(get_size().width, 0), linecolor); + draw_line(Point2(timeline->get_name_limit(), 0), Point2(timeline->get_name_limit(), get_size().height), linecolor); + draw_line(Point2(get_size().width - timeline->get_buttons_width(), 0), Point2(get_size().width - timeline->get_buttons_width(), get_size().height), linecolor); + + int ofs = 0; + draw_texture(icon, Point2(ofs, int(get_size().height - icon->get_height()) / 2)); + ofs += separation + icon->get_width(); + draw_string(font, Point2(ofs, int(get_size().height - font->get_height()) / 2 + font->get_ascent()), node_name, color, timeline->get_name_limit() - ofs); + + int px = (-timeline->get_value() + timeline->get_play_position()) * timeline->get_zoom_scale() + timeline->get_name_limit(); + + if (px >= timeline->get_name_limit() && px < (get_size().width - timeline->get_buttons_width())) { + Color accent = get_color("accent_color", "Editor"); + draw_line(Point2(px, 0), Point2(px, get_size().height), accent); + } + } +} + +void AnimationTrackEditGroup::set_type_and_name(const Ref<Texture> &p_type, const String &p_name, const NodePath &p_node) { + icon = p_type; + node_name = p_name; + node = p_node; + update(); + minimum_size_changed(); +} + +Size2 AnimationTrackEditGroup::get_minimum_size() const { + + Ref<Font> font = get_font("font", "Label"); + int separation = get_constant("vseparation", "ItemList"); + + return Vector2(0, MAX(font->get_height(), icon->get_height()) + separation); +} + +void AnimationTrackEditGroup::set_timeline(AnimationTimelineEdit *p_timeline) { + timeline = p_timeline; + timeline->connect("zoom_changed", this, "_zoom_changed"); +} + +void AnimationTrackEditGroup::set_root(Node *p_root) { + root = p_root; + update(); +} + +void AnimationTrackEditGroup::_zoom_changed() { + update(); +} + +void AnimationTrackEditGroup::_bind_methods() { + ClassDB::bind_method("_zoom_changed", &AnimationTrackEditGroup::_zoom_changed); +} + +AnimationTrackEditGroup::AnimationTrackEditGroup() { + set_mouse_filter(MOUSE_FILTER_PASS); +} + +////////////////////////////////////// + +void AnimationTrackEditor::add_track_edit_plugin(const Ref<AnimationTrackEditPlugin> &p_plugin) { + + if (track_edit_plugins.find(p_plugin) != -1) + return; + track_edit_plugins.push_back(p_plugin); +} + +void AnimationTrackEditor::remove_track_edit_plugin(const Ref<AnimationTrackEditPlugin> &p_plugin) { + + track_edit_plugins.erase(p_plugin); +} + +void AnimationTrackEditor::set_animation(const Ref<Animation> &p_anim) { + + if (animation != p_anim && _get_track_selected() >= 0) { + track_edits[_get_track_selected()]->release_focus(); + } + if (animation.is_valid()) { + animation->disconnect("changed", this, "_animation_changed"); + _clear_selection(); + } + animation = p_anim; + timeline->set_animation(p_anim); + + _cancel_bezier_edit(); + _update_tracks(); + + if (animation.is_valid()) { + animation->connect("changed", this, "_animation_changed"); + + step->set_block_signals(true); + step->set_value(animation->get_step()); + step->set_block_signals(false); + step->set_read_only(false); + snap->set_disabled(false); + } else { + step->set_block_signals(true); + step->set_value(0); + step->set_block_signals(false); + step->set_read_only(true); + snap->set_disabled(true); + } +} + +Ref<Animation> AnimationTrackEditor::get_current_animation() const { + + return animation; +} +void AnimationTrackEditor::_root_removed(Node *p_root) { + root = NULL; +} + +void AnimationTrackEditor::set_root(Node *p_root) { + if (root) { + root->disconnect("tree_exiting", this, "_root_removed"); + } + + root = p_root; + + if (root) { + root->connect("tree_exiting", this, "_root_removed", make_binds(), CONNECT_ONESHOT); + } + + _update_tracks(); +} + +Node *AnimationTrackEditor::get_root() const { + + return root; +} + +void AnimationTrackEditor::update_keying() { + bool keying_enabled = is_visible_in_tree() && animation.is_valid(); + + if (keying_enabled == keying) + return; + + keying = keying_enabled; + //_update_menu(); + emit_signal("keying_changed"); +} + +bool AnimationTrackEditor::has_keying() const { + return keying; +} + +void AnimationTrackEditor::cleanup() { + set_animation(Ref<Animation>()); +} + +void AnimationTrackEditor::_name_limit_changed() { + + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } +} + +void AnimationTrackEditor::_timeline_changed(float p_new_pos, bool p_drag) { + + emit_signal("timeline_changed", p_new_pos, p_drag); +} + +void AnimationTrackEditor::_track_remove_request(int p_track) { + + int idx = p_track; + if (idx >= 0 && idx < animation->get_track_count()) { + _clear_selection(); + undo_redo->create_action(TTR("Remove Anim Track")); + undo_redo->add_do_method(animation.ptr(), "remove_track", idx); + undo_redo->add_undo_method(animation.ptr(), "add_track", animation->track_get_type(idx), idx); + undo_redo->add_undo_method(animation.ptr(), "track_set_path", idx, animation->track_get_path(idx)); + //todo interpolation + for (int i = 0; i < animation->track_get_key_count(idx); i++) { + + Variant v = animation->track_get_key_value(idx, i); + float time = animation->track_get_key_time(idx, i); + float trans = animation->track_get_key_transition(idx, i); + + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, time, v); + undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", idx, i, trans); + } + + undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", idx, animation->track_get_interpolation_type(idx)); + if (animation->track_get_type(idx) == Animation::TYPE_VALUE) { + undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", idx, animation->value_track_get_update_mode(idx)); + } + + undo_redo->commit_action(); + } +} + +void AnimationTrackEditor::set_anim_pos(float p_pos) { + + timeline->set_play_position(p_pos); + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->set_play_position(p_pos); + } + for (int i = 0; i < groups.size(); i++) { + groups[i]->update(); + } + bezier_edit->set_play_position(p_pos); +} + +void AnimationTrackEditor::_query_insert(const InsertData &p_id) { + + if (insert_frame != Engine::get_singleton()->get_frames_drawn()) { + //clear insert list for the frame if frame changed + if (insert_confirm->is_visible_in_tree()) + return; //do nothing + insert_data.clear(); + insert_query = false; + } + insert_frame = Engine::get_singleton()->get_frames_drawn(); + + for (List<InsertData>::Element *E = insert_data.front(); E; E = E->next()) { + //prevent insertion of multiple tracks + if (E->get().path == p_id.path) + return; //already inserted a track for this on this frame + } + + insert_data.push_back(p_id); + + if (p_id.track_idx == -1) { + if (bool(EDITOR_DEF("editors/animation/confirm_insert_track", true))) { + //potential new key, does not exist + if (insert_data.size() == 1) + insert_confirm_text->set_text(vformat(TTR("Create NEW track for %s and insert key?"), p_id.query)); + else + insert_confirm_text->set_text(vformat(TTR("Create %d NEW tracks and insert keys?"), insert_data.size())); + + bool all_bezier = true; + for (int i = 0; i < insert_data.size(); i++) { + if (insert_data[i].type != Animation::TYPE_VALUE && insert_data[i].type != Animation::TYPE_BEZIER) { + all_bezier = false; + } + + if (insert_data[i].type != Animation::TYPE_VALUE) { + continue; + } + switch (insert_data[i].value.get_type()) { + case Variant::INT: + case Variant::REAL: + case Variant::VECTOR2: + case Variant::VECTOR3: + case Variant::QUAT: + case Variant::PLANE: + case Variant::COLOR: { + //good + } break; + default: { + all_bezier = false; + } + } + } + + insert_confirm_bezier->set_visible(all_bezier); + insert_confirm->get_ok()->set_text(TTR("Create")); + insert_confirm->popup_centered_minsize(); + insert_query = true; + } else { + call_deferred("_insert_delay"); + insert_queue = true; + } + + } else { + if (!insert_query && !insert_queue) { + call_deferred("_insert_delay"); + insert_queue = true; + } + } +} + +void AnimationTrackEditor::_insert_delay() { + + if (insert_query) { + //discard since it's entered into query mode + insert_queue = false; + return; + } + + undo_redo->create_action(TTR("Anim Insert")); + + int last_track = animation->get_track_count(); + bool advance = false; + while (insert_data.size()) { + + if (insert_data.front()->get().advance) + advance = true; + last_track = _confirm_insert(insert_data.front()->get(), last_track); + insert_data.pop_front(); + } + + undo_redo->commit_action(); + + if (advance) { + float step = animation->get_step(); + if (step == 0) + step = 1; + + float pos = timeline->get_play_position(); + + pos = Math::stepify(pos + step, step); + if (pos > animation->get_length()) + pos = animation->get_length(); + set_anim_pos(pos); + emit_signal("timeline_changed", pos, true); + } + insert_queue = false; +} + +void AnimationTrackEditor::insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform) { + + if (!keying) + return; + if (!animation.is_valid()) + return; + + ERR_FAIL_COND(!root); + //let's build a node path + String path = root->get_path_to(p_node); + if (p_sub != "") + path += ":" + p_sub; + + NodePath np = path; + + int track_idx = -1; + + for (int i = 0; i < animation->get_track_count(); i++) { + + if (animation->track_get_type(i) != Animation::TYPE_TRANSFORM) + continue; + if (animation->track_get_path(i) != np) + continue; + + track_idx = i; + break; + } + + InsertData id; + Dictionary val; + + id.path = np; + id.track_idx = track_idx; + id.value = p_xform; + id.type = Animation::TYPE_TRANSFORM; + id.query = "node '" + p_node->get_name() + "'"; + id.advance = false; + + //dialog insert + + _query_insert(id); +} + +void AnimationTrackEditor::_insert_animation_key(NodePath p_path, const Variant &p_value) { + + String path = p_path; + + //animation property is a special case, always creates an animation track + for (int i = 0; i < animation->get_track_count(); i++) { + + String np = animation->track_get_path(i); + + if (path == np && animation->track_get_type(i) == Animation::TYPE_ANIMATION) { + //exists + InsertData id; + id.path = path; + id.track_idx = i; + id.value = p_value; + id.type = Animation::TYPE_ANIMATION; + id.query = "animation"; + id.advance = false; + //dialog insert + _query_insert(id); + return; + } + } + + InsertData id; + id.path = path; + id.track_idx = -1; + id.value = p_value; + id.type = Animation::TYPE_ANIMATION; + id.query = "animation"; + id.advance = false; + //dialog insert + _query_insert(id); +} + +void AnimationTrackEditor::insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists) { + + ERR_FAIL_COND(!root); + //let's build a node path + + Node *node = p_node; + + String path = root->get_path_to(node); + + if (Object::cast_to<AnimationPlayer>(node) && p_property == "current_animation") { + if (node == AnimationPlayerEditor::singleton->get_player()) { + EditorNode::get_singleton()->show_warning(TTR("AnimationPlayer can't animate itself, only other players.")); + return; + } + _insert_animation_key(path, p_value); + return; + } + + EditorHistory *history = EditorNode::get_singleton()->get_editor_history(); + for (int i = 1; i < history->get_path_size(); i++) { + + String prop = history->get_path_property(i); + ERR_FAIL_COND(prop == ""); + path += ":" + prop; + } + + path += ":" + p_property; + + NodePath np = path; + + //locate track + + bool inserted = false; + + for (int i = 0; i < animation->get_track_count(); i++) { + + if (animation->track_get_type(i) == Animation::TYPE_VALUE) { + if (animation->track_get_path(i) != np) + continue; + + InsertData id; + id.path = np; + id.track_idx = i; + id.value = p_value; + id.type = Animation::TYPE_VALUE; + id.query = "property '" + p_property + "'"; + id.advance = false; + //dialog insert + _query_insert(id); + inserted = true; + } else if (animation->track_get_type(i) == Animation::TYPE_BEZIER) { + + Variant value; + if (animation->track_get_path(i) == np) { + value = p_value; //all good + } else { + String path = animation->track_get_path(i); + if (NodePath(path.get_basename()) == np) { + String subindex = path.get_extension(); + value = p_value.get(subindex); + } else { + continue; + } + } + + InsertData id; + id.path = animation->track_get_path(i); + id.track_idx = i; + id.value = value; + id.type = Animation::TYPE_BEZIER; + id.query = "property '" + p_property + "'"; + id.advance = false; + //dialog insert + _query_insert(id); + inserted = true; + } + } + + if (inserted || p_only_if_exists) + return; + InsertData id; + id.path = np; + id.track_idx = -1; + id.value = p_value; + id.type = Animation::TYPE_VALUE; + id.query = "property '" + p_property + "'"; + id.advance = false; + //dialog insert + _query_insert(id); +} + +void AnimationTrackEditor::insert_value_key(const String &p_property, const Variant &p_value, bool p_advance) { + + EditorHistory *history = EditorNode::get_singleton()->get_editor_history(); + + ERR_FAIL_COND(!root); + //let's build a node path + ERR_FAIL_COND(history->get_path_size() == 0); + Object *obj = ObjectDB::get_instance(history->get_path_object(0)); + ERR_FAIL_COND(!Object::cast_to<Node>(obj)); + + Node *node = Object::cast_to<Node>(obj); + + String path = root->get_path_to(node); + + if (Object::cast_to<AnimationPlayer>(node) && p_property == "current_animation") { + if (node == AnimationPlayerEditor::singleton->get_player()) { + EditorNode::get_singleton()->show_warning(TTR("AnimationPlayer can't animate itself, only other players.")); + return; + } + _insert_animation_key(path, p_value); + return; + } + + for (int i = 1; i < history->get_path_size(); i++) { + + String prop = history->get_path_property(i); + ERR_FAIL_COND(prop == ""); + path += ":" + prop; + } + + path += ":" + p_property; + + NodePath np = path; + + //locate track + + bool inserted = false; + + for (int i = 0; i < animation->get_track_count(); i++) { + + if (animation->track_get_type(i) == Animation::TYPE_VALUE) { + if (animation->track_get_path(i) != np) + continue; + + InsertData id; + id.path = np; + id.track_idx = i; + id.value = p_value; + id.type = Animation::TYPE_VALUE; + id.query = "property '" + p_property + "'"; + id.advance = p_advance; + //dialog insert + _query_insert(id); + inserted = true; + } else if (animation->track_get_type(i) == Animation::TYPE_BEZIER) { + + Variant value; + if (animation->track_get_path(i) == np) { + value = p_value; //all good + } else { + String path = animation->track_get_path(i); + if (NodePath(path.get_basename()) == np) { + String subindex = path.get_extension(); + value = p_value.get(subindex); + } else { + continue; + } + } + + InsertData id; + id.path = animation->track_get_path(i); + id.track_idx = i; + id.value = value; + id.type = Animation::TYPE_BEZIER; + id.query = "property '" + p_property + "'"; + id.advance = p_advance; + //dialog insert + _query_insert(id); + inserted = true; + } + } + + if (!inserted) { + InsertData id; + id.path = np; + id.track_idx = -1; + id.value = p_value; + id.type = Animation::TYPE_VALUE; + id.query = "property '" + p_property + "'"; + id.advance = p_advance; + //dialog insert + _query_insert(id); + } +} + +void AnimationTrackEditor::_confirm_insert_list() { + + undo_redo->create_action(TTR("Anim Create & Insert")); + + int last_track = animation->get_track_count(); + while (insert_data.size()) { + + last_track = _confirm_insert(insert_data.front()->get(), last_track, insert_confirm_bezier->is_pressed()); + insert_data.pop_front(); + } + + undo_redo->commit_action(); +} + +PropertyInfo AnimationTrackEditor::_find_hint_for_track(int p_idx, NodePath &r_base_path, Variant *r_current_val) { + + r_base_path = NodePath(); + ERR_FAIL_COND_V(!animation.is_valid(), PropertyInfo()); + ERR_FAIL_INDEX_V(p_idx, animation->get_track_count(), PropertyInfo()); + + if (!root) { + return PropertyInfo(); + } + + NodePath path = animation->track_get_path(p_idx); + + if (!root->has_node_and_resource(path)) { + return PropertyInfo(); + } + + RES res; + Vector<StringName> leftover_path; + Node *node = root->get_node_and_resource(path, res, leftover_path, true); + + if (node) { + r_base_path = node->get_path(); + } + + if (leftover_path.empty()) { + if (r_current_val) { + if (res.is_valid()) { + *r_current_val = res; + } else if (node) { + *r_current_val = node; + } + } + return PropertyInfo(); + } + + Variant property_info_base; + if (res.is_valid()) { + property_info_base = res; + if (r_current_val) { + *r_current_val = res->get(leftover_path[leftover_path.size() - 1]); + } + } else if (node) { + property_info_base = node; + if (r_current_val) { + *r_current_val = node->get(leftover_path[leftover_path.size() - 1]); + } + } + + for (int i = 0; i < leftover_path.size() - 1; i++) { + property_info_base = property_info_base.get_named(leftover_path[i]); + } + + List<PropertyInfo> pinfo; + property_info_base.get_property_list(&pinfo); + + for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + + if (E->get().name == leftover_path[leftover_path.size() - 1]) { + return E->get(); + } + } + + return PropertyInfo(); +} + +static Vector<String> _get_bezier_subindices_for_type(Variant::Type p_type, bool *r_valid = NULL) { + Vector<String> subindices; + if (r_valid) { + *r_valid = true; + } + switch (p_type) { + case Variant::INT: { + subindices.push_back(""); + } break; + case Variant::REAL: { + subindices.push_back(""); + } break; + case Variant::VECTOR2: { + subindices.push_back(".x"); + subindices.push_back(".y"); + } break; + case Variant::VECTOR3: { + subindices.push_back(".x"); + subindices.push_back(".y"); + subindices.push_back(".z"); + } break; + case Variant::QUAT: { + subindices.push_back(".x"); + subindices.push_back(".y"); + subindices.push_back(".z"); + subindices.push_back(".w"); + } break; + case Variant::COLOR: { + subindices.push_back(".r"); + subindices.push_back(".g"); + subindices.push_back(".b"); + subindices.push_back(".a"); + } break; + case Variant::PLANE: { + subindices.push_back(".x"); + subindices.push_back(".y"); + subindices.push_back(".z"); + subindices.push_back(".d"); + } break; + default: { + if (r_valid) { + *r_valid = false; + } + } + } + + return subindices; +} + +int AnimationTrackEditor::_confirm_insert(InsertData p_id, int p_last_track, bool p_create_beziers) { + + if (p_last_track == -1) + p_last_track = animation->get_track_count(); + + bool created = false; + if (p_id.track_idx < 0) { + + if (p_create_beziers && (p_id.value.get_type() == Variant::VECTOR2 || + p_id.value.get_type() == Variant::VECTOR3 || + p_id.value.get_type() == Variant::QUAT || + p_id.value.get_type() == Variant::COLOR || + p_id.value.get_type() == Variant::PLANE)) { + + Vector<String> subindices = _get_bezier_subindices_for_type(p_id.value.get_type()); + + for (int i = 0; i < subindices.size(); i++) { + InsertData id = p_id; + id.type = Animation::TYPE_BEZIER; + id.value = p_id.value.get(subindices[i].substr(1, subindices[i].length())); + id.path = String(p_id.path) + subindices[i]; + _confirm_insert(id, p_last_track + i); + } + + return p_last_track + subindices.size() - 1; + } + created = true; + undo_redo->create_action(TTR("Anim Insert Track & Key")); + Animation::UpdateMode update_mode = Animation::UPDATE_DISCRETE; + + if (p_id.type == Animation::TYPE_VALUE || p_id.type == Animation::TYPE_BEZIER) { + //wants a new tack + + { + //hack + NodePath np; + animation->add_track(p_id.type); + animation->track_set_path(animation->get_track_count() - 1, p_id.path); + PropertyInfo h = _find_hint_for_track(animation->get_track_count() - 1, np); + animation->remove_track(animation->get_track_count() - 1); //hack + + if (h.type == Variant::REAL || + h.type == Variant::VECTOR2 || + h.type == Variant::RECT2 || + h.type == Variant::VECTOR3 || + h.type == Variant::AABB || + h.type == Variant::QUAT || + h.type == Variant::COLOR || + h.type == Variant::PLANE || + h.type == Variant::TRANSFORM2D || + h.type == Variant::TRANSFORM) { + + update_mode = Animation::UPDATE_CONTINUOUS; + } + + if (h.usage & PROPERTY_USAGE_ANIMATE_AS_TRIGGER) { + update_mode = Animation::UPDATE_TRIGGER; + } + } + } + + p_id.track_idx = p_last_track; + + undo_redo->add_do_method(animation.ptr(), "add_track", p_id.type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", p_id.track_idx, p_id.path); + if (p_id.type == Animation::TYPE_VALUE) + undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", p_id.track_idx, update_mode); + + } else { + undo_redo->create_action(TTR("Anim Insert Key")); + } + + float time = timeline->get_play_position(); + Variant value; + + switch (p_id.type) { + + case Animation::TYPE_VALUE: { + + value = p_id.value; + + } break; + case Animation::TYPE_TRANSFORM: { + + Transform tr = p_id.value; + Dictionary d; + d["location"] = tr.origin; + d["scale"] = tr.basis.get_scale(); + d["rotation"] = Quat(tr.basis); //.orthonormalized(); + value = d; + } break; + case Animation::TYPE_BEZIER: { + Array array; + array.resize(5); + array[0] = p_id.value; + array[1] = -0.25; + array[2] = 0; + array[3] = 0.25; + array[4] = 0; + value = array; + + } break; + case Animation::TYPE_ANIMATION: { + value = p_id.value; + } break; + default: {} + } + + undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, value); + + if (created) { + + //just remove the track + undo_redo->add_undo_method(animation.ptr(), "remove_track", p_last_track); + p_last_track++; + } else { + + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_id.track_idx, time); + int existing = animation->track_find_key(p_id.track_idx, time, true); + if (existing != -1) { + Variant v = animation->track_get_key_value(p_id.track_idx, existing); + float trans = animation->track_get_key_transition(p_id.track_idx, existing); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, v, trans); + } + } + + /* + undo_redo->add_do_method(this, "update_tracks"); + undo_redo->add_undo_method(this, "update"); + undo_redo->add_do_method(track_editor, "update"); + undo_redo->add_undo_method(track_editor, "update"); + undo_redo->add_do_method(track_pos, "update"); + undo_redo->add_undo_method(track_pos, "update"); +*/ + undo_redo->commit_action(); + + return p_last_track; +} + +void AnimationTrackEditor::show_select_node_warning(bool p_show) { +} + +bool AnimationTrackEditor::is_key_selected(int p_track, int p_key) const { + + SelectedKey sk; + sk.key = p_key; + sk.track = p_track; + + return selection.has(sk); +} + +bool AnimationTrackEditor::is_selection_active() const { + return selection.size(); +} + +void AnimationTrackEditor::_update_tracks() { + + int selected = _get_track_selected(); + + while (track_vbox->get_child_count()) { + memdelete(track_vbox->get_child(0)); + } + + track_edits.clear(); + groups.clear(); + + if (animation.is_null()) + return; + + Map<String, VBoxContainer *> group_sort; + + bool use_grouping = !view_group->is_pressed(); + bool use_filter = selected_filter->is_pressed(); + + for (int i = 0; i < animation->get_track_count(); i++) { + AnimationTrackEdit *track_edit = NULL; + + //find hint and info for plugin + + if (use_filter) { + NodePath path = animation->track_get_path(i); + + if (root && root->has_node(path)) { + Node *node = root->get_node(path); + if (!node) { + continue; // no node, no filter + } + if (!EditorNode::get_singleton()->get_editor_selection()->is_selected(node)) { + continue; //skip track due to not selected + } + } + } + + if (animation->track_get_type(i) == Animation::TYPE_VALUE) { + + NodePath path = animation->track_get_path(i); + + if (root && root->has_node_and_resource(path)) { + RES res; + Vector<StringName> leftover_path; + Node *node = root->get_node_and_resource(path, res, leftover_path, true); + + Object *object = node; + if (res.is_valid()) { + object = res.ptr(); + } else { + object = node; + } + + if (object && !leftover_path.empty()) { + //not a property (value track?) + PropertyInfo pinfo; + pinfo.name = leftover_path[leftover_path.size() - 1]; + //now let's see if we can get more info about it + + List<PropertyInfo> plist; + object->get_property_list(&plist); + + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { + + if (E->get().name == leftover_path[leftover_path.size() - 1]) { + pinfo = E->get(); + break; + } + } + + for (int j = 0; j < track_edit_plugins.size(); j++) { + track_edit = track_edit_plugins[j]->create_value_track_edit(object, pinfo.type, pinfo.name, pinfo.hint, pinfo.hint_string, pinfo.usage); + if (track_edit) { + break; + } + } + } + } + } + if (animation->track_get_type(i) == Animation::TYPE_AUDIO) { + + for (int j = 0; j < track_edit_plugins.size(); j++) { + track_edit = track_edit_plugins[j]->create_audio_track_edit(); + if (track_edit) { + break; + } + } + } + + if (animation->track_get_type(i) == Animation::TYPE_ANIMATION) { + NodePath path = animation->track_get_path(i); + + Node *node = NULL; + if (root && root->has_node(path)) { + node = root->get_node(path); + } + + if (node && Object::cast_to<AnimationPlayer>(node)) { + for (int j = 0; j < track_edit_plugins.size(); j++) { + track_edit = track_edit_plugins[j]->create_animation_track_edit(node); + if (track_edit) { + break; + } + } + } + } + + if (track_edit == NULL) { + //no valid plugin_found + track_edit = memnew(AnimationTrackEdit); + } + + track_edits.push_back(track_edit); + + if (use_grouping) { + String base_path = animation->track_get_path(i); + base_path = base_path.get_slice(":", 0); // remove subpath + + if (!group_sort.has(base_path)) { + AnimationTrackEditGroup *g = memnew(AnimationTrackEditGroup); + Ref<Texture> icon = get_icon("Node", "EditorIcons"); + String name = base_path; + String tooltip; + if (root) { + Node *n = root->get_node(base_path); + if (n) { + if (has_icon(n->get_class(), "EditorIcons")) { + icon = get_icon(n->get_class(), "EditorIcons"); + } + name = n->get_name(); + tooltip = root->get_path_to(n); + } + } + + g->set_type_and_name(icon, name, animation->track_get_path(i)); + g->set_root(root); + g->set_tooltip(tooltip); + g->set_timeline(timeline); + groups.push_back(g); + VBoxContainer *vb = memnew(VBoxContainer); + vb->add_constant_override("separation", 0); + vb->add_child(g); + track_vbox->add_child(vb); + group_sort[base_path] = vb; + } + + track_edit->set_in_group(true); + group_sort[base_path]->add_child(track_edit); + + } else { + track_edit->set_in_group(false); + track_vbox->add_child(track_edit); + } + + track_edit->set_undo_redo(undo_redo); + track_edit->set_timeline(timeline); + track_edit->set_block_animation_update_ptr(&block_animation_update); + track_edit->set_root(root); + track_edit->set_animation_and_track(animation, i); + track_edit->set_play_position(timeline->get_play_position()); + track_edit->set_editor(this); + + if (selected == i) { + track_edit->grab_focus(); + } + + track_edit->connect("timeline_changed", this, "_timeline_changed"); + track_edit->connect("remove_request", this, "_track_remove_request", varray(), CONNECT_DEFERRED); + track_edit->connect("dropped", this, "_dropped_track", varray(), CONNECT_DEFERRED); + track_edit->connect("insert_key", this, "_insert_key_from_track", varray(i), CONNECT_DEFERRED); + track_edit->connect("select_key", this, "_key_selected", varray(i), CONNECT_DEFERRED); + track_edit->connect("deselect_key", this, "_key_deselected", varray(i), CONNECT_DEFERRED); + track_edit->connect("bezier_edit", this, "_bezier_edit", varray(i), CONNECT_DEFERRED); + track_edit->connect("clear_selection", this, "_clear_selection"); + track_edit->connect("move_selection_begin", this, "_move_selection_begin"); + track_edit->connect("move_selection", this, "_move_selection"); + track_edit->connect("move_selection_commit", this, "_move_selection_commit"); + track_edit->connect("move_selection_cancel", this, "_move_selection_cancel"); + + track_edit->connect("duplicate_request", this, "_edit_menu_pressed", varray(EDIT_DUPLICATE_SELECTION), CONNECT_DEFERRED); + track_edit->connect("duplicate_transpose_request", this, "_edit_menu_pressed", varray(EDIT_DUPLICATE_TRANSPOSED), CONNECT_DEFERRED); + track_edit->connect("delete_request", this, "_edit_menu_pressed", varray(EDIT_DELETE_SELECTION), CONNECT_DEFERRED); + } +} + +void AnimationTrackEditor::_animation_changed() { + + timeline->update_values(); + if (block_animation_update) { + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + for (int i = 0; i < groups.size(); i++) { + groups[i]->update(); + } + } else { + _update_tracks(); + } + + bezier_edit->update(); + + step->set_block_signals(true); + step->set_value(animation->get_step()); + step->set_block_signals(false); +} + +MenuButton *AnimationTrackEditor::get_edit_menu() { + return edit; +} + +void AnimationTrackEditor::_notification(int p_what) { + if (p_what == NOTIFICATION_THEME_CHANGED || p_what == NOTIFICATION_ENTER_TREE) { + + zoom_icon->set_texture(get_icon("Zoom", "EditorIcons")); + snap->set_icon(get_icon("Snap", "EditorIcons")); + view_group->set_icon(get_icon(view_group->is_pressed() ? "AnimationTrackList" : "AnimationTrackGroup", "EditorIcons")); + selected_filter->set_icon(get_icon("AnimationFilter", "EditorIcons")); + } + + if (p_what == NOTIFICATION_READY) { + EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed"); + } + + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { + + update_keying(); + EditorNode::get_singleton()->update_keying(); + emit_signal("keying_changed"); + } +} + +void AnimationTrackEditor::_update_scroll(double) { + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + for (int i = 0; i < groups.size(); i++) { + groups[i]->update(); + } +} + +void AnimationTrackEditor::_update_step(double p_new_step) { + + undo_redo->create_action("Change animation step"); + undo_redo->add_do_method(animation.ptr(), "set_step", p_new_step); + undo_redo->add_undo_method(animation.ptr(), "set_step", animation->get_step()); + step->set_block_signals(true); + undo_redo->commit_action(); + step->set_block_signals(false); + emit_signal("animation_step_changed", p_new_step); +} + +void AnimationTrackEditor::_update_length(double p_new_len) { + + emit_signal("animation_len_changed", p_new_len); +} + +void AnimationTrackEditor::_dropped_track(int p_from_track, int p_to_track) { + if (p_to_track >= track_edits.size()) { + p_to_track = track_edits.size() - 1; + } + + if (p_from_track == p_to_track) + return; + + _clear_selection(); + undo_redo->create_action("Rearrange tracks"); + undo_redo->add_do_method(animation.ptr(), "track_swap", p_from_track, p_to_track); + undo_redo->add_undo_method(animation.ptr(), "track_swap", p_to_track, p_from_track); + undo_redo->commit_action(); +} + +void AnimationTrackEditor::_new_track_node_selected(NodePath p_path) { + + ERR_FAIL_COND(!root); + Node *node = get_node(p_path); + ERR_FAIL_COND(!node); + NodePath path_to = root->get_path_to(node); + + if (adding_track_type == Animation::TYPE_TRANSFORM && !node->is_class("Spatial")) { + EditorNode::get_singleton()->show_warning(TTR("Transform tracks only apply to Spatial-based nodes.")); + return; + } + + switch (adding_track_type) { + case Animation::TYPE_VALUE: { + adding_track_path = path_to; + prop_selector->set_type_filter(Vector<Variant::Type>()); + prop_selector->select_property_from_instance(node); + } break; + case Animation::TYPE_TRANSFORM: + case Animation::TYPE_METHOD: { + + undo_redo->create_action("Add Track"); + undo_redo->add_do_method(animation.ptr(), "add_track", adding_track_type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), path_to); + undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); + undo_redo->commit_action(); + + } break; + case Animation::TYPE_BEZIER: { + + Vector<Variant::Type> filter; + filter.push_back(Variant::INT); + filter.push_back(Variant::REAL); + filter.push_back(Variant::VECTOR2); + filter.push_back(Variant::VECTOR3); + filter.push_back(Variant::QUAT); + filter.push_back(Variant::PLANE); + filter.push_back(Variant::COLOR); + + adding_track_path = path_to; + prop_selector->set_type_filter(filter); + prop_selector->select_property_from_instance(node); + } break; + case Animation::TYPE_AUDIO: { + + if (!node->is_class("AudioStreamPlayer") && !node->is_class("AudioStreamPlayer2D") && !node->is_class("AudioStreamPlayer3D")) { + EditorNode::get_singleton()->show_warning(TTR("Audio tracks can only point to nodes of type:\n-AudioStreamPlayer\n-AudioStreamPlayer2D\n-AudioStreamPlayer3D")); + return; + } + + undo_redo->create_action("Add Track"); + undo_redo->add_do_method(animation.ptr(), "add_track", adding_track_type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), path_to); + undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); + undo_redo->commit_action(); + + } break; + case Animation::TYPE_ANIMATION: { + + if (!node->is_class("AnimationPlayer")) { + EditorNode::get_singleton()->show_warning(TTR("Animation tracks can only point to AnimationPlayer nodes.")); + return; + } + + undo_redo->create_action("Add Track"); + undo_redo->add_do_method(animation.ptr(), "add_track", adding_track_type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), path_to); + undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); + undo_redo->commit_action(); + + } break; + } +} + +void AnimationTrackEditor::_add_track(int p_type) { + if (!root) { + EditorNode::get_singleton()->show_warning(TTR("Not possible to add a new track without a root")); + return; + } + adding_track_type = p_type; + pick_track->popup_centered_ratio(); +} + +void AnimationTrackEditor::_new_track_property_selected(String p_name) { + + String full_path = String(adding_track_path) + ":" + p_name; + + if (adding_track_type == Animation::TYPE_VALUE) { + + Animation::UpdateMode update_mode = Animation::UPDATE_DISCRETE; + { + //hack + NodePath np; + animation->add_track(Animation::TYPE_VALUE); + animation->track_set_path(animation->get_track_count() - 1, full_path); + PropertyInfo h = _find_hint_for_track(animation->get_track_count() - 1, np); + animation->remove_track(animation->get_track_count() - 1); //hack + if (h.type == Variant::REAL || + h.type == Variant::VECTOR2 || + h.type == Variant::RECT2 || + h.type == Variant::VECTOR3 || + h.type == Variant::AABB || + h.type == Variant::QUAT || + h.type == Variant::COLOR || + h.type == Variant::PLANE || + h.type == Variant::TRANSFORM2D || + h.type == Variant::TRANSFORM) { + + update_mode = Animation::UPDATE_CONTINUOUS; + } + + if (h.usage & PROPERTY_USAGE_ANIMATE_AS_TRIGGER) { + update_mode = Animation::UPDATE_TRIGGER; + } + } + + undo_redo->create_action("Add Track"); + undo_redo->add_do_method(animation.ptr(), "add_track", adding_track_type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), full_path); + undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", animation->get_track_count(), update_mode); + undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); + undo_redo->commit_action(); + } else { + Vector<String> subindices; + { + //hack + NodePath np; + animation->add_track(Animation::TYPE_VALUE); + animation->track_set_path(animation->get_track_count() - 1, full_path); + PropertyInfo h = _find_hint_for_track(animation->get_track_count() - 1, np); + animation->remove_track(animation->get_track_count() - 1); //hack + bool valid; + subindices = _get_bezier_subindices_for_type(h.type, &valid); + if (!valid) { + EditorNode::get_singleton()->show_warning("Invalid track for Bezier (no suitable sub-properties)"); + return; + } + } + + undo_redo->create_action("Add Bezier Track"); + int base_track = animation->get_track_count(); + for (int i = 0; i < subindices.size(); i++) { + undo_redo->add_do_method(animation.ptr(), "add_track", adding_track_type); + undo_redo->add_do_method(animation.ptr(), "track_set_path", base_track + i, full_path + subindices[i]); + undo_redo->add_undo_method(animation.ptr(), "remove_track", base_track + i); + } + undo_redo->commit_action(); + } +} + +void AnimationTrackEditor::_timeline_value_changed(double) { + + timeline->update_play_position(); + + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + track_edits[i]->update_play_position(); + } + + for (int i = 0; i < groups.size(); i++) { + groups[i]->update(); + } + + bezier_edit->update(); + bezier_edit->update_play_position(); +} + +int AnimationTrackEditor::_get_track_selected() { + + for (int i = 0; i < track_edits.size(); i++) { + if (track_edits[i]->has_focus()) + return i; + } + + return -1; +} + +void AnimationTrackEditor::_insert_key_from_track(float p_ofs, int p_track) { + + ERR_FAIL_INDEX(p_track, animation->get_track_count()); + + if (snap->is_pressed() && step->get_value() != 0) { + p_ofs = Math::stepify(p_ofs, step->get_value()); + } + while (animation->track_find_key(p_track, p_ofs, true) != -1) { //make sure insertion point is valid + p_ofs += 0.001; + } + + switch (animation->track_get_type(p_track)) { + case Animation::TYPE_TRANSFORM: { + if (!root->has_node(animation->track_get_path(p_track))) { + EditorNode::get_singleton()->show_warning(TTR("Track path is invalid, so can't add a key.")); + return; + } + Spatial *base = Object::cast_to<Spatial>(root->get_node(animation->track_get_path(p_track))); + + if (!base) { + EditorNode::get_singleton()->show_warning(TTR("Track is not of type Spatial, can't insert key")); + return; + } + + Transform xf = base->get_transform(); + + Vector3 loc = xf.get_origin(); + Vector3 scale = xf.basis.get_scale_local(); + Quat rot = xf.basis; + + undo_redo->create_action("Add Transform Track Key"); + undo_redo->add_do_method(animation.ptr(), "transform_track_insert_key", p_track, p_ofs, loc, rot, scale); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_track, p_ofs); + undo_redo->commit_action(); + + } break; + case Animation::TYPE_VALUE: { + + NodePath bp; + Variant value; + _find_hint_for_track(p_track, bp, &value); + + undo_redo->create_action("Add Track Key"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_track, p_ofs, value); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_track, p_ofs); + undo_redo->commit_action(); + + } break; + case Animation::TYPE_METHOD: { + if (!root->has_node(animation->track_get_path(p_track))) { + EditorNode::get_singleton()->show_warning(TTR("Track path is invalid, so can't add a method key.")); + return; + } + Node *base = root->get_node(animation->track_get_path(p_track)); + + method_selector->select_method_from_instance(base); + + insert_key_from_track_call_ofs = p_ofs; + insert_key_from_track_call_track = p_track; + + } break; + case Animation::TYPE_BEZIER: { + + NodePath bp; + Variant value; + _find_hint_for_track(p_track, bp, &value); + Array arr; + arr.resize(5); + arr[0] = value; + arr[1] = -0.25; + arr[2] = 0; + arr[3] = 0.25; + arr[4] = 0; + + undo_redo->create_action("Add Track Key"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_track, p_ofs, arr); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_track, p_ofs); + undo_redo->commit_action(); + + } break; + case Animation::TYPE_AUDIO: { + + Dictionary ak; + ak["stream"] = RES(); + ak["start_offset"] = 0; + ak["end_offset"] = 0; + + undo_redo->create_action("Add Track Key"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_track, p_ofs, ak); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_track, p_ofs); + undo_redo->commit_action(); + } break; + case Animation::TYPE_ANIMATION: { + + StringName anim = "[stop]"; + + undo_redo->create_action("Add Track Key"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_track, p_ofs, anim); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", p_track, p_ofs); + undo_redo->commit_action(); + } break; + } +} + +void AnimationTrackEditor::_add_method_key(const String &p_method) { + + if (!root->has_node(animation->track_get_path(insert_key_from_track_call_track))) { + EditorNode::get_singleton()->show_warning(TTR("Track path is invalid, so can't add a method key.")); + return; + } + Node *base = root->get_node(animation->track_get_path(insert_key_from_track_call_track)); + + List<MethodInfo> minfo; + base->get_method_list(&minfo); + + for (List<MethodInfo>::Element *E = minfo.front(); E; E = E->next()) { + if (E->get().name == p_method) { + + Dictionary d; + d["method"] = p_method; + Array params; + int first_defarg = E->get().arguments.size() - E->get().default_arguments.size(); + + for (int i = 0; i < E->get().arguments.size(); i++) { + + if (i >= first_defarg) { + Variant arg = E->get().default_arguments[i - first_defarg]; + params.push_back(arg); + } else { + Variant::CallError ce; + Variant arg = Variant::construct(E->get().arguments[i].type, NULL, 0, ce); + params.push_back(arg); + } + } + d["args"] = params; + + undo_redo->create_action("Add Method Track Key"); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", insert_key_from_track_call_track, insert_key_from_track_call_ofs, d); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", insert_key_from_track_call_track, insert_key_from_track_call_ofs); + undo_redo->commit_action(); + + return; + } + } + + EditorNode::get_singleton()->show_warning(TTR("Method not found in object: ") + p_method); +} + +void AnimationTrackEditor::_key_selected(int p_key, bool p_single, int p_track) { + + ERR_FAIL_INDEX(p_track, animation->get_track_count()); + ERR_FAIL_INDEX(p_key, animation->track_get_key_count(p_track)); + + SelectedKey sk; + sk.key = p_key; + sk.track = p_track; + + if (p_single) { + _clear_selection(); + } + + KeyInfo ki; + ki.pos = animation->track_get_key_time(p_track, p_key); + selection[sk] = ki; + + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + + _update_key_edit(); +} + +void AnimationTrackEditor::_key_deselected(int p_key, int p_track) { + + ERR_FAIL_INDEX(p_track, animation->get_track_count()); + ERR_FAIL_INDEX(p_key, animation->track_get_key_count(p_track)); + + SelectedKey sk; + sk.key = p_key; + sk.track = p_track; + + selection.erase(sk); + + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + + _update_key_edit(); +} + +void AnimationTrackEditor::_move_selection_begin() { + moving_selection = true; + moving_selection_offset = 0; +} + +void AnimationTrackEditor::_move_selection(float p_offset) { + moving_selection_offset = p_offset; + if (snap->is_pressed() && step->get_value() != 0) { + moving_selection_offset = Math::stepify(moving_selection_offset, step->get_value()); + } + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } +} + +struct _AnimMoveRestore { + + int track; + float time; + Variant key; + float transition; +}; +//used for undo/redo + +void AnimationTrackEditor::_clear_key_edit() { + if (key_edit) { + bool go_back = false; + if (EditorNode::get_singleton()->get_inspector()->get_edited_object() == key_edit) { + EditorNode::get_singleton()->push_item(NULL); + go_back = true; + } + + memdelete(key_edit); + key_edit = NULL; + + if (go_back) { + EditorNode::get_singleton()->get_inspector_dock()->go_back(); + } + } +} + +void AnimationTrackEditor::_clear_selection() { + selection.clear(); + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + _clear_key_edit(); +} + +void AnimationTrackEditor::_update_key_edit() { + + _clear_key_edit(); + if (!animation.is_valid()) + return; + if (selection.size() != 1) { + return; + } + + key_edit = memnew(AnimationTrackKeyEdit); + key_edit->animation = animation; + key_edit->track = selection.front()->key().track; + + float ofs = animation->track_get_key_time(key_edit->track, selection.front()->key().key); + key_edit->key_ofs = ofs; + key_edit->root_path = root; + + NodePath np; + key_edit->hint = _find_hint_for_track(key_edit->track, np); + key_edit->undo_redo = undo_redo; + key_edit->base = np; + + EditorNode::get_singleton()->push_item(key_edit); +} + +void AnimationTrackEditor::_clear_selection_for_anim(const Ref<Animation> &p_anim) { + + if (!(animation == p_anim)) + return; + //selection.clear(); + _clear_selection(); +} + +void AnimationTrackEditor::_select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos) { + + if (!(animation == p_anim)) + return; + + int idx = animation->track_find_key(p_track, p_pos, true); + ERR_FAIL_COND(idx < 0); + + SelectedKey sk; + sk.track = p_track; + sk.key = idx; + KeyInfo ki; + ki.pos = p_pos; + + selection.insert(sk, ki); +} + +void AnimationTrackEditor::_move_selection_commit() { + + undo_redo->create_action(TTR("Anim Move Keys")); + + List<_AnimMoveRestore> to_restore; + + float motion = moving_selection_offset; + // 1-remove the keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); + } + // 2- remove overlapped keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newtime = E->get().pos + motion; + int idx = animation->track_find_key(E->key().track, newtime, true); + if (idx == -1) + continue; + SelectedKey sk; + sk.key = idx; + sk.track = E->key().track; + if (selection.has(sk)) + continue; //already in selection, don't save + + undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newtime); + _AnimMoveRestore amr; + + amr.key = animation->track_get_key_value(E->key().track, idx); + amr.track = E->key().track; + amr.time = newtime; + amr.transition = animation->track_get_key_transition(E->key().track, idx); + + to_restore.push_back(amr); + } + + // 3-move the keys (re insert them) + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = E->get().pos + motion; + /* + if (newpos<0) + continue; //no add at the beginning + */ + undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + } + + // 4-(undo) remove inserted keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = E->get().pos + motion; + /* + if (newpos<0) + continue; //no remove what no inserted + */ + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newpos); + } + + // 5-(undo) reinsert keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + } + + // 6-(undo) reinsert overlapped keys + for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + _AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); + } + + // 6-(undo) reinsert overlapped keys + for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + _AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); + } + + undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); + undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); + + // 7-reselect + + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float oldpos = E->get().pos; + float newpos = oldpos + motion; + //if (newpos>=0) + undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos); + undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos); + } + + undo_redo->commit_action(); + + moving_selection = false; + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } +} +void AnimationTrackEditor::_move_selection_cancel() { + + moving_selection = false; + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } +} + +bool AnimationTrackEditor::is_moving_selection() const { + return moving_selection; +} +float AnimationTrackEditor::get_moving_selection_offset() const { + return moving_selection_offset; +} + +void AnimationTrackEditor::_box_selection_draw() { + + Color color = get_color("accent_color", "Editor"); + color.a = 0.2; + Rect2 rect = Rect2(Point2(), box_selection->get_size()); + box_selection->draw_rect(rect, color); +} + +void AnimationTrackEditor::_scroll_input(const Ref<InputEvent> &p_event) { + + Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { + + timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() * 1.05); + scroll->accept_event(); + } + + if (mb.is_valid() && mb->is_pressed() && mb->get_command() && mb->get_button_index() == BUTTON_WHEEL_UP) { + + timeline->get_zoom()->set_value(timeline->get_zoom()->get_value() / 1.05); + scroll->accept_event(); + } + + if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { + if (mb->is_pressed()) { + box_selecting = true; + box_selecting_from = scroll->get_global_transform().xform(mb->get_position()); + box_select_rect = Rect2(); + } else if (box_selecting) { + + if (box_selection->is_visible_in_tree()) { + //only if moved + for (int i = 0; i < track_edits.size(); i++) { + + Rect2 local_rect = box_select_rect; + local_rect.position -= track_edits[i]->get_global_position(); + track_edits[i]->append_to_selection(local_rect); + } + + if (_get_track_selected() == -1) { //minimal hack to make shortcuts work + track_edits[track_edits.size() - 1]->grab_focus(); + } + } else { + _clear_selection(); //clear it + } + + box_selection->hide(); + box_selecting = false; + } + } + + Ref<InputEventMouseMotion> mm = p_event; + + if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_MIDDLE) { + + timeline->set_value(timeline->get_value() - mm->get_relative().x / timeline->get_zoom_scale()); + } + + if (mm.is_valid() && box_selecting) { + + if (!(mm->get_button_mask() & BUTTON_MASK_LEFT)) { + //no longer + box_selection->hide(); + box_selecting = false; + return; + } + + if (!box_selection->is_visible_in_tree()) { + if (!mm->get_shift()) { + _clear_selection(); //only append if shift is pressed + } + box_selection->show(); + } + + Vector2 from = box_selecting_from; + Vector2 to = scroll->get_global_transform().xform(mm->get_position()); + + if (from.x > to.x) { + SWAP(from.x, to.x); + } + + if (from.y > to.y) { + SWAP(from.y, to.y); + } + + Rect2 rect(from, to - from); + Rect2 scroll_rect = Rect2(scroll->get_global_position(), scroll->get_size()); + rect = scroll_rect.clip(rect); + box_selection->set_position(rect.position); + box_selection->set_size(rect.size); + + box_select_rect = rect; + + if (get_local_mouse_position().y < 0) { + //avoid box selection from going up and lose focus to viewport + warp_mouse(Vector2(mm->get_position().x, 0)); + } + } +} + +void AnimationTrackEditor::_cancel_bezier_edit() { + bezier_edit->hide(); + scroll->show(); +} + +void AnimationTrackEditor::_bezier_edit(int p_for_track) { + + _clear_selection(); //bezier probably wants to use a separate selection mode + bezier_edit->set_root(root); + bezier_edit->set_animation_and_track(animation, p_for_track); + scroll->hide(); + bezier_edit->show(); + //search everything within the track and curve- edit it +} + +void AnimationTrackEditor::_anim_duplicate_keys(bool transpose) { + //duplicait! + if (selection.size() && animation.is_valid() && (!transpose || (_get_track_selected() >= 0 && _get_track_selected() < animation->get_track_count()))) { + + int top_track = 0x7FFFFFFF; + float top_time = 1e10; + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + const SelectedKey &sk = E->key(); + + float t = animation->track_get_key_time(sk.track, sk.key); + if (t < top_time) + top_time = t; + if (sk.track < top_track) + top_track = sk.track; + } + ERR_FAIL_COND(top_track == 0x7FFFFFFF || top_time == 1e10); + + // + + int start_track = transpose ? _get_track_selected() : top_track; + + undo_redo->create_action(TTR("Anim Duplicate Keys")); + + List<Pair<int, float> > new_selection_values; + + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + const SelectedKey &sk = E->key(); + + float t = animation->track_get_key_time(sk.track, sk.key); + + float dst_time = t + (timeline->get_play_position() - top_time); + int dst_track = sk.track + (start_track - top_track); + + if (dst_track < 0 || dst_track >= animation->get_track_count()) + continue; + + if (animation->track_get_type(dst_track) != animation->track_get_type(sk.track)) + continue; + + int existing_idx = animation->track_find_key(dst_track, dst_time, true); + + undo_redo->add_do_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", dst_track, dst_time); + + Pair<int, float> p; + p.first = dst_track; + p.second = dst_time; + new_selection_values.push_back(p); + + if (existing_idx != -1) { + + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(dst_track, existing_idx), animation->track_get_key_transition(dst_track, existing_idx)); + } + } + + undo_redo->commit_action(); + + //reselect duplicated + + Map<SelectedKey, KeyInfo> new_selection; + for (List<Pair<int, float> >::Element *E = new_selection_values.front(); E; E = E->next()) { + + int track = E->get().first; + float time = E->get().second; + + int existing_idx = animation->track_find_key(track, time, true); + + if (existing_idx == -1) + continue; + SelectedKey sk2; + sk2.track = track; + sk2.key = existing_idx; + + KeyInfo ki; + ki.pos = time; + + new_selection[sk2] = ki; + } + + selection = new_selection; + _update_tracks(); + _update_key_edit(); + } +} +void AnimationTrackEditor::_edit_menu_pressed(int p_option) { + + last_menu_track_opt = p_option; + switch (p_option) { + case EDIT_COPY_TRACKS: { + track_copy_select->clear(); + TreeItem *troot = track_copy_select->create_item(); + + for (int i = 0; i < animation->get_track_count(); i++) { + + NodePath path = animation->track_get_path(i); + Node *node = NULL; + + if (root && root->has_node(path)) { + node = root->get_node(path); + } + + String text; + Ref<Texture> icon = get_icon("Node", "EditorIcons"); + if (node) { + if (has_icon(node->get_class(), "EditorIcons")) { + icon = get_icon(node->get_class(), "EditorIcons"); + } + + text = node->get_name(); + Vector<StringName> sn = path.get_subnames(); + for (int i = 0; i < sn.size(); i++) { + text += "."; + text += sn[i]; + } + + path = NodePath(node->get_path().get_names(), path.get_subnames(), true); //store full path instead for copying + } else { + text = path; + int sep = text.find(":"); + if (sep != -1) { + text = text.substr(sep + 1, text.length()); + } + } + + switch (animation->track_get_type(i)) { + case Animation::TYPE_TRANSFORM: text += " (Transform)"; break; + case Animation::TYPE_METHOD: text += " (Methods)"; break; + case Animation::TYPE_BEZIER: text += " (Bezier)"; break; + case Animation::TYPE_AUDIO: text += " (Audio)"; break; + default: {}; + } + + TreeItem *it = track_copy_select->create_item(troot); + it->set_editable(0, true); + it->set_selectable(0, true); + it->set_cell_mode(0, TreeItem::CELL_MODE_CHECK); + it->set_icon(0, icon); + it->set_text(0, text); + Dictionary md; + md["track_idx"] = i; + md["path"] = path; + it->set_metadata(0, md); + } + + track_copy_dialog->popup_centered_minsize(Size2(300, 500) * EDSCALE); + } break; + case EDIT_COPY_TRACKS_CONFIRM: { + + track_clipboard.clear(); + TreeItem *root = track_copy_select->get_root(); + if (root) { + + TreeItem *it = root->get_children(); + while (it) { + Dictionary md = it->get_metadata(0); + int idx = md["track_idx"]; + if (it->is_checked(0) && idx >= 0 && idx < animation->get_track_count()) { + TrackClipboard tc; + tc.base_path = animation->track_get_path(idx); + tc.full_path = md["path"]; + tc.track_type = animation->track_get_type(idx); + tc.interp_type = animation->track_get_interpolation_type(idx); + if (tc.track_type == Animation::TYPE_VALUE) { + tc.update_mode = animation->value_track_get_update_mode(idx); + } + tc.loop_wrap = animation->track_get_interpolation_loop_wrap(idx); + tc.enabled = animation->track_is_enabled(idx); + for (int i = 0; i < animation->track_get_key_count(idx); i++) { + TrackClipboard::Key k; + k.time = animation->track_get_key_time(idx, i); + k.value = animation->track_get_key_value(idx, i); + k.transition = animation->track_get_key_transition(idx, i); + tc.keys.push_back(k); + } + track_clipboard.push_back(tc); + } + it = it->get_next(); + } + } + } break; + case EDIT_PASTE_TRACKS: { + + if (track_clipboard.size() == 0) { + EditorNode::get_singleton()->show_warning(TTR("Clipboard is empty")); + break; + } + + int base_track = animation->get_track_count(); + undo_redo->create_action("Paste Tracks"); + for (int i = 0; i < track_clipboard.size(); i++) { + undo_redo->add_do_method(animation.ptr(), "add_track", track_clipboard[i].track_type); + Node *exists = NULL; + NodePath path = track_clipboard[i].base_path; + + if (root) { + NodePath np = track_clipboard[i].full_path; + exists = root->get_node(np); + if (exists) { + path = NodePath(root->get_path_to(exists).get_names(), track_clipboard[i].full_path.get_subnames(), false); + } + } + + undo_redo->add_do_method(animation.ptr(), "track_set_path", base_track, path); + undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", base_track, track_clipboard[i].interp_type); + undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_loop_wrap", base_track, track_clipboard[i].loop_wrap); + undo_redo->add_do_method(animation.ptr(), "track_set_enabled", base_track, track_clipboard[i].enabled); + if (track_clipboard[i].track_type == Animation::TYPE_VALUE) { + undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", base_track, track_clipboard[i].update_mode); + } + + for (int j = 0; j < track_clipboard[i].keys.size(); j++) { + undo_redo->add_do_method(animation.ptr(), "track_insert_key", base_track, track_clipboard[i].keys[j].time, track_clipboard[i].keys[j].value, track_clipboard[i].keys[j].transition); + } + + undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count()); + + base_track++; + } + + undo_redo->commit_action(); + } break; + + case EDIT_SCALE_SELECTION: + case EDIT_SCALE_FROM_CURSOR: { + scale_dialog->popup_centered(Size2(200, 100) * EDSCALE); + } break; + case EDIT_SCALE_CONFIRM: { + if (selection.empty()) + return; + + float from_t = 1e20; + float to_t = -1e20; + float len = -1e20; + float pivot = 0; + + for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) { + float t = animation->track_get_key_time(E->key().track, E->key().key); + if (t < from_t) + from_t = t; + if (t > to_t) + to_t = t; + } + + len = to_t - from_t; + if (last_menu_track_opt == EDIT_SCALE_FROM_CURSOR) { + pivot = timeline->get_play_position(); + + } else { + + pivot = from_t; + } + + float s = scale->get_value(); + if (s == 0) { + ERR_PRINT("Can't scale to 0"); + } + + undo_redo->create_action(TTR("Anim Scale Keys")); + + List<_AnimMoveRestore> to_restore; + + // 1-remove the keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); + } + // 2- remove overlapped keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newtime = (E->get().pos - from_t) * s + from_t; + int idx = animation->track_find_key(E->key().track, newtime, true); + if (idx == -1) + continue; + SelectedKey sk; + sk.key = idx; + sk.track = E->key().track; + if (selection.has(sk)) + continue; //already in selection, don't save + + undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newtime); + _AnimMoveRestore amr; + + amr.key = animation->track_get_key_value(E->key().track, idx); + amr.track = E->key().track; + amr.time = newtime; + amr.transition = animation->track_get_key_transition(E->key().track, idx); + + to_restore.push_back(amr); + } + +#define _NEW_POS(m_ofs) (((s > 0) ? m_ofs : from_t + (len - (m_ofs - from_t))) - pivot) * ABS(s) + from_t + // 3-move the keys (re insert them) + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = _NEW_POS(E->get().pos); + undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + } + + // 4-(undo) remove inserted keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float newpos = _NEW_POS(E->get().pos); + undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_position", E->key().track, newpos); + } + + // 5-(undo) reinsert keys + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + } + + // 6-(undo) reinsert overlapped keys + for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + _AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); + } + + // 6-(undo) reinsert overlapped keys + for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) { + + _AnimMoveRestore &amr = E->get(); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition); + } + + undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); + undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); + + // 7-reselect + + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + float oldpos = E->get().pos; + float newpos = _NEW_POS(oldpos); + if (newpos >= 0) + undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos); + undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos); + } +#undef _NEW_POS + undo_redo->commit_action(); + } break; + case EDIT_DUPLICATE_SELECTION: { + + if (bezier_edit->is_visible()) { + bezier_edit->duplicate_selection(); + break; + } + _anim_duplicate_keys(false); + } break; + case EDIT_DUPLICATE_TRANSPOSED: { + if (bezier_edit->is_visible()) { + EditorNode::get_singleton()->show_warning(TTR("This option does not work for Bezier editing, as it's only a single track.")); + break; + } + _anim_duplicate_keys(true); + } break; + case EDIT_DELETE_SELECTION: { + + if (bezier_edit->is_visible()) { + bezier_edit->delete_selection(); + break; + } + + if (selection.size()) { + undo_redo->create_action(TTR("Anim Delete Keys")); + + for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) { + + undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key); + undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key)); + } + undo_redo->add_do_method(this, "_clear_selection_for_anim", animation); + undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation); + undo_redo->commit_action(); + //selection.clear(); + _update_key_edit(); + } + } break; + case EDIT_GOTO_NEXT_STEP: { + + if (animation.is_null()) + break; + float step = animation->get_step(); + if (step == 0) + step = 1; + + float pos = timeline->get_play_position(); + + pos = Math::stepify(pos + step, step); + if (pos > animation->get_length()) + pos = animation->get_length(); + set_anim_pos(pos); + + emit_signal("timeline_changed", pos, true); + + } break; + case EDIT_GOTO_PREV_STEP: { + if (animation.is_null()) + break; + float step = animation->get_step(); + if (step == 0) + step = 1; + + float pos = timeline->get_play_position(); + pos = Math::stepify(pos - step, step); + if (pos < 0) + pos = 0; + set_anim_pos(pos); + emit_signal("timeline_changed", pos, true); + + } break; + case EDIT_OPTIMIZE_ANIMATION: { + optimize_dialog->popup_centered(Size2(250, 180) * EDSCALE); + + } break; + case EDIT_OPTIMIZE_ANIMATION_CONFIRM: { + animation->optimize(optimize_linear_error->get_value(), optimize_angular_error->get_value(), optimize_max_angle->get_value()); + _update_tracks(); + undo_redo->clear_history(); + + } break; + case EDIT_CLEAN_UP_ANIMATION: { + cleanup_dialog->popup_centered_minsize(Size2(300, 0) * EDSCALE); + + } break; + case EDIT_CLEAN_UP_ANIMATION_CONFIRM: { + if (cleanup_all->is_pressed()) { + List<StringName> names; + AnimationPlayerEditor::singleton->get_player()->get_animation_list(&names); + for (List<StringName>::Element *E = names.front(); E; E = E->next()) { + _cleanup_animation(AnimationPlayerEditor::singleton->get_player()->get_animation(E->get())); + } + } else { + _cleanup_animation(animation); + } + + } break; + } +} + +void AnimationTrackEditor::_cleanup_animation(Ref<Animation> p_animation) { + + for (int i = 0; i < p_animation->get_track_count(); i++) { + + bool prop_exists = false; + Variant::Type valid_type = Variant::NIL; + Object *obj = NULL; + + RES res; + Vector<StringName> leftover_path; + + Node *node = root->get_node_and_resource(p_animation->track_get_path(i), res, leftover_path); + + if (res.is_valid()) { + obj = res.ptr(); + } else if (node) { + obj = node; + } + + if (obj && p_animation->track_get_type(i) == Animation::TYPE_VALUE) { + valid_type = obj->get_static_property_type_indexed(leftover_path, &prop_exists); + } + + if (!obj && cleanup_tracks->is_pressed()) { + + p_animation->remove_track(i); + i--; + continue; + } + + if (!prop_exists || p_animation->track_get_type(i) != Animation::TYPE_VALUE || cleanup_keys->is_pressed() == false) + continue; + + for (int j = 0; j < p_animation->track_get_key_count(i); j++) { + + Variant v = p_animation->track_get_key_value(i, j); + + if (!Variant::can_convert(v.get_type(), valid_type)) { + p_animation->track_remove_key(i, j); + j--; + } + } + + if (p_animation->track_get_key_count(i) == 0 && cleanup_tracks->is_pressed()) { + p_animation->remove_track(i); + i--; + } + } + + undo_redo->clear_history(); + _update_tracks(); +} + +void AnimationTrackEditor::_view_group_toggle() { + _update_tracks(); + view_group->set_icon(get_icon(view_group->is_pressed() ? "AnimationTrackList" : "AnimationTrackGroup", "EditorIcons")); +} + +void AnimationTrackEditor::_selection_changed() { + + if (selected_filter->is_pressed()) { + _update_tracks(); //needs updatin + } else { + for (int i = 0; i < track_edits.size(); i++) { + track_edits[i]->update(); + } + + for (int i = 0; i < groups.size(); i++) { + groups[i]->update(); + } + } +} + +float AnimationTrackEditor::snap_time(float p_value) { + + if (snap->is_pressed()) { + p_value = Math::stepify(p_value, step->get_value()); + } + + return p_value; +} + +void AnimationTrackEditor::_bind_methods() { + + ClassDB::bind_method("_animation_changed", &AnimationTrackEditor::_animation_changed); + ClassDB::bind_method("_timeline_changed", &AnimationTrackEditor::_timeline_changed); + ClassDB::bind_method("_track_remove_request", &AnimationTrackEditor::_track_remove_request); + ClassDB::bind_method("_name_limit_changed", &AnimationTrackEditor::_name_limit_changed); + ClassDB::bind_method("_update_scroll", &AnimationTrackEditor::_update_scroll); + ClassDB::bind_method("_update_step", &AnimationTrackEditor::_update_step); + ClassDB::bind_method("_update_length", &AnimationTrackEditor::_update_length); + ClassDB::bind_method("_dropped_track", &AnimationTrackEditor::_dropped_track); + ClassDB::bind_method("_add_track", &AnimationTrackEditor::_add_track); + ClassDB::bind_method("_new_track_node_selected", &AnimationTrackEditor::_new_track_node_selected); + ClassDB::bind_method("_new_track_property_selected", &AnimationTrackEditor::_new_track_property_selected); + ClassDB::bind_method("_root_removed", &AnimationTrackEditor::_root_removed); + ClassDB::bind_method("_confirm_insert_list", &AnimationTrackEditor::_confirm_insert_list); + ClassDB::bind_method("_insert_delay", &AnimationTrackEditor::_insert_delay); + ClassDB::bind_method("_timeline_value_changed", &AnimationTrackEditor::_timeline_value_changed); + ClassDB::bind_method("_insert_key_from_track", &AnimationTrackEditor::_insert_key_from_track); + ClassDB::bind_method("_add_method_key", &AnimationTrackEditor::_add_method_key); + ClassDB::bind_method("_key_selected", &AnimationTrackEditor::_key_selected); + ClassDB::bind_method("_key_deselected", &AnimationTrackEditor::_key_deselected); + ClassDB::bind_method("_clear_selection", &AnimationTrackEditor::_clear_selection); + ClassDB::bind_method("_move_selection_begin", &AnimationTrackEditor::_move_selection_begin); + ClassDB::bind_method("_move_selection", &AnimationTrackEditor::_move_selection); + ClassDB::bind_method("_move_selection_commit", &AnimationTrackEditor::_move_selection_commit); + ClassDB::bind_method("_move_selection_cancel", &AnimationTrackEditor::_move_selection_cancel); + ClassDB::bind_method("_clear_selection_for_anim", &AnimationTrackEditor::_clear_selection_for_anim); + ClassDB::bind_method("_select_at_anim", &AnimationTrackEditor::_select_at_anim); + ClassDB::bind_method("_scroll_input", &AnimationTrackEditor::_scroll_input); + ClassDB::bind_method("_box_selection_draw", &AnimationTrackEditor::_box_selection_draw); + ClassDB::bind_method("_bezier_edit", &AnimationTrackEditor::_bezier_edit); + ClassDB::bind_method("_cancel_bezier_edit", &AnimationTrackEditor::_cancel_bezier_edit); + ClassDB::bind_method("_edit_menu_pressed", &AnimationTrackEditor::_edit_menu_pressed); + ClassDB::bind_method("_view_group_toggle", &AnimationTrackEditor::_view_group_toggle); + ClassDB::bind_method("_selection_changed", &AnimationTrackEditor::_selection_changed); + + ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "position"), PropertyInfo(Variant::BOOL, "drag"))); + ADD_SIGNAL(MethodInfo("keying_changed")); + ADD_SIGNAL(MethodInfo("animation_len_changed", PropertyInfo(Variant::REAL, "len"))); + ADD_SIGNAL(MethodInfo("animation_step_changed", PropertyInfo(Variant::REAL, "step"))); +} + +AnimationTrackEditor::AnimationTrackEditor() { + root = NULL; + block_animation_update = false; + + undo_redo = EditorNode::get_singleton()->get_undo_redo(); + HBoxContainer *timeline_scroll = memnew(HBoxContainer); + add_child(timeline_scroll); + timeline_scroll->set_v_size_flags(SIZE_EXPAND_FILL); + + VBoxContainer *timeline_vbox = memnew(VBoxContainer); + timeline_scroll->add_child(timeline_vbox); + timeline_vbox->set_v_size_flags(SIZE_EXPAND_FILL); + timeline_vbox->set_h_size_flags(SIZE_EXPAND_FILL); + timeline_vbox->add_constant_override("separation", 0); + + timeline = memnew(AnimationTimelineEdit); + timeline->set_block_animation_update_ptr(&block_animation_update); + timeline->set_undo_redo(undo_redo); + timeline_vbox->add_child(timeline); + timeline->connect("timeline_changed", this, "_timeline_changed"); + timeline->connect("name_limit_changed", this, "_name_limit_changed"); + timeline->connect("track_added", this, "_add_track"); + timeline->connect("value_changed", this, "_timeline_value_changed"); + timeline->connect("length_changed", this, "_update_length"); + + scroll = memnew(ScrollContainer); + timeline_vbox->add_child(scroll); + scroll->set_v_size_flags(SIZE_EXPAND_FILL); + VScrollBar *sb = scroll->get_v_scrollbar(); + scroll->remove_child(sb); + timeline_scroll->add_child(sb); //move here so timeline and tracks are always aligned + scroll->connect("gui_input", this, "_scroll_input"); + + bezier_edit = memnew(AnimationBezierTrackEdit); + timeline_vbox->add_child(bezier_edit); + bezier_edit->set_block_animation_update_ptr(&block_animation_update); + bezier_edit->set_undo_redo(undo_redo); + bezier_edit->set_editor(this); + bezier_edit->set_timeline(timeline); + bezier_edit->hide(); + bezier_edit->set_v_size_flags(SIZE_EXPAND_FILL); + bezier_edit->connect("close_request", this, "_cancel_bezier_edit"); + + timeline_vbox->set_custom_minimum_size(Size2(0, 150) * EDSCALE); + + hscroll = memnew(HScrollBar); + timeline_vbox->add_child(hscroll); + hscroll->share(timeline); + hscroll->connect("value_changed", this, "_update_scroll"); + timeline->set_hscroll(hscroll); + + track_vbox = memnew(VBoxContainer); + scroll->add_child(track_vbox); + track_vbox->set_h_size_flags(SIZE_EXPAND_FILL); + scroll->set_enable_h_scroll(false); + scroll->set_enable_v_scroll(true); + track_vbox->add_constant_override("separation", 0); + + timeline_vbox->add_child(memnew(HSeparator)); + HBoxContainer *bottom_hb = memnew(HBoxContainer); + add_child(bottom_hb); + bottom_hb->add_spacer(); + + selected_filter = memnew(ToolButton); + selected_filter->connect("pressed", this, "_view_group_toggle"); //same function works the same + selected_filter->set_toggle_mode(true); + selected_filter->set_tooltip(TTR("Only show tracks from nodes selected in tree.")); + + bottom_hb->add_child(selected_filter); + + view_group = memnew(ToolButton); + view_group->connect("pressed", this, "_view_group_toggle"); + view_group->set_toggle_mode(true); + view_group->set_tooltip(TTR("Group tracks by node or display them as plain list.")); + + bottom_hb->add_child(view_group); + bottom_hb->add_child(memnew(VSeparator)); + + snap = memnew(ToolButton); + snap->set_text(TTR("Snap (s): ")); + bottom_hb->add_child(snap); + snap->set_disabled(true); + snap->set_toggle_mode(true); + snap->set_pressed(true); + + step = memnew(EditorSpinSlider); + step->set_min(0); + step->set_max(1000); + step->set_step(0.01); + step->set_hide_slider(true); + step->set_custom_minimum_size(Size2(100, 0) * EDSCALE); + bottom_hb->add_child(step); + step->connect("value_changed", this, "_update_step"); + step->set_read_only(true); + + bottom_hb->add_child(memnew(VSeparator)); + + zoom_icon = memnew(TextureRect); + zoom_icon->set_v_size_flags(SIZE_SHRINK_CENTER); + bottom_hb->add_child(zoom_icon); + zoom = memnew(HSlider); + zoom->set_step(0.01); + zoom->set_min(0.0); + zoom->set_max(2.0); + zoom->set_value(1.0); + zoom->set_custom_minimum_size(Size2(200, 0) * EDSCALE); + zoom->set_v_size_flags(SIZE_SHRINK_CENTER); + bottom_hb->add_child(zoom); + timeline->set_zoom(zoom); + + edit = memnew(MenuButton); + edit->set_text(TTR("Edit")); + edit->set_flat(false); + edit->get_popup()->add_item(TTR("Copy Tracks"), EDIT_COPY_TRACKS); + edit->get_popup()->add_item(TTR("Paste Tracks"), EDIT_PASTE_TRACKS); + edit->get_popup()->add_separator(); + edit->get_popup()->add_item(TTR("Scale Selection"), EDIT_SCALE_SELECTION); + edit->get_popup()->add_item(TTR("Scale From Cursor"), EDIT_SCALE_FROM_CURSOR); + edit->get_popup()->add_separator(); + edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/duplicate_selection", TTR("Duplicate Selection"), KEY_MASK_CMD | KEY_D), EDIT_DUPLICATE_SELECTION); + edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/duplicate_selection_transposed", TTR("Duplicate Transposed"), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_D), EDIT_DUPLICATE_TRANSPOSED); + edit->get_popup()->set_item_shortcut_disabled(edit->get_popup()->get_item_index(EDIT_DUPLICATE_SELECTION), true); + edit->get_popup()->set_item_shortcut_disabled(edit->get_popup()->get_item_index(EDIT_DUPLICATE_TRANSPOSED), true); + edit->get_popup()->add_separator(); + edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/delete_selection", TTR("Delete Selection"), KEY_DELETE), EDIT_DELETE_SELECTION); + edit->get_popup()->set_item_shortcut_disabled(edit->get_popup()->get_item_index(EDIT_DELETE_SELECTION), true); + //this shortcut will be checked from the track itself. so no need to enable it here (will conflict with scenetree dock) + + edit->get_popup()->add_separator(); + edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/goto_next_step", TTR("Goto Next Step"), KEY_MASK_CMD | KEY_RIGHT), EDIT_GOTO_NEXT_STEP); + edit->get_popup()->add_shortcut(ED_SHORTCUT("animation_editor/goto_prev_step", TTR("Goto Prev Step"), KEY_MASK_CMD | KEY_LEFT), EDIT_GOTO_PREV_STEP); + edit->get_popup()->add_separator(); + edit->get_popup()->add_item(TTR("Optimize Animation"), EDIT_OPTIMIZE_ANIMATION); + edit->get_popup()->add_item(TTR("Clean-Up Animation"), EDIT_CLEAN_UP_ANIMATION); + + edit->get_popup()->connect("id_pressed", this, "_edit_menu_pressed"); + + pick_track = memnew(SceneTreeDialog); + add_child(pick_track); + pick_track->set_title(TTR("Pick the node that will be animated:")); + pick_track->connect("selected", this, "_new_track_node_selected"); + prop_selector = memnew(PropertySelector); + add_child(prop_selector); + prop_selector->connect("selected", this, "_new_track_property_selected"); + + method_selector = memnew(PropertySelector); + add_child(method_selector); + method_selector->connect("selected", this, "_add_method_key"); + + inserting = false; + insert_query = false; + insert_frame = 0; + insert_queue = false; + + insert_confirm = memnew(ConfirmationDialog); + add_child(insert_confirm); + insert_confirm->connect("confirmed", this, "_confirm_insert_list"); + VBoxContainer *icvb = memnew(VBoxContainer); + insert_confirm->add_child(icvb); + insert_confirm_text = memnew(Label); + icvb->add_child(insert_confirm_text); + insert_confirm_bezier = memnew(CheckBox); + insert_confirm_bezier->set_text(TTR("Use Bezier Curves")); + icvb->add_child(insert_confirm_bezier); + keying = false; + moving_selection = 0; + key_edit = NULL; + + box_selection = memnew(Control); + add_child(box_selection); + box_selection->set_as_toplevel(true); + box_selection->set_mouse_filter(MOUSE_FILTER_IGNORE); + box_selection->hide(); + box_selection->connect("draw", this, "_box_selection_draw"); + box_selecting = false; + + //default plugins + + Ref<AnimationTrackEditDefaultPlugin> def_plugin; + def_plugin.instance(); + add_track_edit_plugin(def_plugin); + + //dialogs + + optimize_dialog = memnew(ConfirmationDialog); + add_child(optimize_dialog); + optimize_dialog->set_title(TTR("Anim. Optimizer")); + VBoxContainer *optimize_vb = memnew(VBoxContainer); + optimize_dialog->add_child(optimize_vb); + + optimize_linear_error = memnew(SpinBox); + optimize_linear_error->set_max(1.0); + optimize_linear_error->set_min(0.001); + optimize_linear_error->set_step(0.001); + optimize_linear_error->set_value(0.05); + optimize_vb->add_margin_child(TTR("Max. Linear Error:"), optimize_linear_error); + optimize_angular_error = memnew(SpinBox); + optimize_angular_error->set_max(1.0); + optimize_angular_error->set_min(0.001); + optimize_angular_error->set_step(0.001); + optimize_angular_error->set_value(0.01); + + optimize_vb->add_margin_child(TTR("Max. Angular Error:"), optimize_angular_error); + optimize_max_angle = memnew(SpinBox); + optimize_vb->add_margin_child(TTR("Max Optimizable Angle:"), optimize_max_angle); + optimize_max_angle->set_max(360.0); + optimize_max_angle->set_min(0.0); + optimize_max_angle->set_step(0.1); + optimize_max_angle->set_value(22); + + optimize_dialog->get_ok()->set_text(TTR("Optimize")); + optimize_dialog->connect("confirmed", this, "_edit_menu_pressed", varray(EDIT_CLEAN_UP_ANIMATION_CONFIRM)); + + // + + cleanup_dialog = memnew(ConfirmationDialog); + add_child(cleanup_dialog); + VBoxContainer *cleanup_vb = memnew(VBoxContainer); + cleanup_dialog->add_child(cleanup_vb); + + cleanup_keys = memnew(CheckButton); + cleanup_keys->set_text(TTR("Remove invalid keys")); + cleanup_keys->set_pressed(true); + cleanup_vb->add_child(cleanup_keys); + + cleanup_tracks = memnew(CheckButton); + cleanup_tracks->set_text(TTR("Remove unresolved and empty tracks")); + cleanup_tracks->set_pressed(true); + cleanup_vb->add_child(cleanup_tracks); + + cleanup_all = memnew(CheckButton); + cleanup_all->set_text(TTR("Clean-up all animations")); + cleanup_vb->add_child(cleanup_all); + + cleanup_dialog->set_title(TTR("Clean-Up Animation(s) (NO UNDO!)")); + cleanup_dialog->get_ok()->set_text(TTR("Clean-Up")); + + cleanup_dialog->connect("confirmed", this, "_edit_menu_pressed", varray(EDIT_CLEAN_UP_ANIMATION_CONFIRM)); + + // + scale_dialog = memnew(ConfirmationDialog); + VBoxContainer *vbc = memnew(VBoxContainer); + scale_dialog->add_child(vbc); + + scale = memnew(SpinBox); + scale->set_min(-99999); + scale->set_max(99999); + scale->set_step(0.001); + vbc->add_margin_child(TTR("Scale Ratio:"), scale); + scale_dialog->connect("confirmed", this, "_edit_menu_pressed", varray(EDIT_SCALE_CONFIRM)); + add_child(scale_dialog); + + track_copy_dialog = memnew(ConfirmationDialog); + add_child(track_copy_dialog); + track_copy_dialog->set_title(TTR("Select tracks to copy:")); + track_copy_dialog->get_ok()->set_text(TTR("Copy")); + + track_copy_select = memnew(Tree); + track_copy_select->set_hide_root(true); + track_copy_dialog->add_child(track_copy_select); + track_copy_dialog->connect("confirmed", this, "_edit_menu_pressed", varray(EDIT_COPY_TRACKS_CONFIRM)); +} + +AnimationTrackEditor::~AnimationTrackEditor() { + if (key_edit) { + memdelete(key_edit); + } +} diff --git a/editor/animation_track_editor.h b/editor/animation_track_editor.h new file mode 100644 index 0000000000..92caa8d408 --- /dev/null +++ b/editor/animation_track_editor.h @@ -0,0 +1,483 @@ +#ifndef ANIMATION_TRACK_EDITOR_H +#define ANIMATION_TRACK_EDITOR_H + +#include "scene/gui/control.h" +#include "scene/gui/file_dialog.h" +#include "scene/gui/menu_button.h" +#include "scene/gui/scroll_bar.h" +#include "scene/gui/slider.h" +#include "scene/gui/spin_box.h" +#include "scene/gui/tab_container.h" +#include "scene/gui/texture_rect.h" +#include "scene/gui/tool_button.h" + +#include "editor/property_selector.h" +#include "editor_data.h" +#include "editor_spin_slider.h" +#include "property_editor.h" +#include "scene/animation/animation_cache.h" +#include "scene/resources/animation.h" +#include "scene_tree_editor.h" + +class AnimationTimelineEdit : public Range { + GDCLASS(AnimationTimelineEdit, Range) + + Ref<Animation> animation; + int name_limit; + Range *zoom; + Range *h_scroll; + float play_position_pos; + + HBoxContainer *len_hb; + EditorSpinSlider *length; + ToolButton *loop; + TextureRect *time_icon; + + MenuButton *add_track; + Control *play_position; //separate control used to draw so updates for only position changed are much faster + HScrollBar *hscroll; + + void _zoom_changed(double); + void _anim_length_changed(double p_new_len); + void _anim_loop_pressed(); + + void _play_position_draw(); + UndoRedo *undo_redo; + Rect2 hsize_rect; + + bool editing; + bool *block_animation_update_ptr; //used to block all tracks re-gen (speed up) + + bool panning_timeline; + float panning_timeline_from; + float panning_timeline_at; + bool dragging_timeline; + bool dragging_hsize; + float dragging_hsize_from; + float dragging_hsize_at; + + void _gui_input(const Ref<InputEvent> &p_event); + void _track_added(int p_track); + +protected: + static void _bind_methods(); + void _notification(int p_what); + +public: + int get_name_limit() const; + int get_buttons_width() const; + + float get_zoom_scale() const; + + virtual Size2 get_minimum_size() const; + void set_animation(const Ref<Animation> &p_animation); + void set_zoom(Range *p_zoom); + Range *get_zoom() const { return zoom; } + void set_undo_redo(UndoRedo *p_undo_redo); + void set_block_animation_update_ptr(bool *p_block_ptr); + + void set_play_position(float p_pos); + float get_play_position() const; + void update_play_position(); + + void update_values(); + + void set_hscroll(HScrollBar *p_hscroll); + + AnimationTimelineEdit(); +}; + +class AnimationTrackEditor; + +class AnimationTrackEdit : public Control { + + GDCLASS(AnimationTrackEdit, Control) + + enum { + MENU_CALL_MODE_CONTINUOUS, + MENU_CALL_MODE_DISCRETE, + MENU_CALL_MODE_TRIGGER, + MENU_CALL_MODE_CAPTURE, + MENU_INTERPOLATION_NEAREST, + MENU_INTERPOLATION_LINEAR, + MENU_INTERPOLATION_CUBIC, + MENU_LOOP_WRAP, + MENU_LOOP_CLAMP, + MENU_KEY_INSERT, + MENU_KEY_DUPLICATE, + MENU_KEY_DELETE + }; + AnimationTimelineEdit *timeline; + UndoRedo *undo_redo; + LineEdit *path; + Node *root; + Control *play_position; //separate control used to draw so updates for only position changed are much faster + float play_position_pos; + + Ref<Animation> animation; + int track; + + Rect2 check_rect; + Rect2 path_rect; + + Rect2 update_mode_rect; + Rect2 interp_mode_rect; + Rect2 loop_mode_rect; + Rect2 remove_rect; + Rect2 bezier_edit_rect; + + Ref<Texture> type_icon; + Ref<Texture> selected_icon; + + PopupMenu *menu; + + bool clicking_on_name; + + void _zoom_changed(); + + Ref<Texture> icon_cache; + String path_cache; + + void _menu_selected(int p_index); + + bool *block_animation_update_ptr; //used to block all tracks re-gen (speed up) + + void _path_entered(const String &p_text); + void _play_position_draw(); + mutable int dropping_at; + + float insert_at_pos; + bool moving_selection_attempt; + int select_single_attempt; + bool moving_selection; + float moving_selection_from_ofs; + + bool in_group; + AnimationTrackEditor *editor; + +protected: + static void _bind_methods(); + void _notification(int p_what); + + virtual void _gui_input(const Ref<InputEvent> &p_event); + +public: + virtual Variant get_drag_data(const Point2 &p_point); + virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const; + virtual void drop_data(const Point2 &p_point, const Variant &p_data); + + virtual String get_tooltip(const Point2 &p_pos) const; + + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right); + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + virtual void draw_bg(int p_clip_left, int p_clip_right); + virtual void draw_fg(int p_clip_left, int p_clip_right); + + //helper + void draw_texture_clipped(const Ref<Texture> &p_texture, const Vector2 &p_pos); + void draw_texture_region_clipped(const Ref<Texture> &p_texture, const Rect2 &p_rect, const Rect2 &p_region); + void draw_rect_clipped(const Rect2 &p_rect, const Color &p_color, bool p_filled = true); + + int get_track() const; + Ref<Animation> get_animation() const; + AnimationTimelineEdit *get_timeline() const { return timeline; } + AnimationTrackEditor *get_editor() const { return editor; } + UndoRedo *get_undo_redo() const { return undo_redo; } + bool *get_block_animation_update_ptr() { return block_animation_update_ptr; } + + void set_animation_and_track(const Ref<Animation> &p_animation, int p_track); + virtual Size2 get_minimum_size() const; + + void set_undo_redo(UndoRedo *p_undo_redo); + void set_timeline(AnimationTimelineEdit *p_timeline); + void set_editor(AnimationTrackEditor *p_editor); + void set_root(Node *p_root); + + void set_block_animation_update_ptr(bool *p_block_ptr); + + void set_play_position(float p_pos); + void update_play_position(); + void cancel_drop(); + + void set_in_group(bool p_enable); + void append_to_selection(const Rect2 &p_box); + + AnimationTrackEdit(); +}; + +class AnimationTrackEditPlugin : public Reference { + GDCLASS(AnimationTrackEditPlugin, Reference) +public: + virtual AnimationTrackEdit *create_value_track_edit(Object *p_object, Variant::Type p_type, const String &p_property, PropertyHint p_hint, const String &p_hint_string, int p_usage); + virtual AnimationTrackEdit *create_audio_track_edit(); + virtual AnimationTrackEdit *create_animation_track_edit(Object *p_object); +}; + +class AnimationTrackKeyEdit; +class AnimationBezierTrackEdit; + +class AnimationTrackEditGroup : public Control { + GDCLASS(AnimationTrackEditGroup, Control) + Ref<Texture> icon; + String node_name; + NodePath node; + Node *root; + AnimationTimelineEdit *timeline; + + void _zoom_changed(); + +protected: + static void _bind_methods(); + void _notification(int p_what); + +public: + void set_type_and_name(const Ref<Texture> &p_type, const String &p_name, const NodePath &p_node); + virtual Size2 get_minimum_size() const; + void set_timeline(AnimationTimelineEdit *p_timeline); + void set_root(Node *p_root); + + AnimationTrackEditGroup(); +}; + +class AnimationTrackEditor : public VBoxContainer { + GDCLASS(AnimationTrackEditor, VBoxContainer) + + enum { + EDIT_COPY_TRACKS, + EDIT_COPY_TRACKS_CONFIRM, + EDIT_PASTE_TRACKS, + EDIT_SCALE_SELECTION, + EDIT_SCALE_FROM_CURSOR, + EDIT_SCALE_CONFIRM, + EDIT_DUPLICATE_SELECTION, + EDIT_DUPLICATE_TRANSPOSED, + EDIT_DELETE_SELECTION, + EDIT_GOTO_NEXT_STEP, + EDIT_GOTO_PREV_STEP, + EDIT_OPTIMIZE_ANIMATION, + EDIT_OPTIMIZE_ANIMATION_CONFIRM, + EDIT_CLEAN_UP_ANIMATION, + EDIT_CLEAN_UP_ANIMATION_CONFIRM + }; + + Ref<Animation> animation; + Node *root; + + MenuButton *edit; + + HScrollBar *hscroll; + ScrollContainer *scroll; + VBoxContainer *track_vbox; + AnimationBezierTrackEdit *bezier_edit; + + AnimationTimelineEdit *timeline; + HSlider *zoom; + EditorSpinSlider *step; + TextureRect *zoom_icon; + ToolButton *snap; + + Vector<AnimationTrackEdit *> track_edits; + Vector<AnimationTrackEditGroup *> groups; + + bool block_animation_update; + + int _get_track_selected(); + void _animation_changed(); + void _update_tracks(); + + void _name_limit_changed(); + void _timeline_changed(float p_new_pos, bool p_drag); + void _track_remove_request(int p_track); + + UndoRedo *undo_redo; + + void _update_scroll(double); + void _update_step(double p_new_step); + void _update_length(double p_new_step); + void _dropped_track(int p_from_track, int p_to_track); + + void _add_track(int p_type); + void _new_track_node_selected(NodePath p_path); + void _new_track_property_selected(String p_name); + + PropertySelector *prop_selector; + PropertySelector *method_selector; + SceneTreeDialog *pick_track; + int adding_track_type; + NodePath adding_track_path; + + bool keying; + + struct InsertData { + + Animation::TrackType type; + NodePath path; + int track_idx; + Variant value; + String query; + bool advance; + }; /* insert_data;*/ + + Label *insert_confirm_text; + CheckBox *insert_confirm_bezier; + ConfirmationDialog *insert_confirm; + bool insert_queue; + bool inserting; + bool insert_query; + List<InsertData> insert_data; + uint64_t insert_frame; + + void _query_insert(const InsertData &p_id); + void _confirm_insert_list(); + int _confirm_insert(InsertData p_id, int p_last_track, bool p_create_beziers = false); + void _insert_delay(); + + void _root_removed(Node *p_root); + + PropertyInfo _find_hint_for_track(int p_idx, NodePath &r_base_path, Variant *r_current_val = NULL); + + void _timeline_value_changed(double); + + float insert_key_from_track_call_ofs; + int insert_key_from_track_call_track; + void _insert_key_from_track(float p_ofs, int p_track); + void _add_method_key(const String &p_method); + + void _clear_selection(); + void _clear_selection_for_anim(const Ref<Animation> &p_anim); + void _select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos); + + //selection + + struct SelectedKey { + + int track; + int key; + bool operator<(const SelectedKey &p_key) const { return track == p_key.track ? key < p_key.key : track < p_key.track; }; + }; + + struct KeyInfo { + + float pos; + }; + + Map<SelectedKey, KeyInfo> selection; + + void _key_selected(int p_key, bool p_single, int p_track); + void _key_deselected(int p_key, int p_track); + + bool moving_selection; + float moving_selection_offset; + void _move_selection_begin(); + void _move_selection(float p_offset); + void _move_selection_commit(); + void _move_selection_cancel(); + + AnimationTrackKeyEdit *key_edit; + void _update_key_edit(); + + void _clear_key_edit(); + + Control *box_selection; + void _box_selection_draw(); + bool box_selecting; + Vector2 box_selecting_from; + Rect2 box_select_rect; + void _scroll_input(const Ref<InputEvent> &p_event); + + Vector<Ref<AnimationTrackEditPlugin> > track_edit_plugins; + + void _cancel_bezier_edit(); + void _bezier_edit(int p_for_track); + + ////////////// edit menu stuff + + ConfirmationDialog *optimize_dialog; + SpinBox *optimize_linear_error; + SpinBox *optimize_angular_error; + SpinBox *optimize_max_angle; + + ConfirmationDialog *cleanup_dialog; + CheckButton *cleanup_keys; + CheckButton *cleanup_tracks; + CheckButton *cleanup_all; + + ConfirmationDialog *scale_dialog; + SpinBox *scale; + + void _edit_menu_pressed(int p_option); + int last_menu_track_opt; + + void _cleanup_animation(Ref<Animation> p_animation); + + void _anim_duplicate_keys(bool transpose); + + void _view_group_toggle(); + ToolButton *view_group; + ToolButton *selected_filter; + + void _selection_changed(); + + ConfirmationDialog *track_copy_dialog; + Tree *track_copy_select; + struct TrackClipboard { + NodePath full_path; + NodePath base_path; + Animation::TrackType track_type; + Animation::InterpolationType interp_type; + Animation::UpdateMode update_mode; + bool loop_wrap; + bool enabled; + + struct Key { + float time; + float transition; + Variant value; + }; + Vector<Key> keys; + }; + + Vector<TrackClipboard> track_clipboard; + + void _insert_animation_key(NodePath p_path, const Variant &p_value); + +protected: + static void _bind_methods(); + void _notification(int p_what); + +public: + void add_track_edit_plugin(const Ref<AnimationTrackEditPlugin> &p_plugin); + void remove_track_edit_plugin(const Ref<AnimationTrackEditPlugin> &p_plugin); + + void set_animation(const Ref<Animation> &p_anim); + Ref<Animation> get_current_animation() const; + void set_root(Node *p_root); + Node *get_root() const; + void update_keying(); + bool has_keying() const; + + void cleanup(); + + void set_anim_pos(float p_pos); + void insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists = false); + void insert_value_key(const String &p_property, const Variant &p_value, bool p_advance); + void insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform); + + void show_select_node_warning(bool p_show); + + bool is_key_selected(int p_track, int p_key) const; + bool is_selection_active() const; + bool is_moving_selection() const; + float get_moving_selection_offset() const; + bool is_snap_enabled(); + float snap_time(float p_value); + + MenuButton *get_edit_menu(); + AnimationTrackEditor(); + ~AnimationTrackEditor(); +}; + +#endif // ANIMATION_TRACK_EDITOR_H diff --git a/editor/animation_track_editor_plugins.cpp b/editor/animation_track_editor_plugins.cpp new file mode 100644 index 0000000000..660c69f4a4 --- /dev/null +++ b/editor/animation_track_editor_plugins.cpp @@ -0,0 +1,1289 @@ +#include "animation_track_editor_plugins.h" +#include "editor/audio_stream_preview.h" +#include "editor_resource_preview.h" +#include "editor_scale.h" +#include "scene/2d/animated_sprite.h" +#include "scene/2d/sprite.h" +#include "scene/3d/sprite_3d.h" +#include "scene/animation/animation_player.h" +#include "servers/audio/audio_stream.h" +/// BOOL /// +int AnimationTrackEditBool::get_key_height() const { + + Ref<Texture> checked = get_icon("checked", "CheckBox"); + return checked->get_height(); +} +Rect2 AnimationTrackEditBool::get_key_rect(int p_index, float p_pixels_sec) { + + Ref<Texture> checked = get_icon("checked", "CheckBox"); + return Rect2(0, 0, checked->get_width(), get_size().height); +} + +bool AnimationTrackEditBool::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditBool::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Ref<Texture> icon; + bool checked = get_animation()->track_get_key_value(get_track(), p_index); + + if (checked) + icon = get_icon("checked", "CheckBox"); + else + icon = get_icon("unchecked", "CheckBox"); + + Vector2 ofs(p_x, int(get_size().height - icon->get_height()) / 2); + + draw_texture_clipped(icon, ofs); + + if (p_selected) { + Color color = get_color("accent_color", "Editor"); + draw_rect_clipped(Rect2(ofs, icon->get_size()), color, false); + } +} + +/// COLOR /// + +int AnimationTrackEditColor::get_key_height() const { + + Ref<Font> font = get_font("font", "Label"); + return font->get_height() * 0.8; +} +Rect2 AnimationTrackEditColor::get_key_rect(int p_index, float p_pixels_sec) { + + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + return Rect2(0, 0, fh, get_size().height); +} + +bool AnimationTrackEditColor::is_key_selectable_by_distance() const { + + return false; +} + +void AnimationTrackEditColor::draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right) { + + int x_from = p_x; + int x_to = p_next_x; + + Ref<Font> font = get_font("font", "Label"); + int fh = (font->get_height() * 0.8); + + x_from += fh - 1; + x_to += 1; + fh /= 3; + + if (x_from > p_clip_right) + return; + + if (x_to < p_clip_left) + return; + + Color color = get_animation()->track_get_key_value(get_track(), p_index); + Color color_next = get_animation()->track_get_key_value(get_track(), p_index + 1); + + if (x_from < p_clip_left) { + float c = float(p_clip_left - x_from) / (x_to - x_from); + color = color.linear_interpolate(color_next, c); + x_from = p_clip_left; + } + + if (x_to > p_clip_right) { + float c = float(p_clip_right - x_from) / (x_to - x_from); + color_next = color.linear_interpolate(color_next, c); + x_to = p_clip_right; + } + + int y_from = (get_size().height - fh) / 2; + + Vector<Vector2> points; + Vector<Color> colors; + + points.push_back(Vector2(x_from, y_from)); + colors.push_back(color); + + points.push_back(Vector2(x_to, y_from)); + colors.push_back(color_next); + + points.push_back(Vector2(x_to, y_from + fh)); + colors.push_back(color_next); + + points.push_back(Vector2(x_from, y_from + fh)); + colors.push_back(color); + + draw_primitive(points, colors, Vector<Vector2>()); +} + +void AnimationTrackEditColor::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Color color = get_animation()->track_get_key_value(get_track(), p_index); + + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + + Rect2 rect(Vector2(p_x, int(get_size().height - fh) / 2), Size2(fh, fh)); + + draw_rect_clipped(Rect2(rect.position, rect.size / 2), Color(0.4, 0.4, 0.4)); + draw_rect_clipped(Rect2(rect.position + rect.size / 2, rect.size / 2), Color(0.4, 0.4, 0.4)); + draw_rect_clipped(Rect2(rect.position + Vector2(rect.size.x / 2, 0), rect.size / 2), Color(0.6, 0.6, 0.6)); + draw_rect_clipped(Rect2(rect.position + Vector2(0, rect.size.y / 2), rect.size / 2), Color(0.6, 0.6, 0.6)); + draw_rect_clipped(rect, color); + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect_clipped(rect, accent, false); + } +} + +/// AUDIO /// + +void AnimationTrackEditAudio::_preview_changed(ObjectID p_which) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) + return; + + Ref<AudioStream> stream = object->call("get_stream"); + + if (stream.is_valid() && stream->get_instance_id() == p_which) { + update(); + } +} + +int AnimationTrackEditAudio::get_key_height() const { + + if (!ObjectDB::get_instance(id)) { + return AnimationTrackEdit::get_key_height(); + } + + Ref<Font> font = get_font("font", "Label"); + return int(font->get_height() * 1.5); +} +Rect2 AnimationTrackEditAudio::get_key_rect(int p_index, float p_pixels_sec) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + Ref<AudioStream> stream = object->call("get_stream"); + + if (!stream.is_valid()) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + bool play = get_animation()->track_get_key_value(get_track(), p_index); + if (play) { + float len = stream->get_length(); + + if (len == 0) { + + Ref<AudioStreamPreview> preview = AudioStreamPreviewGenerator::get_singleton()->generate_preview(stream); + len = preview->get_length(); + } + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + return Rect2(0, 0, len * p_pixels_sec, get_size().height); + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + return Rect2(0, 0, fh, get_size().height); + } +} + +bool AnimationTrackEditAudio::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditAudio::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + Ref<AudioStream> stream = object->call("get_stream"); + + if (!stream.is_valid()) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + Ref<Font> font = get_font("font", "Label"); + float fh = int(font->get_height() * 1.5); + + bool play = get_animation()->track_get_key_value(get_track(), p_index); + if (play) { + float len = stream->get_length(); + + Ref<AudioStreamPreview> preview = AudioStreamPreviewGenerator::get_singleton()->generate_preview(stream); + + float preview_len = preview->get_length(); + + if (len == 0) { + len = preview_len; + } + + int pixel_len = len * p_pixels_sec; + + int pixel_begin = p_x; + int pixel_end = p_x + pixel_len; + + if (pixel_end < p_clip_left) + return; + + if (pixel_begin > p_clip_right) + return; + + int from_x = MAX(pixel_begin, p_clip_left); + int to_x = MIN(pixel_end, p_clip_right); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + float limit = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + int limit_x = pixel_begin + limit * p_pixels_sec; + to_x = MIN(limit_x, to_x); + } + + if (to_x <= from_x) + return; + + int h = get_size().height; + Rect2 rect = Rect2(from_x, (h - fh) / 2, to_x - from_x, fh); + draw_rect(rect, Color(0.25, 0.25, 0.25)); + + Vector<Vector2> lines; + lines.resize((to_x - from_x + 1) * 2); + preview_len = preview->get_length(); + + for (int i = from_x; i < to_x; i++) { + + float ofs = (i - pixel_begin) * preview_len / pixel_len; + float ofs_n = ((i + 1) - pixel_begin) * preview_len / pixel_len; + float max = preview->get_max(ofs, ofs_n) * 0.5 + 0.5; + float min = preview->get_min(ofs, ofs_n) * 0.5 + 0.5; + + int idx = i - from_x; + lines[idx * 2 + 0] = Vector2(i, rect.position.y + min * rect.size.y); + lines[idx * 2 + 1] = Vector2(i, rect.position.y + max * rect.size.y); + } + + Vector<Color> color; + color.push_back(Color(0.75, 0.75, 0.75)); + + VS::get_singleton()->canvas_item_add_multiline(get_canvas_item(), lines, color); + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + Rect2 rect(Vector2(p_x, int(get_size().height - fh) / 2), Size2(fh, fh)); + + Color color = get_color("font_color", "Label"); + draw_rect(rect, color); + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } +} + +void AnimationTrackEditAudio::set_node(Object *p_object) { + + id = p_object->get_instance_id(); +} + +void AnimationTrackEditAudio::_bind_methods() { + ClassDB::bind_method("_preview_changed", &AnimationTrackEditAudio::_preview_changed); +} + +AnimationTrackEditAudio::AnimationTrackEditAudio() { + AudioStreamPreviewGenerator::get_singleton()->connect("preview_updated", this, "_preview_changed"); +} + +/// SPRITE FRAME /// + +int AnimationTrackEditSpriteFrame::get_key_height() const { + + if (!ObjectDB::get_instance(id)) { + return AnimationTrackEdit::get_key_height(); + } + + Ref<Font> font = get_font("font", "Label"); + return int(font->get_height() * 2); +} +Rect2 AnimationTrackEditSpriteFrame::get_key_rect(int p_index, float p_pixels_sec) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + Size2 size; + + if (Object::cast_to<Sprite>(object) || Object::cast_to<Sprite3D>(object)) { + + Ref<Texture> texture = object->call("get_texture"); + if (!texture.is_valid()) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + size = texture->get_size(); + + if (bool(object->call("is_region"))) { + size = Rect2(object->call("get_region_rect")).size; + } + + int hframes = object->call("get_hframes"); + int vframes = object->call("get_vframes"); + + if (hframes > 1) { + size.x /= hframes; + } + if (vframes > 1) { + size.y /= vframes; + } + } else if (Object::cast_to<AnimatedSprite>(object) || Object::cast_to<AnimatedSprite3D>(object)) { + + int frame = get_animation()->track_get_key_value(get_track(), p_index); + String animation = "default"; //may be smart and go through other tracks to find if animation is set + + Ref<SpriteFrames> sf = object->call("get_sprite_frames"); + if (sf.is_null()) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + Ref<Texture> texture = sf->get_frame(animation, frame); + if (!texture.is_valid()) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + size = texture->get_size(); + } + + size = size.floor(); + + Ref<Font> font = get_font("font", "Label"); + int height = int(font->get_height() * 2); + int width = height * size.width / size.height; + + return Rect2(0, 0, width, get_size().height); +} + +bool AnimationTrackEditSpriteFrame::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditSpriteFrame::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + int frame = get_animation()->track_get_key_value(get_track(), p_index); + + Ref<Texture> texture; + Rect2 region; + + if (Object::cast_to<Sprite>(object) || Object::cast_to<Sprite3D>(object)) { + + texture = object->call("get_texture"); + if (!texture.is_valid()) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + region.size = texture->get_size(); + + if (bool(object->call("is_region"))) { + + region = Rect2(object->call("get_region_rect")); + } + + int hframes = object->call("get_hframes"); + int vframes = object->call("get_vframes"); + + if (hframes > 1) { + region.size.x /= hframes; + } + if (vframes > 1) { + region.size.y /= vframes; + } + + region.position.x += region.size.x * (frame % hframes); + region.position.y += region.size.y * (frame / hframes); + + } else if (Object::cast_to<AnimatedSprite>(object) || Object::cast_to<AnimatedSprite3D>(object)) { + + int frame = get_animation()->track_get_key_value(get_track(), p_index); + String animation = "default"; //may be smart and go through other tracks to find if animation is set + + Ref<SpriteFrames> sf = object->call("get_sprite_frames"); + if (sf.is_null()) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + texture = sf->get_frame(animation, frame); + if (!texture.is_valid()) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + region.size = texture->get_size(); + } + + Ref<Font> font = get_font("font", "Label"); + int height = int(font->get_height() * 2); + + int width = height * region.size.width / region.size.height; + + Rect2 rect(p_x, int(get_size().height - height) / 2, width, height); + + if (rect.position.x + rect.size.x < p_clip_left) + return; + + if (rect.position.x > p_clip_right) + return; + + Color accent = get_color("accent_color", "Editor"); + Color bg = accent; + bg.a = 0.15; + + draw_rect_clipped(rect, bg); + + draw_texture_region_clipped(texture, rect, region); + + if (p_selected) { + draw_rect_clipped(rect, accent, false); + } +} + +void AnimationTrackEditSpriteFrame::set_node(Object *p_object) { + + id = p_object->get_instance_id(); +} + +/// SUB ANIMATION /// + +int AnimationTrackEditSubAnim::get_key_height() const { + + if (!ObjectDB::get_instance(id)) { + return AnimationTrackEdit::get_key_height(); + } + + Ref<Font> font = get_font("font", "Label"); + return int(font->get_height() * 1.5); +} +Rect2 AnimationTrackEditSubAnim::get_key_rect(int p_index, float p_pixels_sec) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(object); + + if (!ap) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + String anim = get_animation()->track_get_key_value(get_track(), p_index); + + if (anim != "[stop]" && ap->has_animation(anim)) { + + float len = ap->get_animation(anim)->get_length(); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + return Rect2(0, 0, len * p_pixels_sec, get_size().height); + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + return Rect2(0, 0, fh, get_size().height); + } +} + +bool AnimationTrackEditSubAnim::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditSubAnim::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(object); + + if (!ap) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + String anim = get_animation()->track_get_key_value(get_track(), p_index); + + if (anim != "[stop]" && ap->has_animation(anim)) { + + float len = ap->get_animation(anim)->get_length(); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + int pixel_len = len * p_pixels_sec; + + int pixel_begin = p_x; + int pixel_end = p_x + pixel_len; + + if (pixel_end < p_clip_left) + return; + + if (pixel_begin > p_clip_right) + return; + + int from_x = MAX(pixel_begin, p_clip_left); + int to_x = MIN(pixel_end, p_clip_right); + + if (to_x <= from_x) + return; + + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 1.5; + + Rect2 rect(from_x, int(get_size().height - fh) / 2, to_x - from_x, fh); + + Color color = get_color("font_color", "Label"); + Color bg = color; + bg.r = 1 - color.r; + bg.g = 1 - color.g; + bg.b = 1 - color.b; + draw_rect(rect, bg); + + Vector<Vector2> lines; + Vector<Color> colorv; + { + Ref<Animation> animation = ap->get_animation(anim); + + for (int i = 0; i < animation->get_track_count(); i++) { + + float h = (rect.size.height - 2) / animation->get_track_count(); + + int y = 2 + h * i + h / 2; + + for (int j = 0; j < animation->track_get_key_count(i); j++) { + + float ofs = animation->track_get_key_time(i, j); + int x = p_x + ofs * p_pixels_sec + 2; + + if (x < from_x || x >= (to_x - 4)) + continue; + + lines.push_back(Point2(x, y)); + lines.push_back(Point2(x + 1, y)); + } + } + + colorv.push_back(color); + } + + if (lines.size() > 2) { + VS::get_singleton()->canvas_item_add_multiline(get_canvas_item(), lines, colorv); + } + + int limit = to_x - from_x - 4; + if (limit > 0) { + draw_string(font, Point2(from_x + 2, int(get_size().height - font->get_height()) / 2 + font->get_ascent()), anim, color); + } + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + Rect2 rect(Vector2(p_x, int(get_size().height - fh) / 2), Size2(fh, fh)); + + Color color = get_color("font_color", "Label"); + draw_rect(rect, color); + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } +} + +void AnimationTrackEditSubAnim::set_node(Object *p_object) { + + id = p_object->get_instance_id(); +} + +//// VOLUME DB //// + +int AnimationTrackEditVolumeDB::get_key_height() const { + + Ref<Texture> volume_texture = get_icon("ColorTrackVu", "EditorIcons"); + return volume_texture->get_height() * 1.2; +} + +void AnimationTrackEditVolumeDB::draw_bg(int p_clip_left, int p_clip_right) { + + Ref<Texture> volume_texture = get_icon("ColorTrackVu", "EditorIcons"); + int tex_h = volume_texture->get_height(); + + int y_from = (get_size().height - tex_h) / 2; + int y_size = tex_h; + + Color color(1, 1, 1, 0.3); + draw_texture_rect(volume_texture, Rect2(p_clip_left, y_from, p_clip_right - p_clip_left, y_from + y_size), false, color); +} + +void AnimationTrackEditVolumeDB::draw_fg(int p_clip_left, int p_clip_right) { + + Ref<Texture> volume_texture = get_icon("ColorTrackVu", "EditorIcons"); + int tex_h = volume_texture->get_height(); + int y_from = (get_size().height - tex_h) / 2; + int db0 = y_from + (24 / 80.0) * tex_h; + + draw_line(Vector2(p_clip_left, db0), Vector2(p_clip_right, db0), Color(1, 1, 1, 0.3)); +} + +void AnimationTrackEditVolumeDB::draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right) { + + if (p_x > p_clip_right || p_next_x < p_clip_left) + return; + + float db = get_animation()->track_get_key_value(get_track(), p_index); + float db_n = get_animation()->track_get_key_value(get_track(), p_index + 1); + + db = CLAMP(db, -60, 24); + db_n = CLAMP(db_n, -60, 24); + + float h = 1.0 - ((db + 60) / 84.0); + float h_n = 1.0 - ((db_n + 60) / 84.0); + + int from_x = p_x; + int to_x = p_next_x; + + if (from_x < p_clip_left) { + h = Math::lerp(h, h_n, float(p_clip_left - from_x) / float(to_x - from_x)); + from_x = p_clip_left; + } + + if (to_x > p_clip_right) { + h_n = Math::lerp(h, h_n, float(p_clip_right - from_x) / float(to_x - from_x)); + to_x = p_clip_right; + } + + Ref<Texture> volume_texture = get_icon("ColorTrackVu", "EditorIcons"); + int tex_h = volume_texture->get_height(); + + int y_from = (get_size().height - tex_h) / 2; + + Color color = get_color("font_color", "Label"); + color.a *= 0.7; + + draw_line(Point2(from_x, y_from + h * tex_h), Point2(to_x, y_from + h_n * tex_h), color, 2); +} + +//////////////////////// + +/// AUDIO /// + +void AnimationTrackEditTypeAudio::_preview_changed(ObjectID p_which) { + + for (int i = 0; i < get_animation()->track_get_key_count(get_track()); i++) { + Ref<AudioStream> stream = get_animation()->audio_track_get_key_stream(get_track(), i); + if (stream.is_valid() && stream->get_instance_id() == p_which) { + update(); + return; + } + } +} + +int AnimationTrackEditTypeAudio::get_key_height() const { + + Ref<Font> font = get_font("font", "Label"); + return int(font->get_height() * 1.5); +} +Rect2 AnimationTrackEditTypeAudio::get_key_rect(int p_index, float p_pixels_sec) { + + Ref<AudioStream> stream = get_animation()->audio_track_get_key_stream(get_track(), p_index); + + if (!stream.is_valid()) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + float start_ofs = get_animation()->audio_track_get_key_start_offset(get_track(), p_index); + float end_ofs = get_animation()->audio_track_get_key_end_offset(get_track(), p_index); + + float len = stream->get_length(); + + if (len == 0) { + + Ref<AudioStreamPreview> preview = AudioStreamPreviewGenerator::get_singleton()->generate_preview(stream); + len = preview->get_length(); + } + + len -= end_ofs; + len -= start_ofs; + if (len <= 0.001) { + len = 0.001; + } + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + return Rect2(0, 0, len * p_pixels_sec, get_size().height); +} + +bool AnimationTrackEditTypeAudio::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditTypeAudio::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Ref<AudioStream> stream = get_animation()->audio_track_get_key_stream(get_track(), p_index); + + if (!stream.is_valid()) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + float start_ofs = get_animation()->audio_track_get_key_start_offset(get_track(), p_index); + float end_ofs = get_animation()->audio_track_get_key_end_offset(get_track(), p_index); + + if (len_resizing && p_index == len_resizing_index) { + float ofs_local = -len_resizing_rel / get_timeline()->get_zoom_scale(); + if (len_resizing_start) { + start_ofs += ofs_local; + if (start_ofs < 0) + start_ofs = 0; + } else { + end_ofs += ofs_local; + if (end_ofs < 0) + end_ofs = 0; + } + } + + Ref<Font> font = get_font("font", "Label"); + float fh = int(font->get_height() * 1.5); + + float len = stream->get_length(); + + Ref<AudioStreamPreview> preview = AudioStreamPreviewGenerator::get_singleton()->generate_preview(stream); + + float preview_len = preview->get_length(); + + if (len == 0) { + len = preview_len; + } + + int pixel_total_len = len * p_pixels_sec; + + len -= end_ofs; + len -= start_ofs; + + if (len <= 0.001) { + len = 0.001; + } + + int pixel_len = len * p_pixels_sec; + + int pixel_begin = p_x; + int pixel_end = p_x + pixel_len; + + if (pixel_end < p_clip_left) + return; + + if (pixel_begin > p_clip_right) + return; + + int from_x = MAX(pixel_begin, p_clip_left); + int to_x = MIN(pixel_end, p_clip_right); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + float limit = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + int limit_x = pixel_begin + limit * p_pixels_sec; + to_x = MIN(limit_x, to_x); + } + + if (to_x <= from_x) { + to_x = from_x + 1; + } + + int h = get_size().height; + Rect2 rect = Rect2(from_x, (h - fh) / 2, to_x - from_x, fh); + draw_rect(rect, Color(0.25, 0.25, 0.25)); + + Vector<Vector2> lines; + lines.resize((to_x - from_x + 1) * 2); + preview_len = preview->get_length(); + + for (int i = from_x; i < to_x; i++) { + + float ofs = (i - pixel_begin) * preview_len / pixel_total_len; + float ofs_n = ((i + 1) - pixel_begin) * preview_len / pixel_total_len; + ofs += start_ofs; + ofs_n += start_ofs; + + float max = preview->get_max(ofs, ofs_n) * 0.5 + 0.5; + float min = preview->get_min(ofs, ofs_n) * 0.5 + 0.5; + + int idx = i - from_x; + lines[idx * 2 + 0] = Vector2(i, rect.position.y + min * rect.size.y); + lines[idx * 2 + 1] = Vector2(i, rect.position.y + max * rect.size.y); + } + + Vector<Color> color; + color.push_back(Color(0.75, 0.75, 0.75)); + + VS::get_singleton()->canvas_item_add_multiline(get_canvas_item(), lines, color); + + Color cut_color = get_color("accent_color", "Editor"); + cut_color.a = 0.7; + if (start_ofs > 0 && pixel_begin > p_clip_left) { + draw_rect(Rect2(pixel_begin, rect.position.y, 1, rect.size.y), cut_color); + } + if (end_ofs > 0 && pixel_end < p_clip_right) { + draw_rect(Rect2(pixel_end, rect.position.y, 1, rect.size.y), cut_color); + } + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } +} + +void AnimationTrackEditTypeAudio::_bind_methods() { + ClassDB::bind_method("_preview_changed", &AnimationTrackEditTypeAudio::_preview_changed); +} + +AnimationTrackEditTypeAudio::AnimationTrackEditTypeAudio() { + AudioStreamPreviewGenerator::get_singleton()->connect("preview_updated", this, "_preview_changed"); + len_resizing = false; +} + +bool AnimationTrackEditTypeAudio::can_drop_data(const Point2 &p_point, const Variant &p_data) const { + + if (p_point.x > get_timeline()->get_name_limit() && p_point.x < get_size().width - get_timeline()->get_buttons_width()) { + + Dictionary drag_data = p_data; + if (drag_data.has("type") && String(drag_data["type"]) == "resource") { + Ref<AudioStream> res = drag_data["resource"]; + if (res.is_valid()) { + return true; + } + } + + if (drag_data.has("type") && String(drag_data["type"]) == "files") { + + Vector<String> files = drag_data["files"]; + + if (files.size() == 1) { + String file = files[0]; + Ref<AudioStream> res = ResourceLoader::load(file); + if (res.is_valid()) { + return true; + } + } + } + } + + return AnimationTrackEdit::can_drop_data(p_point, p_data); +} +void AnimationTrackEditTypeAudio::drop_data(const Point2 &p_point, const Variant &p_data) { + + if (p_point.x > get_timeline()->get_name_limit() && p_point.x < get_size().width - get_timeline()->get_buttons_width()) { + + Ref<AudioStream> stream; + Dictionary drag_data = p_data; + if (drag_data.has("type") && String(drag_data["type"]) == "resource") { + stream = drag_data["resource"]; + } else if (drag_data.has("type") && String(drag_data["type"]) == "files") { + + Vector<String> files = drag_data["files"]; + + if (files.size() == 1) { + String file = files[0]; + stream = ResourceLoader::load(file); + } + } + + if (stream.is_valid()) { + + int x = p_point.x - get_timeline()->get_name_limit(); + float ofs = x / get_timeline()->get_zoom_scale(); + ofs += get_timeline()->get_value(); + + ofs = get_editor()->snap_time(ofs); + + while (get_animation()->track_find_key(get_track(), ofs, true) != -1) { //make sure insertion point is valid + ofs += 0.001; + } + + print_line("inserting"); + + *get_block_animation_update_ptr() = true; + get_undo_redo()->create_action("Add Audio Track Clip"); + get_undo_redo()->add_do_method(get_animation().ptr(), "audio_track_insert_key", get_track(), ofs, stream); + get_undo_redo()->add_undo_method(get_animation().ptr(), "track_remove_key_at_position", get_track(), ofs); + get_undo_redo()->commit_action(); + *get_block_animation_update_ptr() = false; + + update(); + return; + } + } + + return AnimationTrackEdit::drop_data(p_point, p_data); +} + +void AnimationTrackEditTypeAudio::_gui_input(const Ref<InputEvent> &p_event) { + + Ref<InputEventMouseMotion> mm = p_event; + if (!len_resizing && mm.is_valid()) { + bool use_hsize_cursor = false; + for (int i = 0; i < get_animation()->track_get_key_count(get_track()); i++) { + + Ref<AudioStream> stream = get_animation()->audio_track_get_key_stream(get_track(), i); + + if (!stream.is_valid()) { + continue; + } + + float start_ofs = get_animation()->audio_track_get_key_start_offset(get_track(), i); + float end_ofs = get_animation()->audio_track_get_key_end_offset(get_track(), i); + float len = stream->get_length(); + + if (len == 0) { + Ref<AudioStreamPreview> preview = AudioStreamPreviewGenerator::get_singleton()->generate_preview(stream); + float preview_len = preview->get_length(); + len = preview_len; + } + + len -= end_ofs; + len -= start_ofs; + if (len <= 0.001) { + len = 0.001; + } + + if (get_animation()->track_get_key_count(get_track()) > i + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), i + 1) - get_animation()->track_get_key_time(get_track(), i)); + } + + float ofs = get_animation()->track_get_key_time(get_track(), i); + + ofs -= get_timeline()->get_value(); + ofs *= get_timeline()->get_zoom_scale(); + ofs += get_timeline()->get_name_limit(); + + int end = ofs + len * get_timeline()->get_zoom_scale(); + + if (end >= get_timeline()->get_name_limit() && end <= get_size().width - get_timeline()->get_buttons_width() && ABS(mm->get_position().x - end) < 5 * EDSCALE) { + use_hsize_cursor = true; + len_resizing_index = i; + } + } + + if (use_hsize_cursor) { + set_default_cursor_shape(CURSOR_HSIZE); + } else { + set_default_cursor_shape(CURSOR_ARROW); + } + } + + if (len_resizing && mm.is_valid()) { + len_resizing_rel += mm->get_relative().x; + len_resizing_start = mm->get_shift(); + update(); + accept_event(); + return; + } + + Ref<InputEventMouseButton> mb = p_event; + if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && get_default_cursor_shape() == CURSOR_HSIZE) { + + len_resizing = true; + len_resizing_start = mb->get_shift(); + len_resizing_from_px = mb->get_position().x; + len_resizing_rel = 0; + update(); + accept_event(); + return; + } + + if (len_resizing && mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { + + float ofs_local = -len_resizing_rel / get_timeline()->get_zoom_scale(); + if (len_resizing_start) { + float prev_ofs = get_animation()->audio_track_get_key_start_offset(get_track(), len_resizing_index); + *get_block_animation_update_ptr() = true; + get_undo_redo()->create_action("Change Audio Track Clip Start Offset"); + get_undo_redo()->add_do_method(get_animation().ptr(), "audio_track_set_key_start_offset", get_track(), len_resizing_index, prev_ofs + ofs_local); + get_undo_redo()->add_undo_method(get_animation().ptr(), "audio_track_set_key_start_offset", get_track(), len_resizing_index, prev_ofs); + get_undo_redo()->commit_action(); + *get_block_animation_update_ptr() = false; + + } else { + float prev_ofs = get_animation()->audio_track_get_key_end_offset(get_track(), len_resizing_index); + *get_block_animation_update_ptr() = true; + get_undo_redo()->create_action("Change Audio Track Clip End Offset"); + get_undo_redo()->add_do_method(get_animation().ptr(), "audio_track_set_key_end_offset", get_track(), len_resizing_index, prev_ofs + ofs_local); + get_undo_redo()->add_undo_method(get_animation().ptr(), "audio_track_set_key_end_offset", get_track(), len_resizing_index, prev_ofs); + get_undo_redo()->commit_action(); + *get_block_animation_update_ptr() = false; + } + + len_resizing = false; + len_resizing_index = -1; + update(); + accept_event(); + return; + } + + AnimationTrackEdit::_gui_input(p_event); +} + +//////////////////// +/// SUB ANIMATION /// + +int AnimationTrackEditTypeAnimation::get_key_height() const { + + if (!ObjectDB::get_instance(id)) { + return AnimationTrackEdit::get_key_height(); + } + + Ref<Font> font = get_font("font", "Label"); + return int(font->get_height() * 1.5); +} +Rect2 AnimationTrackEditTypeAnimation::get_key_rect(int p_index, float p_pixels_sec) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(object); + + if (!ap) { + return AnimationTrackEdit::get_key_rect(p_index, p_pixels_sec); + } + + String anim = get_animation()->animation_track_get_key_animation(get_track(), p_index); + print_line("anim " + anim + " has " + itos(ap->has_animation(anim))); + + if (anim != "[stop]" && ap->has_animation(anim)) { + + float len = ap->get_animation(anim)->get_length(); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + return Rect2(0, 0, len * p_pixels_sec, get_size().height); + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + return Rect2(0, 0, fh, get_size().height); + } +} + +bool AnimationTrackEditTypeAnimation::is_key_selectable_by_distance() const { + + return false; +} +void AnimationTrackEditTypeAnimation::draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right) { + + Object *object = ObjectDB::get_instance(id); + + if (!object) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(object); + + if (!ap) { + AnimationTrackEdit::draw_key(p_index, p_pixels_sec, p_x, p_selected, p_clip_left, p_clip_right); + return; + } + + String anim = get_animation()->animation_track_get_key_animation(get_track(), p_index); + + if (anim != "[stop]" && ap->has_animation(anim)) { + + float len = ap->get_animation(anim)->get_length(); + + if (get_animation()->track_get_key_count(get_track()) > p_index + 1) { + len = MIN(len, get_animation()->track_get_key_time(get_track(), p_index + 1) - get_animation()->track_get_key_time(get_track(), p_index)); + } + + int pixel_len = len * p_pixels_sec; + + int pixel_begin = p_x; + int pixel_end = p_x + pixel_len; + + if (pixel_end < p_clip_left) + return; + + if (pixel_begin > p_clip_right) + return; + + int from_x = MAX(pixel_begin, p_clip_left); + int to_x = MIN(pixel_end, p_clip_right); + + if (to_x <= from_x) + return; + + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 1.5; + + Rect2 rect(from_x, int(get_size().height - fh) / 2, to_x - from_x, fh); + + Color color = get_color("font_color", "Label"); + Color bg = color; + bg.r = 1 - color.r; + bg.g = 1 - color.g; + bg.b = 1 - color.b; + draw_rect(rect, bg); + + Vector<Vector2> lines; + Vector<Color> colorv; + { + Ref<Animation> animation = ap->get_animation(anim); + + for (int i = 0; i < animation->get_track_count(); i++) { + + float h = (rect.size.height - 2) / animation->get_track_count(); + + int y = 2 + h * i + h / 2; + + for (int j = 0; j < animation->track_get_key_count(i); j++) { + + float ofs = animation->track_get_key_time(i, j); + int x = p_x + ofs * p_pixels_sec + 2; + + if (x < from_x || x >= (to_x - 4)) + continue; + + lines.push_back(Point2(x, y)); + lines.push_back(Point2(x + 1, y)); + } + } + + colorv.push_back(color); + } + + if (lines.size() > 2) { + VS::get_singleton()->canvas_item_add_multiline(get_canvas_item(), lines, colorv); + } + + int limit = to_x - from_x - 4; + if (limit > 0) { + draw_string(font, Point2(from_x + 2, int(get_size().height - font->get_height()) / 2 + font->get_ascent()), anim, color); + } + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } else { + Ref<Font> font = get_font("font", "Label"); + int fh = font->get_height() * 0.8; + Rect2 rect(Vector2(p_x, int(get_size().height - fh) / 2), Size2(fh, fh)); + + Color color = get_color("font_color", "Label"); + draw_rect(rect, color); + + if (p_selected) { + Color accent = get_color("accent_color", "Editor"); + draw_rect(rect, accent, false); + } + } +} + +void AnimationTrackEditTypeAnimation::set_node(Object *p_object) { + + id = p_object->get_instance_id(); +} + +AnimationTrackEditTypeAnimation::AnimationTrackEditTypeAnimation() { +} + +///////// +AnimationTrackEdit *AnimationTrackEditDefaultPlugin::create_value_track_edit(Object *p_object, Variant::Type p_type, const String &p_property, PropertyHint p_hint, const String &p_hint_string, int p_usage) { + + if (p_property == "playing" && (p_object->is_class("AudioStreamPlayer") || p_object->is_class("AudioStreamPlayer2D") || p_object->is_class("AudioStreamPlayer3D"))) { + + AnimationTrackEditAudio *audio = memnew(AnimationTrackEditAudio); + audio->set_node(p_object); + return audio; + } + + if (p_property == "frame" && (p_object->is_class("Sprite") || p_object->is_class("Sprite3D") || p_object->is_class("AnimatedSprite") || p_object->is_class("AnimatedSprite3D"))) { + + AnimationTrackEditSpriteFrame *sprite = memnew(AnimationTrackEditSpriteFrame); + sprite->set_node(p_object); + return sprite; + } + + if (p_property == "current_animation" && (p_object->is_class("AnimationPlayer"))) { + + AnimationTrackEditSubAnim *player = memnew(AnimationTrackEditSubAnim); + player->set_node(p_object); + return player; + } + + if (p_property == "volume_db") { + + AnimationTrackEditVolumeDB *vu = memnew(AnimationTrackEditVolumeDB); + return vu; + } + + if (p_type == Variant::BOOL) { + return memnew(AnimationTrackEditBool); + } + if (p_type == Variant::COLOR) { + return memnew(AnimationTrackEditColor); + } + + return NULL; +} + +AnimationTrackEdit *AnimationTrackEditDefaultPlugin::create_audio_track_edit() { + + return memnew(AnimationTrackEditTypeAudio); +} + +AnimationTrackEdit *AnimationTrackEditDefaultPlugin::create_animation_track_edit(Object *p_object) { + + AnimationTrackEditTypeAnimation *an = memnew(AnimationTrackEditTypeAnimation); + an->set_node(p_object); + return an; +} diff --git a/editor/animation_track_editor_plugins.h b/editor/animation_track_editor_plugins.h new file mode 100644 index 0000000000..59604412d9 --- /dev/null +++ b/editor/animation_track_editor_plugins.h @@ -0,0 +1,139 @@ +#ifndef ANIMATION_TRACK_EDITOR_PLUGINS_H +#define ANIMATION_TRACK_EDITOR_PLUGINS_H + +#include "editor/animation_track_editor.h" + +class AnimationTrackEditBool : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditBool, AnimationTrackEdit) + Ref<Texture> icon_checked; + Ref<Texture> icon_unchecked; + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); +}; + +class AnimationTrackEditColor : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditColor, AnimationTrackEdit) + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + virtual void draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right); +}; + +class AnimationTrackEditAudio : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditAudio, AnimationTrackEdit) + + ObjectID id; + + void _preview_changed(ObjectID p_which); + +protected: + static void _bind_methods(); + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + + void set_node(Object *p_object); + + AnimationTrackEditAudio(); +}; + +class AnimationTrackEditSpriteFrame : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditSpriteFrame, AnimationTrackEdit) + + ObjectID id; + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + + void set_node(Object *p_object); +}; + +class AnimationTrackEditSubAnim : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditSubAnim, AnimationTrackEdit) + + ObjectID id; + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + + void set_node(Object *p_object); +}; + +class AnimationTrackEditTypeAudio : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditTypeAudio, AnimationTrackEdit) + + void _preview_changed(ObjectID p_which); + + bool len_resizing; + bool len_resizing_start; + int len_resizing_index; + float len_resizing_from_px; + float len_resizing_rel; + +protected: + static void _bind_methods(); + +public: + virtual void _gui_input(const Ref<InputEvent> &p_event); + + virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const; + virtual void drop_data(const Point2 &p_point, const Variant &p_data); + + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + + AnimationTrackEditTypeAudio(); +}; + +class AnimationTrackEditTypeAnimation : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditTypeAnimation, AnimationTrackEdit) + + ObjectID id; + +public: + virtual int get_key_height() const; + virtual Rect2 get_key_rect(int p_index, float p_pixels_sec); + virtual bool is_key_selectable_by_distance() const; + virtual void draw_key(int p_index, float p_pixels_sec, int p_x, bool p_selected, int p_clip_left, int p_clip_right); + + void set_node(Object *p_object); + AnimationTrackEditTypeAnimation(); +}; + +class AnimationTrackEditVolumeDB : public AnimationTrackEdit { + GDCLASS(AnimationTrackEditVolumeDB, AnimationTrackEdit) + +public: + virtual void draw_bg(int p_clip_left, int p_clip_right); + virtual void draw_fg(int p_clip_left, int p_clip_right); + virtual int get_key_height() const; + virtual void draw_key_link(int p_index, float p_pixels_sec, int p_x, int p_next_x, int p_clip_left, int p_clip_right); +}; + +class AnimationTrackEditDefaultPlugin : public AnimationTrackEditPlugin { + GDCLASS(AnimationTrackEditDefaultPlugin, AnimationTrackEditPlugin) +public: + virtual AnimationTrackEdit *create_value_track_edit(Object *p_object, Variant::Type p_type, const String &p_property, PropertyHint p_hint, const String &p_hint_string, int p_usage); + virtual AnimationTrackEdit *create_audio_track_edit(); + virtual AnimationTrackEdit *create_animation_track_edit(Object *p_object); +}; + +#endif // ANIMATION_TRACK_EDITOR_PLUGINS_H diff --git a/editor/audio_stream_preview.cpp b/editor/audio_stream_preview.cpp new file mode 100644 index 0000000000..6ee4d7f4b0 --- /dev/null +++ b/editor/audio_stream_preview.cpp @@ -0,0 +1,211 @@ +#include "audio_stream_preview.h" + +///////////////////// + +float AudioStreamPreview::get_length() const { + return length; +} +float AudioStreamPreview::get_max(float p_time, float p_time_next) const { + + if (length == 0) + return 0; + + int max = preview.size() / 2; + int time_from = p_time / length * max; + int time_to = p_time_next / length * max; + time_from = CLAMP(time_from, 0, max - 1); + time_to = CLAMP(time_to, 0, max - 1); + + if (time_to <= time_from) { + time_to = time_from + 1; + } + + uint8_t vmax; + + for (int i = time_from; i < time_to; i++) { + + uint8_t v = preview[i * 2 + 1]; + if (i == 0 || v > vmax) { + vmax = v; + } + } + + return (vmax / 255.0) * 2.0 - 1.0; +} +float AudioStreamPreview::get_min(float p_time, float p_time_next) const { + + if (length == 0) + return 0; + + int max = preview.size() / 2; + int time_from = p_time / length * max; + int time_to = p_time_next / length * max; + time_from = CLAMP(time_from, 0, max - 1); + time_to = CLAMP(time_to, 0, max - 1); + + if (time_to <= time_from) { + time_to = time_from + 1; + } + + uint8_t vmin; + + for (int i = time_from; i < time_to; i++) { + + uint8_t v = preview[i * 2]; + if (i == 0 || v < vmin) { + vmin = v; + } + } + + return (vmin / 255.0) * 2.0 - 1.0; +} + +AudioStreamPreview::AudioStreamPreview() { + length = 0; +} + +//// + +void AudioStreamPreviewGenerator::_update_emit(ObjectID p_id) { + emit_signal("preview_updated", p_id); +} + +void AudioStreamPreviewGenerator::_preview_thread(void *p_preview) { + + Preview *preview = (Preview *)p_preview; + + float muxbuff_chunk_s = 0.25; + + int mixbuff_chunk_frames = AudioServer::get_singleton()->get_mix_rate() * muxbuff_chunk_s; + + Vector<AudioFrame> mix_chunk; + mix_chunk.resize(mixbuff_chunk_frames); + + int frames_total = AudioServer::get_singleton()->get_mix_rate() * preview->preview->length; + int frames_todo = frames_total; + + preview->playback->start(); + + while (frames_todo) { + + int ofs_write = uint64_t(frames_total - frames_todo) * uint64_t(preview->preview->preview.size() / 2) / uint64_t(frames_total); + int to_read = MIN(frames_todo, mixbuff_chunk_frames); + int to_write = uint64_t(to_read) * uint64_t(preview->preview->preview.size() / 2) / uint64_t(frames_total); + to_write = MIN(to_write, (preview->preview->preview.size() / 2) - ofs_write); + + preview->playback->mix(mix_chunk.ptrw(), 1.0, to_read); + + for (int i = 0; i < to_write; i++) { + float max = -1000; + float min = 1000; + int from = uint64_t(i) * to_read / to_write; + int to = uint64_t(i + 1) * to_read / to_write; + to = MIN(to, to_read); + from = MIN(from, to_read - 1); + if (to == from) { + to = from + 1; + } + + for (int j = from; j < to; j++) { + + max = MAX(max, mix_chunk[j].l); + max = MAX(max, mix_chunk[j].r); + + min = MIN(min, mix_chunk[j].l); + min = MIN(min, mix_chunk[j].r); + } + + uint8_t pfrom = CLAMP((min * 0.5 + 0.5) * 255, 0, 255); + uint8_t pto = CLAMP((max * 0.5 + 0.5) * 255, 0, 255); + + preview->preview->preview[(ofs_write + i) * 2 + 0] = pfrom; + preview->preview->preview[(ofs_write + i) * 2 + 1] = pto; + } + + frames_todo -= to_read; + singleton->call_deferred("_update_emit", preview->id); + } + + preview->playback->stop(); + + preview->generating = false; +} + +Ref<AudioStreamPreview> AudioStreamPreviewGenerator::generate_preview(const Ref<AudioStream> &p_stream) { + ERR_FAIL_COND_V(p_stream.is_null(), Ref<AudioStreamPreview>()); + + if (previews.has(p_stream->get_instance_id())) { + return previews[p_stream->get_instance_id()].preview; + } + + //no preview exists + + previews[p_stream->get_instance_id()] = Preview(); + + Preview *preview = &previews[p_stream->get_instance_id()]; + preview->base_stream = p_stream; + preview->playback = preview->base_stream->instance_playback(); + preview->generating = true; + preview->id = p_stream->get_instance_id(); + + float len_s = preview->base_stream->get_length(); + if (len_s == 0) { + len_s = 60 * 5; //five minutes + } + + int frames = AudioServer::get_singleton()->get_mix_rate() * len_s; + + Vector<uint8_t> maxmin; + int pw = frames / 20; + maxmin.resize(pw * 2); + { + uint8_t *ptr = maxmin.ptrw(); + for (int i = 0; i < pw * 2; i++) { + ptr[i] = 127; + } + } + + preview->preview.instance(); + preview->preview->preview = maxmin; + preview->preview->length = len_s; + + preview->thread = Thread::create(_preview_thread, preview); + + return preview->preview; +} + +void AudioStreamPreviewGenerator::_bind_methods() { + ClassDB::bind_method("_update_emit", &AudioStreamPreviewGenerator::_update_emit); + ClassDB::bind_method(D_METHOD("generate_preview", "stream"), &AudioStreamPreviewGenerator::generate_preview); + + ADD_SIGNAL(MethodInfo("preview_updated", PropertyInfo(Variant::INT, "obj_id"))); +} + +AudioStreamPreviewGenerator *AudioStreamPreviewGenerator::singleton = NULL; + +void AudioStreamPreviewGenerator::_notification(int p_what) { + if (p_what == NOTIFICATION_PROCESS) { + List<ObjectID> to_erase; + for (Map<ObjectID, Preview>::Element *E = previews.front(); E; E = E->next()) { + if (!E->get().generating) { + if (E->get().thread) { + Thread::wait_to_finish(E->get().thread); + E->get().thread = NULL; + } + if (!ObjectDB::get_instance(E->key())) { //no longer in use, get rid of preview + to_erase.push_back(E->key()); + } + } + } + + while (to_erase.front()) { + previews.erase(to_erase.front()->get()); + to_erase.pop_front(); + } + } +} + +AudioStreamPreviewGenerator::AudioStreamPreviewGenerator() { + singleton = this; + set_process(true); +} diff --git a/editor/audio_stream_preview.h b/editor/audio_stream_preview.h new file mode 100644 index 0000000000..cfe1667e9d --- /dev/null +++ b/editor/audio_stream_preview.h @@ -0,0 +1,56 @@ +#ifndef AUDIO_STREAM_PREVIEW_H +#define AUDIO_STREAM_PREVIEW_H + +#include "os/thread.h" +#include "scene/main/node.h" +#include "servers/audio/audio_stream.h" + +class AudioStreamPreview : public Reference { + GDCLASS(AudioStreamPreview, Reference) + friend class AudioStream; + Vector<uint8_t> preview; + float length; + + friend class AudioStreamPreviewGenerator; + +public: + float get_length() const; + float get_max(float p_time, float p_time_next) const; + float get_min(float p_time, float p_time_next) const; + + AudioStreamPreview(); +}; + +class AudioStreamPreviewGenerator : public Node { + GDCLASS(AudioStreamPreviewGenerator, Node) + + static AudioStreamPreviewGenerator *singleton; + + struct Preview { + Ref<AudioStreamPreview> preview; + Ref<AudioStream> base_stream; + Ref<AudioStreamPlayback> playback; + volatile bool generating; + ObjectID id; + Thread *thread; + }; + + Map<ObjectID, Preview> previews; + + static void _preview_thread(void *p_preview); + + void _update_emit(ObjectID p_id); + +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + static AudioStreamPreviewGenerator *get_singleton() { return singleton; } + + Ref<AudioStreamPreview> generate_preview(const Ref<AudioStream> &p_preview); + + AudioStreamPreviewGenerator(); +}; + +#endif // AUDIO_STREAM_PREVIEW_H diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index a6f159ce34..ebfb63b1f3 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -1331,8 +1331,9 @@ void EditorInspector::update_tree() { } else if (!(p.usage & PROPERTY_USAGE_EDITOR)) continue; - if (hide_script && p.name == "script") + if (p.name == "script" && (hide_script || bool(object->call("_hide_script_from_inspector")))) { continue; + } String basename = p.name; if (group != "") { diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 7e3af2b755..067c451012 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -51,7 +51,6 @@ #include "scene/resources/packed_scene.h" #include "servers/physics_2d_server.h" -#include "editor/animation_editor.h" #include "editor/editor_audio_buses.h" #include "editor/editor_file_system.h" #include "editor/editor_help.h" @@ -3038,6 +3037,7 @@ void EditorNode::register_editor_types() { ClassDB::register_class<EditorInspector>(); ClassDB::register_class<EditorInspectorPlugin>(); ClassDB::register_class<EditorProperty>(); + ClassDB::register_class<AnimationTrackEditPlugin>(); // FIXME: Is this stuff obsolete, or should it be ported to new APIs? ClassDB::register_class<EditorScenePostImport>(); @@ -5300,6 +5300,8 @@ EditorNode::EditorNode() { file->connect("file_selected", this, "_dialog_action"); file_templates->connect("file_selected", this, "_dialog_action"); + preview_gen = memnew(AudioStreamPreviewGenerator); + add_child(preview_gen); //plugin stuff file_server = memnew(EditorFileServer); @@ -5382,8 +5384,7 @@ EditorNode::EditorNode() { resource_preview->add_preview_generator(Ref<EditorPackedScenePreviewPlugin>(memnew(EditorPackedScenePreviewPlugin))); resource_preview->add_preview_generator(Ref<EditorMaterialPreviewPlugin>(memnew(EditorMaterialPreviewPlugin))); resource_preview->add_preview_generator(Ref<EditorScriptPreviewPlugin>(memnew(EditorScriptPreviewPlugin))); - // FIXME: Needs to be rewritten for AudioStream in Godot 3.0+ - //resource_preview->add_preview_generator( Ref<EditorSamplePreviewPlugin>( memnew(EditorSamplePreviewPlugin ))); + resource_preview->add_preview_generator(Ref<EditorAudioStreamPreviewPlugin>(memnew(EditorAudioStreamPreviewPlugin))); resource_preview->add_preview_generator(Ref<EditorMeshPreviewPlugin>(memnew(EditorMeshPreviewPlugin))); resource_preview->add_preview_generator(Ref<EditorBitmapPreviewPlugin>(memnew(EditorBitmapPreviewPlugin))); resource_preview->add_preview_generator(Ref<EditorFontPreviewPlugin>(memnew(EditorFontPreviewPlugin))); diff --git a/editor/editor_node.h b/editor/editor_node.h index bef5bc816c..416ec9b31e 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -32,6 +32,7 @@ #define EDITOR_NODE_H #include "core/print_string.h" +#include "editor/audio_stream_preview.h" #include "editor/connections_dialog.h" #include "editor/create_dialog.h" #include "editor/editor_about.h" @@ -81,6 +82,7 @@ #include "scene/gui/tool_button.h" #include "scene/gui/tree.h" #include "scene/gui/viewport_container.h" + /** @author Juan Linietsky <reduzio@gmail.com> */ @@ -298,6 +300,7 @@ private: Vector<ToolButton *> main_editor_buttons; Vector<EditorPlugin *> editor_table; + AudioStreamPreviewGenerator *preview_gen; ProgressDialog *progress_dialog; BackgroundProgress *progress_hb; diff --git a/editor/editor_spin_slider.cpp b/editor/editor_spin_slider.cpp index 087dcd649f..0852a42794 100644 --- a/editor/editor_spin_slider.cpp +++ b/editor/editor_spin_slider.cpp @@ -37,6 +37,9 @@ String EditorSpinSlider::get_text_value() const { } void EditorSpinSlider::_gui_input(const Ref<InputEvent> &p_event) { + if (read_only) + return; + Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && mb->get_button_index() == BUTTON_LEFT) { @@ -301,10 +304,23 @@ void EditorSpinSlider::_grabber_mouse_exited() { update(); } +void EditorSpinSlider::set_read_only(bool p_enable) { + + read_only = p_enable; + update(); +} + +bool EditorSpinSlider::is_read_only() const { + return read_only; +} + void EditorSpinSlider::_bind_methods() { ClassDB::bind_method(D_METHOD("set_label", "label"), &EditorSpinSlider::set_label); ClassDB::bind_method(D_METHOD("get_label"), &EditorSpinSlider::get_label); + ClassDB::bind_method(D_METHOD("set_read_only", "read_only"), &EditorSpinSlider::set_read_only); + ClassDB::bind_method(D_METHOD("is_read_only"), &EditorSpinSlider::is_read_only); + ClassDB::bind_method(D_METHOD("_gui_input"), &EditorSpinSlider::_gui_input); ClassDB::bind_method(D_METHOD("_grabber_mouse_entered"), &EditorSpinSlider::_grabber_mouse_entered); ClassDB::bind_method(D_METHOD("_grabber_mouse_exited"), &EditorSpinSlider::_grabber_mouse_exited); @@ -313,6 +329,7 @@ void EditorSpinSlider::_bind_methods() { ClassDB::bind_method(D_METHOD("_value_input_entered"), &EditorSpinSlider::_value_input_entered); ADD_PROPERTY(PropertyInfo(Variant::STRING, "label"), "set_label", "get_label"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "read_only"), "set_read_only", "is_read_only"); } EditorSpinSlider::EditorSpinSlider() { @@ -342,4 +359,5 @@ EditorSpinSlider::EditorSpinSlider() { value_input->connect("modal_closed", this, "_value_input_closed"); value_input->connect("text_entered", this, "_value_input_entered"); hide_slider = false; + read_only = false; } diff --git a/editor/editor_spin_slider.h b/editor/editor_spin_slider.h index 4956990dc2..37d8a5f128 100644 --- a/editor/editor_spin_slider.h +++ b/editor/editor_spin_slider.h @@ -55,6 +55,8 @@ class EditorSpinSlider : public Range { bool grabbing_spinner_attempt; bool grabbing_spinner; + + bool read_only; Vector2 grabbing_spinner_mouse_pos; LineEdit *value_input; @@ -80,6 +82,9 @@ public: void set_hide_slider(bool p_hide); bool is_hiding_slider() const; + void set_read_only(bool p_enable); + bool is_read_only() const; + virtual Size2 get_minimum_size() const; EditorSpinSlider(); }; diff --git a/editor/icons/icon_animation_filter.svg b/editor/icons/icon_animation_filter.svg new file mode 100644 index 0000000000..4f8e881ea8 --- /dev/null +++ b/editor/icons/icon_animation_filter.svg @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_animation_filter.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1089" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="10.429825" + inkscape:cx="-5.6414698" + inkscape:cy="10.961343" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g10" /> + <g + transform="matrix(0.02719109,0,0,0.02719109,1.3153462,1.0022864)" + id="g12"> + <g + id="g10"> + <path + inkscape:connector-curvature="0" + d="M 495.289,20.143 H 16.709 c -14.938,0 -22.344,18.205 -11.666,28.636 l 169.7,165.778 v 260.587 c 0,14.041 16.259,21.739 27.131,13.031 L 331.017,384.743 c 3.956,-3.169 6.258,-7.962 6.258,-13.031 V 214.556 L 506.955,48.779 c 10.688,-10.44 3.259,-28.636 -11.666,-28.636 z" + id="path8" + style="fill:#e0e0e0;fill-opacity:1" /> + </g> + </g> +</svg> diff --git a/editor/icons/icon_animation_track_group.svg b/editor/icons/icon_animation_track_group.svg new file mode 100644 index 0000000000..9c4748a528 --- /dev/null +++ b/editor/icons/icon_animation_track_group.svg @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_animation_track_group.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1089" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="10.429825" + inkscape:cx="6.2135985" + inkscape:cy="6.5622523" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <path + style="fill:#e0e0e0" + inkscape:connector-curvature="0" + id="path2" + d="M 5.0508475,2 V 4 H 14 V 2 Z m -3.322034,-0.016949 v 2 h 2 v -2 z M 8.9830508,7 V 9 H 14 V 7 Z m -3.5254237,5 v 2 h 2 v -2 z m 3.5254237,0 v 2 H 14 v -2 z" + sodipodi:nodetypes="ccccccccccccccccccccccccc" /> + <path + style="fill:#e0e0e0" + inkscape:connector-curvature="0" + id="path2-3" + d="m 5.4915255,6.9322039 v 1.999999 h 2 v -1.999999 z" + sodipodi:nodetypes="ccccc" /> +</svg> diff --git a/editor/icons/icon_animation_track_list.svg b/editor/icons/icon_animation_track_list.svg new file mode 100644 index 0000000000..40e8414598 --- /dev/null +++ b/editor/icons/icon_animation_track_list.svg @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_animation_track_list.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1089" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="14.75" + inkscape:cx="8" + inkscape:cy="8" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <g + transform="translate(0 -1036.4)" + id="g4"> + <path + transform="translate(0 1036.4)" + d="m2 2v2h2v-2h-2zm4 0v2h8v-2h-8zm-4 5v2h2v-2h-2zm4 0v2h8v-2h-8zm-4 5v2h2v-2h-2zm4 0v2h8v-2h-8z" + fill="#e0e0e0" + id="path2" /> + </g> +</svg> diff --git a/editor/icons/icon_bezier_handles_balanced.svg b/editor/icons/icon_bezier_handles_balanced.svg new file mode 100644 index 0000000000..8ab99d79bb --- /dev/null +++ b/editor/icons/icon_bezier_handles_balanced.svg @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_bezier_handles_balanced.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1417" + inkscape:window-height="685" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="4.2910315" + inkscape:cy="11.857644" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:1.70000005;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 1.7627119,13.627119 c 0,0 1.2881355,-6.847458 6.5762712,-8.1355935 5.0847459,0.9491522 5.9661009,8.1355925 5.9661009,8.1355925" + id="path4526" + inkscape:connector-curvature="0" + sodipodi:nodetypes="ccc" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846" + cx="1.8983043" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3" + cx="14.237288" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.61799997;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 7.4559186,5.1473018 2.7203863,6.7014816" + id="path5878" + inkscape:connector-curvature="0" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.61489719;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 10.790357,4.2063094 8.2893822,5.149623" + id="path5878-7" + inkscape:connector-curvature="0" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3-6" + cx="8.2711868" + cy="4.7796612" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="M 1.7157324,5.8754878 A 1.2675855,1.1997888 0 0 0 0.44815434,7.0747066 1.2675855,1.1997888 0 0 0 1.7157324,8.2739253 1.2675855,1.1997888 0 0 0 2.9833105,7.0747066 1.2675855,1.1997888 0 0 0 1.7157324,5.8754878 Z m 0.00195,0.4238282 A 0.84677333,0.80148375 0 0 1 2.5653417,7.1000972 0.84677333,0.80148375 0 0 1 1.7176855,7.9008784 0.84677333,0.80148375 0 0 1 0.87002934,7.1000972 0.84677333,0.80148375 0 0 1 1.7176855,6.299316 Z" + id="path5846-5" + inkscape:connector-curvature="0" /> + <path + inkscape:connector-curvature="0" + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.7567277;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="M 11.909414,2.4642073 A 1.2836218,1.231838 0 0 0 10.6258,3.6954601 1.2836218,1.231838 0 0 0 11.909414,4.9267128 1.2836218,1.231838 0 0 0 13.193028,3.6954601 1.2836218,1.231838 0 0 0 11.909414,2.4642073 Z m 0.002,0.4351497 a 0.85748593,0.82289328 0 0 1 0.858383,0.8221719 0.85748593,0.82289328 0 0 1 -0.85838,0.822172 0.85748593,0.82289328 0 0 1 -0.858379,-0.822172 0.85748593,0.82289328 0 0 1 0.858379,-0.8221719 z" + id="path5846-5-6" /> +</svg> diff --git a/editor/icons/icon_bezier_handles_free.svg b/editor/icons/icon_bezier_handles_free.svg new file mode 100644 index 0000000000..e5dfb8d0fc --- /dev/null +++ b/editor/icons/icon_bezier_handles_free.svg @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_bezier_handles_separate.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1417" + inkscape:window-height="685" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="4.2910315" + inkscape:cy="11.857644" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:1.70000005;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 1.7627119,13.627119 c 0,0 1.2881355,-6.847458 6.5762712,-8.1355935 5.0847459,0.9491522 5.9661009,8.1355925 5.9661009,8.1355925" + id="path4526" + inkscape:connector-curvature="0" + sodipodi:nodetypes="ccc" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846" + cx="1.8983043" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3" + cx="14.237288" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.80513805;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 7.6850253,4.7560401 3.9088983,5.4168" + id="path5878" + inkscape:connector-curvature="0" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.73079807;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 11.695505,2.3941651 8.696384,4.6876729" + id="path5878-7" + inkscape:connector-curvature="0" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3-6" + cx="8.2711868" + cy="4.7796612" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="M 2.4961199,4.3976698 A 1.1997888,1.2675855 80.074672 0 0 1.4542161,5.7974257 1.1997888,1.2675855 80.074672 0 0 2.9095255,6.7602105 1.1997888,1.2675855 80.074672 0 0 3.9514292,5.3604547 1.1997888,1.2675855 80.074672 0 0 2.4961199,4.3976698 Z m 0.074974,0.4171488 A 0.80148375,0.84677333 80.074672 0 1 3.5440925,5.4575082 0.80148375,0.84677333 80.074672 0 1 2.8471493,6.3924102 0.80148375,0.84677333 80.074672 0 1 1.8741535,5.74972 0.80148375,0.84677333 80.074672 0 1 2.5710967,4.814818 Z" + id="path5846-5" + inkscape:connector-curvature="0" /> + <path + inkscape:connector-curvature="0" + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.7567277;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 11.838896,0.64428913 a 1.231838,1.2836218 52.593897 0 0 -0.271701,1.75779027 1.231838,1.2836218 52.593897 0 0 1.767576,0.1983008 1.231838,1.2836218 52.593897 0 0 0.271701,-1.75779027 1.231838,1.2836218 52.593897 0 0 -1.767576,-0.1983008 z m 0.265925,0.3444462 A 0.82289328,0.85748593 52.593897 0 1 13.286115,1.1203938 0.82289328,0.85748593 52.593897 0 1 13.103698,2.2949179 0.82289328,0.85748593 52.593897 0 1 11.922407,2.163257 0.82289328,0.85748593 52.593897 0 1 12.104824,0.98873353 Z" + id="path5846-5-6" /> +</svg> diff --git a/editor/icons/icon_bezier_handles_mirror.svg b/editor/icons/icon_bezier_handles_mirror.svg new file mode 100644 index 0000000000..682c898368 --- /dev/null +++ b/editor/icons/icon_bezier_handles_mirror.svg @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_bezier_handles_mirror.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1417" + inkscape:window-height="685" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="4.2910315" + inkscape:cy="11.857644" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:1.70000005;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 1.7627119,13.627119 c 0,0 1.2881355,-6.847458 6.5762712,-8.1355935 5.0847459,0.9491522 5.9661009,8.1355925 5.9661009,8.1355925" + id="path4526" + inkscape:connector-curvature="0" + sodipodi:nodetypes="ccc" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846" + cx="1.8983043" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3" + cx="14.237288" + cy="13.491526" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.80513805;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 8.2033896,4.6779662 H 4.3698875" + id="path5878" + inkscape:connector-curvature="0" /> + <path + style="fill:none;stroke:#84c2ff;stroke-width:0.71670938;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 11.931789,4.6440679 H 8.2033896" + id="path5878-7" + inkscape:connector-curvature="0" /> + <ellipse + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3-6" + cx="8.2711868" + cy="4.7796612" + rx="1.2675855" + ry="1.1997888" /> + <path + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="M 3.1539157,3.4305762 A 1.2675855,1.1997888 0 0 0 1.8863376,4.629795 1.2675855,1.1997888 0 0 0 3.1539157,5.8290137 1.2675855,1.1997888 0 0 0 4.4214938,4.629795 1.2675855,1.1997888 0 0 0 3.1539157,3.4305762 Z m 0.00195,0.4238282 A 0.84677333,0.80148375 0 0 1 4.003525,4.6551856 0.84677333,0.80148375 0 0 1 3.1558688,5.4559668 0.84677333,0.80148375 0 0 1 2.3082126,4.6551856 0.84677333,0.80148375 0 0 1 3.1558688,3.8544044 Z" + id="path5846-5" + inkscape:connector-curvature="0" /> + <path + inkscape:connector-curvature="0" + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 13.093969,3.3750567 a 1.2675855,1.1997888 0 0 0 -1.267578,1.1992188 1.2675855,1.1997888 0 0 0 1.267578,1.1992187 1.2675855,1.1997888 0 0 0 1.267578,-1.1992187 1.2675855,1.1997888 0 0 0 -1.267578,-1.1992188 z m 0.002,0.4238282 a 0.84677333,0.80148375 0 0 1 0.847659,0.8007812 0.84677333,0.80148375 0 0 1 -0.847656,0.8007812 0.84677333,0.80148375 0 0 1 -0.847656,-0.8007812 0.84677333,0.80148375 0 0 1 0.847656,-0.8007812 z" + id="path5846-5-6" /> +</svg> diff --git a/editor/icons/icon_color_track_vu.svg b/editor/icons/icon_color_track_vu.svg new file mode 100644 index 0000000000..cad76d0234 --- /dev/null +++ b/editor/icons/icon_color_track_vu.svg @@ -0,0 +1,115 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="24" + version="1.1" + viewBox="0 0 16 24" + id="svg6" + sodipodi:docname="icon_color_track_vu.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10"> + <linearGradient + id="linearGradient4583" + inkscape:collect="always"> + <stop + id="stop4579" + offset="0" + style="stop-color:#f70000;stop-opacity:1" /> + <stop + id="stop4581" + offset="1" + style="stop-color:#eec315;stop-opacity:1" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient4549"> + <stop + style="stop-color:#288027;stop-opacity:1" + offset="0" + id="stop4545" /> + <stop + style="stop-color:#dbee15;stop-opacity:1" + offset="1" + id="stop4547" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient4549" + id="linearGradient4551" + x1="7.7288136" + y1="16.474577" + x2="7.7288136" + y2="3.8644071" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1.0931873,0,0,1.4762899,-0.98021429,0.08553021)" /> + <linearGradient + gradientTransform="matrix(1.1036585,0,0,0.47778193,-16.507235,-7.9018165)" + inkscape:collect="always" + xlink:href="#linearGradient4583" + id="linearGradient4551-7" + x1="7.7288136" + y1="16.474577" + x2="7.7288136" + y2="3.8644071" + gradientUnits="userSpaceOnUse" /> + </defs> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1170" + inkscape:window-height="712" + id="namedview8" + showgrid="false" + showguides="false" + inkscape:zoom="14.75" + inkscape:cx="5.3261277" + inkscape:cy="13.681053" + inkscape:window-x="397" + inkscape:window-y="233" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <rect + style="fill:url(#linearGradient4551);fill-opacity:1;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;paint-order:fill markers stroke" + id="rect822" + width="18.232145" + height="18.416088" + x="-1.3507863" + y="5.9906898" + ry="0.84580106" /> + <rect + style="fill:url(#linearGradient4551-7);fill-opacity:1;stroke-width:0;stroke-miterlimit:4;stroke-dasharray:none;paint-order:fill markers stroke" + id="rect822-5" + width="18.406782" + height="5.9601259" + x="-16.881357" + y="-5.9906898" + ry="0.27373245" + transform="scale(-1)" /> +</svg> diff --git a/editor/icons/icon_edit_bezier.svg b/editor/icons/icon_edit_bezier.svg new file mode 100644 index 0000000000..542ff52aac --- /dev/null +++ b/editor/icons/icon_edit_bezier.svg @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_edit_bezier.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1039" + inkscape:window-height="585" + id="namedview8" + showgrid="false" + inkscape:zoom="20.85965" + inkscape:cx="11.65471" + inkscape:cy="9.0988062" + inkscape:window-x="277" + inkscape:window-y="113" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1036.4)" + id="g4"> + <path + style="fill:none;stroke:#84c2ff;stroke-width:2.20000005;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + d="m 1.4758015,1050.3064 c 11.6492855,0.7191 3.1098343,-11.4976 12.2331255,-11.3475" + id="path4526" + inkscape:connector-curvature="0" + sodipodi:nodetypes="cc" /> + <circle + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" + id="path5846-3" + cy="1038.7133" + cx="13.470984" + r="1.8230016" /> + <circle + r="1.8230016" + cx="2.4449117" + cy="1050.1708" + id="circle1374" + style="fill:#e0e0e0;fill-opacity:1;stroke:none;stroke-width:5.64574671;stroke-miterlimit:4.9000001;stroke-dasharray:none;stroke-opacity:1" /> + </g> +</svg> diff --git a/editor/icons/icon_key_animation.svg b/editor/icons/icon_key_animation.svg new file mode 100644 index 0000000000..a09567498f --- /dev/null +++ b/editor/icons/icon_key_animation.svg @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_animation.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1852" + inkscape:window-height="781" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="-10.271186" + inkscape:cy="3.4149032" + inkscape:window-x="68" + inkscape:window-y="117" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#ea686c" + id="rect2" + style="fill:#b76ef0;fill-opacity:1" /> + </g> +</svg> diff --git a/editor/icons/icon_key_audio.svg b/editor/icons/icon_key_audio.svg new file mode 100644 index 0000000000..7c728bfd01 --- /dev/null +++ b/editor/icons/icon_key_audio.svg @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_audio.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1053" + inkscape:window-height="591" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="4" + inkscape:cy="4" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#ea686c" + id="rect2" + style="fill:#eae668;fill-opacity:1" /> + </g> +</svg> diff --git a/editor/icons/icon_key_bezier.svg b/editor/icons/icon_key_bezier.svg new file mode 100644 index 0000000000..62af6fdb34 --- /dev/null +++ b/editor/icons/icon_key_bezier.svg @@ -0,0 +1,65 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_bezier.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1852" + inkscape:window-height="781" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="-17.152542" + inkscape:cy="3.4149032" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#ea686c" + id="rect2" + style="fill:#5792f6;fill-opacity:1" /> + </g> +</svg> diff --git a/editor/icons/icon_key_bezier_handle.svg b/editor/icons/icon_key_bezier_handle.svg new file mode 100644 index 0000000000..d7b22d0905 --- /dev/null +++ b/editor/icons/icon_key_bezier_handle.svg @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_bezier_handle.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1853" + inkscape:window-height="1016" + id="namedview8" + showgrid="false" + inkscape:zoom="59" + inkscape:cx="2.0952442" + inkscape:cy="4.6061633" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="1" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <path + style="fill:#e0e0e0;fill-opacity:1" + d="M 3.9960938 -0.037109375 C 3.8010931 -0.037109375 3.6064535 0.038077731 3.4570312 0.1875 L 0.22070312 3.4238281 C -0.078134343 3.7226656 -0.078141414 4.2050617 0.22070312 4.5039062 L 3.4570312 7.7402344 C 3.7558687 8.0390718 4.2382719 8.0390718 4.5371094 7.7402344 L 7.7734375 4.5039062 C 8.072282 4.2050617 8.072275 3.7226656 7.7734375 3.4238281 L 4.5371094 0.1875 C 4.3876871 0.038077731 4.1910944 -0.037109375 3.9960938 -0.037109375 z M 4.0253906 0.81445312 C 4.1770098 0.81445312 4.3291322 0.87241756 4.4453125 0.98828125 L 6.9609375 3.4960938 C 7.193298 3.7278211 7.193298 4.102257 6.9609375 4.3339844 L 4.4453125 6.84375 C 4.212952 7.0754774 3.8378293 7.0754774 3.6054688 6.84375 L 1.0898438 4.3339844 C 0.85748323 4.102257 0.85748323 3.7278211 1.0898438 3.4960938 L 3.6054688 0.98828125 C 3.721649 0.87241756 3.8737714 0.81445312 4.0253906 0.81445312 z " + transform="translate(0,1044.4)" + id="rect2" /> + </g> +</svg> diff --git a/editor/icons/icon_key_bezier_point.svg b/editor/icons/icon_key_bezier_point.svg new file mode 100644 index 0000000000..aa33063c95 --- /dev/null +++ b/editor/icons/icon_key_bezier_point.svg @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_bezier_point.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="836" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="4" + inkscape:cy="4" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#e0e0e0" + id="rect2" /> + </g> +</svg> diff --git a/editor/icons/icon_key_bezier_selected.svg b/editor/icons/icon_key_bezier_selected.svg new file mode 100644 index 0000000000..e3f967707a --- /dev/null +++ b/editor/icons/icon_key_bezier_selected.svg @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_bezier_selected.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="836" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="4" + inkscape:cy="4" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#84c2ff" + id="rect2" /> + </g> +</svg> diff --git a/editor/icons/icon_key_call.svg b/editor/icons/icon_key_call.svg index 7fcc65801a..e702898288 100644 --- a/editor/icons/icon_key_call.svg +++ b/editor/icons/icon_key_call.svg @@ -1,5 +1,64 @@ -<svg width="8" height="8" version="1.1" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg"> -<g transform="translate(0 -1044.4)"> -<rect transform="rotate(-45)" x="-741.53" y="741.08" width="6.1027" height="6.1027" ry=".76286" fill="#adf18f"/> -</g> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_call.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="836" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="4" + inkscape:cy="4" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#adf18f" + id="rect2" + style="fill:#66f376;fill-opacity:1" /> + </g> </svg> diff --git a/editor/icons/icon_key_selected.svg b/editor/icons/icon_key_selected.svg index c73d31981d..2842fd93eb 100644 --- a/editor/icons/icon_key_selected.svg +++ b/editor/icons/icon_key_selected.svg @@ -1,5 +1,76 @@ -<svg width="8" height="8" version="1.1" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg"> -<g transform="translate(0 -1044.4)"> -<rect transform="rotate(-45)" x="-741.53" y="741.08" width="6.1027" height="6.1027" ry=".76286" fill="#84c2ff"/> -</g> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_selected.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1568" + inkscape:window-height="767" + id="namedview8" + showgrid="false" + inkscape:zoom="41.7193" + inkscape:cx="-0.48848775" + inkscape:cy="3.5639274" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g4-3" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#84c2ff" + id="rect2" /> + </g> + <g + transform="translate(0,-1044.4)" + id="g4-3"> + <rect + style="fill:#003e7a;fill-opacity:1;stroke-width:0.56281364" + transform="matrix(0.71728847,-0.69677633,0.71728847,0.69677633,0,0)" + x="-751.20953" + y="753.42743" + width="3.4346831" + height="3.4346831" + ry="0.42934799" + id="rect2-6" /> + </g> </svg> diff --git a/editor/icons/icon_key_xform.svg b/editor/icons/icon_key_xform.svg index 7b73715771..fd22b67f52 100644 --- a/editor/icons/icon_key_xform.svg +++ b/editor/icons/icon_key_xform.svg @@ -1,5 +1,64 @@ -<svg width="8" height="8" version="1.1" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg"> -<g transform="translate(0 -1044.4)"> -<rect transform="rotate(-45)" x="-741.53" y="741.08" width="6.1027" height="6.1027" ry=".76286" fill="#ea686c"/> -</g> +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="8" + height="8" + version="1.1" + viewBox="0 0 8 8" + id="svg6" + sodipodi:docname="icon_key_xform.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="836" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="29.5" + inkscape:cx="4" + inkscape:cy="4" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1044.4)" + id="g4"> + <rect + transform="rotate(-45)" + x="-741.53" + y="741.08" + width="6.1027" + height="6.1027" + ry=".76286" + fill="#ea686c" + id="rect2" + style="fill:#ea9568;fill-opacity:1" /> + </g> </svg> diff --git a/editor/icons/icon_time.svg b/editor/icons/icon_time.svg new file mode 100644 index 0000000000..d50c9570b3 --- /dev/null +++ b/editor/icons/icon_time.svg @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="16" + version="1.1" + viewBox="0 0 16 16" + id="svg6" + sodipodi:docname="icon_time.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="836" + inkscape:window-height="480" + id="namedview8" + showgrid="false" + inkscape:zoom="7.375" + inkscape:cx="4.4999435" + inkscape:cy="13.04848" + inkscape:window-x="744" + inkscape:window-y="280" + inkscape:window-maximized="0" + inkscape:current-layer="g4" /> + <g + transform="translate(0 -1036.4)" + id="g4"> + <g + id="g8" + style="fill:#e0e0e0;fill-opacity:1" + transform="matrix(0.0279396,0,0,0.02755726,0.91401567,1037.1343)"> + <g + id="g6" + style="fill:#e0e0e0;fill-opacity:1"> + <path + d="M 276.193,58.507 V 40.389 h 14.578 c 11.153,0 20.194,-9.042 20.194,-20.194 C 310.965,9.043 301.923,0 290.771,0 h -69.544 c -11.153,0 -20.194,9.042 -20.194,20.194 0,11.152 9.042,20.194 20.194,20.194 h 14.578 V 58.506 C 119.952,68.76 28.799,166.327 28.799,284.799 28.799,410.078 130.721,512 256,512 381.279,512 483.201,410.078 483.201,284.799 483.2,166.327 392.046,68.76 276.193,58.507 Z m 0,412.009 v -20.124 c 0,-11.153 -9.042,-20.194 -20.194,-20.194 -11.153,0 -20.194,9.042 -20.194,20.194 v 20.124 C 148.895,461.131 79.668,391.902 70.283,304.994 h 20.124 c 11.153,0 20.194,-9.042 20.194,-20.194 0,-11.152 -9.042,-20.194 -20.194,-20.194 H 70.282 c 9.385,-86.91 78.614,-156.137 165.522,-165.523 v 20.124 c 0,11.153 9.042,20.194 20.194,20.194 11.153,0 20.194,-9.042 20.194,-20.194 V 99.081 c 86.91,9.385 156.137,78.614 165.522,165.523 H 421.59 c -11.153,0 -20.194,9.042 -20.194,20.194 0,11.152 9.042,20.194 20.194,20.194 h 20.126 c -9.385,86.911 -78.613,156.14 -165.523,165.524 z" + id="path2" + style="fill:#e0e0e0;fill-opacity:1" + inkscape:connector-curvature="0" /> + <path + d="m 317.248,194.99 -58.179,58.18 c -1.011,-0.097 -2.034,-0.151 -3.071,-0.151 -17.552,0 -31.779,14.229 -31.779,31.779 0,17.552 14.228,31.779 31.779,31.779 17.551,0 31.779,-14.229 31.779,-31.779 0,-1.037 -0.054,-2.06 -0.151,-3.07 l 58.178,-58.18 c 7.887,-7.885 7.887,-20.672 0,-28.559 -7.882,-7.886 -20.669,-7.886 -28.556,0.001 z" + id="path4" + style="fill:#e0e0e0;fill-opacity:1" + inkscape:connector-curvature="0" /> + </g> + </g> + </g> +</svg> diff --git a/editor/icons/icon_track_capture.svg b/editor/icons/icon_track_capture.svg new file mode 100644 index 0000000000..da6a662746 --- /dev/null +++ b/editor/icons/icon_track_capture.svg @@ -0,0 +1,61 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="16" + height="8" + version="1.1" + viewBox="0 0 16 8" + id="svg6" + sodipodi:docname="icon_track_capture.svg" + inkscape:version="0.92.3 (2405546, 2018-03-11)"> + <metadata + id="metadata12"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title /> + </cc:Work> + </rdf:RDF> + </metadata> + <defs + id="defs10" /> + <sodipodi:namedview + pagecolor="#ffffff" + bordercolor="#666666" + borderopacity="1" + objecttolerance="10" + gridtolerance="10" + guidetolerance="10" + inkscape:pageopacity="0" + inkscape:pageshadow="2" + inkscape:window-width="1350" + inkscape:window-height="593" + id="namedview8" + showgrid="false" + inkscape:zoom="27.577164" + inkscape:cx="8.347146" + inkscape:cy="4.4012076" + inkscape:window-x="67" + inkscape:window-y="27" + inkscape:window-maximized="0" + inkscape:current-layer="svg6" /> + <path + style="fill:#e0e0e0;fill-opacity:1" + d="m 2.1665128,0.99764963 c -0.422625,0 -0.763672,0.34104737 -0.763672,0.76367187 v 4.5742187 c 0,0.4226242 0.341047,0.7617192 0.763672,0.7617192 h 4.472656 c 0.422625,0 0.763672,-0.339095 0.763672,-0.7617192 V 5.347259 h -3.300781 c -0.1662,0 -0.298828,-0.3390943 -0.298828,-0.7617188 V 3.3609308 c 0,-0.4226244 0.132628,-0.7636718 0.298828,-0.7636718 h 3.300781 V 1.7613215 c 0,-0.4226245 -0.341047,-0.76367187 -0.763672,-0.76367187 z" + id="rect1389" + inkscape:connector-curvature="0" /> + <path + style="fill:#e0e0e0;fill-opacity:1;stroke:#e0e0e0;stroke-width:0.80299997;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 9.1827441,4.7953408 C 9.6993662,3.7537783 10.278269,2.5835979 10.469195,2.1949398 l 0.347137,-0.7066511 0.679654,0.00665 0.679654,0.00665 0.956945,2.3125 c 0.526319,1.271875 1.007254,2.4334375 1.068744,2.5812497 l 0.1118,0.26875 H 13.715914 13.1187 L 12.785851,6.0203387 12.453002,5.3765887 H 11.319176 10.185351 L 9.8066761,6.032702 9.4280014,6.6888154 l -0.5922856,1.37e-4 -0.592285,1.36e-4 z m 3.1779349,-0.369483 c 0.0042,-0.00346 -0.233487,-0.4884588 -0.528245,-1.0777779 l -0.535922,-1.0714891 -0.03691,0.0875 c -0.0203,0.048125 -0.183516,0.425 -0.362699,0.8375 -0.179182,0.4125 -0.355738,0.85125 -0.392346,0.975 -0.03661,0.12375 -0.07127,0.2390723 -0.07703,0.2562715 -0.0083,0.024853 0.188215,0.027989 0.957503,0.015278 0.532385,-0.0088 0.971429,-0.018823 0.975651,-0.022283 z" + id="path1424" + inkscape:connector-curvature="0" /> +</svg> diff --git a/editor/inspector_dock.cpp b/editor/inspector_dock.cpp index 4159a3658e..6c7843273e 100644 --- a/editor/inspector_dock.cpp +++ b/editor/inspector_dock.cpp @@ -292,14 +292,14 @@ void InspectorDock::_menu_expandall() { } void InspectorDock::_property_keyed(const String &p_keyed, const Variant &p_value, bool p_advance) { - AnimationPlayerEditor::singleton->get_key_editor()->insert_value_key(p_keyed, p_value, p_advance); + AnimationPlayerEditor::singleton->get_track_editor()->insert_value_key(p_keyed, p_value, p_advance); } void InspectorDock::_transform_keyed(Object *sp, const String &p_sub, const Transform &p_key) { Spatial *s = Object::cast_to<Spatial>(sp); if (!s) return; - AnimationPlayerEditor::singleton->get_key_editor()->insert_transform_key(s, p_sub, p_key); + AnimationPlayerEditor::singleton->get_track_editor()->insert_transform_key(s, p_sub, p_key); } void InspectorDock::_warning_pressed() { @@ -435,10 +435,14 @@ void InspectorDock::update(Object *p_object) { } } +void InspectorDock::go_back() { + _edit_back(); +} + void InspectorDock::update_keying() { bool valid = false; - if (AnimationPlayerEditor::singleton->get_key_editor()->has_keying()) { + if (AnimationPlayerEditor::singleton->get_track_editor()->has_keying()) { EditorHistory *editor_history = EditorNode::get_singleton()->get_editor_history(); if (editor_history->get_path_size() >= 1) { diff --git a/editor/inspector_dock.h b/editor/inspector_dock.h index 688c8beed7..f347056158 100644 --- a/editor/inspector_dock.h +++ b/editor/inspector_dock.h @@ -31,7 +31,7 @@ #ifndef INSPECTOR_DOCK_H #define INSPECTOR_DOCK_H -#include "editor/animation_editor.h" +#include "editor/animation_track_editor.h" #include "editor/connections_dialog.h" #include "editor/create_dialog.h" #include "editor/editor_data.h" @@ -121,6 +121,7 @@ protected: static void _bind_methods(); public: + void go_back(); void update_keying(); void edit_resource(const Ref<Resource> &p_resource); void open_resource(const String &p_type); diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp index 23c5e36a92..536d5c3208 100644 --- a/editor/plugins/animation_player_editor_plugin.cpp +++ b/editor/plugins/animation_player_editor_plugin.cpp @@ -30,7 +30,7 @@ #include "animation_player_editor_plugin.h" -#include "editor/animation_editor.h" +#include "editor/animation_track_editor.h" #include "editor/editor_settings.h" #include "io/resource_loader.h" #include "io/resource_saver.h" @@ -50,9 +50,9 @@ void AnimationPlayerEditor::_node_removed(Node *p_node) { set_process(false); - key_editor->set_animation(Ref<Animation>()); - key_editor->set_root(NULL); - key_editor->show_select_node_warning(true); + track_editor->set_animation(Ref<Animation>()); + track_editor->set_root(NULL); + track_editor->show_select_node_warning(true); _update_player(); //editor->animation_editor_make_visible(false); } @@ -84,7 +84,7 @@ void AnimationPlayerEditor::_notification(int p_what) { } } frame->set_value(player->get_current_animation_position()); - key_editor->set_anim_pos(player->get_current_animation_position()); + track_editor->set_anim_pos(player->get_current_animation_position()); EditorNode::get_singleton()->get_inspector()->refresh(); } else if (last_active) { @@ -101,8 +101,6 @@ void AnimationPlayerEditor::_notification(int p_what) { case NOTIFICATION_ENTER_TREE: { - save_anim->get_popup()->connect("id_pressed", this, "_animation_save_menu"); - tool_anim->get_popup()->connect("id_pressed", this, "_animation_tool_menu"); onion_skinning->get_popup()->connect("id_pressed", this, "_onion_skinning_menu"); @@ -121,16 +119,8 @@ void AnimationPlayerEditor::_notification(int p_what) { case NOTIFICATION_THEME_CHANGED: { - add_anim->set_icon(get_icon("New", "EditorIcons")); - rename_anim->set_icon(get_icon("Rename", "EditorIcons")); - duplicate_anim->set_icon(get_icon("Duplicate", "EditorIcons")); autoplay->set_icon(get_icon("AutoPlay", "EditorIcons")); - load_anim->set_icon(get_icon("Folder", "EditorIcons")); - save_anim->set_icon(get_icon("Save", "EditorIcons")); - - remove_anim->set_icon(get_icon("Remove", "EditorIcons")); - blend_anim->set_icon(get_icon("Blend", "EditorIcons")); play->set_icon(get_icon("PlayStart", "EditorIcons")); play_from->set_icon(get_icon("Play", "EditorIcons")); play_bw->set_icon(get_icon("PlayStartBackwards", "EditorIcons")); @@ -138,11 +128,26 @@ void AnimationPlayerEditor::_notification(int p_what) { autoplay_icon = get_icon("AutoPlay", "EditorIcons"); stop->set_icon(get_icon("Stop", "EditorIcons")); - resource_edit_anim->set_icon(get_icon("EditResource", "EditorIcons")); + pin->set_icon(get_icon("Pin", "EditorIcons")); - tool_anim->set_icon(get_icon("Tools", "EditorIcons")); onion_skinning->set_icon(get_icon("Onion", "EditorIcons")); + tool_anim->add_style_override("normal", get_stylebox("normal", "Button")); + track_editor->get_edit_menu()->add_style_override("normal", get_stylebox("normal", "Button")); + +#define ITEM_ICON(m_item, m_icon) tool_anim->get_popup()->set_item_icon(tool_anim->get_popup()->get_item_index(m_item), get_icon(m_icon, "EditorIcons")) + + ITEM_ICON(TOOL_NEW_ANIM, "New"); + ITEM_ICON(TOOL_LOAD_ANIM, "Load"); + ITEM_ICON(TOOL_SAVE_ANIM, "Save"); + ITEM_ICON(TOOL_SAVE_AS_ANIM, "Save"); + ITEM_ICON(TOOL_DUPLICATE_ANIM, "Duplicate"); + ITEM_ICON(TOOL_RENAME_ANIM, "Rename"); + ITEM_ICON(TOOL_EDIT_TRANSITIONS, "Blend"); + ITEM_ICON(TOOL_REMOVE_ANIM, "Remove"); + //ITEM_ICON(TOOL_COPY_ANIM, "Copy"); + //ITEM_ICON(TOOL_PASTE_ANIM, "Paste"); + } break; } } @@ -304,10 +309,10 @@ void AnimationPlayerEditor::_animation_selected(int p_which) { Ref<Animation> anim = player->get_animation(current); { - key_editor->set_animation(anim); + track_editor->set_animation(anim); Node *root = player->get_node(player->get_root()); if (root) { - key_editor->set_root(root); + track_editor->set_root(root); } } frame->set_max(anim->get_length()); @@ -317,8 +322,8 @@ void AnimationPlayerEditor::_animation_selected(int p_which) { frame->set_step(0.00001); } else { - key_editor->set_animation(Ref<Animation>()); - key_editor->set_root(NULL); + track_editor->set_animation(Ref<Animation>()); + track_editor->set_root(NULL); } autoplay->set_pressed(current == player->get_autoplay()); @@ -704,16 +709,16 @@ void AnimationPlayerEditor::_animation_edit() { if (animation->get_item_count()) { String current = animation->get_item_text(animation->get_selected()); Ref<Animation> anim = player->get_animation(current); - key_editor->set_animation(anim); + track_editor->set_animation(anim); Node *root = player->get_node(player->get_root()); if (root) { - key_editor->set_root(root); + track_editor->set_root(root); } } else { - key_editor->set_animation(Ref<Animation>()); - key_editor->set_root(NULL); + track_editor->set_animation(Ref<Animation>()); + track_editor->set_root(NULL); } } void AnimationPlayerEditor::_dialog_action(String p_file) { @@ -810,8 +815,16 @@ void AnimationPlayerEditor::_update_player() { animation->clear(); - add_anim->set_disabled(player == NULL); - load_anim->set_disabled(player == NULL); +#define ITEM_DISABLED(m_item, m_disabled) tool_anim->get_popup()->set_item_disabled(tool_anim->get_popup()->get_item_index(m_item), m_disabled) + + ITEM_DISABLED(TOOL_SAVE_ANIM, animlist.size() == 0); + ITEM_DISABLED(TOOL_SAVE_AS_ANIM, animlist.size() == 0); + ITEM_DISABLED(TOOL_DUPLICATE_ANIM, animlist.size() == 0); + ITEM_DISABLED(TOOL_RENAME_ANIM, animlist.size() == 0); + ITEM_DISABLED(TOOL_EDIT_TRANSITIONS, animlist.size() == 0); + ITEM_DISABLED(TOOL_COPY_ANIM, animlist.size() == 0); + ITEM_DISABLED(TOOL_REMOVE_ANIM, animlist.size() == 0); + stop->set_disabled(animlist.size() == 0); play->set_disabled(animlist.size() == 0); play_bw->set_disabled(animlist.size() == 0); @@ -820,12 +833,6 @@ void AnimationPlayerEditor::_update_player() { frame->set_editable(animlist.size() != 0); animation->set_disabled(animlist.size() == 0); autoplay->set_disabled(animlist.size() == 0); - duplicate_anim->set_disabled(animlist.size() == 0); - rename_anim->set_disabled(animlist.size() == 0); - blend_anim->set_disabled(animlist.size() == 0); - remove_anim->set_disabled(animlist.size() == 0); - resource_edit_anim->set_disabled(animlist.size() == 0); - save_anim->set_disabled(animlist.size() == 0); tool_anim->set_disabled(player == NULL); onion_skinning->set_disabled(player == NULL); pin->set_disabled(player == NULL); @@ -863,10 +870,10 @@ void AnimationPlayerEditor::_update_player() { if (animation->get_item_count()) { String current = animation->get_item_text(animation->get_selected()); Ref<Animation> anim = player->get_animation(current); - key_editor->set_animation(anim); + track_editor->set_animation(anim); Node *root = player->get_node(player->get_root()); if (root) { - key_editor->set_root(root); + track_editor->set_root(root); } } @@ -884,9 +891,9 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) { if (player) { _update_player(); - key_editor->show_select_node_warning(false); + track_editor->show_select_node_warning(false); } else { - key_editor->show_select_node_warning(true); + track_editor->show_select_node_warning(true); //hide(); } @@ -1024,7 +1031,7 @@ void AnimationPlayerEditor::_seek_value_changed(float p_value, bool p_set) { player->seek(pos, true); } - key_editor->set_anim_pos(pos); + track_editor->set_anim_pos(pos); updating = true; }; @@ -1084,16 +1091,55 @@ void AnimationPlayerEditor::_hide_anim_editors() { hide(); set_process(false); - key_editor->set_animation(Ref<Animation>()); - key_editor->set_root(NULL); - key_editor->show_select_node_warning(true); + track_editor->set_animation(Ref<Animation>()); + track_editor->set_root(NULL); + track_editor->show_select_node_warning(true); //editor->animation_editor_make_visible(false); } +void AnimationPlayerEditor::_animation_about_to_show_menu() { +} + void AnimationPlayerEditor::_animation_tool_menu(int p_option) { + String current = animation->get_item_text(animation->get_selected()); + Ref<Animation> anim; + if (current != "") { + anim = player->get_animation(current); + } + switch (p_option) { + case TOOL_NEW_ANIM: { + _animation_new(); + } break; + + case TOOL_LOAD_ANIM: { + _animation_load(); + break; + } break; + case TOOL_SAVE_ANIM: { + if (anim.is_valid()) { + _animation_save(anim); + } + } break; + case TOOL_SAVE_AS_ANIM: { + if (anim.is_valid()) { + _animation_save_as(anim); + } + } break; + case TOOL_DUPLICATE_ANIM: { + _animation_duplicate(); + } break; + case TOOL_RENAME_ANIM: { + _animation_rename(); + } break; + case TOOL_EDIT_TRANSITIONS: { + _animation_blend(); + } break; + case TOOL_REMOVE_ANIM: { + _animation_remove(); + } break; case TOOL_COPY_ANIM: { if (!animation->get_item_count()) { @@ -1156,23 +1202,6 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) { } } -void AnimationPlayerEditor::_animation_save_menu(int p_option) { - - String current = animation->get_item_text(animation->get_selected()); - if (current != "") { - Ref<Animation> anim = player->get_animation(current); - - switch (p_option) { - case ANIM_SAVE: - _animation_save(anim); - break; - case ANIM_SAVE_AS: - _animation_save_as(anim); - break; - } - } -} - void AnimationPlayerEditor::_onion_skinning_menu(int p_option) { PopupMenu *menu = onion_skinning->get_popup(); @@ -1431,7 +1460,7 @@ void AnimationPlayerEditor::_prepare_onion_layers_2() { float pos = cpos + step_off * anim->get_step(); - bool valid = anim->has_loop() || pos >= 0 && pos <= anim->get_length(); + bool valid = anim->has_loop() || (pos >= 0 && pos <= anim->get_length()); onion.captures_valid[cidx] = valid; if (valid) { player->seek(pos, true); @@ -1494,6 +1523,10 @@ void AnimationPlayerEditor::_stop_onion_skinning() { } } +void AnimationPlayerEditor::_pin_pressed() { + EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->update_tree(); +} + void AnimationPlayerEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &AnimationPlayerEditor::_gui_input); @@ -1532,11 +1565,13 @@ void AnimationPlayerEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_blend_editor_next_changed"), &AnimationPlayerEditor::_blend_editor_next_changed); ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &AnimationPlayerEditor::_unhandled_key_input); ClassDB::bind_method(D_METHOD("_animation_tool_menu"), &AnimationPlayerEditor::_animation_tool_menu); - ClassDB::bind_method(D_METHOD("_animation_save_menu"), &AnimationPlayerEditor::_animation_save_menu); + ClassDB::bind_method(D_METHOD("_onion_skinning_menu"), &AnimationPlayerEditor::_onion_skinning_menu); ClassDB::bind_method(D_METHOD("_editor_visibility_changed"), &AnimationPlayerEditor::_editor_visibility_changed); ClassDB::bind_method(D_METHOD("_prepare_onion_layers_1"), &AnimationPlayerEditor::_prepare_onion_layers_1); ClassDB::bind_method(D_METHOD("_prepare_onion_layers_2"), &AnimationPlayerEditor::_prepare_onion_layers_2); + + ClassDB::bind_method(D_METHOD("_pin_pressed"), &AnimationPlayerEditor::_pin_pressed); } AnimationPlayerEditor *AnimationPlayerEditor::singleton = NULL; @@ -1606,26 +1641,6 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay scale->set_tooltip(TTR("Scale animation playback globally for the node.")); scale->hide(); - add_anim = memnew(ToolButton); - ED_SHORTCUT("animation_player_editor/add_animation", TTR("Create new animation in player.")); - add_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/add_animation")); - add_anim->set_tooltip(TTR("Create new animation in player.")); - - hb->add_child(add_anim); - - load_anim = memnew(ToolButton); - ED_SHORTCUT("animation_player_editor/load_from_disk", TTR("Load animation from disk.")); - add_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/load_from_disk")); - load_anim->set_tooltip(TTR("Load an animation from disk.")); - hb->add_child(load_anim); - - save_anim = memnew(MenuButton); - save_anim->set_tooltip(TTR("Save the current animation.")); - save_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save", TTR("Save")), ANIM_SAVE); - save_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save_as", TTR("Save As")), ANIM_SAVE_AS); - save_anim->set_focus_mode(Control::FOCUS_NONE); - hb->add_child(save_anim); - accept = memnew(AcceptDialog); add_child(accept); accept->connect("confirmed", this, "_menu_confirm_current"); @@ -1634,23 +1649,27 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay add_child(delete_dialog); delete_dialog->connect("confirmed", this, "_animation_remove_confirmed"); - duplicate_anim = memnew(ToolButton); - hb->add_child(duplicate_anim); - ED_SHORTCUT("animation_player_editor/duplicate_animation", TTR("Duplicate Animation")); - duplicate_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/duplicate_animation")); - duplicate_anim->set_tooltip(TTR("Duplicate Animation")); - - rename_anim = memnew(ToolButton); - hb->add_child(rename_anim); - ED_SHORTCUT("animation_player_editor/rename_animation", TTR("Rename Animation")); - rename_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/rename_animation")); - rename_anim->set_tooltip(TTR("Rename Animation")); - - remove_anim = memnew(ToolButton); - hb->add_child(remove_anim); - ED_SHORTCUT("animation_player_editor/remove_animation", TTR("Remove Animation")); - remove_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/remove_animation")); - remove_anim->set_tooltip(TTR("Remove Animation")); + tool_anim = memnew(MenuButton); + tool_anim->set_flat(false); + //tool_anim->set_flat(false); + tool_anim->set_tooltip(TTR("Animation Tools")); + tool_anim->set_text("Animation"); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/new_animation", TTR("New...")), TOOL_NEW_ANIM); + tool_anim->get_popup()->add_separator(); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/open_animation", TTR("Load...")), TOOL_LOAD_ANIM); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save_animation", TTR("Save")), TOOL_SAVE_ANIM); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save_as_animation", TTR("Save As..")), TOOL_SAVE_AS_ANIM); + tool_anim->get_popup()->add_separator(); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/copy_animation", TTR("Copy")), TOOL_COPY_ANIM); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation", TTR("Paste")), TOOL_PASTE_ANIM); + tool_anim->get_popup()->add_separator(); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/duplicate_animation", TTR("Duplicate")), TOOL_DUPLICATE_ANIM); + tool_anim->get_popup()->add_separator(); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/rename_animation", TTR("Rename...")), TOOL_RENAME_ANIM); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/edit_transitions", TTR("Edit Transitions...")), TOOL_EDIT_TRANSITIONS); + tool_anim->get_popup()->add_separator(); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/remove_animation", TTR("Remove")), TOOL_REMOVE_ANIM); + hb->add_child(tool_anim); animation = memnew(OptionButton); hb->add_child(animation); @@ -1662,18 +1681,12 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay hb->add_child(autoplay); autoplay->set_tooltip(TTR("Autoplay on Load")); - blend_anim = memnew(ToolButton); - hb->add_child(blend_anim); - blend_anim->set_tooltip(TTR("Edit Target Blend Times")); - - tool_anim = memnew(MenuButton); - //tool_anim->set_flat(false); - tool_anim->set_tooltip(TTR("Animation Tools")); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/copy_animation", TTR("Copy Animation")), TOOL_COPY_ANIM); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation", TTR("Paste Animation")), TOOL_PASTE_ANIM); //tool_anim->get_popup()->add_separator(); //tool_anim->get_popup()->add_item("Edit Anim Resource",TOOL_PASTE_ANIM); - hb->add_child(tool_anim); + + track_editor = memnew(AnimationTrackEditor); + + hb->add_child(track_editor->get_edit_menu()); onion_skinning = memnew(MenuButton); //onion_skinning->set_flat(false); @@ -1702,10 +1715,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay pin->set_toggle_mode(true); pin->set_tooltip(TTR("Pin AnimationPlayer")); hb->add_child(pin); - - resource_edit_anim = memnew(Button); - hb->add_child(resource_edit_anim); - resource_edit_anim->hide(); + pin->connect("pressed", this, "_pin_pressed"); file = memnew(EditorFileDialog); add_child(file); @@ -1758,16 +1768,10 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay play_bw_from->connect("pressed", this, "_play_bw_from_pressed"); stop->connect("pressed", this, "_stop_pressed"); //pause->connect("pressed", this,"_pause_pressed"); - add_anim->connect("pressed", this, "_animation_new"); - rename_anim->connect("pressed", this, "_animation_rename"); - load_anim->connect("pressed", this, "_animation_load"); - duplicate_anim->connect("pressed", this, "_animation_duplicate"); //frame->connect("text_entered", this,"_seek_frame_changed"); - blend_anim->connect("pressed", this, "_animation_blend"); - remove_anim->connect("pressed", this, "_animation_remove"); animation->connect("item_selected", this, "_animation_selected", Vector<Variant>(), true); - resource_edit_anim->connect("pressed", this, "_animation_resource_edit"); + file->connect("file_selected", this, "_dialog_action"); frame->connect("value_changed", this, "_seek_value_changed", Vector<Variant>(), true); scale->connect("text_entered", this, "_scale_changed", Vector<Variant>(), true); @@ -1777,18 +1781,17 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay set_process_unhandled_key_input(true); - key_editor = memnew(AnimationKeyEditor); - add_child(key_editor); - key_editor->set_v_size_flags(SIZE_EXPAND_FILL); - key_editor->connect("timeline_changed", this, "_animation_key_editor_seek"); - key_editor->connect("animation_len_changed", this, "_animation_key_editor_anim_len_changed"); - key_editor->connect("animation_step_changed", this, "_animation_key_editor_anim_step_changed"); + add_child(track_editor); + track_editor->set_v_size_flags(SIZE_EXPAND_FILL); + track_editor->connect("timeline_changed", this, "_animation_key_editor_seek"); + track_editor->connect("animation_len_changed", this, "_animation_key_editor_anim_len_changed"); + track_editor->connect("animation_step_changed", this, "_animation_key_editor_anim_step_changed"); _update_player(); // Onion skinning - key_editor->connect("visibility_changed", this, "_editor_visibility_changed"); + track_editor->connect("visibility_changed", this, "_editor_visibility_changed"); onion.enabled = false; onion.past = true; diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h index a7b7c6c465..5ac7b99903 100644 --- a/editor/plugins/animation_player_editor_plugin.h +++ b/editor/plugins/animation_player_editor_plugin.h @@ -42,8 +42,9 @@ /** @author Juan Linietsky <reduzio@gmail.com> */ -class AnimationKeyEditor; +class AnimationTrackEditor; class AnimationPlayerEditorPlugin; + class AnimationPlayerEditor : public VBoxContainer { GDCLASS(AnimationPlayerEditor, VBoxContainer); @@ -53,6 +54,14 @@ class AnimationPlayerEditor : public VBoxContainer { AnimationPlayer *player; enum { + TOOL_NEW_ANIM, + TOOL_LOAD_ANIM, + TOOL_SAVE_ANIM, + TOOL_SAVE_AS_ANIM, + TOOL_DUPLICATE_ANIM, + TOOL_RENAME_ANIM, + TOOL_EDIT_TRANSITIONS, + TOOL_REMOVE_ANIM, TOOL_COPY_ANIM, TOOL_PASTE_ANIM, TOOL_EDIT_RESOURCE @@ -72,6 +81,7 @@ class AnimationPlayerEditor : public VBoxContainer { }; enum { + ANIM_OPEN, ANIM_SAVE, ANIM_SAVE_AS }; @@ -89,16 +99,8 @@ class AnimationPlayerEditor : public VBoxContainer { Button *play_bw_from; //Button *pause; - Button *add_anim; Button *autoplay; - Button *rename_anim; - Button *duplicate_anim; - - Button *resource_edit_anim; - Button *load_anim; - MenuButton *save_anim; - Button *blend_anim; - Button *remove_anim; + MenuButton *tool_anim; MenuButton *onion_skinning; ToolButton *pin; @@ -130,7 +132,7 @@ class AnimationPlayerEditor : public VBoxContainer { bool updating; bool updating_blends; - AnimationKeyEditor *key_editor; + AnimationTrackEditor *track_editor; // Onion skinning struct { @@ -207,8 +209,8 @@ class AnimationPlayerEditor : public VBoxContainer { void _unhandled_key_input(const Ref<InputEvent> &p_ev); void _animation_tool_menu(int p_option); - void _animation_save_menu(int p_option); void _onion_skinning_menu(int p_option); + void _animation_about_to_show_menu(); void _editor_visibility_changed(); bool _are_onion_layers_valid(); @@ -219,6 +221,8 @@ class AnimationPlayerEditor : public VBoxContainer { void _start_onion_skinning(); void _stop_onion_skinning(); + void _pin_pressed(); + AnimationPlayerEditor(); ~AnimationPlayerEditor(); @@ -232,7 +236,9 @@ public: AnimationPlayer *get_player() const; static AnimationPlayerEditor *singleton; - AnimationKeyEditor *get_key_editor() { return key_editor; } + bool is_pinned() const { return pin->is_pressed(); } + void unpin() { pin->set_pressed(false); } + AnimationTrackEditor *get_track_editor() { return track_editor; } Dictionary get_state() const; void set_state(const Dictionary &p_state); diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp index ad49ab86c9..13a9a84de1 100644 --- a/editor/plugins/canvas_item_editor_plugin.cpp +++ b/editor/plugins/canvas_item_editor_plugin.cpp @@ -30,7 +30,6 @@ #include "canvas_item_editor_plugin.h" -#include "editor/animation_editor.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/plugins/animation_player_editor_plugin.h" @@ -365,7 +364,7 @@ Object *CanvasItemEditor::_get_editor_data(Object *p_what) { void CanvasItemEditor::_keying_changed() { - if (AnimationPlayerEditor::singleton->get_key_editor()->is_visible_in_tree()) + if (AnimationPlayerEditor::singleton->get_track_editor()->is_visible_in_tree()) animation_hb->show(); else animation_hb->hide(); @@ -3080,7 +3079,7 @@ void CanvasItemEditor::_notification(int p_what) { select_sb->set_default_margin(Margin(i), 4); } - AnimationPlayerEditor::singleton->get_key_editor()->connect("visibility_changed", this, "_keying_changed"); + AnimationPlayerEditor::singleton->get_track_editor()->connect("visibility_changed", this, "_keying_changed"); _keying_changed(); get_tree()->connect("node_added", this, "_tree_changed", varray()); get_tree()->connect("node_removed", this, "_tree_changed", varray()); @@ -3692,11 +3691,11 @@ void CanvasItemEditor::_popup_callback(int p_op) { Node2D *n2d = Object::cast_to<Node2D>(canvas_item); if (key_pos) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "position", n2d->get_position(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "position", n2d->get_position(), existing); if (key_rot) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "rotation_degrees", Math::rad2deg(n2d->get_rotation()), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "rotation_degrees", Math::rad2deg(n2d->get_rotation()), existing); if (key_scale) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "scale", n2d->get_scale(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(n2d, "scale", n2d->get_scale(), existing); if (n2d->has_meta("_edit_bone_") && n2d->get_parent_item()) { //look for an IK chain @@ -3723,11 +3722,11 @@ void CanvasItemEditor::_popup_callback(int p_op) { for (List<Node2D *>::Element *F = ik_chain.front(); F; F = F->next()) { if (key_pos) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "position", F->get()->get_position(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "position", F->get()->get_position(), existing); if (key_rot) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "rotation_degrees", Math::rad2deg(F->get()->get_rotation()), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "rotation_degrees", Math::rad2deg(F->get()->get_rotation()), existing); if (key_scale) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "scale", F->get()->get_scale(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(F->get(), "scale", F->get()->get_scale(), existing); } } } @@ -3737,11 +3736,11 @@ void CanvasItemEditor::_popup_callback(int p_op) { Control *ctrl = Object::cast_to<Control>(canvas_item); if (key_pos) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl, "rect_position", ctrl->get_position(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_position", ctrl->get_position(), existing); if (key_rot) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl, "rect_rotation", ctrl->get_rotation_degrees(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_rotation", ctrl->get_rotation_degrees(), existing); if (key_scale) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl, "rect_size", ctrl->get_size(), existing); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl, "rect_size", ctrl->get_size(), existing); } } @@ -3837,7 +3836,7 @@ void CanvasItemEditor::_popup_callback(int p_op) { ctrl->set_position(Point2()); /* if (key_scale) - AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl,"rect/size",ctrl->get_size()); + AnimationPlayerEditor::singleton->get_track_editor()->insert_node_value_key(ctrl,"rect/size",ctrl->get_size()); */ } } diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp index d065a756b4..0d25b3685a 100644 --- a/editor/plugins/editor_preview_plugins.cpp +++ b/editor/plugins/editor_preview_plugins.cpp @@ -554,274 +554,92 @@ EditorScriptPreviewPlugin::EditorScriptPreviewPlugin() { } /////////////////////////////////////////////////////////////////// -// FIXME: Needs to be rewritten for AudioStream in Godot 3.0+ -#if 0 -bool EditorSamplePreviewPlugin::handles(const String& p_type) const { +bool EditorAudioStreamPreviewPlugin::handles(const String &p_type) const { - return ClassDB::is_parent_class(p_type,"Sample"); + return ClassDB::is_parent_class(p_type, "AudioStream"); } -Ref<Texture> EditorSamplePreviewPlugin::generate(const RES& p_from) { - - Ref<Sample> smp =p_from; - ERR_FAIL_COND_V(smp.is_null(),Ref<Texture>()); +Ref<Texture> EditorAudioStreamPreviewPlugin::generate(const RES &p_from) { + Ref<AudioStream> stream = p_from; + ERR_FAIL_COND_V(stream.is_null(), Ref<Texture>()); int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size"); - thumbnail_size*=EDSCALE; + thumbnail_size *= EDSCALE; PoolVector<uint8_t> img; int w = thumbnail_size; int h = thumbnail_size; - img.resize(w*h*3); + img.resize(w * h * 3); PoolVector<uint8_t>::Write imgdata = img.write(); - uint8_t * imgw = imgdata.ptr(); - PoolVector<uint8_t> data = smp->get_data(); - PoolVector<uint8_t>::Read sampledata = data.read(); - const uint8_t *sdata=sampledata.ptr(); + uint8_t *imgw = imgdata.ptr(); - bool stereo = smp->is_stereo(); - bool _16=smp->get_format()==Sample::FORMAT_PCM16; - int len = smp->get_length(); + Ref<AudioStreamPlayback> playback = stream->instance_playback(); - if (len<1) - return Ref<Texture>(); + float len_s = stream->get_length(); + if (len_s == 0) { + len_s = 60; //one minute audio if no length specified + } + int frame_length = AudioServer::get_singleton()->get_mix_rate() * len_s; - if (smp->get_format()==Sample::FORMAT_IMA_ADPCM) { - - struct IMA_ADPCM_State { - - int16_t step_index; - int32_t predictor; - /* values at loop point */ - int16_t loop_step_index; - int32_t loop_predictor; - int32_t last_nibble; - int32_t loop_pos; - int32_t window_ofs; - const uint8_t *ptr; - } ima_adpcm; - - ima_adpcm.step_index=0; - ima_adpcm.predictor=0; - ima_adpcm.loop_step_index=0; - ima_adpcm.loop_predictor=0; - ima_adpcm.last_nibble=-1; - ima_adpcm.loop_pos=0x7FFFFFFF; - ima_adpcm.window_ofs=0; - ima_adpcm.ptr=NULL; - - - for(int i=0;i<w;i++) { - - float max[2]={-1e10,-1e10}; - float min[2]={1e10,1e10}; - int from = i*len/w; - int to = (i+1)*len/w; - if (to>=len) - to=len-1; - - for(int j=from;j<to;j++) { - - while(j>ima_adpcm.last_nibble) { - - static const int16_t _ima_adpcm_step_table[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 - }; - - static const int8_t _ima_adpcm_index_table[16] = { - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8 - }; - - int16_t nibble,diff,step; - - ima_adpcm.last_nibble++; - const uint8_t *src_ptr=sdata; - - int ofs = ima_adpcm.last_nibble>>1; - - if (stereo) - ofs*=2; - - - nibble = (ima_adpcm.last_nibble&1)? - (src_ptr[ofs]>>4):(src_ptr[ofs]&0xF); - step=_ima_adpcm_step_table[ima_adpcm.step_index]; - - ima_adpcm.step_index += _ima_adpcm_index_table[nibble]; - if (ima_adpcm.step_index<0) - ima_adpcm.step_index=0; - if (ima_adpcm.step_index>88) - ima_adpcm.step_index=88; - - diff = step >> 3 ; - if (nibble & 1) - diff += step >> 2 ; - if (nibble & 2) - diff += step >> 1 ; - if (nibble & 4) - diff += step ; - if (nibble & 8) - diff = -diff ; - - ima_adpcm.predictor+=diff; - if (ima_adpcm.predictor<-0x8000) - ima_adpcm.predictor=-0x8000; - else if (ima_adpcm.predictor>0x7FFF) - ima_adpcm.predictor=0x7FFF; - - - /* store loop if there */ - if (ima_adpcm.last_nibble==ima_adpcm.loop_pos) { - - ima_adpcm.loop_step_index = ima_adpcm.step_index; - ima_adpcm.loop_predictor = ima_adpcm.predictor; - } + Vector<AudioFrame> frames; + frames.resize(frame_length); - } + playback->start(); + playback->mix(frames.ptrw(), 1, frames.size()); + playback->stop(); - float v=ima_adpcm.predictor/32767.0; - if (v>max[0]) - max[0]=v; - if (v<min[0]) - min[0]=v; - } - max[0]*=0.8; - min[0]*=0.8; - - for(int j=0;j<h;j++) { - float v = (j/(float)h) * 2.0 - 1.0; - uint8_t* imgofs = &imgw[(uint64_t(j)*w+i)*3]; - if (v>min[0] && v<max[0]) { - imgofs[0]=255; - imgofs[1]=150; - imgofs[2]=80; - } else { - imgofs[0]=0; - imgofs[1]=0; - imgofs[2]=0; - } - } - } - } else { - for(int i=0;i<w;i++) { - // i trust gcc will optimize this loop - float max[2]={-1e10,-1e10}; - float min[2]={1e10,1e10}; - int c=stereo?2:1; - int from = uint64_t(i)*len/w; - int to = (uint64_t(i)+1)*len/w; - if (to>=len) - to=len-1; - - if (_16) { - const int16_t*src =(const int16_t*)sdata; - - for(int j=0;j<c;j++) { - - for(int k=from;k<=to;k++) { - - float v = src[uint64_t(k)*c+j]/32768.0; - if (v>max[j]) - max[j]=v; - if (v<min[j]) - min[j]=v; - } + for (int i = 0; i < w; i++) { - } - } else { - - const int8_t*src =(const int8_t*)sdata; + float max = -1000; + float min = 1000; + int from = uint64_t(i) * frame_length / w; + int to = uint64_t(i + 1) * frame_length / w; + to = MIN(to, frame_length); + from = MIN(from, frame_length - 1); + if (to == from) { + to = from + 1; + } - for(int j=0;j<c;j++) { + for (int j = from; j < to; j++) { - for(int k=from;k<=to;k++) { + max = MAX(max, frames[j].l); + max = MAX(max, frames[j].r); - float v = src[uint64_t(k)*c+j]/128.0; - if (v>max[j]) - max[j]=v; - if (v<min[j]) - min[j]=v; - } + min = MIN(min, frames[j].l); + min = MIN(min, frames[j].r); + } - } - } + int pfrom = CLAMP((min * 0.5 + 0.5) * h / 2, 0, h / 2) + h / 4; + int pto = CLAMP((max * 0.5 + 0.5) * h / 2, 0, h / 2) + h / 4; - max[0]*=0.8; - max[1]*=0.8; - min[0]*=0.8; - min[1]*=0.8; - - if (!stereo) { - for(int j=0;j<h;j++) { - float v = (j/(float)h) * 2.0 - 1.0; - uint8_t* imgofs = &imgw[(j*w+i)*3]; - if (v>min[0] && v<max[0]) { - imgofs[0]=255; - imgofs[1]=150; - imgofs[2]=80; - } else { - imgofs[0]=0; - imgofs[1]=0; - imgofs[2]=0; - } - } + for (int j = 0; j < h; j++) { + uint8_t *p = &imgw[(j * w + i) * 3]; + if (j < pfrom || j > pto) { + p[0] = 100; + p[1] = 100; + p[2] = 100; } else { - - for(int j=0;j<h;j++) { - - int half; - float v; - if (j<(h/2)) { - half=0; - v = (j/(float)(h/2)) * 2.0 - 1.0; - } else { - half=1; - if( (float)(h/2) != 0 ) { - v = ((j-(h/2))/(float)(h/2)) * 2.0 - 1.0; - } else { - v = ((j-(h/2))/(float)(1/2)) * 2.0 - 1.0; - } - } - - uint8_t* imgofs = &imgw[(j*w+i)*3]; - if (v>min[half] && v<max[half]) { - imgofs[0]=255; - imgofs[1]=150; - imgofs[2]=80; - } else { - imgofs[0]=0; - imgofs[1]=0; - imgofs[2]=0; - } - } - + p[0] = 180; + p[1] = 180; + p[2] = 180; } - } } imgdata = PoolVector<uint8_t>::Write(); - post_process_preview(img); + //post_process_preview(img); - Ref<ImageTexture> ptex = Ref<ImageTexture>( memnew( ImageTexture)); - ptex->create_from_image(Image(w,h,0,Image::FORMAT_RGB8,img),0); + Ref<ImageTexture> ptex = Ref<ImageTexture>(memnew(ImageTexture)); + Ref<Image> image; + image.instance(); + image->create(w, h, false, Image::FORMAT_RGB8, img); + ptex->create_from_image(image, 0); return ptex; - } -EditorSamplePreviewPlugin::EditorSamplePreviewPlugin() { +EditorAudioStreamPreviewPlugin::EditorAudioStreamPreviewPlugin() { } -#endif /////////////////////////////////////////////////////////////////////////// diff --git a/editor/plugins/editor_preview_plugins.h b/editor/plugins/editor_preview_plugins.h index 332f991b49..140d9f849f 100644 --- a/editor/plugins/editor_preview_plugins.h +++ b/editor/plugins/editor_preview_plugins.h @@ -100,17 +100,13 @@ public: EditorScriptPreviewPlugin(); }; -// FIXME: Needs to be rewritten for AudioStream in Godot 3.0+ -#if 0 -class EditorSamplePreviewPlugin : public EditorResourcePreviewGenerator { +class EditorAudioStreamPreviewPlugin : public EditorResourcePreviewGenerator { public: + virtual bool handles(const String &p_type) const; + virtual Ref<Texture> generate(const RES &p_from); - virtual bool handles(const String& p_type) const; - virtual Ref<Texture> generate(const RES& p_from); - - EditorSamplePreviewPlugin(); + EditorAudioStreamPreviewPlugin(); }; -#endif class EditorMeshPreviewPlugin : public EditorResourcePreviewGenerator { diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index a19fb5e64f..83072534b8 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -1215,6 +1215,9 @@ void ScriptEditor::_notification(int p_what) { script_forward->set_icon(get_icon("Forward", "EditorIcons")); script_back->set_icon(get_icon("Back", "EditorIcons")); + members_overview_alphabeta_sort_button->set_icon(get_icon("Sort", "EditorIcons")); + filename->add_style_override("normal", editor->get_gui_base()->get_stylebox("normal", "LineEdit")); + recent_scripts->set_as_minsize(); } break; diff --git a/editor/plugins/spatial_editor_plugin.cpp b/editor/plugins/spatial_editor_plugin.cpp index 5b713ef3c4..f02efd9e4d 100644 --- a/editor/plugins/spatial_editor_plugin.cpp +++ b/editor/plugins/spatial_editor_plugin.cpp @@ -32,7 +32,7 @@ #include "camera_matrix.h" #include "core/os/input.h" -#include "editor/animation_editor.h" + #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/plugins/animation_player_editor_plugin.h" @@ -1829,7 +1829,7 @@ void SpatialEditorViewport::_sinput(const Ref<InputEvent> &p_event) { if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) return; - if (!AnimationPlayerEditor::singleton->get_key_editor()->has_keying()) { + if (!AnimationPlayerEditor::singleton->get_track_editor()->has_keying()) { set_message(TTR("Keying is disabled (no key inserted).")); return; } diff --git a/editor/plugins/tile_map_editor_plugin.cpp b/editor/plugins/tile_map_editor_plugin.cpp index 72b3af5a09..ea133cd749 100644 --- a/editor/plugins/tile_map_editor_plugin.cpp +++ b/editor/plugins/tile_map_editor_plugin.cpp @@ -35,6 +35,7 @@ #include "editor/editor_settings.h" #include "os/input.h" #include "os/keyboard.h" +#include "scene/gui/split_container.h" void TileMapEditor::_notification(int p_what) { @@ -168,6 +169,13 @@ void TileMapEditor::_menu_option(int p_option) { } } +void TileMapEditor::_palette_selected(int index) { + + if (manual_autotile) { + _update_palette(); + } +} + void TileMapEditor::_canvas_mouse_enter() { mouse_over = true; @@ -209,12 +217,37 @@ void TileMapEditor::_set_cell(const Point2i &p_pos, int p_value, bool p_flip_h, bool prev_flip_h = node->is_cell_x_flipped(p_pos.x, p_pos.y); bool prev_flip_v = node->is_cell_y_flipped(p_pos.x, p_pos.y); bool prev_transpose = node->is_cell_transposed(p_pos.x, p_pos.y); + Vector2 prev_position = node->get_cell_autotile_coord(p_pos.x, p_pos.y); - if (p_value == prev_val && p_flip_h == prev_flip_h && p_flip_v == prev_flip_v && p_transpose == prev_transpose) + Vector2 position; + int current = manual_palette->get_current(); + if (current != -1) { + position = manual_palette->get_item_metadata(current); + } else { + // if there is no manual tile selected, that either means that + // autotiling is enabled, or the given tile is not autotiling. Either + // way, the coordinate of the tile does not matter, so assigning it to + // the coordinate of the existing tile works fine. + position = prev_position; + } + + if (p_value == prev_val && p_flip_h == prev_flip_h && p_flip_v == prev_flip_v && p_transpose == prev_transpose && prev_position == position) return; //check that it's actually different node->set_cell(p_pos.x, p_pos.y, p_value, p_flip_h, p_flip_v, p_transpose); - node->update_bitmask_area(Point2(p_pos)); + if (manual_autotile) { + if (current != -1) { + node->set_cell_autotile_coord(p_pos.x, p_pos.y, position); + } + } else { + // manually placing tiles should not update bitmasks + node->update_bitmask_area(Point2(p_pos)); + } +} + +void TileMapEditor::_manual_toggled(bool p_enabled) { + manual_autotile = p_enabled; + _update_palette(); } void TileMapEditor::_text_entered(const String &p_text) { @@ -261,6 +294,8 @@ void TileMapEditor::_update_palette() { int selected = get_selected_tile(); palette->clear(); + manual_palette->clear(); + manual_palette->hide(); Ref<TileSet> tileset = node->get_tileset(); if (tileset.is_null()) @@ -268,7 +303,6 @@ void TileMapEditor::_update_palette() { List<int> tiles; tileset->get_tile_list(&tiles); - if (tiles.empty()) return; @@ -284,6 +318,9 @@ void TileMapEditor::_update_palette() { palette->set_fixed_icon_size(Size2(min_size, min_size)); palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1)); + palette->set_same_column_width(true); + manual_palette->set_fixed_icon_size(Size2(min_size, min_size)); + manual_palette->set_same_column_width(true); String filter = search_box->get_text().strip_edges(); @@ -344,12 +381,51 @@ void TileMapEditor::_update_palette() { palette->set_item_metadata(palette->get_item_count() - 1, entries[i].id); } - palette->set_same_column_width(true); - if (selected != -1) set_selected_tile(selected); else palette->select(0); + + if (manual_autotile && tileset->tile_get_tile_mode(get_selected_tile()) == TileSet::AUTO_TILE) { + + const Map<Vector2, uint16_t> &tiles = tileset->autotile_get_bitmask_map(get_selected_tile()); + + Vector<Vector2> entries; + for (const Map<Vector2, uint16_t>::Element *E = tiles.front(); E; E = E->next()) { + entries.push_back(E->key()); + } + entries.sort(); + + Ref<Texture> tex = tileset->tile_get_texture(get_selected_tile()); + + for (int i = 0; i < entries.size(); i++) { + + manual_palette->add_item(String()); + + if (tex.is_valid()) { + + Rect2 region = tileset->tile_get_region(get_selected_tile()); + int spacing = tileset->autotile_get_spacing(get_selected_tile()); + region.size = tileset->autotile_get_size(get_selected_tile()); + region.position += (region.size + Vector2(spacing, spacing)) * entries[i]; + + if (!region.has_no_area()) + manual_palette->set_item_icon_region(manual_palette->get_item_count() - 1, region); + + manual_palette->set_item_icon(manual_palette->get_item_count() - 1, tex); + } + + manual_palette->set_item_metadata(manual_palette->get_item_count() - 1, entries[i]); + } + } + + if (manual_palette->get_item_count() > 0) { + // Only show the manual palette if at least tile exists in it + int selected = manual_palette->get_current(); + if (selected == -1) selected = 0; + manual_palette->set_current(selected); + manual_palette->show(); + } } void TileMapEditor::_pick_tile(const Point2 &p_pos) { @@ -533,9 +609,17 @@ void TileMapEditor::_draw_cell(int p_cell, const Point2i &p_point, bool p_flip_h Rect2 r = node->get_tileset()->tile_get_region(p_cell); if (node->get_tileset()->tile_get_tile_mode(p_cell) == TileSet::AUTO_TILE) { + Vector2 offset; + int selected = manual_palette->get_current(); + if (manual_autotile && selected != -1) { + offset = manual_palette->get_item_metadata(selected); + } else { + offset = node->get_tileset()->autotile_get_icon_coordinate(p_cell); + } + int spacing = node->get_tileset()->autotile_get_spacing(p_cell); r.size = node->get_tileset()->autotile_get_size(p_cell); - r.position += (r.size + Vector2(spacing, spacing)) * node->get_tileset()->autotile_get_icon_coordinate(p_cell); + r.position += (r.size + Vector2(spacing, spacing)) * offset; } Size2 sc = p_xform.get_scale(); @@ -1503,12 +1587,14 @@ void TileMapEditor::_tileset_settings_changed() { void TileMapEditor::_icon_size_changed(float p_value) { if (node) { palette->set_icon_scale(p_value); + manual_palette->set_icon_scale(p_value); _update_palette(); } } void TileMapEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_manual_toggled"), &TileMapEditor::_manual_toggled); ClassDB::bind_method(D_METHOD("_text_entered"), &TileMapEditor::_text_entered); ClassDB::bind_method(D_METHOD("_text_changed"), &TileMapEditor::_text_changed); ClassDB::bind_method(D_METHOD("_sbox_input"), &TileMapEditor::_sbox_input); @@ -1517,6 +1603,7 @@ void TileMapEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_canvas_mouse_exit"), &TileMapEditor::_canvas_mouse_exit); ClassDB::bind_method(D_METHOD("_tileset_settings_changed"), &TileMapEditor::_tileset_settings_changed); ClassDB::bind_method(D_METHOD("_update_transform_buttons"), &TileMapEditor::_update_transform_buttons); + ClassDB::bind_method(D_METHOD("_palette_selected"), &TileMapEditor::_palette_selected); ClassDB::bind_method(D_METHOD("_fill_points"), &TileMapEditor::_fill_points); ClassDB::bind_method(D_METHOD("_erase_points"), &TileMapEditor::_erase_points); @@ -1574,6 +1661,8 @@ void TileMapEditor::_update_transform_buttons(Object *p_button) { TileMapEditor::TileMapEditor(EditorNode *p_editor) { node = NULL; + manual_autotile = false; + manual_position = Vector2(0, 0); canvas_item_editor = NULL; editor = p_editor; undo_redo = editor->get_undo_redo(); @@ -1601,6 +1690,11 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { HBoxContainer *tool_hb2 = memnew(HBoxContainer); add_child(tool_hb2); + manual_button = memnew(CheckBox); + manual_button->set_text("Disable Autotile"); + manual_button->connect("toggled", this, "_manual_toggled"); + add_child(manual_button); + search_box = memnew(LineEdit); search_box->set_h_size_flags(SIZE_EXPAND_FILL); search_box->connect("text_entered", this, "_text_entered"); @@ -1619,14 +1713,30 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { int mw = EDITOR_DEF("editors/tile_map/palette_min_width", 80); + VSplitContainer *palette_container = memnew(VSplitContainer); + palette_container->set_v_size_flags(SIZE_EXPAND_FILL); + palette_container->set_custom_minimum_size(Size2(mw, 0)); + add_child(palette_container); + // Add tile palette palette = memnew(ItemList); + palette->set_h_size_flags(SIZE_EXPAND_FILL); palette->set_v_size_flags(SIZE_EXPAND_FILL); - palette->set_custom_minimum_size(Size2(mw, 0)); palette->set_max_columns(0); palette->set_icon_mode(ItemList::ICON_MODE_TOP); palette->set_max_text_lines(2); - add_child(palette); + palette->connect("item_selected", this, "_palette_selected"); + palette_container->add_child(palette); + + // Add autotile override palette + manual_palette = memnew(ItemList); + manual_palette->set_h_size_flags(SIZE_EXPAND_FILL); + manual_palette->set_v_size_flags(SIZE_EXPAND_FILL); + manual_palette->set_max_columns(0); + manual_palette->set_icon_mode(ItemList::ICON_MODE_TOP); + manual_palette->set_max_text_lines(2); + manual_palette->hide(); + palette_container->add_child(manual_palette); // Add menu items toolbar = memnew(HBoxContainer); diff --git a/editor/plugins/tile_map_editor_plugin.h b/editor/plugins/tile_map_editor_plugin.h index 642870aec0..a1f5d93a8d 100644 --- a/editor/plugins/tile_map_editor_plugin.h +++ b/editor/plugins/tile_map_editor_plugin.h @@ -35,6 +35,7 @@ #include "editor/editor_plugin.h" #include "scene/2d/tile_map.h" +#include "scene/gui/check_box.h" #include "scene/gui/label.h" #include "scene/gui/line_edit.h" #include "scene/gui/menu_button.h" @@ -77,6 +78,8 @@ class TileMapEditor : public VBoxContainer { }; TileMap *node; + bool manual_autotile; + Vector2 manual_position; EditorNode *editor; UndoRedo *undo_redo; @@ -85,6 +88,7 @@ class TileMapEditor : public VBoxContainer { LineEdit *search_box; HSlider *size_slider; ItemList *palette; + ItemList *manual_palette; HBoxContainer *toolbar; @@ -97,6 +101,7 @@ class TileMapEditor : public VBoxContainer { ToolButton *rotate_90; ToolButton *rotate_180; ToolButton *rotate_270; + CheckBox *manual_button; Tool tool; @@ -168,11 +173,13 @@ class TileMapEditor : public VBoxContainer { int get_selected_tile() const; void set_selected_tile(int p_tile); + void _manual_toggled(bool p_enabled); void _text_entered(const String &p_text); void _text_changed(const String &p_text); void _sbox_input(const Ref<InputEvent> &p_ie); void _update_palette(); void _menu_option(int p_option); + void _palette_selected(int index); void _set_cell(const Point2i &p_pos, int p_value, bool p_flip_h = false, bool p_flip_v = false, bool p_transpose = false); diff --git a/editor/property_selector.cpp b/editor/property_selector.cpp index 3e95064ead..d927e07976 100644 --- a/editor/property_selector.cpp +++ b/editor/property_selector.cpp @@ -120,33 +120,33 @@ void PropertySelector::_update_search() { bool found = false; Ref<Texture> type_icons[Variant::VARIANT_MAX] = { - Control::get_icon("MiniVariant", "EditorIcons"), - Control::get_icon("MiniBoolean", "EditorIcons"), - Control::get_icon("MiniInteger", "EditorIcons"), - Control::get_icon("MiniFloat", "EditorIcons"), - Control::get_icon("MiniString", "EditorIcons"), - Control::get_icon("MiniVector2", "EditorIcons"), - Control::get_icon("MiniRect2", "EditorIcons"), - Control::get_icon("MiniVector3", "EditorIcons"), - Control::get_icon("MiniMatrix2", "EditorIcons"), - Control::get_icon("MiniPlane", "EditorIcons"), - Control::get_icon("MiniQuat", "EditorIcons"), - Control::get_icon("MiniAabb", "EditorIcons"), - Control::get_icon("MiniMatrix3", "EditorIcons"), - Control::get_icon("MiniTransform", "EditorIcons"), - Control::get_icon("MiniColor", "EditorIcons"), - Control::get_icon("MiniPath", "EditorIcons"), - Control::get_icon("MiniRid", "EditorIcons"), - Control::get_icon("MiniObject", "EditorIcons"), - Control::get_icon("MiniDictionary", "EditorIcons"), - Control::get_icon("MiniArray", "EditorIcons"), - Control::get_icon("MiniRawArray", "EditorIcons"), - Control::get_icon("MiniIntArray", "EditorIcons"), - Control::get_icon("MiniFloatArray", "EditorIcons"), - Control::get_icon("MiniStringArray", "EditorIcons"), - Control::get_icon("MiniVector2Array", "EditorIcons"), - Control::get_icon("MiniVector3Array", "EditorIcons"), - Control::get_icon("MiniColorArray", "EditorIcons") + Control::get_icon("Variant", "EditorIcons"), + Control::get_icon("bool", "EditorIcons"), + Control::get_icon("int", "EditorIcons"), + Control::get_icon("float", "EditorIcons"), + Control::get_icon("String", "EditorIcons"), + Control::get_icon("Vector2", "EditorIcons"), + Control::get_icon("Rect2", "EditorIcons"), + Control::get_icon("Vector3", "EditorIcons"), + Control::get_icon("Transform2D", "EditorIcons"), + Control::get_icon("Plane", "EditorIcons"), + Control::get_icon("Quat", "EditorIcons"), + Control::get_icon("AABB", "EditorIcons"), + Control::get_icon("Basis", "EditorIcons"), + Control::get_icon("Transform", "EditorIcons"), + Control::get_icon("Color", "EditorIcons"), + Control::get_icon("Path", "EditorIcons"), + Control::get_icon("RID", "EditorIcons"), + Control::get_icon("Object", "EditorIcons"), + Control::get_icon("Dictionary", "EditorIcons"), + Control::get_icon("Array", "EditorIcons"), + Control::get_icon("PoolByteArray", "EditorIcons"), + Control::get_icon("PoolIntArray", "EditorIcons"), + Control::get_icon("PoolRealArray", "EditorIcons"), + Control::get_icon("PoolStringArray", "EditorIcons"), + Control::get_icon("PoolVector2Array", "EditorIcons"), + Control::get_icon("PoolVector3Array", "EditorIcons"), + Control::get_icon("PoolColorArray", "EditorIcons") }; for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { @@ -175,6 +175,10 @@ void PropertySelector::_update_search() { if (search_box->get_text() != String() && E->get().name.find(search_box->get_text()) == -1) continue; + + if (type_filter.size() && type_filter.find(E->get().type) == -1) + continue; + TreeItem *item = search_options->create_item(category ? category : root); item->set_text(0, E->get().name); item->set_metadata(0, E->get().name); @@ -534,6 +538,10 @@ void PropertySelector::select_property_from_instance(Object *p_instance, const S _update_search(); } +void PropertySelector::set_type_filter(const Vector<Variant::Type> &p_type_filter) { + type_filter = p_type_filter; +} + void PropertySelector::_bind_methods() { ClassDB::bind_method(D_METHOD("_text_changed"), &PropertySelector::_text_changed); diff --git a/editor/property_selector.h b/editor/property_selector.h index d9b1aee422..f5b34d210e 100644 --- a/editor/property_selector.h +++ b/editor/property_selector.h @@ -60,6 +60,8 @@ class PropertySelector : public ConfirmationDialog { void _item_selected(); + Vector<Variant::Type> type_filter; + protected: void _notification(int p_what); static void _bind_methods(); @@ -75,6 +77,8 @@ public: void select_property_from_basic_type(Variant::Type p_type, const String &p_current = ""); void select_property_from_instance(Object *p_instance, const String &p_current = ""); + void set_type_filter(const Vector<Variant::Type> &p_type_filter); + PropertySelector(); }; diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index 65e3cdedea..77ee65879b 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -33,7 +33,7 @@ #include "core/io/resource_saver.h" #include "core/os/keyboard.h" #include "core/project_settings.h" -#include "editor/animation_editor.h" + #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/multi_node_edit.h" @@ -1248,7 +1248,7 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V path_renames[ni].second = fixed_node_path; } - editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, -1); + editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, p_position_in_parent + inc); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)) + "/" + new_name), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index()); if (p_keep_global_xform) { @@ -1262,8 +1262,8 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners); - if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) - editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); + if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == node) + editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", node); editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node); editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]); @@ -1290,8 +1290,8 @@ void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, V editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); - if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node) - editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node); + if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == node) + editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", node); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) @@ -1392,8 +1392,8 @@ void SceneTreeDock::_delete_confirm() { editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index()); - if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == n) - editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", n); + if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == n) + editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", n); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); editor_data->get_undo_redo().add_undo_reference(n); diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp index 6fe52e3337..7d2127d4f8 100644 --- a/editor/scene_tree_editor.cpp +++ b/editor/scene_tree_editor.cpp @@ -30,6 +30,7 @@ #include "scene_tree_editor.h" +#include "editor/plugins/animation_player_editor_plugin.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor_node.h" #include "message_queue.h" @@ -90,6 +91,12 @@ void SceneTreeEditor::_cell_button_pressed(Object *p_item, int p_column, int p_i _update_tree(); emit_signal("node_changed"); } + } else if (p_id == BUTTON_PIN) { + + if (n->is_class("AnimationPlayer")) { + AnimationPlayerEditor::singleton->unpin(); + _update_tree(); + } } else if (p_id == BUTTON_GROUP) { if (n->is_class("CanvasItem")) { @@ -284,6 +291,13 @@ bool SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) { p_node->connect("visibility_changed", this, "_node_visibility_changed", varray(p_node)); _update_visibility_color(p_node, item); + } else if (p_node->is_class("AnimationPlayer")) { + + bool is_pinned = AnimationPlayerEditor::singleton->get_player() == p_node && AnimationPlayerEditor::singleton->is_pinned(); + + if (is_pinned) { + item->add_button(0, get_icon("Pin", "EditorIcons"), BUTTON_PIN, false, TTR("AnimationPlayer is pinned.\nClick to unpin.")); + } } } diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h index 896fd6c431..b173d7d215 100644 --- a/editor/scene_tree_editor.h +++ b/editor/scene_tree_editor.h @@ -55,6 +55,7 @@ class SceneTreeEditor : public Control { BUTTON_WARNING = 5, BUTTON_SIGNALS = 6, BUTTON_GROUPS = 7, + BUTTON_PIN = 8, }; Tree *tree; diff --git a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs index a5dd37b5dc..16beacb45c 100644 --- a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs +++ b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs @@ -234,7 +234,7 @@ namespace GodotSharpTools.Build private static bool IsDebugMSBuildRequested() { - return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD").Trim() == "1"; + return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1"; } public void Dispose() diff --git a/modules/upnp/SCsub b/modules/upnp/SCsub new file mode 100644 index 0000000000..cde231867f --- /dev/null +++ b/modules/upnp/SCsub @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_upnp = env_modules.Clone() + +# Thirdparty source files + +if env['builtin_miniupnpc']: + thirdparty_dir = "#thirdparty/miniupnpc/" + thirdparty_sources = [ + "miniupnpc.c", + "upnpcommands.c", + "miniwget.c", + "upnpdev.c", + "igd_desc_parse.c", + "minissdpc.c", + "minisoap.c", + "minixml.c", + "connecthostport.c", + "receivedata.c", + "portlistingparse.c", + "upnpreplyparse.c", + ] + thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources] + + env_upnp.add_source_files(env.modules_sources, thirdparty_sources) + env_upnp.Append(CPPPATH=[thirdparty_dir]) + env_upnp.Append(CPPFLAGS=["-DMINIUPNP_STATICLIB"]) + +env_upnp.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/upnp/config.py b/modules/upnp/config.py new file mode 100644 index 0000000000..8724ff1a51 --- /dev/null +++ b/modules/upnp/config.py @@ -0,0 +1,14 @@ +def can_build(env, platform): + return True + +def configure(env): + pass + +def get_doc_classes(): + return [ + "UPNP", + "UPNPDevice" + ] + +def get_doc_path(): + return "doc_classes" diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml new file mode 100644 index 0000000000..30be9c836b --- /dev/null +++ b/modules/upnp/doc_classes/UPNP.xml @@ -0,0 +1,227 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="UPNP" inherits="Reference" category="Core" version="3.1"> + <brief_description> + UPNP network functions. + </brief_description> + <description> + Provides UPNP functionality to discover [UPNPDevice]s on the local network and execute commands on them, like managing port mappings (port forwarding) and querying the local and remote network IP address. Note that methods on this class are synchronous and block the calling thread. + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + <method name="add_device"> + <return type="void"> + </return> + <argument index="0" name="device" type="UPNPDevice"> + </argument> + <description> + Adds the given [UPNPDevice] to the list of discovered devices. + </description> + </method> + <method name="add_port_mapping" qualifiers="const"> + <return type="int"> + </return> + <argument index="0" name="port" type="int"> + </argument> + <argument index="1" name="port_internal" type="int" default="0"> + </argument> + <argument index="2" name="desc" type="String" default=""""> + </argument> + <argument index="3" name="proto" type="String" default=""UDP""> + </argument> + <argument index="4" name="duration" type="int" default="0"> + </argument> + <description> + Adds a mapping to forward the external [code]port[/code] (between 1 and 65535) on the default gateway (see [method get_gateway]) to the [code]internal_port[/code] on the local machine for the given protocol [code]proto[/code] (either [code]TCP[/code] or [code]UDP[/code], with UDP being the default). If a port mapping for the given port and protocol combination already exists on that gateway device, this method tries to overwrite it. If that is not desired, you can retrieve the gateway manually with [method get_gateway] and call [method add_port_mapping] on it, if any. + If [code]internal_port[/code] is [code]0[/code] (the default), the same port number is used for both the external and the internal port (the [code]port[/code] value). + The description ([code]desc[/code]) is shown in some router UIs and can be used to point out which application added the mapping, and the lifetime of the mapping can be limited by [code]duration[/code]. However, some routers are incompatible with one or both of these, so use with caution and add fallback logic in case of errors to retry without them if in doubt. + See [enum UPNPResult] for possible return values. + </description> + </method> + <method name="clear_devices"> + <return type="void"> + </return> + <description> + Clears the list of discovered devices. + </description> + </method> + <method name="delete_port_mapping" qualifiers="const"> + <return type="int"> + </return> + <argument index="0" name="port" type="int"> + </argument> + <argument index="1" name="proto" type="String" default=""UDP""> + </argument> + <description> + Deletes the port mapping for the given port and protocol combination on the default gateway (see [method get_gateway]) if one exists. [code]port[/code] must be a valid port between 1 and 65535, [code]proto[/code] can be either [code]TCP[/code] or [code]UDP[/code]. See [enum UPNPResult] for possible return values. + </description> + </method> + <method name="discover"> + <return type="int"> + </return> + <argument index="0" name="timeout" type="int" default="2000"> + </argument> + <argument index="1" name="ttl" type="int" default="2"> + </argument> + <argument index="2" name="device_filter" type="String" default=""InternetGatewayDevice""> + </argument> + <description> + Discovers local [UPNPDevice]s. Clears the list of previously discovered devices. + Filters for IGD (InternetGatewayDevice) type devices by default, as those manage port forwarding. [code]timeout[/code] is the time to wait for responses in miliseconds. [code]ttl[/code] is the time-to-live; only touch this if you know what you're doing. + See [enum UPNPResult] for possible return values. + </description> + </method> + <method name="get_device" qualifiers="const"> + <return type="UPNPDevice"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <description> + Returns the [UPNPDevice] at the given [code]index[/code]. + </description> + </method> + <method name="get_device_count" qualifiers="const"> + <return type="int"> + </return> + <description> + Returns the number of discovered [UPNPDevice]s. + </description> + </method> + <method name="get_gateway" qualifiers="const"> + <return type="UPNPDevice"> + </return> + <description> + Returns the default gateway. That is the first discovered [UPNPDevice] that is also a valid IGD (InternetGatewayDevice). + </description> + </method> + <method name="query_external_address" qualifiers="const"> + <return type="String"> + </return> + <description> + Returns the external [IP] address of the default gateway (see [method get_gateway]) as string. Returns an empty string on error. + </description> + </method> + <method name="remove_device"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <description> + Removes the device at [code]index[/code] from the list of discovered devices. + </description> + </method> + <method name="set_device"> + <return type="void"> + </return> + <argument index="0" name="index" type="int"> + </argument> + <argument index="1" name="device" type="UPNPDevice"> + </argument> + <description> + Sets the device at [code]index[/code] from the list of discovered devices to [code]device[/code]. + </description> + </method> + </methods> + <members> + <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6"> + If [code]true[/code], IPv6 is used for [UPNPDevice] discovery. + </member> + <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port"> + If [code]0[/code], the local port to use for discovery is chosen automatically by the system. If [code]1[/code], discovery will be done from the source port 1900 (same as destination port). Otherwise, the value will be used as the port. + </member> + <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if"> + Multicast interface to use for discovery. Uses the default multicast interface if empty. + </member> + </members> + <constants> + <constant name="UPNP_RESULT_SUCCESS" value="0" enum="UPNPResult"> + UPNP command or discovery was successful. + </constant> + <constant name="UPNP_RESULT_NOT_AUTHORIZED" value="1" enum="UPNPResult"> + Not authorized to use the command on the [UPNPDevice]. May be returned when the user disabled UPNP on their router. + </constant> + <constant name="UPNP_RESULT_PORT_MAPPING_NOT_FOUND" value="2" enum="UPNPResult"> + No port mapping was found for the given port, protocol combination on the given [UPNPDevice]. + </constant> + <constant name="UPNP_RESULT_INCONSISTENT_PARAMETERS" value="3" enum="UPNPResult"> + Inconsistent parameters. + </constant> + <constant name="UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY" value="4" enum="UPNPResult"> + No such entry in array. May be returned if a given port, protocol combination is not found on an [UPNPDevice]. + </constant> + <constant name="UPNP_RESULT_ACTION_FAILED" value="5" enum="UPNPResult"> + The action failed. + </constant> + <constant name="UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED" value="6" enum="UPNPResult"> + The [UPNPDevice] does not allow wildcard values for the source IP address. + </constant> + <constant name="UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED" value="7" enum="UPNPResult"> + The [UPNPDevice] does not allow wildcard values for the external port. + </constant> + <constant name="UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED" value="8" enum="UPNPResult"> + The [UPNPDevice] does not allow wildcard values for the internal port. + </constant> + <constant name="UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD" value="9" enum="UPNPResult"> + The remote host value must be a wildcard. + </constant> + <constant name="UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD" value="10" enum="UPNPResult"> + The external port value must be a wildcard. + </constant> + <constant name="UPNP_RESULT_NO_PORT_MAPS_AVAILABLE" value="11" enum="UPNPResult"> + No port maps are available. May also be returned if port mapping functionality is not available. + </constant> + <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM" value="12" enum="UPNPResult"> + Conflict with other mechanism. May be returned instead of [code]UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING[/code] if a port mapping conflicts with an existing one. + </constant> + <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING" value="13" enum="UPNPResult"> + Conflict with an existing port mapping. + </constant> + <constant name="UPNP_RESULT_SAME_PORT_VALUES_REQUIRED" value="14" enum="UPNPResult"> + External and internal port values must be the same. + </constant> + <constant name="UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED" value="15" enum="UPNPResult"> + Only permanent leases are supported. Do not use the [code]duration[/code] parameter when adding port mappings. + </constant> + <constant name="UPNP_RESULT_INVALID_GATEWAY" value="16" enum="UPNPResult"> + Invalid gateway. + </constant> + <constant name="UPNP_RESULT_INVALID_PORT" value="17" enum="UPNPResult"> + Invalid port. + </constant> + <constant name="UPNP_RESULT_INVALID_PROTOCOL" value="18" enum="UPNPResult"> + Invalid protocol. + </constant> + <constant name="UPNP_RESULT_INVALID_DURATION" value="19" enum="UPNPResult"> + Invalid duration. + </constant> + <constant name="UPNP_RESULT_INVALID_ARGS" value="20" enum="UPNPResult"> + Invalid arguments. + </constant> + <constant name="UPNP_RESULT_INVALID_RESPONSE" value="21" enum="UPNPResult"> + Invalid response. + </constant> + <constant name="UPNP_RESULT_INVALID_PARAM" value="22" enum="UPNPResult"> + Invalid parameter. + </constant> + <constant name="UPNP_RESULT_HTTP_ERROR" value="23" enum="UPNPResult"> + HTTP error. + </constant> + <constant name="UPNP_RESULT_SOCKET_ERROR" value="24" enum="UPNPResult"> + Socket error. + </constant> + <constant name="UPNP_RESULT_MEM_ALLOC_ERROR" value="25" enum="UPNPResult"> + Error allocating memory. + </constant> + <constant name="UPNP_RESULT_NO_GATEWAY" value="26" enum="UPNPResult"> + No gateway available. You may need to call [method discover] first, or discovery didn't detect any valid IGDs (InternetGatewayDevices). + </constant> + <constant name="UPNP_RESULT_NO_DEVICES" value="27" enum="UPNPResult"> + No devices available. You may need to call [method discover] first, or discovery didn't detect any valid [UPNPDevice]s. + </constant> + <constant name="UPNP_RESULT_UNKNOWN_ERROR" value="28" enum="UPNPResult"> + Unknown error. + </constant> + </constants> +</class> diff --git a/modules/upnp/doc_classes/UPNPDevice.xml b/modules/upnp/doc_classes/UPNPDevice.xml new file mode 100644 index 0000000000..9de8042daf --- /dev/null +++ b/modules/upnp/doc_classes/UPNPDevice.xml @@ -0,0 +1,109 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="UPNPDevice" inherits="Reference" category="Core" version="3.1"> + <brief_description> + UPNP device. + </brief_description> + <description> + UPNP device. See [UPNP] for UPNP discovery and utility functions. Provides low-level access to UPNP control commands. Allows to manage port mappings (port forwarding) and to query network information of the device (like local and external IP address and status). Note that methods on this class are synchronous and block the calling thread. + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + <method name="add_port_mapping" qualifiers="const"> + <return type="int"> + </return> + <argument index="0" name="port" type="int"> + </argument> + <argument index="1" name="port_internal" type="int" default="0"> + </argument> + <argument index="2" name="desc" type="String" default=""""> + </argument> + <argument index="3" name="proto" type="String" default=""UDP""> + </argument> + <argument index="4" name="duration" type="int" default="0"> + </argument> + <description> + Adds a port mapping to forward the given external port on this [UPNPDevice] for the given protocol to the local machine. See [method UPNP.add_port_mapping]. + </description> + </method> + <method name="delete_port_mapping" qualifiers="const"> + <return type="int"> + </return> + <argument index="0" name="port" type="int"> + </argument> + <argument index="1" name="proto" type="String" default=""UDP""> + </argument> + <description> + Deletes the port mapping identified by the given port and protocol combination on this device. See [method UPNP.delete_port_mapping]. + </description> + </method> + <method name="is_valid_gateway" qualifiers="const"> + <return type="bool"> + </return> + <description> + Returns [code]true[/code] if this is a valid IGD (InternetGatewayDevice) which potentially supports port forwarding. + </description> + </method> + <method name="query_external_address" qualifiers="const"> + <return type="String"> + </return> + <description> + Returns the external IP address of this [UPNPDevice] or an empty string. + </description> + </method> + </methods> + <members> + <member name="description_url" type="String" setter="set_description_url" getter="get_description_url"> + URL to the device description. + </member> + <member name="igd_control_url" type="String" setter="set_igd_control_url" getter="get_igd_control_url"> + IDG control URL. + </member> + <member name="igd_our_addr" type="String" setter="set_igd_our_addr" getter="get_igd_our_addr"> + Address of the local machine in the network connecting it to this [UPNPDevice]. + </member> + <member name="igd_service_type" type="String" setter="set_igd_service_type" getter="get_igd_service_type"> + IGD service type. + </member> + <member name="igd_status" type="int" setter="set_igd_status" getter="get_igd_status" enum="UPNPDevice.IGDStatus"> + IGD status. See [enum IGDStatus]. + </member> + <member name="service_type" type="String" setter="set_service_type" getter="get_service_type"> + Service type. + </member> + </members> + <constants> + <constant name="IGD_STATUS_OK" value="0" enum="IGDStatus"> + OK. + </constant> + <constant name="IGD_STATUS_HTTP_ERROR" value="1" enum="IGDStatus"> + HTTP error. + </constant> + <constant name="IGD_STATUS_HTTP_EMPTY" value="2" enum="IGDStatus"> + Empty HTTP response. + </constant> + <constant name="IGD_STATUS_NO_URLS" value="3" enum="IGDStatus"> + Returned response contained no URLs. + </constant> + <constant name="IGD_STATUS_NO_IGD" value="4" enum="IGDStatus"> + Not a valid IGD. + </constant> + <constant name="IGD_STATUS_DISCONNECTED" value="5" enum="IGDStatus"> + Disconnected. + </constant> + <constant name="IGD_STATUS_UNKNOWN_DEVICE" value="6" enum="IGDStatus"> + Unknown device. + </constant> + <constant name="IGD_STATUS_INVALID_CONTROL" value="7" enum="IGDStatus"> + Invalid control. + </constant> + <constant name="IGD_STATUS_MALLOC_ERROR" value="8" enum="IGDStatus"> + Memory allocation error. + </constant> + <constant name="IGD_STATUS_UNKNOWN_ERROR" value="9" enum="IGDStatus"> + Unknown error. + </constant> + </constants> +</class> diff --git a/modules/upnp/register_types.cpp b/modules/upnp/register_types.cpp new file mode 100644 index 0000000000..c79155c4d2 --- /dev/null +++ b/modules/upnp/register_types.cpp @@ -0,0 +1,43 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "register_types.h" +#include "error_macros.h" +#include "upnp.h" +#include "upnpdevice.h" + +void register_upnp_types() { + + ClassDB::register_class<UPNP>(); + ClassDB::register_class<UPNPDevice>(); +} + +void unregister_upnp_types() { +} diff --git a/modules/upnp/register_types.h b/modules/upnp/register_types.h new file mode 100644 index 0000000000..2aeb06abc7 --- /dev/null +++ b/modules/upnp/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +void register_upnp_types(); +void unregister_upnp_types(); diff --git a/modules/upnp/upnp.cpp b/modules/upnp/upnp.cpp new file mode 100644 index 0000000000..32fdfe22f8 --- /dev/null +++ b/modules/upnp/upnp.cpp @@ -0,0 +1,401 @@ +/*************************************************************************/ +/* upnp.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "upnp.h" +#include "miniupnpc/miniwget.h" +#include "upnpcommands.h" +#include <stdlib.h> + +bool UPNP::is_common_device(const String &dev) const { + return dev.empty() || + dev.find("InternetGatewayDevice") >= 0 || + dev.find("WANIPConnection") >= 0 || + dev.find("WANPPPConnection") >= 0 || + dev.find("rootdevice") >= 0; +} + +int UPNP::discover(int timeout, int ttl, const String &device_filter) { + ERR_FAIL_COND_V(timeout < 0, UPNP_RESULT_INVALID_PARAM); + ERR_FAIL_COND_V(ttl < 0, UPNP_RESULT_INVALID_PARAM); + ERR_FAIL_COND_V(ttl > 255, UPNP_RESULT_INVALID_PARAM); + + devices.clear(); + + int error = 0; + struct UPNPDev *devlist; + + if (is_common_device(device_filter)) { + devlist = upnpDiscover(timeout, discover_multicast_if.utf8().get_data(), NULL, discover_local_port, discover_ipv6, ttl, &error); + } else { + devlist = upnpDiscoverAll(timeout, discover_multicast_if.utf8().get_data(), NULL, discover_local_port, discover_ipv6, ttl, &error); + } + + if (error != UPNPDISCOVER_SUCCESS) { + switch (error) { + case UPNPDISCOVER_SOCKET_ERROR: + return UPNP_RESULT_SOCKET_ERROR; + case UPNPDISCOVER_MEMORY_ERROR: + return UPNP_RESULT_MEM_ALLOC_ERROR; + default: + return UPNP_RESULT_UNKNOWN_ERROR; + } + } + + if (!devlist) { + return UPNP_RESULT_NO_DEVICES; + } + + struct UPNPDev *dev = devlist; + + while (dev) { + if (device_filter.empty() || strstr(dev->st, device_filter.utf8().get_data())) { + add_device_to_list(dev, devlist); + } + + dev = dev->pNext; + } + + freeUPNPDevlist(devlist); + + return UPNP_RESULT_SUCCESS; +} + +void UPNP::add_device_to_list(UPNPDev *dev, UPNPDev *devlist) { + Ref<UPNPDevice> new_device; + new_device.instance(); + + new_device->set_description_url(dev->descURL); + new_device->set_service_type(dev->st); + + parse_igd(new_device, devlist); + + devices.push_back(new_device); +} + +char *UPNP::load_description(const String &url, int *size, int *status_code) const { + return (char *)miniwget(url.utf8().get_data(), size, 0, status_code); +} + +void UPNP::parse_igd(Ref<UPNPDevice> dev, UPNPDev *devlist) { + int size = 0; + int status_code = -1; + char *xml = load_description(dev->get_description_url(), &size, &status_code); + + if (status_code != 200) { + dev->set_igd_status(UPNPDevice::IGD_STATUS_HTTP_ERROR); + return; + } + + if (!xml || size < 1) { + dev->set_igd_status(UPNPDevice::IGD_STATUS_HTTP_EMPTY); + return; + } + + struct UPNPUrls *urls = (UPNPUrls *)malloc(sizeof(struct UPNPUrls)); + + if (!urls) { + dev->set_igd_status(UPNPDevice::IGD_STATUS_MALLOC_ERROR); + return; + } + + struct IGDdatas data; + + memset(urls, 0, sizeof(struct UPNPUrls)); + + parserootdesc(xml, size, &data); + free(xml); + xml = 0; + + GetUPNPUrls(urls, &data, dev->get_description_url().utf8().get_data(), 0); + + if (!urls) { + dev->set_igd_status(UPNPDevice::IGD_STATUS_NO_URLS); + return; + } + + char addr[16]; + int i = UPNP_GetValidIGD(devlist, urls, &data, (char *)&addr, 16); + + if (i != 1) { + FreeUPNPUrls(urls); + + switch (i) { + case 0: + dev->set_igd_status(UPNPDevice::IGD_STATUS_NO_IGD); + return; + case 2: + dev->set_igd_status(UPNPDevice::IGD_STATUS_DISCONNECTED); + return; + case 3: + dev->set_igd_status(UPNPDevice::IGD_STATUS_UNKNOWN_DEVICE); + return; + default: + dev->set_igd_status(UPNPDevice::IGD_STATUS_UNKNOWN_ERROR); + return; + } + } + + if (urls->controlURL[0] == '\0') { + FreeUPNPUrls(urls); + dev->set_igd_status(UPNPDevice::IGD_STATUS_INVALID_CONTROL); + return; + } + + dev->set_igd_control_url(urls->controlURL); + dev->set_igd_service_type(data.first.servicetype); + dev->set_igd_our_addr(addr); + dev->set_igd_status(UPNPDevice::IGD_STATUS_OK); + + FreeUPNPUrls(urls); +} + +int UPNP::upnp_result(int in) { + switch (in) { + case UPNPCOMMAND_SUCCESS: + return UPNP_RESULT_SUCCESS; + case UPNPCOMMAND_UNKNOWN_ERROR: + return UPNP_RESULT_UNKNOWN_ERROR; + case UPNPCOMMAND_INVALID_ARGS: + return UPNP_RESULT_INVALID_ARGS; + case UPNPCOMMAND_HTTP_ERROR: + return UPNP_RESULT_HTTP_ERROR; + case UPNPCOMMAND_INVALID_RESPONSE: + return UPNP_RESULT_INVALID_RESPONSE; + case UPNPCOMMAND_MEM_ALLOC_ERROR: + return UPNP_RESULT_MEM_ALLOC_ERROR; + + case 402: + return UPNP_RESULT_INVALID_ARGS; + case 403: + return UPNP_RESULT_NOT_AUTHORIZED; + case 501: + return UPNP_RESULT_ACTION_FAILED; + case 606: + return UPNP_RESULT_NOT_AUTHORIZED; + case 714: + return UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY; + case 715: + return UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED; + case 716: + return UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED; + case 718: + return UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING; + case 724: + return UPNP_RESULT_SAME_PORT_VALUES_REQUIRED; + case 725: + return UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED; + case 726: + return UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD; + case 727: + return UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD; + case 728: + return UPNP_RESULT_NO_PORT_MAPS_AVAILABLE; + case 729: + return UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM; + case 732: + return UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED; + case 733: + return UPNP_RESULT_INCONSISTENT_PARAMETERS; + } + + return UPNP_RESULT_UNKNOWN_ERROR; +} + +int UPNP::get_device_count() const { + return devices.size(); +} + +Ref<UPNPDevice> UPNP::get_device(int index) const { + ERR_FAIL_INDEX_V(index, devices.size(), NULL); + + return devices.get(index); +} + +void UPNP::add_device(Ref<UPNPDevice> device) { + ERR_FAIL_COND(device == NULL); + + devices.push_back(device); +} + +void UPNP::set_device(int index, Ref<UPNPDevice> device) { + ERR_FAIL_INDEX(index, devices.size()); + ERR_FAIL_COND(device == NULL); + + devices.set(index, device); +} + +void UPNP::remove_device(int index) { + ERR_FAIL_INDEX(index, devices.size()); + + devices.remove(index); +} + +void UPNP::clear_devices() { + devices.clear(); +} + +Ref<UPNPDevice> UPNP::get_gateway() const { + ERR_FAIL_COND_V(devices.size() < 1, NULL); + + for (int i = 0; i < devices.size(); i++) { + Ref<UPNPDevice> dev = get_device(i); + + if (dev != NULL && dev->is_valid_gateway()) { + return dev; + } + } + + return NULL; +} + +void UPNP::set_discover_multicast_if(const String &m_if) { + discover_multicast_if = m_if; +} + +String UPNP::get_discover_multicast_if() const { + return discover_multicast_if; +} + +void UPNP::set_discover_local_port(int port) { + discover_local_port = port; +} + +int UPNP::get_discover_local_port() const { + return discover_local_port; +} + +void UPNP::set_discover_ipv6(bool ipv6) { + discover_ipv6 = ipv6; +} + +bool UPNP::is_discover_ipv6() const { + return discover_ipv6; +} + +String UPNP::query_external_address() const { + Ref<UPNPDevice> dev = get_gateway(); + + if (dev == NULL) { + return ""; + } + + return dev->query_external_address(); +} + +int UPNP::add_port_mapping(int port, int port_internal, String desc, String proto, int duration) const { + Ref<UPNPDevice> dev = get_gateway(); + + if (dev == NULL) { + return UPNP_RESULT_NO_GATEWAY; + } + + dev->delete_port_mapping(port, proto); + + return dev->add_port_mapping(port, port_internal, desc, proto, duration); +} + +int UPNP::delete_port_mapping(int port, String proto) const { + Ref<UPNPDevice> dev = get_gateway(); + + if (dev == NULL) { + return UPNP_RESULT_NO_GATEWAY; + } + + return dev->delete_port_mapping(port, proto); +} + +void UPNP::_bind_methods() { + ClassDB::bind_method(D_METHOD("get_device_count"), &UPNP::get_device_count); + ClassDB::bind_method(D_METHOD("get_device", "index"), &UPNP::get_device); + ClassDB::bind_method(D_METHOD("add_device", "device"), &UPNP::add_device); + ClassDB::bind_method(D_METHOD("set_device", "index", "device"), &UPNP::set_device); + ClassDB::bind_method(D_METHOD("remove_device", "index"), &UPNP::remove_device); + ClassDB::bind_method(D_METHOD("clear_devices"), &UPNP::clear_devices); + + ClassDB::bind_method(D_METHOD("get_gateway"), &UPNP::get_gateway); + + ClassDB::bind_method(D_METHOD("discover", "timeout", "ttl", "device_filter"), &UPNP::discover, DEFVAL(2000), DEFVAL(2), DEFVAL("InternetGatewayDevice")); + + ClassDB::bind_method(D_METHOD("query_external_address"), &UPNP::query_external_address); + + ClassDB::bind_method(D_METHOD("add_port_mapping", "port", "port_internal", "desc", "proto", "duration"), &UPNP::add_port_mapping, DEFVAL(0), DEFVAL(""), DEFVAL("UDP"), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("delete_port_mapping", "port", "proto"), &UPNP::delete_port_mapping, DEFVAL("UDP")); + + ClassDB::bind_method(D_METHOD("set_discover_multicast_if", "m_if"), &UPNP::set_discover_multicast_if); + ClassDB::bind_method(D_METHOD("get_discover_multicast_if"), &UPNP::get_discover_multicast_if); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "discover_multicast_if"), "set_discover_multicast_if", "get_discover_multicast_if"); + + ClassDB::bind_method(D_METHOD("set_discover_local_port", "port"), &UPNP::set_discover_local_port); + ClassDB::bind_method(D_METHOD("get_discover_local_port"), &UPNP::get_discover_local_port); + ADD_PROPERTY(PropertyInfo(Variant::INT, "discover_local_port", PROPERTY_HINT_RANGE, "0,65535"), "set_discover_local_port", "get_discover_local_port"); + + ClassDB::bind_method(D_METHOD("set_discover_ipv6", "ipv6"), &UPNP::set_discover_ipv6); + ClassDB::bind_method(D_METHOD("is_discover_ipv6"), &UPNP::is_discover_ipv6); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "discover_ipv6"), "set_discover_ipv6", "is_discover_ipv6"); + + BIND_ENUM_CONSTANT(UPNP_RESULT_SUCCESS); + BIND_ENUM_CONSTANT(UPNP_RESULT_NOT_AUTHORIZED); + BIND_ENUM_CONSTANT(UPNP_RESULT_PORT_MAPPING_NOT_FOUND); + BIND_ENUM_CONSTANT(UPNP_RESULT_INCONSISTENT_PARAMETERS); + BIND_ENUM_CONSTANT(UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY); + BIND_ENUM_CONSTANT(UPNP_RESULT_ACTION_FAILED); + BIND_ENUM_CONSTANT(UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED); + BIND_ENUM_CONSTANT(UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED); + BIND_ENUM_CONSTANT(UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED); + BIND_ENUM_CONSTANT(UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD); + BIND_ENUM_CONSTANT(UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD); + BIND_ENUM_CONSTANT(UPNP_RESULT_NO_PORT_MAPS_AVAILABLE); + BIND_ENUM_CONSTANT(UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM); + BIND_ENUM_CONSTANT(UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING); + BIND_ENUM_CONSTANT(UPNP_RESULT_SAME_PORT_VALUES_REQUIRED); + BIND_ENUM_CONSTANT(UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_GATEWAY); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_PORT); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_PROTOCOL); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_DURATION); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_ARGS); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_RESPONSE); + BIND_ENUM_CONSTANT(UPNP_RESULT_INVALID_PARAM); + BIND_ENUM_CONSTANT(UPNP_RESULT_HTTP_ERROR); + BIND_ENUM_CONSTANT(UPNP_RESULT_SOCKET_ERROR); + BIND_ENUM_CONSTANT(UPNP_RESULT_MEM_ALLOC_ERROR); + BIND_ENUM_CONSTANT(UPNP_RESULT_NO_GATEWAY); + BIND_ENUM_CONSTANT(UPNP_RESULT_NO_DEVICES); + BIND_ENUM_CONSTANT(UPNP_RESULT_UNKNOWN_ERROR); +} + +UPNP::UPNP() { + discover_multicast_if = ""; + discover_local_port = 0; + discover_ipv6 = false; +} + +UPNP::~UPNP() { +} diff --git a/modules/upnp/upnp.h b/modules/upnp/upnp.h new file mode 100644 index 0000000000..fb0c0f30a0 --- /dev/null +++ b/modules/upnp/upnp.h @@ -0,0 +1,124 @@ +/*************************************************************************/ +/* upnp.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GODOT_UPNP_H +#define GODOT_UPNP_H + +#include "miniupnpc/miniupnpc.h" +#include "upnpdevice.h" +#include <reference.h> + +class UPNP : public Reference { + + GDCLASS(UPNP, Reference); + +private: + String discover_multicast_if; + int discover_local_port; + bool discover_ipv6; + + Vector<Ref<UPNPDevice> > devices; + + bool is_common_device(const String &dev) const; + void add_device_to_list(UPNPDev *dev, UPNPDev *devlist); + void parse_igd(Ref<UPNPDevice> dev, UPNPDev *devlist); + char *load_description(const String &url, int *size, int *status_code) const; + +protected: + static void _bind_methods(); + +public: + enum UPNPResult { + + UPNP_RESULT_SUCCESS, + UPNP_RESULT_NOT_AUTHORIZED, + UPNP_RESULT_PORT_MAPPING_NOT_FOUND, + UPNP_RESULT_INCONSISTENT_PARAMETERS, + UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY, + UPNP_RESULT_ACTION_FAILED, + UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED, + UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED, + UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED, + UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD, + UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD, + UPNP_RESULT_NO_PORT_MAPS_AVAILABLE, + UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM, + UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING, + UPNP_RESULT_SAME_PORT_VALUES_REQUIRED, + UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED, + UPNP_RESULT_INVALID_GATEWAY, + UPNP_RESULT_INVALID_PORT, + UPNP_RESULT_INVALID_PROTOCOL, + UPNP_RESULT_INVALID_DURATION, + UPNP_RESULT_INVALID_ARGS, + UPNP_RESULT_INVALID_RESPONSE, + UPNP_RESULT_INVALID_PARAM, + UPNP_RESULT_HTTP_ERROR, + UPNP_RESULT_SOCKET_ERROR, + UPNP_RESULT_MEM_ALLOC_ERROR, + UPNP_RESULT_NO_GATEWAY, + UPNP_RESULT_NO_DEVICES, + UPNP_RESULT_UNKNOWN_ERROR, + }; + + static int upnp_result(int in); + + int get_device_count() const; + Ref<UPNPDevice> get_device(int index) const; + void add_device(Ref<UPNPDevice> device); + void set_device(int index, Ref<UPNPDevice> device); + void remove_device(int index); + void clear_devices(); + + Ref<UPNPDevice> get_gateway() const; + + int discover(int timeout = 2000, int ttl = 2, const String &device_filter = "InternetGatewayDevice"); + + String query_external_address() const; + + int add_port_mapping(int port, int port_internal = 0, String desc = "", String proto = "UDP", int duration = 0) const; + int delete_port_mapping(int port, String proto = "UDP") const; + + void set_discover_multicast_if(const String &m_if); + String get_discover_multicast_if() const; + + void set_discover_local_port(int port); + int get_discover_local_port() const; + + void set_discover_ipv6(bool ipv6); + bool is_discover_ipv6() const; + + UPNP(); + ~UPNP(); +}; + +VARIANT_ENUM_CAST(UPNP::UPNPResult) + +#endif // GODOT_UPNP_H diff --git a/modules/upnp/upnpdevice.cpp b/modules/upnp/upnpdevice.cpp new file mode 100644 index 0000000000..a5959cf649 --- /dev/null +++ b/modules/upnp/upnpdevice.cpp @@ -0,0 +1,197 @@ +/*************************************************************************/ +/* upnpdevice.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "upnpdevice.h" +#include "upnp.h" +#include "upnpcommands.h" + +String UPNPDevice::query_external_address() const { + ERR_FAIL_COND_V(!is_valid_gateway(), ""); + + char addr[16]; + int i = UPNP_GetExternalIPAddress( + igd_control_url.utf8().get_data(), + igd_service_type.utf8().get_data(), + (char *)&addr); + + ERR_FAIL_COND_V(i != UPNPCOMMAND_SUCCESS, ""); + + return String(addr); +} + +int UPNPDevice::add_port_mapping(int port, int port_internal, String desc, String proto, int duration) const { + ERR_FAIL_COND_V(!is_valid_gateway(), UPNP::UPNP_RESULT_INVALID_GATEWAY); + ERR_FAIL_COND_V(port < 1 || port > 65535, UPNP::UPNP_RESULT_INVALID_PORT); + ERR_FAIL_COND_V(port_internal < 0 || port_internal > 65535, UPNP::UPNP_RESULT_INVALID_PORT); // Needs to allow 0 because 0 signifies "use external port as internal port" + ERR_FAIL_COND_V(proto != "UDP" && proto != "TCP", UPNP::UPNP_RESULT_INVALID_PROTOCOL); + ERR_FAIL_COND_V(duration < 0, UPNP::UPNP_RESULT_INVALID_DURATION); + + if (port_internal < 1) { + port_internal = port; + } + + int i = UPNP_AddPortMapping( + igd_control_url.utf8().get_data(), + igd_service_type.utf8().get_data(), + itos(port).utf8().get_data(), + itos(port_internal).utf8().get_data(), + igd_our_addr.utf8().get_data(), + desc.empty() ? 0 : desc.utf8().get_data(), + proto.utf8().get_data(), + NULL, // Remote host, always NULL as IGDs don't support it + duration > 0 ? itos(duration).utf8().get_data() : 0); + + ERR_FAIL_COND_V(i != UPNPCOMMAND_SUCCESS, UPNP::upnp_result(i)); + + return UPNP::UPNP_RESULT_SUCCESS; +} + +int UPNPDevice::delete_port_mapping(int port, String proto) const { + ERR_FAIL_COND_V(port < 1 || port > 65535, UPNP::UPNP_RESULT_INVALID_PORT); + ERR_FAIL_COND_V(proto != "UDP" && proto != "TCP", UPNP::UPNP_RESULT_INVALID_PROTOCOL); + + int i = UPNP_DeletePortMapping( + igd_control_url.utf8().get_data(), + igd_service_type.utf8().get_data(), + itos(port).utf8().get_data(), + proto.utf8().get_data(), + NULL // Remote host, always NULL as IGDs don't support it + ); + + ERR_FAIL_COND_V(i != UPNPCOMMAND_SUCCESS, UPNP::upnp_result(i)); + + return UPNP::UPNP_RESULT_SUCCESS; +} + +void UPNPDevice::set_description_url(const String &url) { + description_url = url; +} + +String UPNPDevice::get_description_url() const { + return description_url; +} + +void UPNPDevice::set_service_type(const String &type) { + service_type = type; +} + +String UPNPDevice::get_service_type() const { + return service_type; +} + +void UPNPDevice::set_igd_control_url(const String &url) { + igd_control_url = url; +} + +String UPNPDevice::get_igd_control_url() const { + return igd_control_url; +} + +void UPNPDevice::set_igd_service_type(const String &type) { + igd_service_type = type; +} + +String UPNPDevice::get_igd_service_type() const { + return igd_service_type; +} + +void UPNPDevice::set_igd_our_addr(const String &addr) { + igd_our_addr = addr; +} + +String UPNPDevice::get_igd_our_addr() const { + return igd_our_addr; +} + +void UPNPDevice::set_igd_status(IGDStatus status) { + igd_status = status; +} + +UPNPDevice::IGDStatus UPNPDevice::get_igd_status() const { + return igd_status; +} + +bool UPNPDevice::is_valid_gateway() const { + return igd_status == IGD_STATUS_OK; +} + +void UPNPDevice::_bind_methods() { + ClassDB::bind_method(D_METHOD("is_valid_gateway"), &UPNPDevice::is_valid_gateway); + ClassDB::bind_method(D_METHOD("query_external_address"), &UPNPDevice::query_external_address); + ClassDB::bind_method(D_METHOD("add_port_mapping", "port", "port_internal", "desc", "proto", "duration"), &UPNPDevice::add_port_mapping, DEFVAL(0), DEFVAL(""), DEFVAL("UDP"), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("delete_port_mapping", "port", "proto"), &UPNPDevice::delete_port_mapping, DEFVAL("UDP")); + + ClassDB::bind_method(D_METHOD("set_description_url", "url"), &UPNPDevice::set_description_url); + ClassDB::bind_method(D_METHOD("get_description_url"), &UPNPDevice::get_description_url); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "description_url"), "set_description_url", "get_description_url"); + + ClassDB::bind_method(D_METHOD("set_service_type", "type"), &UPNPDevice::set_service_type); + ClassDB::bind_method(D_METHOD("get_service_type"), &UPNPDevice::get_service_type); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "service_type"), "set_service_type", "get_service_type"); + + ClassDB::bind_method(D_METHOD("set_igd_control_url", "url"), &UPNPDevice::set_igd_control_url); + ClassDB::bind_method(D_METHOD("get_igd_control_url"), &UPNPDevice::get_igd_control_url); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "igd_control_url"), "set_igd_control_url", "get_igd_control_url"); + + ClassDB::bind_method(D_METHOD("set_igd_service_type", "type"), &UPNPDevice::set_igd_service_type); + ClassDB::bind_method(D_METHOD("get_igd_service_type"), &UPNPDevice::get_igd_service_type); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "igd_service_type"), "set_igd_service_type", "get_igd_service_type"); + + ClassDB::bind_method(D_METHOD("set_igd_our_addr", "addr"), &UPNPDevice::set_igd_our_addr); + ClassDB::bind_method(D_METHOD("get_igd_our_addr"), &UPNPDevice::get_igd_our_addr); + ADD_PROPERTY(PropertyInfo(Variant::STRING, "igd_our_addr"), "set_igd_our_addr", "get_igd_our_addr"); + + ClassDB::bind_method(D_METHOD("set_igd_status", "status"), &UPNPDevice::set_igd_status); + ClassDB::bind_method(D_METHOD("get_igd_status"), &UPNPDevice::get_igd_status); + ADD_PROPERTY(PropertyInfo(Variant::INT, "igd_status", PROPERTY_HINT_ENUM), "set_igd_status", "get_igd_status"); + + BIND_ENUM_CONSTANT(IGD_STATUS_OK); + BIND_ENUM_CONSTANT(IGD_STATUS_HTTP_ERROR); + BIND_ENUM_CONSTANT(IGD_STATUS_HTTP_EMPTY); + BIND_ENUM_CONSTANT(IGD_STATUS_NO_URLS); + BIND_ENUM_CONSTANT(IGD_STATUS_NO_IGD); + BIND_ENUM_CONSTANT(IGD_STATUS_DISCONNECTED); + BIND_ENUM_CONSTANT(IGD_STATUS_UNKNOWN_DEVICE); + BIND_ENUM_CONSTANT(IGD_STATUS_INVALID_CONTROL); + BIND_ENUM_CONSTANT(IGD_STATUS_MALLOC_ERROR); + BIND_ENUM_CONSTANT(IGD_STATUS_UNKNOWN_ERROR); +} + +UPNPDevice::UPNPDevice() { + description_url = ""; + service_type = ""; + igd_control_url = ""; + igd_service_type = ""; + igd_our_addr = ""; + igd_status = IGD_STATUS_UNKNOWN_ERROR; +} + +UPNPDevice::~UPNPDevice() { +} diff --git a/modules/upnp/upnpdevice.h b/modules/upnp/upnpdevice.h new file mode 100644 index 0000000000..25c9fe1ba3 --- /dev/null +++ b/modules/upnp/upnpdevice.h @@ -0,0 +1,95 @@ +/*************************************************************************/ +/* upnpdevice.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef GODOT_UPNPDEVICE_H +#define GODOT_UPNPDEVICE_H + +#include <reference.h> + +class UPNPDevice : public Reference { + + GDCLASS(UPNPDevice, Reference); + +public: + enum IGDStatus { + + IGD_STATUS_OK, + IGD_STATUS_HTTP_ERROR, + IGD_STATUS_HTTP_EMPTY, + IGD_STATUS_NO_URLS, + IGD_STATUS_NO_IGD, + IGD_STATUS_DISCONNECTED, + IGD_STATUS_UNKNOWN_DEVICE, + IGD_STATUS_INVALID_CONTROL, + IGD_STATUS_MALLOC_ERROR, + IGD_STATUS_UNKNOWN_ERROR, + }; + + void set_description_url(const String &url); + String get_description_url() const; + + void set_service_type(const String &type); + String get_service_type() const; + + void set_igd_control_url(const String &url); + String get_igd_control_url() const; + + void set_igd_service_type(const String &type); + String get_igd_service_type() const; + + void set_igd_our_addr(const String &addr); + String get_igd_our_addr() const; + + void set_igd_status(IGDStatus status); + IGDStatus get_igd_status() const; + + bool is_valid_gateway() const; + String query_external_address() const; + int add_port_mapping(int port, int port_internal = 0, String desc = "", String proto = "UDP", int duration = 0) const; + int delete_port_mapping(int port, String proto = "UDP") const; + + UPNPDevice(); + ~UPNPDevice(); + +protected: + static void _bind_methods(); + +private: + String description_url; + String service_type; + String igd_control_url; + String igd_service_type; + String igd_our_addr; + IGDStatus igd_status; +}; + +VARIANT_ENUM_CAST(UPNPDevice::IGDStatus) + +#endif // GODOT_UPNPDEVICE_H diff --git a/modules/websocket/SCsub b/modules/websocket/SCsub index b36f1beacd..15a88773e7 100644 --- a/modules/websocket/SCsub +++ b/modules/websocket/SCsub @@ -7,47 +7,57 @@ Import('env_modules') env_lws = env_modules.Clone() -thirdparty_dir = "#thirdparty/lws/" +thirdparty_dir = "#thirdparty/libwebsockets/" helper_dir = "win32helpers/" thirdparty_sources = [ - "client/client.c", - "client/client-handshake.c", - "client/client-parser.c", - "client/ssl-client.c", - - "ext/extension.c", - "ext/extension-permessage-deflate.c", - - "server/fops-zip.c", - "server/lejp-conf.c", - "server/parsers.c", - "server/ranges.c", - "server/server.c", - "server/server-handshake.c", - "server/ssl-server.c", + + "core/alloc.c", + "core/context.c", + "core/libwebsockets.c", + "core/output.c", + "core/pollfd.c", + "core/service.c", + + "event-libs/poll/poll.c", "misc/base64-decode.c", "misc/lejp.c", "misc/sha-1.c", - "alloc.c", - "context.c", - "handshake.c", - "header.c", - "libwebsockets.c", - "output.c", - "pollfd.c", - "service.c", - "ssl.c", - - "mbedtls_wrapper/library/ssl_cert.c", - "mbedtls_wrapper/library/ssl_pkey.c", - "mbedtls_wrapper/library/ssl_stack.c", - "mbedtls_wrapper/library/ssl_methods.c", - "mbedtls_wrapper/library/ssl_lib.c", - "mbedtls_wrapper/library/ssl_x509.c", - "mbedtls_wrapper/platform/ssl_port.c", - "mbedtls_wrapper/platform/ssl_pm.c", + "roles/h1/ops-h1.c", + "roles/http/header.c", + "roles/http/client/client.c", + "roles/http/client/client-handshake.c", + "roles/http/server/fops-zip.c", + "roles/http/server/lejp-conf.c", + "roles/http/server/parsers.c", + "roles/http/server/server.c", + "roles/listen/ops-listen.c", + "roles/pipe/ops-pipe.c", + "roles/raw/ops-raw.c", + + "roles/ws/client-ws.c", + "roles/ws/client-parser-ws.c", + "roles/ws/ops-ws.c", + "roles/ws/server-ws.c", + + "tls/tls.c", + "tls/tls-client.c", + "tls/tls-server.c", + + "tls/mbedtls/wrapper/library/ssl_cert.c", + "tls/mbedtls/wrapper/library/ssl_pkey.c", + "tls/mbedtls/wrapper/library/ssl_stack.c", + "tls/mbedtls/wrapper/library/ssl_methods.c", + "tls/mbedtls/wrapper/library/ssl_lib.c", + "tls/mbedtls/wrapper/library/ssl_x509.c", + "tls/mbedtls/wrapper/platform/ssl_port.c", + "tls/mbedtls/wrapper/platform/ssl_pm.c", + "tls/mbedtls/lws-genhash.c", + "tls/mbedtls/mbedtls-client.c", + "tls/mbedtls/lws-genrsa.c", + "tls/mbedtls/ssl.c", + "tls/mbedtls/mbedtls-server.c" ] if env_lws["platform"] == "android": # Builtin getifaddrs @@ -67,7 +77,7 @@ else: env_lws.add_source_files(env.modules_sources, thirdparty_sources) env_lws.Append(CPPPATH=[thirdparty_dir]) - wrapper_includes = ["#thirdparty/lws/mbedtls_wrapper/include/" + inc for inc in ["internal", "openssl", "platform", ""]] + wrapper_includes = ["#thirdparty/libwebsockets/tls/mbedtls/wrapper/include/" + inc for inc in ["internal", "openssl", "platform", ""]] env_lws.Prepend(CPPPATH=wrapper_includes) if env['builtin_mbedtls']: diff --git a/modules/websocket/lws_client.cpp b/modules/websocket/lws_client.cpp index 2220c9adf2..06f97aaf05 100644 --- a/modules/websocket/lws_client.cpp +++ b/modules/websocket/lws_client.cpp @@ -32,6 +32,7 @@ #include "lws_client.h" #include "core/io/ip.h" #include "core/io/stream_peer_ssl.h" +#include "tls/mbedtls/wrapper/include/openssl/ssl.h" Error LWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) { @@ -140,7 +141,7 @@ int LWSClient::_handle_cb(struct lws *wsi, enum lws_callback_reasons reason, voi destroy_context(); return -1; // we should close the connection (would probably happen anyway) - case LWS_CALLBACK_CLOSED: + case LWS_CALLBACK_CLIENT_CLOSED: peer_data->in_count = 0; peer_data->out_count = 0; peer_data->rbw.resize(0); diff --git a/modules/websocket/lws_peer.cpp b/modules/websocket/lws_peer.cpp index 3855a39aef..96acb99cc4 100644 --- a/modules/websocket/lws_peer.cpp +++ b/modules/websocket/lws_peer.cpp @@ -191,8 +191,8 @@ IP_Address LWSPeer::get_connected_host() const { IP_Address ip; int port = 0; - socklen_t len = 0; struct sockaddr_storage addr; + socklen_t len = sizeof(addr); int fd = lws_get_socket_fd(wsi); ERR_FAIL_COND_V(fd == -1, IP_Address()); @@ -212,8 +212,8 @@ uint16_t LWSPeer::get_connected_port() const { IP_Address ip; int port = 0; - socklen_t len = 0; struct sockaddr_storage addr; + socklen_t len = sizeof(addr); int fd = lws_get_socket_fd(wsi); ERR_FAIL_COND_V(fd == -1, 0); diff --git a/platform/haiku/detect.py b/platform/haiku/detect.py index 7c62654ef6..2959023204 100644 --- a/platform/haiku/detect.py +++ b/platform/haiku/detect.py @@ -22,7 +22,7 @@ def get_opts(): from SCons.Variables import EnumVariable return [ - EnumVariable('debug_symbols', 'Add debug symbols to release version', 'yes', ('yes', 'no', 'full')), + EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), ] diff --git a/platform/osx/detect.py b/platform/osx/detect.py index 1e9631fae0..72b8aa99f8 100644 --- a/platform/osx/detect.py +++ b/platform/osx/detect.py @@ -23,8 +23,8 @@ def get_opts(): return [ ('osxcross_sdk', 'OSXCross SDK version', 'darwin14'), - EnumVariable('debug_symbols', 'Add debug symbols to release version', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file with the debug symbols', False), + EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), + BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), ] diff --git a/platform/server/detect.py b/platform/server/detect.py index 7bf445b43f..266b0c5cc9 100644 --- a/platform/server/detect.py +++ b/platform/server/detect.py @@ -67,9 +67,6 @@ def configure(env): # FIXME: Check for existence of the libs before parsing their flags with pkg-config - if not env['builtin_libwebp']: - env.ParseConfig('pkg-config libwebp --cflags --libs') - # freetype depends on libpng and zlib, so bundling one of them while keeping others # as shared libraries leads to weird issues if env['builtin_freetype'] or env['builtin_libpng'] or env['builtin_zlib']: @@ -124,6 +121,21 @@ def configure(env): if not env['builtin_libogg']: env.ParseConfig('pkg-config ogg --cflags --libs') + if not env['builtin_libwebp']: + env.ParseConfig('pkg-config libwebp --cflags --libs') + + if not env['builtin_mbedtls']: + # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 + env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) + + if not env['builtin_libwebsockets']: + env.ParseConfig('pkg-config libwebsockets --cflags --libs') + + if not env['builtin_miniupnpc']: + # No pkgconfig file so far, hardcode default paths. + env.Append(CPPPATH=["/usr/include/miniupnpc"]) + env.Append(LIBS=["miniupnpc"]) + # On Linux wchar_t should be 32-bits # 16-bit library shouldn't be required due to compiler optimisations if not env['builtin_pcre2']: diff --git a/platform/uwp/detect.py b/platform/uwp/detect.py index 0e7b125dc5..559f23ca5b 100644 --- a/platform/uwp/detect.py +++ b/platform/uwp/detect.py @@ -28,8 +28,8 @@ def get_opts(): from SCons.Variables import BoolVariable return [ - ('msvc_version', 'MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.', None), - BoolVariable('use_mingw', 'Use the Mingw compiler, even if MSVC is installed. Only used on Windows.', False), + ('msvc_version', 'MSVC version to use (ignored if the VCINSTALLDIR environment variable is set)', None), + BoolVariable('use_mingw', 'Use the MinGW compiler even if MSVC is installed (only used on Windows)', False), ] @@ -112,7 +112,7 @@ def configure(env): env["bits"] = "32" print("Compiled program architecture will be a x86 executable. (forcing bits=32).") else: - print("Failed to detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup.") + print("Failed to detect MSVC compiler architecture version... Defaulting to 32-bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup.") env["bits"] = "32" if (env["bits"] == "32"): diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 6d559520d7..05806d2fe8 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -62,8 +62,8 @@ def get_opts(): # XP support dropped after EOL due to missing API for IPv6 and other issues # Vista support dropped after EOL due to GH-10243 ('target_win_version', 'Targeted Windows version, >= 0x0601 (Windows 7)', '0x0601'), - EnumVariable('debug_symbols', 'Add debug symbols to release version', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file with the debug symbols', False), + EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), + BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), ('msvc_version', 'MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.', None), BoolVariable('use_mingw', 'Use the Mingw compiler, even if MSVC is installed. Only used on Windows.', False), ] diff --git a/platform/x11/detect.py b/platform/x11/detect.py index ad2620c9f5..09e16ad078 100644 --- a/platform/x11/detect.py +++ b/platform/x11/detect.py @@ -59,8 +59,8 @@ def get_opts(): BoolVariable('use_leak_sanitizer', 'Use LLVM compiler memory leaks sanitizer (implies use_sanitizer)', False), BoolVariable('pulseaudio', 'Detect & use pulseaudio', True), BoolVariable('udev', 'Use udev for gamepad connection callbacks', False), - EnumVariable('debug_symbols', 'Add debug symbols to release version', 'yes', ('yes', 'no', 'full')), - BoolVariable('separate_debug_symbols', 'Create a separate file with the debug symbols', False), + EnumVariable('debug_symbols', 'Add debugging symbols to release builds', 'yes', ('yes', 'no', 'full')), + BoolVariable('separate_debug_symbols', 'Create a separate file containing debugging symbols', False), BoolVariable('touch', 'Enable touch events', True), ] @@ -158,14 +158,6 @@ def configure(env): # FIXME: Check for existence of the libs before parsing their flags with pkg-config - if not env['builtin_mbedtls']: - # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 - env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) - - if not env['builtin_libwebp']: - env.ParseConfig('pkg-config libwebp --cflags --libs') - - # freetype depends on libpng and zlib, so bundling one of them while keeping others # as shared libraries leads to weird issues if env['builtin_freetype'] or env['builtin_libpng'] or env['builtin_zlib']: @@ -205,6 +197,10 @@ def configure(env): env['builtin_libogg'] = False # Needed to link against system libtheora env['builtin_libvorbis'] = False # Needed to link against system libtheora env.ParseConfig('pkg-config theora theoradec --cflags --libs') + else: + list_of_x86 = ['x86_64', 'x86', 'i386', 'i586'] + if any(platform.machine() in s for s in list_of_x86): + env["x86_libtheora_opt_gcc"] = True if not env['builtin_libvpx']: env.ParseConfig('pkg-config vpx --cflags --libs') @@ -220,10 +216,20 @@ def configure(env): if not env['builtin_libogg']: env.ParseConfig('pkg-config ogg --cflags --libs') - if env['builtin_libtheora']: - list_of_x86 = ['x86_64', 'x86', 'i386', 'i586'] - if any(platform.machine() in s for s in list_of_x86): - env["x86_libtheora_opt_gcc"] = True + if not env['builtin_libwebp']: + env.ParseConfig('pkg-config libwebp --cflags --libs') + + if not env['builtin_mbedtls']: + # mbedTLS does not provide a pkgconfig config yet. See https://github.com/ARMmbed/mbedtls/issues/228 + env.Append(LIBS=['mbedtls', 'mbedcrypto', 'mbedx509']) + + if not env['builtin_libwebsockets']: + env.ParseConfig('pkg-config libwebsockets --cflags --libs') + + if not env['builtin_miniupnpc']: + # No pkgconfig file so far, hardcode default paths. + env.Append(CPPPATH=["/usr/include/miniupnpc"]) + env.Append(LIBS=["miniupnpc"]) # On Linux wchar_t should be 32-bits # 16-bit library shouldn't be required due to compiler optimisations diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp index d88e148b2c..050a3f245d 100644 --- a/scene/2d/tile_map.cpp +++ b/scene/2d/tile_map.cpp @@ -977,6 +977,14 @@ void TileMap::set_cell_autotile_coord(int p_x, int p_y, const Vector2 &p_coord) c.autotile_coord_x = p_coord.x; c.autotile_coord_y = p_coord.y; tile_map[pk] = c; + + PosKey qk(p_x / _get_quadrant_size(), p_y / _get_quadrant_size()); + Map<PosKey, Quadrant>::Element *Q = quadrant_map.find(qk); + + if (!Q) + return; + + _make_quadrant_dirty(Q); } Vector2 TileMap::get_cell_autotile_coord(int p_x, int p_y) const { diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index a0e0137863..0aabc3b38c 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -33,7 +33,7 @@ #include "engine.h" #include "message_queue.h" #include "scene/scene_string_names.h" - +#include "servers/audio/audio_stream.h" #ifdef TOOLS_ENABLED void AnimatedValuesBackup::update_skeletons() { @@ -325,10 +325,27 @@ void AnimationPlayer::_ensure_node_caches(AnimationData *p_anim) { p_anim->node_cache[i]->property_anim[a->track_get_path(i).get_concatenated_subnames()] = pa; } } + + if (a->track_get_type(i) == Animation::TYPE_BEZIER && leftover_path.size()) { + + if (!p_anim->node_cache[i]->bezier_anim.has(a->track_get_path(i).get_concatenated_subnames())) { + + TrackNodeCache::BezierAnim ba; + String path = leftover_path[leftover_path.size() - 1]; + Vector<String> index = path.split("."); + for (int j = 0; j < index.size(); j++) { + ba.bezier_property.push_back(index[j]); + } + ba.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child; + ba.owner = p_anim->node_cache[i]; + + p_anim->node_cache[i]->bezier_anim[a->track_get_path(i).get_concatenated_subnames()] = ba; + } + } } } -void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete) { +void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_is_current, bool p_seeked, bool p_started) { _ensure_node_caches(p_anim); ERR_FAIL_COND(p_anim->node_cache.size() != p_anim->animation->get_track_count()); @@ -394,7 +411,39 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float TrackNodeCache::PropertyAnim *pa = &E->get(); - if (a->value_track_get_update_mode(i) == Animation::UPDATE_CONTINUOUS || (p_delta == 0 && a->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE)) { //delta == 0 means seek + Animation::UpdateMode update_mode = a->value_track_get_update_mode(i); + + if (update_mode == Animation::UPDATE_CAPTURE) { + + if (p_started) { + pa->capture = pa->object->get_indexed(pa->subpath); + } + + if (a->track_get_key_count(i) == 0) + continue; //eeh not worth it + + float first_key_time = a->track_get_key_time(i, 0); + + if (p_time < first_key_time) { + float c = p_time / first_key_time; + Variant first_value = a->track_get_key_value(i, 0); + Variant interp_value; + Variant::interpolate(pa->capture, first_value, c, interp_value); + + if (pa->accum_pass != accum_pass) { + ERR_CONTINUE(cache_update_prop_size >= NODE_CACHE_UPDATE_MAX); + cache_update_prop[cache_update_prop_size++] = pa; + pa->value_accum = interp_value; + pa->accum_pass = accum_pass; + } else { + Variant::interpolate(pa->value_accum, interp_value, p_interp, pa->value_accum); + } + + continue; //handled + } + } + + if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE || (p_delta == 0 && update_mode == Animation::UPDATE_DISCRETE)) { //delta == 0 means seek Variant value = a->value_track_interpolate(i, p_time); @@ -415,7 +464,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float Variant::interpolate(pa->value_accum, value, p_interp, pa->value_accum); } - } else if (p_allow_discrete && p_delta != 0) { + } else if (p_is_current && p_delta != 0) { List<int> indices; a->value_track_get_key_indices(i, p_time, p_delta, &indices); @@ -470,9 +519,10 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float if (!nc->node) continue; - if (p_delta == 0) + if (p_delta == 0) { continue; - if (!p_allow_discrete) + } + if (!p_is_current) break; List<int> indices; @@ -500,11 +550,180 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float } } break; + case Animation::TYPE_BEZIER: { + + if (!nc->node) + continue; + + Map<StringName, TrackNodeCache::BezierAnim>::Element *E = nc->bezier_anim.find(a->track_get_path(i).get_concatenated_subnames()); + ERR_CONTINUE(!E); //should it continue, or create a new one? + + TrackNodeCache::BezierAnim *ba = &E->get(); + + float bezier = a->bezier_track_interpolate(i, p_time); + if (ba->accum_pass != accum_pass) { + ERR_CONTINUE(cache_update_bezier_size >= NODE_CACHE_UPDATE_MAX); + cache_update_bezier[cache_update_bezier_size++] = ba; + ba->bezier_accum = bezier; + ba->accum_pass = accum_pass; + } else { + ba->bezier_accum = Math::lerp(ba->bezier_accum, bezier, p_interp); + } + + } break; + case Animation::TYPE_AUDIO: { + + if (!nc->node) + continue; + if (p_delta == 0) { + continue; + } + + if (p_seeked) { + //find whathever should be playing + int idx = a->track_find_key(i, p_time); + if (idx < 0) + continue; + + Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx); + if (!stream.is_valid()) { + nc->node->call("stop"); + nc->audio_playing = false; + playing_caches.erase(nc); + } else { + float start_ofs = a->audio_track_get_key_start_offset(i, idx); + start_ofs += p_time - a->track_get_key_time(i, idx); + float end_ofs = a->audio_track_get_key_end_offset(i, idx); + float len = stream->get_length(); + + if (start_ofs > len - end_ofs) { + nc->node->call("stop"); + nc->audio_playing = false; + playing_caches.erase(nc); + continue; + } + + nc->node->call("set_stream", stream); + nc->node->call("play", start_ofs); + + nc->audio_playing = true; + playing_caches.insert(nc); + if (len && end_ofs > 0) { //force a end at a time + nc->audio_len = len - start_ofs - end_ofs; + } else { + nc->audio_len = 0; + } + + nc->audio_start = p_time; + } + + } else { + //find stuff to play + List<int> to_play; + a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play); + if (to_play.size()) { + int idx = to_play.back()->get(); + + Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx); + if (!stream.is_valid()) { + nc->node->call("stop"); + nc->audio_playing = false; + playing_caches.erase(nc); + } else { + float start_ofs = a->audio_track_get_key_start_offset(i, idx); + float end_ofs = a->audio_track_get_key_end_offset(i, idx); + float len = stream->get_length(); + + nc->node->call("set_stream", stream); + nc->node->call("play", start_ofs); + + nc->audio_playing = true; + playing_caches.insert(nc); + if (len && end_ofs > 0) { //force a end at a time + nc->audio_len = len - start_ofs - end_ofs; + } else { + nc->audio_len = 0; + } + + nc->audio_start = p_time; + } + } else if (nc->audio_playing) { + if (nc->audio_start > p_time || (nc->audio_len > 0 && p_time - nc->audio_start < nc->audio_len)) { + //time to stop + nc->node->call("stop"); + nc->audio_playing = false; + playing_caches.erase(nc); + } + } + } + + } break; + case Animation::TYPE_ANIMATION: { + + AnimationPlayer *player = Object::cast_to<AnimationPlayer>(nc->node); + if (!player) + continue; + + if (p_delta == 0 || p_seeked) { + //seek + int idx = a->track_find_key(i, p_time); + if (idx < 0) + continue; + + float pos = a->track_get_key_time(i, idx); + + StringName anim_name = a->animation_track_get_key_animation(i, idx); + if (String(anim_name) == "[stop]" || !player->has_animation(anim_name)) + continue; + + Ref<Animation> anim = player->get_animation(anim_name); + + float at_anim_pos; + + if (anim->has_loop()) { + at_anim_pos = Math::fposmod(p_time - pos, anim->get_length()); //seek to loop + } else { + at_anim_pos = MAX(anim->get_length(), p_time - pos); //seek to end + } + + if (player->is_playing() || p_seeked) { + player->play(anim_name); + player->seek(at_anim_pos); + nc->animation_playing = true; + playing_caches.insert(nc); + } else { + player->set_assigned_animation(anim_name); + player->seek(at_anim_pos, true); + } + } else { + //find stuff to play + List<int> to_play; + a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play); + if (to_play.size()) { + int idx = to_play.back()->get(); + + StringName anim_name = a->animation_track_get_key_animation(i, idx); + if (String(anim_name) == "[stop]" || !player->has_animation(anim_name)) { + + if (playing_caches.has(nc)) { + playing_caches.erase(nc); + player->stop(); + nc->animation_playing = false; + } + } else { + player->play(anim_name); + nc->animation_playing = true; + playing_caches.insert(nc); + } + } + } + + } break; } } } -void AnimationPlayer::_animation_process_data(PlaybackData &cd, float p_delta, float p_blend) { +void AnimationPlayer::_animation_process_data(PlaybackData &cd, float p_delta, float p_blend, bool p_seeked, bool p_started) { float delta = p_delta * speed_scale * cd.speed_scale; float next_pos = cd.pos + delta; @@ -553,22 +772,25 @@ void AnimationPlayer::_animation_process_data(PlaybackData &cd, float p_delta, f cd.pos = next_pos; - _animation_process_animation(cd.from, cd.pos, delta, p_blend, &cd == &playback.current); + _animation_process_animation(cd.from, cd.pos, delta, p_blend, &cd == &playback.current, p_seeked, p_started); } -void AnimationPlayer::_animation_process2(float p_delta) { +void AnimationPlayer::_animation_process2(float p_delta, bool p_started) { Playback &c = playback; accum_pass++; - _animation_process_data(c.current, p_delta, 1.0f); + _animation_process_data(c.current, p_delta, 1.0f, c.seeked && p_delta != 0, p_started); + if (p_delta != 0) { + c.seeked = false; + } List<Blend>::Element *prev = NULL; for (List<Blend>::Element *E = c.blend.back(); E; E = prev) { Blend &b = E->get(); float blend = b.blend_left / b.blend_time; - _animation_process_data(b.data, p_delta, blend); + _animation_process_data(b.data, p_delta, blend, false, false); b.blend_left -= Math::absf(speed_scale * p_delta); @@ -652,6 +874,16 @@ void AnimationPlayer::_animation_update_transforms() { } cache_update_prop_size = 0; + + for (int i = 0; i < cache_update_bezier_size; i++) { + + TrackNodeCache::BezierAnim *ba = cache_update_bezier[i]; + + ERR_CONTINUE(ba->accum_pass != accum_pass); + ba->object->set_indexed(ba->bezier_property, ba->bezier_accum); + } + + cache_update_bezier_size = 0; } void AnimationPlayer::_animation_process(float p_delta) { @@ -660,7 +892,12 @@ void AnimationPlayer::_animation_process(float p_delta) { end_reached = false; end_notify = false; - _animation_process2(p_delta); + _animation_process2(p_delta, playback.started); + + if (playback.started) { + playback.started = false; + } + _animation_update_transforms(); if (end_reached) { if (queued.size()) { @@ -865,7 +1102,7 @@ void AnimationPlayer::queue(const StringName &p_name) { void AnimationPlayer::clear_queue() { queued.clear(); -}; +} void AnimationPlayer::play_backwards(const StringName &p_name, float p_custom_blend) { @@ -930,10 +1167,14 @@ void AnimationPlayer::play(const StringName &p_name, float p_custom_blend, float } } + _stop_playing_caches(); + c.current.from = &animation_set[name]; c.current.pos = p_from_end ? c.current.from->animation->get_length() : 0; c.current.speed_scale = p_custom_scale; c.assigned = p_name; + c.seeked = false; + c.started = true; if (!end_reached) queued.clear(); @@ -1004,6 +1245,7 @@ String AnimationPlayer::get_assigned_animation() const { void AnimationPlayer::stop(bool p_reset) { + _stop_playing_caches(); Playback &c = playback; c.blend.clear(); if (p_reset) { @@ -1042,6 +1284,7 @@ void AnimationPlayer::seek(float p_time, bool p_update) { } playback.current.pos = p_time; + playback.seeked = true; if (p_update) { _animation_process(0); } @@ -1086,6 +1329,24 @@ void AnimationPlayer::_animation_changed() { clear_caches(); } +void AnimationPlayer::_stop_playing_caches() { + + for (Set<TrackNodeCache *>::Element *E = playing_caches.front(); E; E = E->next()) { + + if (E->get()->node && E->get()->audio_playing) { + E->get()->node->call("stop"); + } + if (E->get()->node && E->get()->animation_playing) { + AnimationPlayer *player = Object::cast_to<AnimationPlayer>(E->get()->node); + if (!player) + continue; + player->stop(); + } + } + + playing_caches.clear(); +} + void AnimationPlayer::_node_removed(Node *p_node) { clear_caches(); // nodes contained here ar being removed, clear the caches @@ -1093,6 +1354,8 @@ void AnimationPlayer::_node_removed(Node *p_node) { void AnimationPlayer::clear_caches() { + _stop_playing_caches(); + node_cache_map.clear(); for (Map<StringName, AnimationData>::Element *E = animation_set.front(); E; E = E->next()) { @@ -1102,6 +1365,7 @@ void AnimationPlayer::clear_caches() { cache_update_size = 0; cache_update_prop_size = 0; + cache_update_bezier_size = 0; } void AnimationPlayer::set_active(bool p_active) { @@ -1368,6 +1632,7 @@ AnimationPlayer::AnimationPlayer() { accum_pass = 1; cache_update_size = 0; cache_update_prop_size = 0; + cache_update_bezier_size = 0; speed_scale = 1; end_reached = false; end_notify = false; @@ -1377,6 +1642,8 @@ AnimationPlayer::AnimationPlayer() { root = SceneStringNames::get_singleton()->path_pp; playing = false; active = true; + playback.seeked = false; + playback.started = false; } AnimationPlayer::~AnimationPlayer() { diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h index af2022ddac..49c73e54ad 100644 --- a/scene/animation/animation_player.h +++ b/scene/animation/animation_player.h @@ -98,6 +98,12 @@ private: Vector3 scale_accum; uint64_t accum_pass; + bool audio_playing; + float audio_start; + float audio_len; + + bool animation_playing; + struct PropertyAnim { TrackNodeCache *owner; @@ -106,6 +112,7 @@ private: Object *object; Variant value_accum; uint64_t accum_pass; + Variant capture; PropertyAnim() { accum_pass = 0; object = NULL; @@ -114,6 +121,22 @@ private: Map<StringName, PropertyAnim> property_anim; + struct BezierAnim { + + Vector<StringName> bezier_property; + TrackNodeCache *owner; + float bezier_accum; + Object *object; + uint64_t accum_pass; + BezierAnim() { + accum_pass = 0; + bezier_accum = 0; + object = NULL; + } + }; + + Map<StringName, BezierAnim> bezier_anim; + TrackNodeCache() { skeleton = NULL; spatial = NULL; @@ -121,6 +144,8 @@ private: accum_pass = 0; bone_idx = -1; node_2d = NULL; + audio_playing = false; + animation_playing = false; } }; @@ -146,6 +171,10 @@ private: int cache_update_size; TrackNodeCache::PropertyAnim *cache_update_prop[NODE_CACHE_UPDATE_MAX]; int cache_update_prop_size; + TrackNodeCache::BezierAnim *cache_update_bezier[NODE_CACHE_UPDATE_MAX]; + int cache_update_bezier_size; + Set<TrackNodeCache *> playing_caches; + Map<Ref<Animation>, int> used_anims; uint64_t accum_pass; @@ -202,6 +231,8 @@ private: List<Blend> blend; PlaybackData current; StringName assigned; + bool seeked; + bool started; } playback; List<StringName> queued; @@ -216,15 +247,16 @@ private: NodePath root; - void _animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete = true); + void _animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_is_current = true, bool p_seeked = false, bool p_started = false); void _ensure_node_caches(AnimationData *p_anim); - void _animation_process_data(PlaybackData &cd, float p_delta, float p_blend); - void _animation_process2(float p_delta); + void _animation_process_data(PlaybackData &cd, float p_delta, float p_blend, bool p_seeked, bool p_started); + void _animation_process2(float p_delta, bool p_started); void _animation_update_transforms(); void _animation_process(float p_delta); void _node_removed(Node *p_node); + void _stop_playing_caches(); // bind helpers PoolVector<String> _get_animation_list() const { diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp index 4eefcc9ced..9f7503577b 100644 --- a/scene/animation/tween.cpp +++ b/scene/animation/tween.cpp @@ -201,6 +201,7 @@ void Tween::_bind_methods() { ClassDB::bind_method(D_METHOD("reset_all"), &Tween::reset_all); ClassDB::bind_method(D_METHOD("stop", "object", "key"), &Tween::stop, DEFVAL("")); ClassDB::bind_method(D_METHOD("stop_all"), &Tween::stop_all); + ClassDB::bind_method(D_METHOD("is_stopped"), &Tween::is_stopped); ClassDB::bind_method(D_METHOD("resume", "object", "key"), &Tween::resume, DEFVAL("")); ClassDB::bind_method(D_METHOD("resume_all"), &Tween::resume_all); ClassDB::bind_method(D_METHOD("remove", "object", "key"), &Tween::remove, DEFVAL("")); @@ -743,6 +744,10 @@ bool Tween::stop(Object *p_object, StringName p_key) { return true; } +bool Tween::is_stopped() const { + return tell() >= get_runtime(); +} + bool Tween::stop_all() { set_active(false); diff --git a/scene/animation/tween.h b/scene/animation/tween.h index 757d80e90a..36094bf294 100644 --- a/scene/animation/tween.h +++ b/scene/animation/tween.h @@ -162,6 +162,7 @@ public: bool reset_all(); bool stop(Object *p_object, StringName p_key); bool stop_all(); + bool is_stopped() const; bool resume(Object *p_object, StringName p_key); bool resume_all(); bool remove(Object *p_object, StringName p_key); diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp index 4bd92d888d..25cb74a494 100644 --- a/scene/gui/file_dialog.cpp +++ b/scene/gui/file_dialog.cpp @@ -777,6 +777,7 @@ void FileDialog::_bind_methods() { ClassDB::bind_method(D_METHOD("set_mode", "mode"), &FileDialog::set_mode); ClassDB::bind_method(D_METHOD("get_mode"), &FileDialog::get_mode); ClassDB::bind_method(D_METHOD("get_vbox"), &FileDialog::get_vbox); + ClassDB::bind_method(D_METHOD("get_line_edit"), &FileDialog::get_line_edit); ClassDB::bind_method(D_METHOD("set_access", "access"), &FileDialog::set_access); ClassDB::bind_method(D_METHOD("get_access"), &FileDialog::get_access); ClassDB::bind_method(D_METHOD("set_show_hidden_files", "show"), &FileDialog::set_show_hidden_files); diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp index 93865cebde..18e609c798 100644 --- a/scene/gui/popup_menu.cpp +++ b/scene/gui/popup_menu.cpp @@ -440,6 +440,8 @@ void PopupMenu::_notification(int p_what) { float h; Size2 icon_size; + Color icon_color(1, 1, 1, items[i].disabled ? 0.5 : 1); + item_ofs.x += items[i].h_ofs; if (!items[i].icon.is_null()) { @@ -463,18 +465,18 @@ void PopupMenu::_notification(int p_what) { if (items[i].checkable_type) { Texture *icon = (items[i].checked ? check[items[i].checkable_type - 1] : uncheck[items[i].checkable_type - 1]).ptr(); - icon->draw(ci, item_ofs + Point2(0, Math::floor((h - icon->get_height()) / 2.0))); + icon->draw(ci, item_ofs + Point2(0, Math::floor((h - icon->get_height()) / 2.0)), icon_color); item_ofs.x += icon->get_width() + hseparation; } if (!items[i].icon.is_null()) { - items[i].icon->draw(ci, item_ofs + Point2(0, Math::floor((h - icon_size.height) / 2.0))); + items[i].icon->draw(ci, item_ofs + Point2(0, Math::floor((h - icon_size.height) / 2.0)), icon_color); item_ofs.x += items[i].icon->get_width(); item_ofs.x += hseparation; } if (items[i].submenu != "") { - submenu->draw(ci, Point2(size.width - style->get_margin(MARGIN_RIGHT) - submenu->get_width(), item_ofs.y + Math::floor(h - submenu->get_height()) / 2)); + submenu->draw(ci, Point2(size.width - style->get_margin(MARGIN_RIGHT) - submenu->get_width(), item_ofs.y + Math::floor(h - submenu->get_height()) / 2), icon_color); } item_ofs.y += font->get_ascent(); @@ -913,6 +915,13 @@ void PopupMenu::set_item_multistate(int p_idx, int p_state) { update(); } +void PopupMenu::set_item_shortcut_disabled(int p_idx, bool p_disabled) { + + ERR_FAIL_INDEX(p_idx, items.size()); + items[p_idx].shortcut_is_disabled = p_disabled; + update(); +} + void PopupMenu::toggle_item_multistate(int p_idx) { ERR_FAIL_INDEX(p_idx, items.size()); @@ -937,6 +946,12 @@ bool PopupMenu::is_item_radio_checkable(int p_idx) const { return items[p_idx].checkable_type == Item::CHECKABLE_TYPE_RADIO_BUTTON; } +bool PopupMenu::is_item_shortcut_disabled(int p_idx) const { + + ERR_FAIL_INDEX_V(p_idx, items.size(), false); + return items[p_idx].shortcut_is_disabled; +} + int PopupMenu::get_item_count() const { return items.size(); @@ -963,7 +978,7 @@ bool PopupMenu::activate_item_by_event(const Ref<InputEvent> &p_event, bool p_fo int il = items.size(); for (int i = 0; i < il; i++) { - if (is_item_disabled(i)) + if (is_item_disabled(i) || items[i].shortcut_is_disabled) continue; if (items[i].shortcut.is_valid() && items[i].shortcut->is_shortcut(p_event) && (items[i].shortcut_is_global || !p_for_global_only)) { @@ -1248,6 +1263,7 @@ void PopupMenu::_bind_methods() { ClassDB::bind_method(D_METHOD("set_item_tooltip", "idx", "tooltip"), &PopupMenu::set_item_tooltip); ClassDB::bind_method(D_METHOD("set_item_shortcut", "idx", "shortcut", "global"), &PopupMenu::set_item_shortcut, DEFVAL(false)); ClassDB::bind_method(D_METHOD("set_item_multistate", "idx", "state"), &PopupMenu::set_item_multistate); + ClassDB::bind_method(D_METHOD("set_item_shortcut_disabled", "idx", "disabled"), &PopupMenu::set_item_shortcut_disabled); ClassDB::bind_method(D_METHOD("toggle_item_checked", "idx"), &PopupMenu::toggle_item_checked); ClassDB::bind_method(D_METHOD("toggle_item_multistate", "idx"), &PopupMenu::toggle_item_multistate); @@ -1264,6 +1280,7 @@ void PopupMenu::_bind_methods() { ClassDB::bind_method(D_METHOD("is_item_separator", "idx"), &PopupMenu::is_item_separator); ClassDB::bind_method(D_METHOD("is_item_checkable", "idx"), &PopupMenu::is_item_checkable); ClassDB::bind_method(D_METHOD("is_item_radio_checkable", "idx"), &PopupMenu::is_item_radio_checkable); + ClassDB::bind_method(D_METHOD("is_item_shortcut_disabled", "idx"), &PopupMenu::is_item_shortcut_disabled); ClassDB::bind_method(D_METHOD("get_item_tooltip", "idx"), &PopupMenu::get_item_tooltip); ClassDB::bind_method(D_METHOD("get_item_shortcut", "idx"), &PopupMenu::get_item_shortcut); diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h index fde91bd845..d3ee9be1c0 100644 --- a/scene/gui/popup_menu.h +++ b/scene/gui/popup_menu.h @@ -64,6 +64,7 @@ class PopupMenu : public Popup { int h_ofs; Ref<ShortCut> shortcut; bool shortcut_is_global; + bool shortcut_is_disabled; Item() { checked = false; @@ -76,6 +77,7 @@ class PopupMenu : public Popup { _ofs_cache = 0; h_ofs = 0; shortcut_is_global = false; + shortcut_is_disabled = false; } }; @@ -149,6 +151,7 @@ public: void set_item_h_offset(int p_idx, int p_offset); void set_item_multistate(int p_idx, int p_state); void toggle_item_multistate(int p_idx); + void set_item_shortcut_disabled(int p_idx, bool p_disabled); void toggle_item_checked(int p_idx); @@ -165,6 +168,7 @@ public: bool is_item_separator(int p_idx) const; bool is_item_checkable(int p_idx) const; bool is_item_radio_checkable(int p_idx) const; + bool is_item_shortcut_disabled(int p_idx) const; String get_item_tooltip(int p_idx) const; Ref<ShortCut> get_item_shortcut(int p_idx) const; int get_item_state(int p_idx) const; diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp index 2dd5c64378..495d618930 100644 --- a/scene/gui/scroll_container.cpp +++ b/scene/gui/scroll_container.cpp @@ -241,10 +241,10 @@ void ScrollContainer::_notification(int p_what) { size -= sb->get_minimum_size(); ofs += sb->get_offset(); - if (h_scroll->is_visible_in_tree()) + if (h_scroll->is_visible_in_tree() && h_scroll->get_parent() == this) //scrolls may have been moved out for reasons size.y -= h_scroll->get_minimum_size().y; - if (v_scroll->is_visible_in_tree()) + if (v_scroll->is_visible_in_tree() && v_scroll->get_parent() == this) //scrolls may have been moved out for reasons size.x -= h_scroll->get_minimum_size().x; for (int i = 0; i < get_child_count(); i++) { @@ -482,6 +482,16 @@ String ScrollContainer::get_configuration_warning() const { return ""; } +HScrollBar *ScrollContainer::get_h_scrollbar() { + + return h_scroll; +} + +VScrollBar *ScrollContainer::get_v_scrollbar() { + + return v_scroll; +} + void ScrollContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("_scroll_moved"), &ScrollContainer::_scroll_moved); @@ -498,6 +508,9 @@ void ScrollContainer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_deadzone", "deadzone"), &ScrollContainer::set_deadzone); ClassDB::bind_method(D_METHOD("get_deadzone"), &ScrollContainer::get_deadzone); + ClassDB::bind_method(D_METHOD("get_h_scrollbar"), &ScrollContainer::get_h_scrollbar); + ClassDB::bind_method(D_METHOD("get_v_scrollbar"), &ScrollContainer::get_v_scrollbar); + ADD_SIGNAL(MethodInfo("scroll_started")); ADD_SIGNAL(MethodInfo("scroll_ended")); diff --git a/scene/gui/scroll_container.h b/scene/gui/scroll_container.h index 3fe1ed447a..abef80294a 100644 --- a/scene/gui/scroll_container.h +++ b/scene/gui/scroll_container.h @@ -92,6 +92,9 @@ public: int get_deadzone() const; void set_deadzone(int p_deadzone); + HScrollBar *get_h_scrollbar(); + VScrollBar *get_v_scrollbar(); + virtual bool clips_input() const; virtual String get_configuration_warning() const; diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index ca9be9823a..1236aea2dd 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -1308,13 +1308,37 @@ void Viewport::_gui_cancel_tooltip() { } } +String Viewport::_gui_get_tooltip(Control *p_control, const Vector2 &p_pos) { + + Vector2 pos = p_pos; + String tooltip; + + while (p_control) { + + tooltip = p_control->get_tooltip(pos); + + if (tooltip != String()) + break; + pos = p_control->get_transform().xform(pos); + + if (p_control->data.mouse_filter == Control::MOUSE_FILTER_STOP) + break; + if (p_control->is_set_as_toplevel()) + break; + + p_control = p_control->get_parent_control(); + } + + return tooltip; +} + void Viewport::_gui_show_tooltip() { if (!gui.tooltip) { return; } - String tooltip = gui.tooltip->get_tooltip(gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos)); + String tooltip = _gui_get_tooltip(gui.tooltip, gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos)); if (tooltip.length() == 0) return; // bye @@ -1388,12 +1412,14 @@ void Viewport::_gui_call_input(Control *p_control, const Ref<InputEvent> &p_inpu Control *control = Object::cast_to<Control>(ci); if (control) { - control->call_multilevel(SceneStringNames::get_singleton()->_gui_input, ev); + + control->emit_signal(SceneStringNames::get_singleton()->gui_input, ev); //signal should be first, so it's possible to override an event (and then accept it) if (gui.key_event_accepted) break; if (!control->is_inside_tree()) break; - control->emit_signal(SceneStringNames::get_singleton()->gui_input, ev); + control->call_multilevel(SceneStringNames::get_singleton()->_gui_input, ev); + if (!control->is_inside_tree() || control->is_set_as_toplevel()) break; if (gui.key_event_accepted) @@ -1864,7 +1890,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) { if (gui.tooltip_popup) { if (can_tooltip) { - String tooltip = over->get_tooltip(gui.tooltip->get_global_transform().xform_inv(mpos)); + String tooltip = _gui_get_tooltip(over, gui.tooltip->get_global_transform().xform_inv(mpos)); if (tooltip.length() == 0) _gui_cancel_tooltip(); @@ -1886,7 +1912,23 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) { mm->set_position(pos); - Control::CursorShape cursor_shape = over->get_cursor_shape(pos); + Control::CursorShape cursor_shape = Control::CURSOR_ARROW; + { + Control *c = over; + Vector2 cpos = pos; + while (c) { + cursor_shape = c->get_cursor_shape(cpos); + cpos = c->get_transform().xform(cpos); + if (cursor_shape != Control::CURSOR_ARROW) + break; + if (c->data.mouse_filter == Control::MOUSE_FILTER_STOP) + break; + if (c->is_set_as_toplevel()) + break; + c = c->get_parent_control(); + } + } + OS::get_singleton()->set_cursor_shape((OS::CursorShape)cursor_shape); if (over->can_process()) { diff --git a/scene/main/viewport.h b/scene/main/viewport.h index c1ef58de69..3000398540 100644 --- a/scene/main/viewport.h +++ b/scene/main/viewport.h @@ -312,6 +312,7 @@ private: void _gui_remove_root_control(List<Control *>::Element *RI); void _gui_remove_subwindow_control(List<Control *>::Element *SI); + String _gui_get_tooltip(Control *p_control, const Vector2 &p_pos); void _gui_cancel_tooltip(); void _gui_show_tooltip(); diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp index 7a1fffaa26..9c95cba357 100644 --- a/scene/resources/animation.cpp +++ b/scene/resources/animation.cpp @@ -54,6 +54,15 @@ bool Animation::_set(const StringName &p_name, const Variant &p_value) { } else if (type == "method") { add_track(TYPE_METHOD); + } else if (type == "bezier") { + + add_track(TYPE_BEZIER); + } else if (type == "audio") { + + add_track(TYPE_AUDIO); + } else if (type == "animation") { + + add_track(TYPE_ANIMATION); } else { return false; @@ -163,7 +172,7 @@ bool Animation::_set(const StringName &p_name, const Variant &p_value) { return true; - } else { + } else if (track_get_type(track) == TYPE_METHOD) { while (track_get_key_count(track)) track_remove_key(track, 0); //well shouldn't be set anyway @@ -201,6 +210,114 @@ bool Animation::_set(const StringName &p_name, const Variant &p_value) { } } } + } else if (track_get_type(track) == TYPE_BEZIER) { + + BezierTrack *bt = static_cast<BezierTrack *>(tracks[track]); + Dictionary d = p_value; + ERR_FAIL_COND_V(!d.has("times"), false); + ERR_FAIL_COND_V(!d.has("points"), false); + + PoolVector<float> times = d["times"]; + PoolRealArray values = d["points"]; + + ERR_FAIL_COND_V(times.size() * 5 != values.size(), false); + + if (times.size()) { + + int valcount = times.size(); + + PoolVector<float>::Read rt = times.read(); + PoolVector<float>::Read rv = values.read(); + + bt->values.resize(valcount); + + for (int i = 0; i < valcount; i++) { + + bt->values[i].time = rt[i]; + bt->values[i].transition = 0; //unused in bezier + bt->values[i].value.value = rv[i * 5 + 0]; + bt->values[i].value.in_handle.x = rv[i * 5 + 1]; + bt->values[i].value.in_handle.y = rv[i * 5 + 2]; + bt->values[i].value.out_handle.x = rv[i * 5 + 3]; + bt->values[i].value.out_handle.y = rv[i * 5 + 4]; + } + } + + return true; + } else if (track_get_type(track) == TYPE_AUDIO) { + + AudioTrack *ad = static_cast<AudioTrack *>(tracks[track]); + Dictionary d = p_value; + ERR_FAIL_COND_V(!d.has("times"), false); + ERR_FAIL_COND_V(!d.has("clips"), false); + + PoolVector<float> times = d["times"]; + Array clips = d["clips"]; + + ERR_FAIL_COND_V(clips.size() != times.size(), false); + + if (times.size()) { + + int valcount = times.size(); + + PoolVector<float>::Read rt = times.read(); + + ad->values.clear(); + + for (int i = 0; i < valcount; i++) { + + Dictionary d = clips[i]; + if (!d.has("start_offset")) + continue; + if (!d.has("end_offset")) + continue; + if (!d.has("stream")) + continue; + + TKey<AudioKey> ak; + ak.time = rt[i]; + ak.value.start_offset = d["start_offset"]; + ak.value.end_offset = d["end_offset"]; + ak.value.stream = d["stream"]; + + ad->values.push_back(ak); + } + } + + return true; + } else if (track_get_type(track) == TYPE_ANIMATION) { + + AnimationTrack *an = static_cast<AnimationTrack *>(tracks[track]); + Dictionary d = p_value; + ERR_FAIL_COND_V(!d.has("times"), false); + ERR_FAIL_COND_V(!d.has("clips"), false); + + PoolVector<float> times = d["times"]; + PoolVector<String> clips = d["clips"]; + + ERR_FAIL_COND_V(clips.size() != times.size(), false); + + if (times.size()) { + + int valcount = times.size(); + + PoolVector<float>::Read rt = times.read(); + PoolVector<String>::Read rc = clips.read(); + + an->values.resize(valcount); + + for (int i = 0; i < valcount; i++) { + + TKey<StringName> ak; + ak.time = rt[i]; + ak.value = rc[i]; + an->values[i] = ak; + } + } + + return true; + } else { + return false; } } else return false; @@ -232,6 +349,9 @@ bool Animation::_get(const StringName &p_name, Variant &r_ret) const { case TYPE_TRANSFORM: r_ret = "transform"; break; case TYPE_VALUE: r_ret = "value"; break; case TYPE_METHOD: r_ret = "method"; break; + case TYPE_BEZIER: r_ret = "bezier"; break; + case TYPE_AUDIO: r_ret = "audio"; break; + case TYPE_ANIMATION: r_ret = "animation"; break; } return true; @@ -329,7 +449,7 @@ bool Animation::_get(const StringName &p_name, Variant &r_ret) const { return true; - } else { + } else if (track_get_type(track) == TYPE_METHOD) { Dictionary d; @@ -368,6 +488,119 @@ bool Animation::_get(const StringName &p_name, Variant &r_ret) const { r_ret = d; return true; + } else if (track_get_type(track) == TYPE_BEZIER) { + + const BezierTrack *bt = static_cast<const BezierTrack *>(tracks[track]); + + Dictionary d; + + PoolVector<float> key_times; + PoolVector<float> key_points; + + int kk = bt->values.size(); + + key_times.resize(kk); + key_points.resize(kk * 5); + + PoolVector<float>::Write wti = key_times.write(); + PoolVector<float>::Write wpo = key_points.write(); + + int idx = 0; + + const TKey<BezierKey> *vls = bt->values.ptr(); + + for (int i = 0; i < kk; i++) { + + wti[idx] = vls[i].time; + wpo[idx * 5 + 0] = vls[i].value.value; + wpo[idx * 5 + 1] = vls[i].value.in_handle.x; + wpo[idx * 5 + 2] = vls[i].value.in_handle.y; + wpo[idx * 5 + 3] = vls[i].value.out_handle.x; + wpo[idx * 5 + 4] = vls[i].value.out_handle.y; + idx++; + } + + wti = PoolVector<float>::Write(); + wpo = PoolVector<float>::Write(); + + d["times"] = key_times; + d["points"] = key_points; + + r_ret = d; + + return true; + } else if (track_get_type(track) == TYPE_AUDIO) { + + const AudioTrack *ad = static_cast<const AudioTrack *>(tracks[track]); + + Dictionary d; + + PoolVector<float> key_times; + Array clips; + + int kk = ad->values.size(); + + key_times.resize(kk); + + PoolVector<float>::Write wti = key_times.write(); + + int idx = 0; + + const TKey<AudioKey> *vls = ad->values.ptr(); + + for (int i = 0; i < kk; i++) { + + wti[idx] = vls[i].time; + Dictionary clip; + clip["start_offset"] = vls[i].value.start_offset; + clip["end_offset"] = vls[i].value.end_offset; + clip["stream"] = vls[i].value.stream; + clips.push_back(clip); + idx++; + } + + wti = PoolVector<float>::Write(); + + d["times"] = key_times; + d["clips"] = clips; + + r_ret = d; + + return true; + } else if (track_get_type(track) == TYPE_ANIMATION) { + + const AnimationTrack *an = static_cast<const AnimationTrack *>(tracks[track]); + + Dictionary d; + + PoolVector<float> key_times; + PoolVector<String> clips; + + int kk = an->values.size(); + + key_times.resize(kk); + clips.resize(kk); + + PoolVector<float>::Write wti = key_times.write(); + PoolVector<String>::Write wcl = clips.write(); + + const TKey<StringName> *vls = an->values.ptr(); + + for (int i = 0; i < kk; i++) { + + wti[i] = vls[i].time; + wcl[i] = vls[i].value; + } + + wti = PoolVector<float>::Write(); + wcl = PoolVector<String>::Write(); + + d["times"] = key_times; + d["clips"] = clips; + + r_ret = d; + + return true; } } else return false; @@ -412,6 +645,21 @@ int Animation::add_track(TrackType p_type, int p_at_pos) { tracks.insert(p_at_pos, memnew(MethodTrack)); } break; + case TYPE_BEZIER: { + + tracks.insert(p_at_pos, memnew(BezierTrack)); + + } break; + case TYPE_AUDIO: { + + tracks.insert(p_at_pos, memnew(AudioTrack)); + + } break; + case TYPE_ANIMATION: { + + tracks.insert(p_at_pos, memnew(AnimationTrack)); + + } break; default: { ERR_PRINT("Unknown track type"); @@ -446,6 +694,24 @@ void Animation::remove_track(int p_track) { _clear(mt->methods); } break; + case TYPE_BEZIER: { + + BezierTrack *bz = static_cast<BezierTrack *>(t); + _clear(bz->values); + + } break; + case TYPE_AUDIO: { + + AudioTrack *ad = static_cast<AudioTrack *>(t); + _clear(ad->values); + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *an = static_cast<AnimationTrack *>(t); + _clear(an->values); + + } break; } memdelete(t); @@ -642,6 +908,27 @@ void Animation::track_remove_key(int p_track, int p_idx) { mt->methods.remove(p_idx); } break; + case TYPE_BEZIER: { + + BezierTrack *bz = static_cast<BezierTrack *>(t); + ERR_FAIL_INDEX(p_idx, bz->values.size()); + bz->values.remove(p_idx); + + } break; + case TYPE_AUDIO: { + + AudioTrack *ad = static_cast<AudioTrack *>(t); + ERR_FAIL_INDEX(p_idx, ad->values.size()); + ad->values.remove(p_idx); + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *an = static_cast<AnimationTrack *>(t); + ERR_FAIL_INDEX(p_idx, an->values.size()); + an->values.remove(p_idx); + + } break; } emit_changed(); @@ -686,6 +973,39 @@ int Animation::track_find_key(int p_track, float p_time, bool p_exact) const { return k; } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + int k = _find(bt->values, p_time); + if (k < 0 || k >= bt->values.size()) + return -1; + if (bt->values[k].time != p_time && p_exact) + return -1; + return k; + + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + int k = _find(at->values, p_time); + if (k < 0 || k >= at->values.size()) + return -1; + if (at->values[k].time != p_time && p_exact) + return -1; + return k; + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + int k = _find(at->values, p_time); + if (k < 0 || k >= at->values.size()) + return -1; + if (at->values[k].time != p_time && p_exact) + return -1; + return k; + + } break; } return -1; @@ -748,6 +1068,51 @@ void Animation::track_insert_key(int p_track, float p_time, const Variant &p_key _insert(p_time, mt->methods, k); } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + Array arr = p_key; + ERR_FAIL_COND(arr.size() != 5); + + TKey<BezierKey> k; + k.time = p_time; + k.value.value = arr[0]; + k.value.in_handle.x = arr[1]; + k.value.in_handle.y = arr[2]; + k.value.out_handle.x = arr[3]; + k.value.out_handle.y = arr[4]; + _insert(p_time, bt->values, k); + + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + + Dictionary k = p_key; + ERR_FAIL_COND(!k.has("start_offset")); + ERR_FAIL_COND(!k.has("end_offset")); + ERR_FAIL_COND(!k.has("stream")); + + TKey<AudioKey> ak; + ak.time = p_time; + ak.value.start_offset = k["start_offset"]; + ak.value.end_offset = k["end_offset"]; + ak.value.stream = k["stream"]; + _insert(p_time, at->values, ak); + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + + TKey<StringName> ak; + ak.time = p_time; + ak.value = p_key; + + _insert(p_time, at->values, ak); + + } break; } emit_changed(); @@ -776,6 +1141,21 @@ int Animation::track_get_key_count(int p_track) const { MethodTrack *mt = static_cast<MethodTrack *>(t); return mt->methods.size(); } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + return bt->values.size(); + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + return at->values.size(); + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + return at->values.size(); + } break; } ERR_FAIL_V(-1); @@ -817,6 +1197,41 @@ Variant Animation::track_get_key_value(int p_track, int p_key_idx) const { return d; } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, bt->values.size(), Variant()); + + Array arr; + arr.resize(5); + arr[0] = bt->values[p_key_idx].value.value; + arr[1] = bt->values[p_key_idx].value.in_handle.x; + arr[2] = bt->values[p_key_idx].value.in_handle.y; + arr[3] = bt->values[p_key_idx].value.out_handle.x; + arr[4] = bt->values[p_key_idx].value.out_handle.y; + return arr; + + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, at->values.size(), Variant()); + + Dictionary k; + k["start_offset"] = at->values[p_key_idx].value.start_offset; + k["end_offset"] = at->values[p_key_idx].value.end_offset; + k["stream"] = at->values[p_key_idx].value.stream; + return k; + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, at->values.size(), Variant()); + + return at->values[p_key_idx].value; + + } break; } ERR_FAIL_V(Variant()); @@ -849,6 +1264,27 @@ float Animation::track_get_key_time(int p_track, int p_key_idx) const { return mt->methods[p_key_idx].time; } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, bt->values.size(), -1); + return bt->values[p_key_idx].time; + + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, at->values.size(), -1); + return at->values[p_key_idx].time; + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + ERR_FAIL_INDEX_V(p_key_idx, at->values.size(), -1); + return at->values[p_key_idx].time; + + } break; } ERR_FAIL_V(-1); @@ -881,6 +1317,18 @@ float Animation::track_get_key_transition(int p_track, int p_key_idx) const { return mt->methods[p_key_idx].transition; } break; + case TYPE_BEZIER: { + + return 1; //bezier does not really use transitions + } break; + case TYPE_AUDIO: { + + return 1; //audio does not really use transitions + } break; + case TYPE_ANIMATION: { + + return 1; //animation does not really use transitions + } break; } ERR_FAIL_V(0); @@ -923,6 +1371,42 @@ void Animation::track_set_key_value(int p_track, int p_key_idx, const Variant &p if (d.has("args")) mt->methods[p_key_idx].params = d["args"]; } break; + case TYPE_BEZIER: { + + BezierTrack *bt = static_cast<BezierTrack *>(t); + ERR_FAIL_INDEX(p_key_idx, bt->values.size()); + + Array arr = p_value; + ERR_FAIL_COND(arr.size() != 5); + + bt->values[p_key_idx].value.value = arr[0]; + bt->values[p_key_idx].value.in_handle.x = arr[1]; + bt->values[p_key_idx].value.in_handle.y = arr[2]; + bt->values[p_key_idx].value.out_handle.x = arr[3]; + bt->values[p_key_idx].value.out_handle.y = arr[4]; + + } break; + case TYPE_AUDIO: { + + AudioTrack *at = static_cast<AudioTrack *>(t); + + Dictionary k = p_value; + ERR_FAIL_COND(!k.has("start_offset")); + ERR_FAIL_COND(!k.has("end_offset")); + ERR_FAIL_COND(!k.has("stream")); + + at->values[p_key_idx].value.start_offset = k["start_offset"]; + at->values[p_key_idx].value.end_offset = k["end_offset"]; + at->values[p_key_idx].value.stream = k["stream"]; + + } break; + case TYPE_ANIMATION: { + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + + at->values[p_key_idx].value = p_value; + + } break; } } @@ -953,6 +1437,11 @@ void Animation::track_set_key_transition(int p_track, int p_key_idx, float p_tra mt->methods[p_key_idx].transition = p_transition; } break; + case TYPE_BEZIER: + case TYPE_AUDIO: + case TYPE_ANIMATION: { + // they dont use transition + } break; } } @@ -1410,7 +1899,7 @@ void Animation::value_track_set_update_mode(int p_track, UpdateMode p_mode) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; ERR_FAIL_COND(t->type != TYPE_VALUE); - ERR_FAIL_INDEX(p_mode, 3); + ERR_FAIL_INDEX(p_mode, 4); ValueTrack *vt = static_cast<ValueTrack *>(t); vt->update_mode = p_mode; @@ -1426,6 +1915,161 @@ Animation::UpdateMode Animation::value_track_get_update_mode(int p_track) const return vt->update_mode; } +template <class T> +void Animation::_track_get_key_indices_in_range(const Vector<T> &p_array, float from_time, float to_time, List<int> *p_indices) const { + + if (from_time != length && to_time == length) + to_time = length * 1.01; //include a little more if at the end + + int to = _find(p_array, to_time); + + // can't really send the events == time, will be sent in the next frame. + // if event>=len then it will probably never be requested by the anim player. + + if (to >= 0 && p_array[to].time >= to_time) + to--; + + if (to < 0) + return; // not bother + + int from = _find(p_array, from_time); + + // position in the right first event.+ + if (from < 0 || p_array[from].time < from_time) + from++; + + int max = p_array.size(); + + for (int i = from; i <= to; i++) { + + ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen + p_indices->push_back(i); + } +} + +void Animation::track_get_key_indices_in_range(int p_track, float p_time, float p_delta, List<int> *p_indices) const { + + ERR_FAIL_INDEX(p_track, tracks.size()); + const Track *t = tracks[p_track]; + + float from_time = p_time - p_delta; + float to_time = p_time; + + if (from_time > to_time) + SWAP(from_time, to_time); + + if (loop) { + + if (from_time > length || from_time < 0) + from_time = Math::fposmod(from_time, length); + + if (to_time > length || to_time < 0) + to_time = Math::fposmod(to_time, length); + + if (from_time > to_time) { + // handle loop by splitting + + switch (t->type) { + + case TYPE_TRANSFORM: { + + const TransformTrack *tt = static_cast<const TransformTrack *>(t); + _track_get_key_indices_in_range(tt->transforms, from_time, length, p_indices); + _track_get_key_indices_in_range(tt->transforms, 0, to_time, p_indices); + + } break; + case TYPE_VALUE: { + + const ValueTrack *vt = static_cast<const ValueTrack *>(t); + _track_get_key_indices_in_range(vt->values, from_time, length, p_indices); + _track_get_key_indices_in_range(vt->values, 0, to_time, p_indices); + + } break; + case TYPE_METHOD: { + + const MethodTrack *mt = static_cast<const MethodTrack *>(t); + _track_get_key_indices_in_range(mt->methods, from_time, length, p_indices); + _track_get_key_indices_in_range(mt->methods, 0, to_time, p_indices); + + } break; + case TYPE_BEZIER: { + + const BezierTrack *bz = static_cast<const BezierTrack *>(t); + _track_get_key_indices_in_range(bz->values, from_time, length, p_indices); + _track_get_key_indices_in_range(bz->values, 0, to_time, p_indices); + + } break; + case TYPE_AUDIO: { + + const AudioTrack *ad = static_cast<const AudioTrack *>(t); + _track_get_key_indices_in_range(ad->values, from_time, length, p_indices); + _track_get_key_indices_in_range(ad->values, 0, to_time, p_indices); + + } break; + case TYPE_ANIMATION: { + + const AnimationTrack *an = static_cast<const AnimationTrack *>(t); + _track_get_key_indices_in_range(an->values, from_time, length, p_indices); + _track_get_key_indices_in_range(an->values, 0, to_time, p_indices); + + } break; + } + return; + } + } else { + + if (from_time < 0) + from_time = 0; + if (from_time > length) + from_time = length; + + if (to_time < 0) + to_time = 0; + if (to_time > length) + to_time = length; + } + + switch (t->type) { + + case TYPE_TRANSFORM: { + + const TransformTrack *tt = static_cast<const TransformTrack *>(t); + _track_get_key_indices_in_range(tt->transforms, from_time, to_time, p_indices); + + } break; + case TYPE_VALUE: { + + const ValueTrack *vt = static_cast<const ValueTrack *>(t); + _track_get_key_indices_in_range(vt->values, from_time, to_time, p_indices); + + } break; + case TYPE_METHOD: { + + const MethodTrack *mt = static_cast<const MethodTrack *>(t); + _track_get_key_indices_in_range(mt->methods, from_time, to_time, p_indices); + + } break; + case TYPE_BEZIER: { + + const BezierTrack *bz = static_cast<const BezierTrack *>(t); + _track_get_key_indices_in_range(bz->values, from_time, to_time, p_indices); + + } break; + case TYPE_AUDIO: { + + const AudioTrack *ad = static_cast<const AudioTrack *>(t); + _track_get_key_indices_in_range(ad->values, from_time, to_time, p_indices); + + } break; + case TYPE_ANIMATION: { + + const AnimationTrack *an = static_cast<const AnimationTrack *>(t); + _track_get_key_indices_in_range(an->values, from_time, to_time, p_indices); + + } break; + } +} + void Animation::_method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const { if (from_time != length && to_time == length) @@ -1527,6 +2171,357 @@ StringName Animation::method_track_get_name(int p_track, int p_key_idx) const { return pm->methods[p_key_idx].method; } +int Animation::bezier_track_insert_key(int p_track, float p_time, float p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle) { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_BEZIER, -1); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + TKey<BezierKey> k; + k.time = p_time; + k.value.value = p_value; + k.value.in_handle = p_in_handle; + if (k.value.in_handle.x > 0) { + k.value.in_handle.x = 0; + } + k.value.out_handle = p_out_handle; + if (k.value.out_handle.x < 0) { + k.value.out_handle.x = 0; + } + + int key = _insert(p_time, bt->values, k); + + emit_changed(); + + return key; +} + +void Animation::bezier_track_set_key_value(int p_track, int p_index, float p_value) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_BEZIER); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX(p_index, bt->values.size()); + + bt->values[p_index].value.value = p_value; + emit_changed(); +} + +void Animation::bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_BEZIER); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX(p_index, bt->values.size()); + + bt->values[p_index].value.in_handle = p_handle; + if (bt->values[p_index].value.in_handle.x > 0) { + bt->values[p_index].value.in_handle.x = 0; + } + emit_changed(); +} +void Animation::bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_BEZIER); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX(p_index, bt->values.size()); + + bt->values[p_index].value.out_handle = p_handle; + if (bt->values[p_index].value.out_handle.x < 0) { + bt->values[p_index].value.out_handle.x = 0; + } + emit_changed(); +} +float Animation::bezier_track_get_key_value(int p_track, int p_index) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_BEZIER, 0); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX_V(p_index, bt->values.size(), 0); + + return bt->values[p_index].value.value; +} +Vector2 Animation::bezier_track_get_key_in_handle(int p_track, int p_index) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector2()); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_BEZIER, Vector2()); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX_V(p_index, bt->values.size(), Vector2()); + + return bt->values[p_index].value.in_handle; +} +Vector2 Animation::bezier_track_get_key_out_handle(int p_track, int p_index) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector2()); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_BEZIER, Vector2()); + + BezierTrack *bt = static_cast<BezierTrack *>(t); + + ERR_FAIL_INDEX_V(p_index, bt->values.size(), Vector2()); + + return bt->values[p_index].value.out_handle; +} + +static _FORCE_INLINE_ Vector2 _bezier_interp(real_t t, const Vector2 &start, const Vector2 &control_1, const Vector2 &control_2, const Vector2 &end) { + /* Formula from Wikipedia article on Bezier curves. */ + real_t omt = (1.0 - t); + real_t omt2 = omt * omt; + real_t omt3 = omt2 * omt; + real_t t2 = t * t; + real_t t3 = t2 * t; + + return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3; +} + +float Animation::bezier_track_interpolate(int p_track, float p_time) const { + //this uses a different interpolation scheme + ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); + Track *track = tracks[p_track]; + ERR_FAIL_COND_V(track->type != TYPE_BEZIER, 0); + + BezierTrack *bt = static_cast<BezierTrack *>(track); + + int len = _find(bt->values, length) + 1; // try to find last key (there may be more past the end) + + if (len <= 0) { + // (-1 or -2 returned originally) (plus one above) + return 0; + } else if (len == 1) { // one key found (0+1), return it + return bt->values[0].value.value; + } + + int idx = _find(bt->values, p_time); + + ERR_FAIL_COND_V(idx == -2, 0); + + //there really is no looping interpolation on bezier + + if (idx < 0) { + return bt->values[0].value.value; + } + + if (idx >= bt->values.size() - 1) { + return bt->values[bt->values.size() - 1].value.value; + } + + float t = p_time - bt->values[idx].time; + + int iterations = 10; + + float low = 0; + float high = bt->values[idx + 1].time - bt->values[idx].time; + float middle = 0; + + Vector2 start(0, bt->values[idx].value.value); + Vector2 start_out = start + bt->values[idx].value.out_handle; + Vector2 end(high, bt->values[idx + 1].value.value); + Vector2 end_in = end + bt->values[idx + 1].value.in_handle; + + //narrow high and low as much as possible + for (int i = 0; i < iterations; i++) { + + middle = (low + high) / 2; + + Vector2 interp = _bezier_interp(middle, start, start_out, end_in, end); + + if (interp.x < t) { + low = middle; + } else { + high = middle; + } + } + + //interpolate the result: + Vector2 low_pos = _bezier_interp(low, start, start_out, end_in, end); + Vector2 high_pos = _bezier_interp(high, start, start_out, end_in, end); + + float c = (t - low_pos.x) / (high_pos.x - low_pos.x); + + return low_pos.linear_interpolate(high_pos, c).y; +} + +int Animation::audio_track_insert_key(int p_track, float p_time, const RES &p_stream, float p_start_offset, float p_end_offset) { + + print_line("really insert key? "); + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_AUDIO, -1); + + AudioTrack *at = static_cast<AudioTrack *>(t); + + TKey<AudioKey> k; + k.time = p_time; + k.value.stream = p_stream; + k.value.start_offset = p_start_offset; + if (k.value.start_offset < 0) + k.value.start_offset = 0; + k.value.end_offset = p_end_offset; + if (k.value.end_offset < 0) + k.value.end_offset = 0; + + int key = _insert(p_time, at->values, k); + + emit_changed(); + + return key; +} + +void Animation::audio_track_set_key_stream(int p_track, int p_key, const RES &p_stream) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_AUDIO); + + AudioTrack *at = static_cast<AudioTrack *>(t); + + ERR_FAIL_INDEX(p_key, at->values.size()); + + at->values[p_key].value.stream = p_stream; + + emit_changed(); +} + +void Animation::audio_track_set_key_start_offset(int p_track, int p_key, float p_offset) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_AUDIO); + + AudioTrack *at = static_cast<AudioTrack *>(t); + + ERR_FAIL_INDEX(p_key, at->values.size()); + + if (p_offset < 0) + p_offset = 0; + + at->values[p_key].value.start_offset = p_offset; + + emit_changed(); +} + +void Animation::audio_track_set_key_end_offset(int p_track, int p_key, float p_offset) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_AUDIO); + + AudioTrack *at = static_cast<AudioTrack *>(t); + + ERR_FAIL_INDEX(p_key, at->values.size()); + + if (p_offset < 0) + p_offset = 0; + + at->values[p_key].value.end_offset = p_offset; + + emit_changed(); +} + +RES Animation::audio_track_get_key_stream(int p_track, int p_key) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), RES()); + const Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_AUDIO, RES()); + + const AudioTrack *at = static_cast<const AudioTrack *>(t); + + ERR_FAIL_INDEX_V(p_key, at->values.size(), RES()); + + return at->values[p_key].value.stream; +} +float Animation::audio_track_get_key_start_offset(int p_track, int p_key) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); + const Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_AUDIO, 0); + + const AudioTrack *at = static_cast<const AudioTrack *>(t); + + ERR_FAIL_INDEX_V(p_key, at->values.size(), 0); + + return at->values[p_key].value.start_offset; +} +float Animation::audio_track_get_key_end_offset(int p_track, int p_key) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); + const Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_AUDIO, 0); + + const AudioTrack *at = static_cast<const AudioTrack *>(t); + + ERR_FAIL_INDEX_V(p_key, at->values.size(), 0); + + return at->values[p_key].value.end_offset; +} + +// + +int Animation::animation_track_insert_key(int p_track, float p_time, const StringName &p_animation) { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); + Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_ANIMATION, -1); + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + + TKey<StringName> k; + k.time = p_time; + k.value = p_animation; + + int key = _insert(p_time, at->values, k); + + emit_changed(); + + return key; +} + +void Animation::animation_track_set_key_animation(int p_track, int p_key, const StringName &p_animation) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + Track *t = tracks[p_track]; + ERR_FAIL_COND(t->type != TYPE_ANIMATION); + + AnimationTrack *at = static_cast<AnimationTrack *>(t); + + ERR_FAIL_INDEX(p_key, at->values.size()); + + at->values[p_key].value = p_animation; + + emit_changed(); +} + +StringName Animation::animation_track_get_key_animation(int p_track, int p_key) const { + + ERR_FAIL_INDEX_V(p_track, tracks.size(), StringName()); + const Track *t = tracks[p_track]; + ERR_FAIL_COND_V(t->type != TYPE_ANIMATION, StringName()); + + const AnimationTrack *at = static_cast<const AnimationTrack *>(t); + + ERR_FAIL_INDEX_V(p_key, at->values.size(), StringName()); + + return at->values[p_key].value; +} + void Animation::set_length(float p_length) { ERR_FAIL_COND(length < 0); @@ -1592,6 +2587,16 @@ void Animation::track_move_down(int p_track) { emit_changed(); } +void Animation::track_swap(int p_track, int p_with_track) { + + ERR_FAIL_INDEX(p_track, tracks.size()); + ERR_FAIL_INDEX(p_with_track, tracks.size()); + if (p_track == p_with_track) + return; + SWAP(tracks[p_track], tracks[p_with_track]); + emit_changed(); +} + void Animation::set_step(float p_step) { step = p_step; @@ -1631,6 +2636,7 @@ void Animation::_bind_methods() { ClassDB::bind_method(D_METHOD("track_move_up", "idx"), &Animation::track_move_up); ClassDB::bind_method(D_METHOD("track_move_down", "idx"), &Animation::track_move_down); + ClassDB::bind_method(D_METHOD("track_swap", "idx", "with_idx"), &Animation::track_swap); ClassDB::bind_method(D_METHOD("track_set_imported", "idx", "imported"), &Animation::track_set_imported); ClassDB::bind_method(D_METHOD("track_is_imported", "idx"), &Animation::track_is_imported); @@ -1667,6 +2673,30 @@ void Animation::_bind_methods() { ClassDB::bind_method(D_METHOD("method_track_get_name", "idx", "key_idx"), &Animation::method_track_get_name); ClassDB::bind_method(D_METHOD("method_track_get_params", "idx", "key_idx"), &Animation::method_track_get_params); + ClassDB::bind_method(D_METHOD("bezier_track_insert_key", "track", "time", "value", "in_handle", "out_handle"), &Animation::bezier_track_insert_key, DEFVAL(Vector2()), DEFVAL(Vector2())); + + ClassDB::bind_method(D_METHOD("bezier_track_set_key_value", "idx", "key_idx", "value"), &Animation::bezier_track_set_key_value); + ClassDB::bind_method(D_METHOD("bezier_track_set_key_in_handle", "idx", "key_idx", "in_handle"), &Animation::bezier_track_set_key_in_handle); + ClassDB::bind_method(D_METHOD("bezier_track_set_key_out_handle", "idx", "key_idx", "out_handle"), &Animation::bezier_track_set_key_out_handle); + + ClassDB::bind_method(D_METHOD("bezier_track_get_key_value", "idx", "key_idx"), &Animation::bezier_track_get_key_value); + ClassDB::bind_method(D_METHOD("bezier_track_get_key_in_handle", "idx", "key_idx"), &Animation::bezier_track_get_key_in_handle); + ClassDB::bind_method(D_METHOD("bezier_track_get_key_out_handle", "idx", "key_idx"), &Animation::bezier_track_get_key_out_handle); + + ClassDB::bind_method(D_METHOD("bezier_track_interpolate", "track", "time"), &Animation::bezier_track_interpolate); + + ClassDB::bind_method(D_METHOD("audio_track_insert_key", "track", "time", "stream", "start_offset", "end_offset"), &Animation::audio_track_insert_key, DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("audio_track_set_key_stream", "idx", "key_idx", "stream"), &Animation::audio_track_set_key_stream); + ClassDB::bind_method(D_METHOD("audio_track_set_key_start_offset", "idx", "key_idx", "offset"), &Animation::audio_track_set_key_start_offset); + ClassDB::bind_method(D_METHOD("audio_track_set_key_end_offset", "idx", "key_idx", "offset"), &Animation::audio_track_set_key_end_offset); + ClassDB::bind_method(D_METHOD("audio_track_get_key_stream", "idx", "key_idx"), &Animation::audio_track_get_key_stream); + ClassDB::bind_method(D_METHOD("audio_track_get_key_start_offset", "idx", "key_idx"), &Animation::audio_track_get_key_start_offset); + ClassDB::bind_method(D_METHOD("audio_track_get_key_end_offset", "idx", "key_idx"), &Animation::audio_track_get_key_end_offset); + + ClassDB::bind_method(D_METHOD("animation_track_insert_key", "track", "time", "animation"), &Animation::animation_track_insert_key); + ClassDB::bind_method(D_METHOD("animation_track_set_key_animation", "idx", "key_idx", "animation"), &Animation::animation_track_set_key_animation); + ClassDB::bind_method(D_METHOD("animation_track_get_key_animation", "idx", "key_idx"), &Animation::animation_track_get_key_animation); + ClassDB::bind_method(D_METHOD("set_length", "time_sec"), &Animation::set_length); ClassDB::bind_method(D_METHOD("get_length"), &Animation::get_length); @@ -1686,6 +2716,9 @@ void Animation::_bind_methods() { BIND_ENUM_CONSTANT(TYPE_VALUE); BIND_ENUM_CONSTANT(TYPE_TRANSFORM); BIND_ENUM_CONSTANT(TYPE_METHOD); + BIND_ENUM_CONSTANT(TYPE_BEZIER); + BIND_ENUM_CONSTANT(TYPE_AUDIO); + BIND_ENUM_CONSTANT(TYPE_ANIMATION); BIND_ENUM_CONSTANT(INTERPOLATION_NEAREST); BIND_ENUM_CONSTANT(INTERPOLATION_LINEAR); @@ -1694,6 +2727,7 @@ void Animation::_bind_methods() { BIND_ENUM_CONSTANT(UPDATE_CONTINUOUS); BIND_ENUM_CONSTANT(UPDATE_DISCRETE); BIND_ENUM_CONSTANT(UPDATE_TRIGGER); + BIND_ENUM_CONSTANT(UPDATE_CAPTURE); } void Animation::clear() { diff --git a/scene/resources/animation.h b/scene/resources/animation.h index 73691a69f2..a41e6ea5d7 100644 --- a/scene/resources/animation.h +++ b/scene/resources/animation.h @@ -45,6 +45,9 @@ public: TYPE_VALUE, ///< Set a value in a property, can be interpolated. TYPE_TRANSFORM, ///< Transform a node or a bone. TYPE_METHOD, ///< Call any method on a specific node. + TYPE_BEZIER, ///< Bezier curve + TYPE_AUDIO, + TYPE_ANIMATION, }; enum InterpolationType { @@ -57,6 +60,7 @@ public: UPDATE_CONTINUOUS, UPDATE_DISCRETE, UPDATE_TRIGGER, + UPDATE_CAPTURE, }; @@ -137,6 +141,55 @@ private: MethodTrack() { type = TYPE_METHOD; } }; + /* BEZIER TRACK */ + + struct BezierKey { + Vector2 in_handle; //relative (x always <0) + Vector2 out_handle; //relative (x always >0) + float value; + }; + + struct BezierTrack : public Track { + + Vector<TKey<BezierKey> > values; + + BezierTrack() { + type = TYPE_BEZIER; + } + }; + + /* AUDIO TRACK */ + + struct AudioKey { + RES stream; + float start_offset; //offset from start + float end_offset; //offset from end, if 0 then full length or infinite + AudioKey() { + start_offset = 0; + end_offset = 0; + } + }; + + struct AudioTrack : public Track { + + Vector<TKey<AudioKey> > values; + + AudioTrack() { + type = TYPE_AUDIO; + } + }; + + /* AUDIO TRACK */ + + struct AnimationTrack : public Track { + + Vector<TKey<StringName> > values; + + AnimationTrack() { + type = TYPE_ANIMATION; + } + }; + Vector<Track *> tracks; /* @@ -168,6 +221,9 @@ private: template <class T> _FORCE_INLINE_ T _interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const; + template <class T> + _FORCE_INLINE_ void _track_get_key_indices_in_range(const Vector<T> &p_array, float from_time, float to_time, List<int> *p_indices) const; + _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const; _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const; @@ -238,6 +294,7 @@ public: void track_move_up(int p_track); void track_move_down(int p_track); + void track_swap(int p_track, int p_with_track); void track_set_imported(int p_track, bool p_imported); bool track_is_imported(int p_track) const; @@ -245,7 +302,6 @@ public: void track_set_enabled(int p_track, bool p_enabled); bool track_is_enabled(int p_track) const; - int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot = Quat(), const Vector3 &p_scale = Vector3()); void track_insert_key(int p_track, float p_time, const Variant &p_key, float p_transition = 1); void track_set_key_transition(int p_track, int p_key_idx, float p_transition); void track_set_key_value(int p_track, int p_key_idx, const Variant &p_value); @@ -257,10 +313,33 @@ public: float track_get_key_time(int p_track, int p_key_idx) const; float track_get_key_transition(int p_track, int p_key_idx) const; + int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot = Quat(), const Vector3 &p_scale = Vector3()); Error transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const; void track_set_interpolation_type(int p_track, InterpolationType p_interp); InterpolationType track_get_interpolation_type(int p_track) const; + int bezier_track_insert_key(int p_track, float p_time, float p_value, const Vector2 &p_in_handle, const Vector2 &p_out_handle); + void bezier_track_set_key_value(int p_track, int p_index, float p_value); + void bezier_track_set_key_in_handle(int p_track, int p_index, const Vector2 &p_handle); + void bezier_track_set_key_out_handle(int p_track, int p_index, const Vector2 &p_handle); + float bezier_track_get_key_value(int p_track, int p_index) const; + Vector2 bezier_track_get_key_in_handle(int p_track, int p_index) const; + Vector2 bezier_track_get_key_out_handle(int p_track, int p_index) const; + + float bezier_track_interpolate(int p_track, float p_time) const; + + int audio_track_insert_key(int p_track, float p_time, const RES &p_stream, float p_start_offset = 0, float p_end_offset = 0); + void audio_track_set_key_stream(int p_track, int p_key, const RES &p_stream); + void audio_track_set_key_start_offset(int p_track, int p_key, float p_offset); + void audio_track_set_key_end_offset(int p_track, int p_key, float p_offset); + RES audio_track_get_key_stream(int p_track, int p_key) const; + float audio_track_get_key_start_offset(int p_track, int p_key) const; + float audio_track_get_key_end_offset(int p_track, int p_key) const; + + int animation_track_insert_key(int p_track, float p_time, const StringName &p_animation); + void animation_track_set_key_animation(int p_track, int p_key, const StringName &p_animation); + StringName animation_track_get_key_animation(int p_track, int p_key) const; + void track_set_interpolation_loop_wrap(int p_track, bool p_enable); bool track_get_interpolation_loop_wrap(int p_track) const; @@ -277,6 +356,8 @@ public: void copy_track(int p_track, Ref<Animation> p_to_animation); + void track_get_key_indices_in_range(int p_track, float p_time, float p_delta, List<int> *p_indices) const; + void set_length(float p_length); float get_length() const; diff --git a/servers/audio/audio_stream.cpp b/servers/audio/audio_stream.cpp index 0ad30987e7..113f23f8f2 100644 --- a/servers/audio/audio_stream.cpp +++ b/servers/audio/audio_stream.cpp @@ -89,6 +89,7 @@ void AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, } } } + //////////////////////////////// void AudioStream::_bind_methods() { diff --git a/servers/audio/audio_stream.h b/servers/audio/audio_stream.h index fda4fc2ccc..3312ce1ff6 100644 --- a/servers/audio/audio_stream.h +++ b/servers/audio/audio_stream.h @@ -31,6 +31,7 @@ #ifndef AUDIO_STREAM_H #define AUDIO_STREAM_H +#include "image.h" #include "resource.h" #include "servers/audio/audio_filter_sw.h" #include "servers/audio_server.h" diff --git a/thirdparty/README.md b/thirdparty/README.md index 25d6e3df9a..d30b70fede 100644 --- a/thirdparty/README.md +++ b/thirdparty/README.md @@ -15,6 +15,7 @@ Important: Some files have Godot-made changes. They are marked with `// -- GODOT start --` and `// -- GODOT end --` comments. + ## bullet - Upstream: https://github.com/bulletphysics/bullet3 @@ -76,6 +77,7 @@ Important: Some files have Godot-made changes. They are marked with `// -- GODOT start --` and `// -- GODOT end --` comments. + ## fonts ### Noto Sans @@ -175,6 +177,7 @@ Important: Some files have Godot-made changes. They are marked with `// -- GODOT start --` and `// -- GODOT end --` comments. + ## libtheora - Upstream: https://www.theora.org @@ -234,24 +237,29 @@ changes are marked with `// -- GODOT --` comments. ## libwebsockets - Upstream: https://github.com/warmcat/libwebsockets -- Version: 2.4.2 +- Version: 3.0.0 - License: LGPLv2.1 + static linking exception File extracted from upstream source: -- Everything in `lib/` except `minilex.c`, `http2/`, `event-libs/`. - - From `misc/` exclude `lws-genhash.c`, `lws-ring.c`, `romfs.{c,h}`, `smtp.c`. - - From `plat/` exclude `lws-plat-{esp*,optee}.c`. - - From `server/` exclude `access-log.c`, `cgi.c`, `daemonize.c`, `lws-spa.c`, -`peer-limits.c`, `rewrite.c` -- Also copy `win32helpers/` from `win32port/` -- `mbedtls_wrapper/include/platform/ssl_port.h` has a small change to check for OSX and FreeBSD (missing `malloc.h`). - The bug is fixed in upstream master via `LWS_HAVE_MALLOC_H`, but not in the 2.4.1 branch (as the file structure has changed). -- You might need to apply the patch in `thirdparty/lws/mbedtls_verify.diff` (port of PR 1215) to future `2.4.x` releases if it does not get cherry picked. +- From `lib/` into `thirdparty/libwebsockets`: + - Everything from `core` + - From `event-libs` only the `poll` subfolder + - From `misc` only `base64-decode.c`, `getifaddrs.c`, `getifaddrs.h`, `lejp.c`, and `sha-1.c` + - From `plat` only `lws-plat-unix.c` and `lws-plat-win.c` + - From `roles` only `private.h`, `h1`, `http`, `listen`, `pipe`, `raw`, `ws` + - From `roles/http` exclude `minilex.c` + - From `roles/http/server` exclude `access-log.c`, `lws-spa.c`, `ranges.c`, and `rewrite.c` + - From `roles/ws` exclude `ext` folder. + - From `tls` exclude `openssl` folder. +- Also copy `win32helpers/` from `win32port/` inside `thirdparty/libwebsockets` +- A small fix has been added in `libwebsockets/libwebsockets.h` to `#include <sys/socket.h>` for the BSD family. + This change has been PRed upstream, and should be merged before the next update. Remember to check and remove this line. Important: `lws_config.h` and `lws_config_private.h` contains custom Godot build configurations, check them out when updating. -## mbedTLS + +## mbedtls - Upstream: https://tls.mbed.org/ - Version: 2.8.0 @@ -264,6 +272,16 @@ File extracted from upstream release tarball `mbedtls-2.8.0-apache.tgz`: Be sure to check the Godot addition to only redfine it when undefined or `< 0x0501` (PRed upstream). - Applied the patch in `thirdparty/mbedtls/1453.diff` (PR 1453). Soon to be merged upstream. Check it out at next update. + +## miniupnpc + +- Upstream: https://github.com/miniupnp/miniupnp/tree/master/miniupnpc +- Version: 2.1 (git 25615e0, 2018-05-08) with modifications +- License: BSD-3-Clause + +The only modified file is miniupnpcstrings.h, which was created for Godot (is usually autogenerated by cmake). + + ## minizip - Upstream: http://www.zlib.net @@ -293,6 +311,10 @@ Collection of single-file libraries used in Godot components. * Upstream: http://episec.com/people/edelkind/c.html * Version: latest, as of April 2017 * License: Public Domain + - `clipper.{cpp,hpp}` + * Upstream: https://sourceforge.net/projects/polyclipping + * Version: 6.4.2 + * License: BSL-1.0 - `fastlz.{c,h}` * Upstream: https://github.com/ariya/FastLZ * Version: git (f121734, 2007) @@ -361,6 +383,7 @@ Files extracted from the upstream source: - All .h files in `src/` - LICENSE.txt + ## opus - Upstream: https://opus-codec.org diff --git a/thirdparty/lws/LICENSE.txt b/thirdparty/libwebsockets/LICENSE index 34a42d5687..6c7cd90cdc 100644 --- a/thirdparty/lws/LICENSE.txt +++ b/thirdparty/libwebsockets/LICENSE @@ -33,19 +33,21 @@ to get original sources with the liberal terms. Original liberal license retained - - lib/sha-1.c - 3-clause BSD license retained, link to original + - lib/misc/sha-1.c - 3-clause BSD license retained, link to original - win32port/zlib - ZLIB license (see zlib.h) + - lib/tls/mbedtls/wrapper - Apache 2.0 (only built if linked against mbedtls) Relicensed to libwebsocket license - - lib/base64-decode.c - relicensed to LGPL2.1+SLE, link to original - - lib/daemonize.c - relicensed from Public Domain to LGPL2.1+SLE, - link to original Public Domain version + - lib/misc/base64-decode.c - relicensed to LGPL2.1+SLE, link to original + - lib/misc/daemonize.c - relicensed from Public Domain to LGPL2.1+SLE, + link to original Public Domain version Public Domain (CC-zero) to simplify reuse - - test-server/*.c - - test-server/*.h + - test-apps/*.c + - test-apps/*.h + - minimal-examples/* - lwsws/* ------ end of exceptions @@ -107,7 +109,7 @@ modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - + Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a @@ -163,7 +165,7 @@ modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - + GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @@ -210,7 +212,7 @@ Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - + 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 @@ -268,7 +270,7 @@ instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - + Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. @@ -319,7 +321,7 @@ Library will still fall under Section 6.) distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - + 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work @@ -381,7 +383,7 @@ restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - + 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined @@ -422,7 +424,7 @@ subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - + 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or @@ -474,7 +476,7 @@ conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - + 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is @@ -508,7 +510,7 @@ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS - + How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest @@ -552,4 +554,3 @@ necessary. Here is a sample; alter the names: Ty Coon, President of Vice That's all there is to it! - diff --git a/thirdparty/lws/alloc.c b/thirdparty/libwebsockets/core/alloc.c index 898db12464..f169fc3767 100644 --- a/thirdparty/lws/alloc.c +++ b/thirdparty/libwebsockets/core/alloc.c @@ -1,4 +1,4 @@ -#include "private-libwebsockets.h" +#include "core/private.h" #if defined(LWS_PLAT_OPTEE) @@ -51,10 +51,12 @@ void lws_set_allocator(void *(*cb)(void *ptr, size_t size, const char *reason)) static void *_realloc(void *ptr, size_t size, const char *reason) { if (size) { -#if defined(LWS_PLAT_ESP32) - lwsl_notice("%s: size %lu: %s\n", __func__, (unsigned long)size, reason); +#if defined(LWS_WITH_ESP32) + lwsl_notice("%s: size %lu: %s (free heap %d)\n", __func__, + (unsigned long)size, reason, (unsigned int)esp_get_free_heap_size() - (int)size); #else - lwsl_debug("%s: size %lu: %s\n", __func__, (unsigned long)size, reason); + lwsl_debug("%s: size %lu: %s\n", __func__, + (unsigned long)size, reason); #endif #if defined(LWS_PLAT_OPTEE) return (void *)TEE_Realloc(ptr, size); diff --git a/thirdparty/lws/context.c b/thirdparty/libwebsockets/core/context.c index 9f221f50f1..db9151b95f 100644 --- a/thirdparty/lws/context.c +++ b/thirdparty/libwebsockets/core/context.c @@ -1,7 +1,7 @@ /* * libwebsockets - small server side websockets and web server implementation * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -19,12 +19,41 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" #ifndef LWS_BUILD_HASH #define LWS_BUILD_HASH "unknown-build-hash" #endif +const struct lws_role_ops *available_roles[] = { +#if defined(LWS_ROLE_H2) + &role_ops_h2, +#endif +#if defined(LWS_ROLE_H1) + &role_ops_h1, +#endif +#if defined(LWS_ROLE_WS) + &role_ops_ws, +#endif + NULL +}; + +const struct lws_event_loop_ops *available_event_libs[] = { +#if defined(LWS_WITH_POLL) + &event_loop_ops_poll, +#endif +#if defined(LWS_WITH_LIBUV) + &event_loop_ops_uv, +#endif +#if defined(LWS_WITH_LIBEVENT) + &event_loop_ops_event, +#endif +#if defined(LWS_WITH_LIBEV) + &event_loop_ops_ev, +#endif + NULL +}; + static const char *library_version = LWS_LIBRARY_VERSION " " LWS_BUILD_HASH; /** @@ -40,6 +69,23 @@ lws_get_library_version(void) return library_version; } +int +lws_role_call_alpn_negotiated(struct lws *wsi, const char *alpn) +{ +#if defined(LWS_WITH_TLS) + if (!alpn) + return 0; + + lwsl_info("%s: '%s'\n", __func__, alpn); + + LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) + if (ar->alpn && !strcmp(ar->alpn, alpn) && ar->alpn_negotiated) + return ar->alpn_negotiated(wsi, alpn); + LWS_FOR_EVERY_AVAILABLE_ROLE_END; +#endif + return 0; +} + static const char * const mount_protocols[] = { "http://", "https://", @@ -50,66 +96,6 @@ static const char * const mount_protocols[] = { "callback://" }; -#if defined(LWS_WITH_HTTP2) -/* - * These are the standardized defaults. - * Override what actually goes in the vhost settings in platform or user code. - * Leave these alone because they are used to determine "what is different - * from the protocol defaults". - */ -const struct http2_settings lws_h2_defaults = { { - 1, - /* H2SET_HEADER_TABLE_SIZE */ 4096, - /* *** This controls how many entries in the dynamic table *** - * Allows the sender to inform the remote endpoint of the maximum - * size of the header compression table used to decode header - * blocks, in octets. The encoder can select any size equal to or - * less than this value by using signaling specific to the header - * compression format inside a header block (see [COMPRESSION]). - * The initial value is 4,096 octets. - */ - /* H2SET_ENABLE_PUSH */ 1, - /* H2SET_MAX_CONCURRENT_STREAMS */ 0x7fffffff, - /* H2SET_INITIAL_WINDOW_SIZE */ 65535, - /* H2SET_MAX_FRAME_SIZE */ 16384, - /* H2SET_MAX_HEADER_LIST_SIZE */ 0x7fffffff, - /*< This advisory setting informs a peer of the maximum size of - * header list that the sender is prepared to accept, in octets. - * The value is based on the uncompressed size of header fields, - * including the length of the name and value in octets plus an - * overhead of 32 octets for each header field. - */ - -}}; - -const struct http2_settings lws_h2_stock_settings = { { - 1, - /* H2SET_HEADER_TABLE_SIZE */ 4096, - /* *** This controls how many entries in the dynamic table *** - * Allows the sender to inform the remote endpoint of the maximum - * size of the header compression table used to decode header - * blocks, in octets. The encoder can select any size equal to or - * less than this value by using signaling specific to the header - * compression format inside a header block (see [COMPRESSION]). - * The initial value is 4,096 octets. - * - * Can't pass h2spec with less than 4096 here... - */ - /* H2SET_ENABLE_PUSH */ 1, - /* H2SET_MAX_CONCURRENT_STREAMS */ 24, - /* H2SET_INITIAL_WINDOW_SIZE */ 65535, - /* H2SET_MAX_FRAME_SIZE */ 16384, - /* H2SET_MAX_HEADER_LIST_SIZE */ 4096, - /*< This advisory setting informs a peer of the maximum size of - * header list that the sender is prepared to accept, in octets. - * The value is based on the uncompressed size of header fields, - * including the length of the name and value in octets plus an - * overhead of 32 octets for each header field. - */ - -}}; -#endif - LWS_VISIBLE void * lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot, int size) @@ -119,7 +105,8 @@ lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, /* allocate the vh priv array only on demand */ if (!vhost->protocol_vh_privs) { vhost->protocol_vh_privs = (void **)lws_zalloc( - vhost->count_protocols * sizeof(void *), "protocol_vh_privs"); + vhost->count_protocols * sizeof(void *), + "protocol_vh_privs"); if (!vhost->protocol_vh_privs) return NULL; } @@ -195,7 +182,7 @@ lws_protocol_init(struct lws_context *context) struct lws_vhost *vh = context->vhost_list; const struct lws_protocol_vhost_options *pvo, *pvo1; struct lws wsi; - int n; + int n, any = 0; if (context->doing_protocol_init) return 0; @@ -211,7 +198,8 @@ lws_protocol_init(struct lws_context *context) wsi.vhost = vh; /* only do the protocol init once for a given vhost */ - if (vh->created_vhost_protocols) + if (vh->created_vhost_protocols || + (vh->options & LWS_SERVER_OPTION_SKIP_PROTOCOL_INIT)) goto next; /* initialize supported protocols on this vhost */ @@ -231,21 +219,23 @@ lws_protocol_init(struct lws_context *context) pvo = pvo1->options; while (pvo) { - lwsl_notice( - " vhost \"%s\", protocol \"%s\", option \"%s\"\n", + lwsl_debug( + " vhost \"%s\", " + "protocol \"%s\", " + "option \"%s\"\n", vh->name, vh->protocols[n].name, pvo->name); if (!strcmp(pvo->name, "default")) { - lwsl_notice("Setting default " + lwsl_info("Setting default " "protocol for vh %s to %s\n", vh->name, vh->protocols[n].name); vh->default_protocol_index = n; } if (!strcmp(pvo->name, "raw")) { - lwsl_notice("Setting raw " + lwsl_info("Setting raw " "protocol for vh %s to %s\n", vh->name, vh->protocols[n].name); @@ -257,6 +247,10 @@ lws_protocol_init(struct lws_context *context) pvo = pvo1->options; } +#if defined(LWS_WITH_TLS) + any |= !!vh->tls.ssl_ctx; +#endif + /* * inform all the protocols that they are doing their * one-time initialization if they want to. @@ -267,10 +261,10 @@ lws_protocol_init(struct lws_context *context) if (vh->protocols[n].callback(&wsi, LWS_CALLBACK_PROTOCOL_INIT, NULL, (void *)pvo, 0)) { - lwsl_err("%s: vhost %s failed init\n", __func__, + lws_free(vh->protocol_vh_privs[n]); + vh->protocol_vh_privs[n] = NULL; + lwsl_err("%s: protocol %s failed init\n", __func__, vh->protocols[n].name); - context->doing_protocol_init = 0; - return 1; } } @@ -286,6 +280,9 @@ next: context->protocol_init_done = 1; + if (any) + lws_tls_check_all_cert_lifetimes(context); + return 0; } @@ -303,6 +300,7 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, #endif switch (reason) { +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) case LWS_CALLBACK_HTTP: #ifndef LWS_NO_SERVER if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL)) @@ -325,14 +323,16 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, LWS_CB_REASON_AUX_BF__CGI)) { n = lws_cgi_write_split_stdout_headers(wsi); if (n < 0) { - lwsl_debug("LWS_CB_REASON_AUX_BF__CGI forcing close\n"); + lwsl_debug("AUX_BF__CGI forcing close\n"); return -1; } if (!n) - lws_rx_flow_control(wsi->cgi->stdwsi[LWS_STDOUT], 1); + lws_rx_flow_control( + wsi->http.cgi->stdwsi[LWS_STDOUT], 1); if (wsi->reason_bf & LWS_CB_REASON_AUX_BF__CGI_HEADERS) - wsi->reason_bf &= ~LWS_CB_REASON_AUX_BF__CGI_HEADERS; + wsi->reason_bf &= + ~LWS_CB_REASON_AUX_BF__CGI_HEADERS; else wsi->reason_bf &= ~LWS_CB_REASON_AUX_BF__CGI; break; @@ -341,12 +341,13 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, if (wsi->reason_bf & LWS_CB_REASON_AUX_BF__CGI_CHUNK_END) { if (!wsi->http2_substream) { memcpy(buf + LWS_PRE, "0\x0d\x0a\x0d\x0a", 5); - lwsl_debug("writing chunk terminator and exiting\n"); - n = lws_write(wsi, (unsigned char *)buf + LWS_PRE, - 5, LWS_WRITE_HTTP); + lwsl_debug("writing chunk term and exiting\n"); + n = lws_write(wsi, (unsigned char *)buf + + LWS_PRE, 5, LWS_WRITE_HTTP); } else - n = lws_write(wsi, (unsigned char *)buf + LWS_PRE, - 0, LWS_WRITE_HTTP_FINAL); + n = lws_write(wsi, (unsigned char *)buf + + LWS_PRE, 0, + LWS_WRITE_HTTP_FINAL); /* always close after sending it */ return -1; @@ -366,7 +367,8 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, wsi->reason_bf &= ~LWS_CB_REASON_AUX_BF__PROXY; if (!lws_get_child(wsi)) break; - if (lws_http_client_read(lws_get_child(wsi), &px, &lenx) < 0) + if (lws_http_client_read(lws_get_child(wsi), &px, + &lenx) < 0) return -1; break; } @@ -467,10 +469,10 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, case LWS_CALLBACK_CGI_TERMINATED: lwsl_debug("LWS_CALLBACK_CGI_TERMINATED: %d %" PRIu64 "\n", - wsi->cgi->explicitly_chunked, - (uint64_t)wsi->cgi->content_length); - if (!wsi->cgi->explicitly_chunked && - !wsi->cgi->content_length) { + wsi->http.cgi->explicitly_chunked, + (uint64_t)wsi->http.cgi->content_length); + if (!wsi->http.cgi->explicitly_chunked && + !wsi->http.cgi->content_length) { /* send terminating chunk */ lwsl_debug("LWS_CALLBACK_CGI_TERMINATED: ending\n"); wsi->reason_bf |= LWS_CB_REASON_AUX_BF__CGI_CHUNK_END; @@ -492,7 +494,7 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, "sent %d only %d went", n, args->len); return n; #endif - +#endif case LWS_CALLBACK_SSL_INFO: si = in; @@ -514,11 +516,13 @@ static const struct lws_protocols protocols_dummy[] = { /* first protocol must always be HTTP handler */ { - "http-only", /* name */ - lws_callback_http_dummy, /* callback */ - 0, /* per_session_data_size */ - 0, /* max frame size / rx buffer */ - 0, NULL, 0 + "http-only", /* name */ + lws_callback_http_dummy, /* callback */ + 0, /* per_session_data_size */ + 0, /* rx_buffer_size */ + 0, /* id */ + NULL, /* user */ + 0 /* tx_packet_size */ }, /* * the other protocols are provided by lws plugins @@ -530,20 +534,25 @@ static const struct lws_protocols protocols_dummy[] = { #undef LWS_HAVE_GETENV #endif +static void +lws_vhost_destroy2(struct lws_vhost *vh); + LWS_VISIBLE struct lws_vhost * lws_create_vhost(struct lws_context *context, - struct lws_context_creation_info *info) + const struct lws_context_creation_info *info) { struct lws_vhost *vh = lws_zalloc(sizeof(*vh), "create vhost"), **vh1 = &context->vhost_list; const struct lws_http_mount *mounts; + const struct lws_protocols *pcols = info->protocols; const struct lws_protocol_vhost_options *pvo; #ifdef LWS_WITH_PLUGINS struct lws_plugin *plugin = context->plugin_list; #endif struct lws_protocols *lwsp; int m, f = !info->pvo; -#ifdef LWS_HAVE_GETENV + char buf[20]; +#if !defined(LWS_WITHOUT_CLIENT) && defined(LWS_HAVE_GETENV) char *p; #endif int n; @@ -551,8 +560,12 @@ lws_create_vhost(struct lws_context *context, if (!vh) return NULL; - if (!info->protocols) - info->protocols = &protocols_dummy[0]; +#if LWS_MAX_SMP > 1 + pthread_mutex_init(&vh->lock, NULL); +#endif + + if (!pcols) + pcols = &protocols_dummy[0]; vh->context = context; if (!info->vhost_name) @@ -560,23 +573,21 @@ lws_create_vhost(struct lws_context *context, else vh->name = info->vhost_name; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + vh->http.error_document_404 = info->error_document_404; +#endif + if (info->options & LWS_SERVER_OPTION_ONLY_RAW) lwsl_info("%s set to only support RAW\n", vh->name); -#if defined(LWS_WITH_HTTP2) - vh->set = context->set; - if (info->http2_settings[0]) - for (n = 1; n < LWS_H2_SETTINGS_LEN; n++) - vh->set.s[n] = info->http2_settings[n]; -#endif - vh->iface = info->iface; -#if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32) +#if !defined(LWS_WITH_ESP32) && \ + !defined(OPTEE_TA) && !defined(WIN32) vh->bind_iface = info->bind_iface; #endif for (vh->count_protocols = 0; - info->protocols[vh->count_protocols].callback; + pcols[vh->count_protocols].callback; vh->count_protocols++) ; @@ -584,7 +595,14 @@ lws_create_vhost(struct lws_context *context, vh->pvo = info->pvo; vh->headers = info->headers; vh->user = info->user; - vh->ssl_info_event_mask = info->ssl_info_event_mask; + + LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) + if (ar->init_vhost) + if (ar->init_vhost(vh, info)) + return NULL; + LWS_FOR_EVERY_AVAILABLE_ROLE_END; + + if (info->keepalive_timeout) vh->keepalive_timeout = info->keepalive_timeout; else @@ -595,20 +613,49 @@ lws_create_vhost(struct lws_context *context, else vh->timeout_secs_ah_idle = 10; +#if defined(LWS_WITH_TLS) + + vh->tls.alpn = info->alpn; + vh->tls.ssl_info_event_mask = info->ssl_info_event_mask; + + if (info->ecdh_curve) + lws_strncpy(vh->tls.ecdh_curve, info->ecdh_curve, + sizeof(vh->tls.ecdh_curve)); + + /* carefully allocate and take a copy of cert + key paths if present */ + n = 0; + if (info->ssl_cert_filepath) + n += (int)strlen(info->ssl_cert_filepath) + 1; + if (info->ssl_private_key_filepath) + n += (int)strlen(info->ssl_private_key_filepath) + 1; + + if (n) { + vh->tls.key_path = vh->tls.alloc_cert_path = lws_malloc(n, "vh paths"); + if (info->ssl_cert_filepath) { + n = (int)strlen(info->ssl_cert_filepath) + 1; + memcpy(vh->tls.alloc_cert_path, info->ssl_cert_filepath, n); + vh->tls.key_path += n; + } + if (info->ssl_private_key_filepath) + memcpy(vh->tls.key_path, info->ssl_private_key_filepath, + strlen(info->ssl_private_key_filepath) + 1); + } +#endif + /* * give the vhost a unified list of protocols including the * ones that came from plugins */ - lwsp = lws_zalloc(sizeof(struct lws_protocols) * - (vh->count_protocols + - context->plugin_protocol_count + 1), "vhost-specific plugin table"); + lwsp = lws_zalloc(sizeof(struct lws_protocols) * (vh->count_protocols + + context->plugin_protocol_count + 1), + "vhost-specific plugin table"); if (!lwsp) { lwsl_err("OOM\n"); return NULL; } m = vh->count_protocols; - memcpy(lwsp, info->protocols, sizeof(struct lws_protocols) * m); + memcpy(lwsp, pcols, sizeof(struct lws_protocols) * m); /* for compatibility, all protocols enabled on vhost if only * the default vhost exists. Otherwise only vhosts who ask @@ -648,43 +695,58 @@ lws_create_vhost(struct lws_context *context, context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS) vh->protocols = lwsp; else { - vh->protocols = info->protocols; + vh->protocols = pcols; lws_free(lwsp); } vh->same_vh_protocol_list = (struct lws **) - lws_zalloc(sizeof(struct lws *) * vh->count_protocols, "same vh list"); - - vh->mount_list = info->mounts; + lws_zalloc(sizeof(struct lws *) * vh->count_protocols, + "same vh list"); +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + vh->http.mount_list = info->mounts; +#endif #ifdef LWS_WITH_UNIX_SOCK if (LWS_UNIX_SOCK_ENABLED(context)) { lwsl_notice("Creating Vhost '%s' path \"%s\", %d protocols\n", - vh->name, info->iface, vh->count_protocols); + vh->name, vh->iface, vh->count_protocols); } else #endif - lwsl_notice("Creating Vhost '%s' port %d, %d protocols, IPv6 %s\n", - vh->name, info->port, vh->count_protocols, - LWS_IPV6_ENABLED(vh) ? "on" : "off"); - + { + switch(info->port) { + case CONTEXT_PORT_NO_LISTEN: + strcpy(buf, "(serving disabled)"); + break; + case CONTEXT_PORT_NO_LISTEN_SERVER: + strcpy(buf, "(no listener)"); + break; + default: + lws_snprintf(buf, sizeof(buf), "port %u", info->port); + break; + } + lwsl_notice("Creating Vhost '%s' %s, %d protocols, IPv6 %s\n", + vh->name, buf, vh->count_protocols, + LWS_IPV6_ENABLED(vh) ? "on" : "off"); + } mounts = info->mounts; while (mounts) { (void)mount_protocols[0]; - lwsl_notice(" mounting %s%s to %s\n", - mount_protocols[mounts->origin_protocol], - mounts->origin, mounts->mountpoint); + lwsl_info(" mounting %s%s to %s\n", + mount_protocols[mounts->origin_protocol], + mounts->origin, mounts->mountpoint); /* convert interpreter protocol names to pointers */ pvo = mounts->interpret; while (pvo) { - for (n = 0; n < vh->count_protocols; n++) - if (!strcmp(pvo->value, vh->protocols[n].name)) { - ((struct lws_protocol_vhost_options *)pvo)->value = - (const char *)(lws_intptr_t)n; - break; - } + for (n = 0; n < vh->count_protocols; n++) { + if (strcmp(pvo->value, vh->protocols[n].name)) + continue; + ((struct lws_protocol_vhost_options *)pvo)-> + value = (const char *)(lws_intptr_t)n; + break; + } if (n == vh->count_protocols) - lwsl_err("ignoring unknown interpret protocol %s\n", + lwsl_err("ignoring unknown interp pr %s\n", pvo->value); pvo = pvo->next; } @@ -692,64 +754,35 @@ lws_create_vhost(struct lws_context *context, mounts = mounts->mount_next; } -#ifndef LWS_NO_EXTENSIONS -#ifdef LWS_WITH_PLUGINS - if (context->plugin_extension_count) { - - m = 0; - while (info->extensions && info->extensions[m].callback) - m++; - - /* - * give the vhost a unified list of extensions including the - * ones that came from plugins - */ - vh->extensions = lws_zalloc(sizeof(struct lws_extension) * - (m + - context->plugin_extension_count + 1), "extensions"); - if (!vh->extensions) - return NULL; - - memcpy((struct lws_extension *)vh->extensions, info->extensions, - sizeof(struct lws_extension) * m); - plugin = context->plugin_list; - while (plugin) { - memcpy((struct lws_extension *)&vh->extensions[m], - plugin->caps.extensions, - sizeof(struct lws_extension) * - plugin->caps.count_extensions); - m += plugin->caps.count_extensions; - plugin = plugin->list; - } - } else -#endif - vh->extensions = info->extensions; -#endif - vh->listen_port = info->port; -#if !defined(LWS_WITH_ESP8266) - vh->http_proxy_port = 0; - vh->http_proxy_address[0] = '\0'; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + vh->http.http_proxy_port = 0; + vh->http.http_proxy_address[0] = '\0'; +#endif #if defined(LWS_WITH_SOCKS5) vh->socks_proxy_port = 0; vh->socks_proxy_address[0] = '\0'; #endif +#if !defined(LWS_WITHOUT_CLIENT) /* either use proxy from info, or try get it from env var */ - +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) /* http proxy */ if (info->http_proxy_address) { /* override for backwards compatibility */ if (info->http_proxy_port) - vh->http_proxy_port = info->http_proxy_port; + vh->http.http_proxy_port = info->http_proxy_port; lws_set_proxy(vh, info->http_proxy_address); - } else { + } else +#endif + { #ifdef LWS_HAVE_GETENV p = getenv("http_proxy"); if (p) lws_set_proxy(vh, p); #endif } +#endif #if defined(LWS_WITH_SOCKS5) /* socks proxy */ if (info->socks_proxy_address) { @@ -765,7 +798,6 @@ lws_create_vhost(struct lws_context *context, #endif } #endif -#endif vh->ka_time = info->ka_time; vh->ka_interval = info->ka_interval; @@ -793,15 +825,23 @@ lws_create_vhost(struct lws_context *context, } else vh->log_fd = (int)LWS_INVALID_FILE; #endif - if (lws_context_init_server_ssl(info, vh)) - goto bail; - if (lws_context_init_client_ssl(info, vh)) - goto bail; - if (lws_context_init_server(info, vh)) { + if (lws_context_init_server_ssl(info, vh)) { + lwsl_err("%s: lws_context_init_server_ssl failed\n", __func__); + goto bail1; + } + if (lws_context_init_client_ssl(info, vh)) { + lwsl_err("%s: lws_context_init_client_ssl failed\n", __func__); + goto bail1; + } + lws_context_lock(context); + n = _lws_vhost_init_server(info, vh); + lws_context_unlock(context); + if (n < 0) { lwsl_err("init server failed\n"); - goto bail; + goto bail1; } + while (1) { if (!(*vh1)) { *vh1 = vh; @@ -809,15 +849,27 @@ lws_create_vhost(struct lws_context *context, } vh1 = &(*vh1)->vhost_next; }; + /* for the case we are adding a vhost much later, after server init */ if (context->protocol_init_done) - lws_protocol_init(context); + if (lws_protocol_init(context)) { + lwsl_err("%s: lws_protocol_init failed\n", __func__); + goto bail1; + } return vh; +bail1: + lws_vhost_destroy(vh); + lws_vhost_destroy2(vh); + + return NULL; + +#ifdef LWS_WITH_ACCESS_LOG bail: lws_free(vh); +#endif return NULL; } @@ -834,8 +886,100 @@ lws_init_vhost_client_ssl(const struct lws_context_creation_info *info, return lws_context_init_client_ssl(&i, vhost); } +LWS_VISIBLE void +lws_cancel_service_pt(struct lws *wsi) +{ + lws_plat_pipe_signal(wsi); +} + +LWS_VISIBLE void +lws_cancel_service(struct lws_context *context) +{ + struct lws_context_per_thread *pt = &context->pt[0]; + short m = context->count_threads; + + if (context->being_destroyed1) + return; + + lwsl_info("%s\n", __func__); + + while (m--) { + if (pt->pipe_wsi) + lws_plat_pipe_signal(pt->pipe_wsi); + pt++; + } +} + +int +lws_create_event_pipes(struct lws_context *context) +{ + struct lws *wsi; + int n; + + /* + * Create the pt event pipes... these are unique in that they are + * not bound to a vhost or protocol (both are NULL) + */ + + for (n = 0; n < context->count_threads; n++) { + if (context->pt[n].pipe_wsi) + continue; + + wsi = lws_zalloc(sizeof(*wsi), "event pipe wsi"); + if (!wsi) { + lwsl_err("Out of mem\n"); + return 1; + } + wsi->context = context; + lws_role_transition(wsi, 0, LRS_UNCONNECTED, &role_ops_pipe); + wsi->protocol = NULL; + wsi->tsi = n; + wsi->vhost = NULL; + wsi->event_pipe = 1; + + if (lws_plat_pipe_create(wsi)) { + lws_free(wsi); + continue; + } + wsi->desc.sockfd = context->pt[n].dummy_pipe_fds[0]; + lwsl_debug("event pipe fd %d\n", wsi->desc.sockfd); + + context->pt[n].pipe_wsi = wsi; + + if (context->event_loop_ops->accept) + context->event_loop_ops->accept(wsi); + + if (__insert_wsi_socket_into_fds(context, wsi)) + return 1; + + //lws_change_pollfd(context->pt[n].pipe_wsi, 0, LWS_POLLIN); + context->count_wsi_allocated++; + } + + return 0; +} + +void +lws_destroy_event_pipe(struct lws *wsi) +{ + lwsl_info("%s\n", __func__); + __remove_wsi_socket_from_fds(wsi); + + if (wsi->context->event_loop_ops->wsi_logical_close) { + wsi->context->event_loop_ops->wsi_logical_close(wsi); + lws_plat_pipe_close(wsi); + return; + } + + if (wsi->context->event_loop_ops->destroy_wsi) + wsi->context->event_loop_ops->destroy_wsi(wsi); + lws_plat_pipe_close(wsi); + wsi->context->count_wsi_allocated--; + lws_free(wsi); +} + LWS_VISIBLE struct lws_context * -lws_create_context(struct lws_context_creation_info *info) +lws_create_context(const struct lws_context_creation_info *info) { struct lws_context *context = NULL; struct lws_plat_file_ops *prev; @@ -847,12 +991,14 @@ lws_create_context(struct lws_context_creation_info *info) struct rlimit rt; #endif + + lwsl_info("Initial logging level %d\n", log_level); lwsl_info("Libwebsockets version: %s\n", library_version); #if defined(GCC_VER) lwsl_info("Compiled with %s\n", GCC_VER); #endif -#if LWS_POSIX + #ifdef LWS_WITH_IPV6 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_IPV6)) lwsl_info("IPV6 compiled in and enabled\n"); @@ -861,11 +1007,7 @@ lws_create_context(struct lws_context_creation_info *info) #else lwsl_info("IPV6 not compiled in\n"); #endif -#if !defined(LWS_PLAT_OPTEE) && !defined(LWS_PLAT_ESP32) - lws_feature_status_libev(info); - lws_feature_status_libuv(info); -#endif -#endif + lwsl_info(" LWS_DEF_HEADER_LEN : %u\n", LWS_DEF_HEADER_LEN); lwsl_info(" LWS_MAX_PROTOCOLS : %u\n", LWS_MAX_PROTOCOLS); lwsl_info(" LWS_MAX_SMP : %u\n", LWS_MAX_SMP); @@ -873,13 +1015,11 @@ lws_create_context(struct lws_context_creation_info *info) #if defined(LWS_WITH_STATS) lwsl_info(" LWS_WITH_STATS : on\n"); #endif -#if LWS_POSIX lwsl_info(" SYSTEM_RANDOM_FILEPATH: '%s'\n", SYSTEM_RANDOM_FILEPATH); -#endif #if defined(LWS_WITH_HTTP2) lwsl_info(" HTTP2 support : available\n"); #else - lwsl_info(" HTTP2 support : not configured"); + lwsl_info(" HTTP2 support : not configured\n"); #endif if (lws_plat_context_early_init()) return NULL; @@ -889,13 +1029,22 @@ lws_create_context(struct lws_context_creation_info *info) lwsl_err("No memory for websocket context\n"); return NULL; } + +#if defined(LWS_WITH_TLS) +#if defined(LWS_WITH_MBEDTLS) + context->tls_ops = &tls_ops_mbedtls; +#else + context->tls_ops = &tls_ops_openssl; +#endif +#endif + if (info->pt_serv_buf_size) context->pt_serv_buf_size = info->pt_serv_buf_size; else context->pt_serv_buf_size = 4096; -#if defined(LWS_WITH_HTTP2) - context->set = lws_h2_stock_settings; +#if defined(LWS_ROLE_H2) + role_ops_h2.init_context(context, info); #endif #if LWS_MAX_SMP > 1 @@ -943,8 +1092,10 @@ lws_create_context(struct lws_context_creation_info *info) info->external_baggage_free_on_destroy; context->time_up = time(NULL); + context->pcontext_finalize = info->pcontext; - context->simultaneous_ssl_restriction = info->simultaneous_ssl_restriction; + context->simultaneous_ssl_restriction = + info->simultaneous_ssl_restriction; #ifndef LWS_NO_DAEMONIZE if (pid_daemon) { @@ -975,6 +1126,67 @@ lws_create_context(struct lws_context_creation_info *info) context->options = info->options; + /* + * set the context event loops ops struct + * + * after this, all event_loop actions use the generic ops + */ + +#if defined(LWS_WITH_POLL) + context->event_loop_ops = &event_loop_ops_poll; +#endif + + if (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBUV)) +#if defined(LWS_WITH_LIBUV) + context->event_loop_ops = &event_loop_ops_uv; +#else + goto fail_event_libs; +#endif + + if (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEV)) +#if defined(LWS_WITH_LIBEV) + context->event_loop_ops = &event_loop_ops_ev; +#else + goto fail_event_libs; +#endif + + if (lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEVENT)) +#if defined(LWS_WITH_LIBEVENT) + context->event_loop_ops = &event_loop_ops_event; +#else + goto fail_event_libs; +#endif + + if (!context->event_loop_ops) + goto fail_event_libs; + + lwsl_info("Using event loop: %s\n", context->event_loop_ops->name); + +#if defined(LWS_WITH_TLS) + time(&context->tls.last_cert_check_s); + if (info->alpn) + context->tls.alpn_default = info->alpn; + else { + char *p = context->tls.alpn_discovered, first = 1; + + LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) { + if (ar->alpn) { + if (!first) + *p++ = ','; + p += lws_snprintf(p, + context->tls.alpn_discovered + + sizeof(context->tls.alpn_discovered) - + 2 - p, "%s", ar->alpn); + first = 0; + } + } LWS_FOR_EVERY_AVAILABLE_ROLE_END; + + context->tls.alpn_default = context->tls.alpn_discovered; + } + + lwsl_info("Default ALPN advertisment: %s\n", context->tls.alpn_default); +#endif + if (info->timeout_secs) context->timeout_secs = info->timeout_secs; else @@ -992,10 +1204,17 @@ lws_create_context(struct lws_context_creation_info *info) info->max_http_header_data2; else context->max_http_header_data = LWS_DEF_HEADER_LEN; + if (info->max_http_header_pool) context->max_http_header_pool = info->max_http_header_pool; else - context->max_http_header_pool = LWS_DEF_HEADER_POOL; + context->max_http_header_pool = context->max_fds; + + if (info->fd_limit_per_thread) + context->fd_limit_per_thread = info->fd_limit_per_thread; + else + context->fd_limit_per_thread = context->max_fds / + context->count_threads; /* * Allocate the per-thread storage for scratchpad buffers, @@ -1009,22 +1228,16 @@ lws_create_context(struct lws_context_creation_info *info) return NULL; } -#ifdef LWS_WITH_LIBUV context->pt[n].context = context; -#endif context->pt[n].tid = n; - context->pt[n].ah_list = NULL; - context->pt[n].ah_pool_length = 0; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + context->pt[n].http.ah_list = NULL; + context->pt[n].http.ah_pool_length = 0; +#endif lws_pt_mutex_init(&context->pt[n]); } - if (info->fd_limit_per_thread) - context->fd_limit_per_thread = info->fd_limit_per_thread; - else - context->fd_limit_per_thread = context->max_fds / - context->count_threads; - lwsl_info(" Threads: %d each %d fds\n", context->count_threads, context->fd_limit_per_thread); @@ -1033,36 +1246,6 @@ lws_create_context(struct lws_context_creation_info *info) return NULL; } -#ifdef LWS_WITH_LIBEV - /* (Issue #264) In order to *avoid breaking backwards compatibility*, we - * enable libev mediated SIGINT handling with a default handler of - * lws_sigint_cb. The handler can be overridden or disabled - * by invoking lws_sigint_cfg after creating the context, but - * before invoking lws_initloop: - */ - context->use_ev_sigint = 1; - context->lws_ev_sigint_cb = &lws_ev_sigint_cb; -#endif /* LWS_WITH_LIBEV */ -#ifdef LWS_WITH_LIBUV - /* (Issue #264) In order to *avoid breaking backwards compatibility*, we - * enable libev mediated SIGINT handling with a default handler of - * lws_sigint_cb. The handler can be overridden or disabled - * by invoking lws_sigint_cfg after creating the context, but - * before invoking lws_initloop: - */ - context->use_ev_sigint = 1; - context->lws_uv_sigint_cb = &lws_uv_sigint_cb; -#endif -#ifdef LWS_WITH_LIBEVENT - /* (Issue #264) In order to *avoid breaking backwards compatibility*, we - * enable libev mediated SIGINT handling with a default handler of - * lws_sigint_cb. The handler can be overridden or disabled - * by invoking lws_sigint_cfg after creating the context, but - * before invoking lws_initloop: - */ - context->use_ev_sigint = 1; - context->lws_event_sigint_cb = &lws_event_sigint_cb; -#endif /* LWS_WITH_LIBEVENT */ #if defined(LWS_WITH_PEER_LIMITS) /* scale the peer hash table according to the max fds for the process, @@ -1077,14 +1260,14 @@ lws_create_context(struct lws_context_creation_info *info) context->ip_limit_wsi = info->ip_limit_wsi; #endif - lwsl_info(" mem: context: %5lu bytes (%ld ctx + (%ld thr x %d))\n", + lwsl_info(" mem: context: %5lu B (%ld ctx + (%ld thr x %d))\n", (long)sizeof(struct lws_context) + (context->count_threads * context->pt_serv_buf_size), (long)sizeof(struct lws_context), (long)context->count_threads, context->pt_serv_buf_size); - - lwsl_info(" mem: http hdr rsvd: %5lu bytes (%u thr x (%u + %lu) x %u))\n", +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + lwsl_info(" mem: http hdr rsvd: %5lu B (%u thr x (%u + %lu) x %u))\n", (long)(context->max_http_header_data + sizeof(struct allocated_headers)) * context->max_http_header_pool * context->count_threads, @@ -1092,6 +1275,7 @@ lws_create_context(struct lws_context_creation_info *info) context->max_http_header_data, (long)sizeof(struct allocated_headers), context->max_http_header_pool); +#endif n = sizeof(struct lws_pollfd) * context->count_threads * context->fd_limit_per_thread; context->pt[0].fds = lws_zalloc(n, "fds table"); @@ -1117,14 +1301,24 @@ lws_create_context(struct lws_context_creation_info *info) if (lws_plat_init(context, info)) goto bail; -#if defined(LWS_WITH_HTTP2) - /* - * let the user code see what the platform default SETTINGS were, he - * can modify them when he creates the vhosts. - */ - for (n = 1; n < LWS_H2_SETTINGS_LEN; n++) - info->http2_settings[n] = context->set.s[n]; -#endif + if (context->event_loop_ops->init_context) + if (context->event_loop_ops->init_context(context, info)) + goto bail; + + + if (context->event_loop_ops->init_pt) + for (n = 0; n < context->count_threads; n++) { + void *lp = NULL; + + if (info->foreign_loops) + lp = info->foreign_loops[n]; + + if (context->event_loop_ops->init_pt(context, lp, n)) + goto bail; + } + + if (lws_create_event_pipes(context)) + goto bail; lws_context_init_ssl_library(info); @@ -1137,6 +1331,14 @@ lws_create_context(struct lws_context_creation_info *info) if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) if (!lws_create_vhost(context, info)) { lwsl_err("Failed to create default vhost\n"); + for (n = 0; n < context->count_threads; n++) + lws_free_set_NULL(context->pt[n].serv_buf); +#if defined(LWS_WITH_PEER_LIMITS) + lws_free_set_NULL(context->pl_hash_table); +#endif + lws_free_set_NULL(context->pt[0].fds); + lws_plat_context_late_destroy(context); + lws_free_set_NULL(context); return NULL; } @@ -1164,23 +1366,32 @@ lws_create_context(struct lws_context_creation_info *info) if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) lws_plat_drop_app_privileges(info); - /* - * give all extensions a chance to create any per-context - * allocations they need - */ - if (info->port != CONTEXT_PORT_NO_LISTEN) { - if (lws_ext_cb_all_exts(context, NULL, - LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT, NULL, 0) < 0) - goto bail; - } else - if (lws_ext_cb_all_exts(context, NULL, - LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT, NULL, 0) < 0) - goto bail; + /* expedite post-context init (eg, protocols) */ + lws_cancel_service(context); + +#if defined(LWS_WITH_SELFTESTS) + lws_jws_selftest(); +#endif return context; bail: lws_context_destroy(context); + + return NULL; + +fail_event_libs: + lwsl_err("Requested event library support not configured, available:\n"); + { + const struct lws_event_loop_ops **elops = available_event_libs; + + while (*elops) { + lwsl_err(" - %s\n", (*elops)->name); + elops++; + } + } + lws_free(context); + return NULL; } @@ -1205,7 +1416,7 @@ lws_context_deprecate(struct lws_context *context, lws_reload_func cb) wsi = vh->lserv_wsi; if (wsi) { wsi->socket_is_permanently_unusable = 1; - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "ctx deprecate"); wsi->context->deprecation_pending_listen_close_count++; /* * other vhosts can share the listen port, they @@ -1231,11 +1442,7 @@ lws_context_is_deprecated(struct lws_context *context) return context->deprecated; } -LWS_VISIBLE void -lws_context_destroy2(struct lws_context *context); - - -static void +void lws_vhost_destroy1(struct lws_vhost *vh) { const struct lws_protocols *protocol = NULL; @@ -1259,7 +1466,8 @@ lws_vhost_destroy1(struct lws_vhost *vh) */ if (vh->lserv_wsi) - lws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) { + lws_start_foreach_ll(struct lws_vhost *, v, + context->vhost_list) { if (v != vh && !v->being_destroyed && v->listen_port == vh->listen_port && @@ -1302,13 +1510,21 @@ lws_vhost_destroy1(struct lws_vhost *vh) continue; lws_close_free_wsi(wsi, - LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY + LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY, + "vh destroy" /* no protocol close */); n--; } } /* + * destroy any pending timed events + */ + + while (vh->timed_vh_protocol_list) + lws_timed_callback_remove(vh, vh->timed_vh_protocol_list); + + /* * let the protocols destroy the per-vhost protocol objects */ @@ -1316,7 +1532,7 @@ lws_vhost_destroy1(struct lws_vhost *vh) wsi.context = vh->context; wsi.vhost = vh; protocol = vh->protocols; - if (protocol) { + if (protocol && vh->created_vhost_protocols) { n = 0; while (n < vh->count_protocols) { wsi.protocol = protocol; @@ -1397,28 +1613,37 @@ lws_vhost_destroy2(struct lws_vhost *vh) lws_free(vh->protocol_vh_privs); lws_ssl_SSL_CTX_destroy(vh); lws_free(vh->same_vh_protocol_list); -#ifdef LWS_WITH_PLUGINS - if (LWS_LIBUV_ENABLED(context)) { - if (context->plugin_list) - lws_free((void *)vh->protocols); - } else -#endif - { - if (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS) - lws_free((void *)vh->protocols); - } -#ifdef LWS_WITH_PLUGINS -#ifndef LWS_NO_EXTENSIONS - if (context->plugin_extension_count) - lws_free((void *)vh->extensions); -#endif -#endif + if (context->plugin_list || + (context->options & LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) + lws_free((void *)vh->protocols); + + LWS_FOR_EVERY_AVAILABLE_ROLE_START(ar) + if (ar->destroy_vhost) + ar->destroy_vhost(vh); + LWS_FOR_EVERY_AVAILABLE_ROLE_END; + #ifdef LWS_WITH_ACCESS_LOG if (vh->log_fd != (int)LWS_INVALID_FILE) close(vh->log_fd); #endif +#if defined (LWS_WITH_TLS) + lws_free_set_NULL(vh->tls.alloc_cert_path); +#endif + +#if LWS_MAX_SMP > 1 + pthread_mutex_destroy(&vh->lock); +#endif + +#if defined(LWS_WITH_UNIX_SOCK) + if (LWS_UNIX_SOCK_ENABLED(context)) { + n = unlink(vh->iface); + if (n) + lwsl_info("Closing unix socket %s: errno %d\n", + vh->iface, errno); + } +#endif /* * although async event callbacks may still come for wsi handles with * pending close in the case of asycn event library like libuv, @@ -1439,7 +1664,8 @@ lws_check_deferred_free(struct lws_context *context, int force) lws_start_foreach_llp(struct lws_deferred_free **, pdf, context->deferred_free_list) { - if (now > (*pdf)->deadline || force) { + if (force || + lws_compare_time_t(context, now, (*pdf)->deadline) > 5) { df = *pdf; *pdf = df->next; /* finalize vh destruction */ @@ -1466,119 +1692,86 @@ lws_vhost_destroy(struct lws_vhost *vh) /* part 2 is deferred to allow all the handle closes to complete */ df->next = vh->context->deferred_free_list; - df->deadline = lws_now_secs() + 5; + df->deadline = lws_now_secs(); df->payload = vh; vh->context->deferred_free_list = df; } -LWS_VISIBLE void -lws_context_destroy(struct lws_context *context) -{ - struct lws_context_per_thread *pt; - struct lws_vhost *vh = NULL; - struct lws wsi; - int n, m; - - if (!context) { - lwsl_notice("%s: ctx %p\n", __func__, context); - return; - } - if (context->being_destroyed1) { - lwsl_notice("%s: ctx %p: already being destroyed\n", - __func__, context); - return; - } - - lwsl_info("%s: ctx %p\n", __func__, context); - - m = context->count_threads; - context->being_destroyed = 1; - context->being_destroyed1 = 1; - - memset(&wsi, 0, sizeof(wsi)); - wsi.context = context; - -#ifdef LWS_LATENCY - if (context->worst_latency_info[0]) - lwsl_notice("Worst latency: %s\n", context->worst_latency_info); -#endif - - while (m--) { - pt = &context->pt[m]; - - for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) { - struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd); - if (!wsi) - continue; - - lws_close_free_wsi(wsi, - LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY - /* no protocol close */); - n--; - } - lws_pt_mutex_destroy(pt); - } - - /* - * give all extensions a chance to clean up any per-context - * allocations they might have made - */ - - n = lws_ext_cb_all_exts(context, NULL, - LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT, NULL, 0); +/* + * When using an event loop, the context destruction is in three separate + * parts. This is to cover both internal and foreign event loops cleanly. + * + * - lws_context_destroy() simply starts a soft close of all wsi and + * related allocations. The event loop continues. + * + * As the closes complete in the event loop, reference counting is used + * to determine when everything is closed. It then calls + * lws_context_destroy2(). + * + * - lws_context_destroy2() cleans up the rest of the higher-level logical + * lws pieces like vhosts. If the loop was foreign, it then proceeds to + * lws_context_destroy3(). If it the loop is internal, it stops the + * internal loops and waits for lws_context_destroy() to be called again + * outside the event loop (since we cannot destroy the loop from + * within the loop). That will cause lws_context_destroy3() to run + * directly. + * + * - lws_context_destroy3() destroys any internal event loops and then + * destroys the context itself, setting what was info.pcontext to NULL. + */ - n = lws_ext_cb_all_exts(context, NULL, - LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT, NULL, 0); +/* + * destroy the actual context itself + */ - /* - * inform all the protocols that they are done and will have no more - * callbacks. - * - * We can't free things until after the event loop shuts down. - */ - if (context->protocol_init_done) - vh = context->vhost_list; - while (vh) { - struct lws_vhost *vhn = vh->vhost_next; - lws_vhost_destroy1(vh); - vh = vhn; - } +static void +lws_context_destroy3(struct lws_context *context) +{ + struct lws_context **pcontext_finalize = context->pcontext_finalize; + struct lws_context_per_thread *pt; + int n; for (n = 0; n < context->count_threads; n++) { pt = &context->pt[n]; - lws_libev_destroyloop(context, n); - lws_libuv_destroyloop(context, n); - lws_libevent_destroyloop(context, n); + if (context->event_loop_ops->destroy_pt) + context->event_loop_ops->destroy_pt(context, n); lws_free_set_NULL(context->pt[n].serv_buf); - while (pt->ah_list) - _lws_destroy_ah(pt, pt->ah_list); +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + while (pt->http.ah_list) + _lws_destroy_ah(pt, pt->http.ah_list); +#endif } - lws_plat_context_early_destroy(context); - if (context->pt[0].fds) - lws_free_set_NULL(context->pt[0].fds); + lws_free(context); + lwsl_info("%s: ctx %p freed\n", __func__, context); - if (!LWS_LIBUV_ENABLED(context)) - lws_context_destroy2(context); + if (pcontext_finalize) + *pcontext_finalize = NULL; } /* - * call the second one after the event loop has been shut down cleanly + * really start destroying things */ -LWS_VISIBLE void +void lws_context_destroy2(struct lws_context *context) { struct lws_vhost *vh = NULL, *vh1; #if defined(LWS_WITH_PEER_LIMITS) - uint32_t n; + uint32_t nu; #endif + int n; lwsl_info("%s: ctx %p\n", __func__, context); + context->being_destroyed2 = 1; + + if (context->pt[0].fds) + lws_free_set_NULL(context->pt[0].fds); + /* * free all the per-vhost allocations */ @@ -1603,9 +1796,9 @@ lws_context_destroy2(struct lws_context *context) lws_plat_context_late_destroy(context); #if defined(LWS_WITH_PEER_LIMITS) - for (n = 0; n < context->pl_hash_elements; n++) { + for (nu = 0; nu < context->pl_hash_elements; nu++) { lws_start_foreach_llp(struct lws_peer **, peer, - context->pl_hash_table[n]) { + context->pl_hash_table[nu]) { struct lws_peer *df = *peer; *peer = df->next; lws_free(df); @@ -1624,5 +1817,141 @@ lws_context_destroy2(struct lws_context *context) pthread_mutex_destroy(&context->lock); #endif - lws_free(context); + if (context->event_loop_ops->destroy_context2) + if (context->event_loop_ops->destroy_context2(context)) { + context->finalize_destroy_after_internal_loops_stopped = 1; + return; + } + + if (!context->pt[0].event_loop_foreign) + for (n = 0; n < context->count_threads; n++) + if (context->pt[n].inside_service) + return; + + lws_context_destroy3(context); +} + +/* + * Begin the context takedown + */ + +LWS_VISIBLE void +lws_context_destroy(struct lws_context *context) +{ + volatile struct lws_foreign_thread_pollfd *ftp, *next; + volatile struct lws_context_per_thread *vpt; + struct lws_context_per_thread *pt; + struct lws_vhost *vh = NULL; + struct lws wsi; + int n, m; + + if (!context) + return; + + if (context->finalize_destroy_after_internal_loops_stopped) { + if (context->event_loop_ops->destroy_context2) + context->event_loop_ops->destroy_context2(context); + + lws_context_destroy3(context); + + return; + } + + if (context->being_destroyed1) { + if (!context->being_destroyed2) { + lws_context_destroy2(context); + + return; + } + lwsl_info("%s: ctx %p: already being destroyed\n", + __func__, context); + + lws_context_destroy3(context); + return; + } + + lwsl_info("%s: ctx %p\n", __func__, context); + + m = context->count_threads; + context->being_destroyed = 1; + context->being_destroyed1 = 1; + context->requested_kill = 1; + + memset(&wsi, 0, sizeof(wsi)); + wsi.context = context; + +#ifdef LWS_LATENCY + if (context->worst_latency_info[0]) + lwsl_notice("Worst latency: %s\n", context->worst_latency_info); +#endif + + while (m--) { + pt = &context->pt[m]; + vpt = (volatile struct lws_context_per_thread *)pt; + + ftp = vpt->foreign_pfd_list; + while (ftp) { + next = ftp->next; + lws_free((void *)ftp); + ftp = next; + } + vpt->foreign_pfd_list = NULL; + + for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) { + struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd); + if (!wsi) + continue; + + if (wsi->event_pipe) + lws_destroy_event_pipe(wsi); + else + lws_close_free_wsi(wsi, + LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY, + "ctx destroy" + /* no protocol close */); + n--; + } + lws_pt_mutex_destroy(pt); + } + + /* + * inform all the protocols that they are done and will have no more + * callbacks. + * + * We can't free things until after the event loop shuts down. + */ + if (context->protocol_init_done) + vh = context->vhost_list; + while (vh) { + struct lws_vhost *vhn = vh->vhost_next; + lws_vhost_destroy1(vh); + vh = vhn; + } + + lws_plat_context_early_destroy(context); + + /* + * We face two different needs depending if foreign loop or not. + * + * 1) If foreign loop, we really want to advance the destroy_context() + * past here, and block only for libuv-style async close completion. + * + * 2a) If poll, and we exited by ourselves and are calling a final + * destroy_context() outside of any service already, we want to + * advance all the way in one step. + * + * 2b) If poll, and we are reacting to a SIGINT, service thread(s) may + * be in poll wait or servicing. We can't advance the + * destroy_context() to the point it's freeing things; we have to + * leave that for the final destroy_context() after the service + * thread(s) are finished calling for service. + */ + + if (context->event_loop_ops->destroy_context1) { + context->event_loop_ops->destroy_context1(context); + + return; + } + + lws_context_destroy2(context); } diff --git a/thirdparty/lws/libwebsockets.c b/thirdparty/libwebsockets/core/libwebsockets.c index 8fe0854041..0da02b17e4 100644 --- a/thirdparty/lws/libwebsockets.c +++ b/thirdparty/libwebsockets/core/libwebsockets.c @@ -19,7 +19,7 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" #ifdef LWS_HAVE_SYS_TYPES_H #include <sys/types.h> @@ -27,6 +27,7 @@ #ifdef LWS_WITH_IPV6 #if defined(WIN32) || defined(_WIN32) +#include <wincrypt.h> #include <Iphlpapi.h> #else #include <net/if.h> @@ -57,16 +58,41 @@ static const char * const log_level_names[] = { }; #endif -void -lws_free_wsi(struct lws *wsi) +#if defined (_DEBUG) +void lwsi_set_role(struct lws *wsi, lws_wsi_state_t role) { - struct lws_context_per_thread *pt; - struct allocated_headers *ah; + wsi->wsistate = (wsi->wsistate & (~LWSI_ROLE_MASK)) | role; + + lwsl_debug("lwsi_set_role(%p, 0x%x)\n", wsi, wsi->wsistate); +} + +void lwsi_set_state(struct lws *wsi, lws_wsi_state_t lrs) +{ + wsi->wsistate = (wsi->wsistate & (~LRS_MASK)) | lrs; + lwsl_debug("lwsi_set_state(%p, 0x%x)\n", wsi, wsi->wsistate); +} +#endif + +signed char char_to_hex(const char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + + return -1; +} + +void +__lws_free_wsi(struct lws *wsi) +{ if (!wsi) return; - - pt = &wsi->context->pt[(int)wsi->tsi]; /* * Protocol user data may be allocated either internally by lws @@ -76,51 +102,32 @@ lws_free_wsi(struct lws *wsi) wsi->user_space && !wsi->user_space_externally_allocated) lws_free(wsi->user_space); - lws_free_set_NULL(wsi->rxflow_buffer); + lws_buflist_destroy_all_segments(&wsi->buflist); lws_free_set_NULL(wsi->trunc_alloc); + lws_free_set_NULL(wsi->udp); - /* we may not have an ah, but may be on the waiting list... */ - lwsl_info("ah det due to close\n"); - /* we're closing, losing some rx is OK */ - lws_header_table_force_to_detachable_state(wsi); - lws_header_table_detach(wsi, 0); - - if (wsi->vhost->lserv_wsi == wsi) + if (wsi->vhost && wsi->vhost->lserv_wsi == wsi) wsi->vhost->lserv_wsi = NULL; - lws_pt_lock(pt); - ah = pt->ah_list; - while (ah) { - if (ah->in_use && ah->wsi == wsi) { - lwsl_err("%s: ah leak: wsi %p\n", __func__, wsi); - ah->in_use = 0; - ah->wsi = NULL; - pt->ah_count_in_use--; - break; - } - ah = ah->next; - } + // lws_peer_dump_from_wsi(wsi); + + if (wsi->role_ops->destroy_role) + wsi->role_ops->destroy_role(wsi); #if defined(LWS_WITH_PEER_LIMITS) lws_peer_track_wsi_close(wsi->context, wsi->peer); wsi->peer = NULL; #endif -#if defined(LWS_WITH_HTTP2) - if (wsi->upgraded_to_http2 || wsi->http2_substream) { - lws_hpack_destroy_dynamic_header(wsi); + /* since we will destroy the wsi, make absolutely sure now */ - if (wsi->u.h2.h2n) - lws_free_set_NULL(wsi->u.h2.h2n); - } +#if defined(LWS_WITH_OPENSSL) + __lws_ssl_remove_wsi_from_buffered_list(wsi); #endif + __lws_remove_from_timeout_list(wsi); - lws_pt_unlock(pt); - - /* since we will destroy the wsi, make absolutely sure now */ - - lws_ssl_remove_wsi_from_buffered_list(wsi); - lws_remove_from_timeout_list(wsi); + if (wsi->context->event_loop_ops->destroy_wsi) + wsi->context->event_loop_ops->destroy_wsi(wsi); wsi->context->count_wsi_allocated--; lwsl_debug("%s: %p, remaining wsi %d\n", __func__, wsi, @@ -130,63 +137,301 @@ lws_free_wsi(struct lws *wsi) } void -lws_remove_from_timeout_list(struct lws *wsi) +lws_dll_add_front(struct lws_dll *d, struct lws_dll *phead) { - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + if (d->prev) + return; + + /* our next guy is current first guy */ + d->next = phead->next; + /* if there is a next guy, set his prev ptr to our next ptr */ + if (d->next) + d->next->prev = d; + /* our prev ptr is first ptr */ + d->prev = phead; + /* set the first guy to be us */ + phead->next = d; +} + +/* situation is: + * + * HEAD: struct lws_dll * = &entry1 + * + * Entry 1: struct lws_dll .pprev = &HEAD , .next = Entry 2 + * Entry 2: struct lws_dll .pprev = &entry1 , .next = &entry2 + * Entry 3: struct lws_dll .pprev = &entry2 , .next = NULL + * + * Delete Entry1: + * + * - HEAD = &entry2 + * - Entry2: .pprev = &HEAD, .next = &entry3 + * - Entry3: .pprev = &entry2, .next = NULL + * + * Delete Entry2: + * + * - HEAD = &entry1 + * - Entry1: .pprev = &HEAD, .next = &entry3 + * - Entry3: .pprev = &entry1, .next = NULL + * + * Delete Entry3: + * + * - HEAD = &entry1 + * - Entry1: .pprev = &HEAD, .next = &entry2 + * - Entry2: .pprev = &entry1, .next = NULL + * + */ - if (!wsi->timeout_list_prev) /* ie, not part of the list */ +void +lws_dll_remove(struct lws_dll *d) +{ + if (!d->prev) /* ie, not part of the list */ return; - lws_pt_lock(pt); + /* + * remove us + * + * USp <-> us <-> USn --> USp <-> USn + */ + /* if we have a next guy, set his prev to our prev */ - if (wsi->timeout_list) - wsi->timeout_list->timeout_list_prev = wsi->timeout_list_prev; + if (d->next) + d->next->prev = d->prev; + /* set our prev guy to our next guy instead of us */ - *wsi->timeout_list_prev = wsi->timeout_list; + if (d->prev) + d->prev->next = d->next; /* we're out of the list, we should not point anywhere any more */ - wsi->timeout_list_prev = NULL; - wsi->timeout_list = NULL; + d->prev = NULL; + d->next = NULL; +} + +void +__lws_remove_from_timeout_list(struct lws *wsi) +{ + lws_dll_lws_remove(&wsi->dll_timeout); +} + +void +lws_remove_from_timeout_list(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + lws_pt_lock(pt, __func__); + __lws_remove_from_timeout_list(wsi); lws_pt_unlock(pt); } +void +lws_dll_dump(struct lws_dll_lws *head, const char *title) +{ + int n = 0; + + (void)n; + lwsl_notice("%s: %s (head.next %p)\n", __func__, title, head->next); + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, head->next) { + struct lws *wsi = lws_container_of(d, struct lws, dll_hrtimer); + + (void)wsi; + + lwsl_notice(" %d: wsi %p: %llu\n", n++, wsi, + (unsigned long long)wsi->pending_timer); + } lws_end_foreach_dll_safe(d, d1); +} + +void +__lws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct lws_dll_lws *dd = &pt->dll_head_hrtimer; + struct timeval now; + struct lws *wsi1; + int bef = 0; + + lws_dll_lws_remove(&wsi->dll_hrtimer); + + if (usecs == LWS_SET_TIMER_USEC_CANCEL) + return; + + gettimeofday(&now, NULL); + wsi->pending_timer = ((now.tv_sec * 1000000ll) + now.tv_usec) + usecs; + + /* + * we sort the hrtimer list with the earliest timeout first + */ + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + pt->dll_head_hrtimer.next) { + dd = d; + wsi1 = lws_container_of(d, struct lws, dll_hrtimer); + + if (wsi1->pending_timer >= wsi->pending_timer) { + /* d, dprev's next, is >= our time */ + bef = 1; + break; + } + } lws_end_foreach_dll_safe(d, d1); + + if (bef) { + /* + * we go before dd + * DDp <-> DD <-> DDn --> DDp <-> us <-> DD <-> DDn + */ + /* we point forward to dd */ + wsi->dll_hrtimer.next = dd; + /* we point back to what dd used to point back to */ + wsi->dll_hrtimer.prev = dd->prev; + /* DDp points forward to us now */ + dd->prev->next = &wsi->dll_hrtimer; + /* DD points back to us now */ + dd->prev = &wsi->dll_hrtimer; + } else { + /* + * we go after dd + * DDp <-> DD <-> DDn --> DDp <-> DD <-> us <-> DDn + */ + /* we point forward to what dd used to point forward to */ + wsi->dll_hrtimer.next = dd->next; + /* we point back to dd */ + wsi->dll_hrtimer.prev = dd; + /* DDn points back to us */ + if (dd->next) + dd->next->prev = &wsi->dll_hrtimer; + /* DD points forward to us */ + dd->next = &wsi->dll_hrtimer; + } + +// lws_dll_dump(&pt->dll_head_hrtimer, "after set_timer_usec"); +} + LWS_VISIBLE void -lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs) +lws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs) +{ + __lws_set_timer_usecs(wsi, usecs); +} + +lws_usec_t +__lws_hrtimer_service(struct lws_context_per_thread *pt) +{ + struct timeval now; + struct lws *wsi; + lws_usec_t t; + + gettimeofday(&now, NULL); + t = (now.tv_sec * 1000000ll) + now.tv_usec; + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + pt->dll_head_hrtimer.next) { + wsi = lws_container_of(d, struct lws, dll_hrtimer); + + /* + * if we met one in the future, we are done, because the list + * is sorted by time in the future. + */ + if (wsi->pending_timer > t) + break; + + lws_set_timer_usecs(wsi, LWS_SET_TIMER_USEC_CANCEL); + + /* it's time for the timer to be serviced */ + + if (wsi->protocol && + wsi->protocol->callback(wsi, LWS_CALLBACK_TIMER, + wsi->user_space, NULL, 0)) + __lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "timer cb errored"); + } lws_end_foreach_dll_safe(d, d1); + + /* return an estimate how many us until next timer hit */ + + if (!pt->dll_head_hrtimer.next) + return LWS_HRTIMER_NOWAIT; + + wsi = lws_container_of(pt->dll_head_hrtimer.next, struct lws, dll_hrtimer); + + gettimeofday(&now, NULL); + t = (now.tv_sec * 1000000ll) + now.tv_usec; + + if (wsi->pending_timer < t) + return 0; + + return wsi->pending_timer - t; +} + +void +__lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; time_t now; + time(&now); + + lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs); + wsi->pending_timeout_limit = secs; + wsi->pending_timeout_set = now; + wsi->pending_timeout = reason; + + if (!reason) + lws_dll_lws_remove(&wsi->dll_timeout); + else + lws_dll_lws_add_front(&wsi->dll_timeout, &pt->dll_head_timeout); +} + +LWS_VISIBLE void +lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + if (secs == LWS_TO_KILL_SYNC) { lws_remove_from_timeout_list(wsi); lwsl_debug("synchronously killing %p\n", wsi); - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "to sync kill"); return; } - lws_pt_lock(pt); + if (secs == LWS_TO_KILL_ASYNC) + secs = 0; - time(&now); + lws_pt_lock(pt, __func__); + __lws_set_timeout(wsi, reason, secs); + lws_pt_unlock(pt); +} - if (reason && !wsi->timeout_list_prev) { - /* our next guy is current first guy */ - wsi->timeout_list = pt->timeout_list; - /* if there is a next guy, set his prev ptr to our next ptr */ - if (wsi->timeout_list) - wsi->timeout_list->timeout_list_prev = &wsi->timeout_list; - /* our prev ptr is first ptr */ - wsi->timeout_list_prev = &pt->timeout_list; - /* set the first guy to be us */ - *wsi->timeout_list_prev = wsi; - } +int +lws_timed_callback_remove(struct lws_vhost *vh, struct lws_timed_vh_protocol *p) +{ + lws_start_foreach_llp(struct lws_timed_vh_protocol **, pt, + vh->timed_vh_protocol_list) { + if (*pt == p) { + *pt = p->next; + lws_free(p); - lwsl_debug("%s: %p: %d secs\n", __func__, wsi, secs); - wsi->pending_timeout_limit = now + secs; - wsi->pending_timeout = reason; + return 0; + } + } lws_end_foreach_llp(pt, next); - lws_pt_unlock(pt); + return 1; +} - if (!reason) - lws_remove_from_timeout_list(wsi); +LWS_VISIBLE LWS_EXTERN int +lws_timed_callback_vh_protocol(struct lws_vhost *vh, const struct lws_protocols *prot, + int reason, int secs) +{ + struct lws_timed_vh_protocol *p = (struct lws_timed_vh_protocol *) + lws_malloc(sizeof(*p), "timed_vh"); + + if (!p) + return 1; + + p->protocol = prot; + p->reason = reason; + p->time = lws_now_secs() + secs; + p->next = vh->timed_vh_protocol_list; + + vh->timed_vh_protocol_list = p; + + return 0; } static void @@ -229,9 +474,11 @@ lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p) // return 0; const struct lws_protocols *vp = wsi->vhost->protocols, *vpo; - if (wsi->protocol) + if (wsi->protocol && wsi->protocol_bind_balance) { wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL, wsi->user_space, NULL, 0); + wsi->protocol_bind_balance = 0; + } if (!wsi->user_space_externally_allocated) lws_free_set_NULL(wsi->user_space); @@ -245,7 +492,7 @@ lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p) return 1; if (p > vp && p < &vp[wsi->vhost->count_protocols]) - lws_same_vh_protocol_insert(wsi, p - vp); + lws_same_vh_protocol_insert(wsi, (int)(p - vp)); else { int n = wsi->vhost->count_protocols; int hit = 0; @@ -255,7 +502,7 @@ lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p) while (n--) { if (p->name && vp->name && !strcmp(p->name, vp->name)) { hit = 1; - lws_same_vh_protocol_insert(wsi, vp - vpo); + lws_same_vh_protocol_insert(wsi, (int)(vp - vpo)); break; } vp++; @@ -269,42 +516,65 @@ lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p) wsi->user_space, NULL, 0)) return 1; + wsi->protocol_bind_balance = 1; + return 0; } void -lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason) +__lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason, const char *caller) { struct lws_context_per_thread *pt; struct lws *wsi1, *wsi2; struct lws_context *context; - struct lws_tokens eff_buf; - int n, m, ret; + int n; - lwsl_debug("%s: %p\n", __func__, wsi); + lwsl_info("%s: %p: caller: %s\n", __func__, wsi, caller); if (!wsi) return; lws_access_log(wsi); -#if defined(LWS_WITH_ESP8266) - if (wsi->premature_rx) - lws_free(wsi->premature_rx); - - if (wsi->pending_send_completion && !wsi->close_is_pending_send_completion) { - lwsl_notice("delaying close\n"); - wsi->close_is_pending_send_completion = 1; - return; - } -#endif - - /* we're closing, losing some rx is OK */ - lws_header_table_force_to_detachable_state(wsi); context = wsi->context; pt = &context->pt[(int)wsi->tsi]; lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_CLOSE, 1); +#if !defined(LWS_NO_CLIENT) + + lws_free_set_NULL(wsi->client_hostname_copy); + /* we are no longer an active client connection that can piggyback */ + lws_dll_lws_remove(&wsi->dll_active_client_conns); + + /* + * if we have wsi in our transaction queue, if we are closing we + * must go through and close all those first + */ + if (wsi->vhost) { + if ((int)reason != -1) + lws_vhost_lock(wsi->vhost); + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + wsi->dll_client_transaction_queue_head.next) { + struct lws *w = lws_container_of(d, struct lws, + dll_client_transaction_queue); + + __lws_close_free_wsi(w, -1, "trans q leader closing"); + } lws_end_foreach_dll_safe(d, d1); + + /* + * !!! If we are closing, but we have pending pipelined transaction + * results we already sent headers for, that's going to destroy sync + * for HTTP/1 and leave H2 stream with no live swsi. + * + * However this is normal if we are being closed because the transaction + * queue leader is closing. + */ + lws_dll_lws_remove(&wsi->dll_client_transaction_queue); + if ((int)reason !=-1) + lws_vhost_unlock(wsi->vhost); + } +#endif + /* if we have children, close them first */ if (wsi->child_list) { wsi2 = wsi->child_list; @@ -313,302 +583,146 @@ lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason) wsi2->parent = NULL; /* stop it doing shutdown processing */ wsi2->socket_is_permanently_unusable = 1; - lws_close_free_wsi(wsi2, reason); + __lws_close_free_wsi(wsi2, reason, "general child recurse"); wsi2 = wsi1; } wsi->child_list = NULL; } -#if defined(LWS_WITH_HTTP2) - - if (wsi->u.h2.parent_wsi) { - lwsl_info(" wsi: %p, his parent %p: siblings:\n", wsi, wsi->u.h2.parent_wsi); - lws_start_foreach_llp(struct lws **, w, wsi->u.h2.parent_wsi->u.h2.child_list) { - lwsl_info(" \\---- child %p\n", *w); - } lws_end_foreach_llp(w, u.h2.sibling_list); - } - - if (wsi->upgraded_to_http2 || wsi->http2_substream) { - lwsl_info("closing %p: parent %p\n", wsi, wsi->u.h2.parent_wsi); - - if (wsi->u.h2.child_list) { - lwsl_info(" parent %p: closing children: list:\n", wsi); - lws_start_foreach_llp(struct lws **, w, wsi->u.h2.child_list) { - lwsl_info(" \\---- child %p\n", *w); - } lws_end_foreach_llp(w, u.h2.sibling_list); - /* trigger closing of all of our http2 children first */ - lws_start_foreach_llp(struct lws **, w, wsi->u.h2.child_list) { - lwsl_info(" closing child %p\n", *w); - /* disconnect from siblings */ - wsi2 = (*w)->u.h2.sibling_list; - (*w)->u.h2.sibling_list = NULL; - (*w)->socket_is_permanently_unusable = 1; - lws_close_free_wsi(*w, reason); - *w = wsi2; - continue; - } lws_end_foreach_llp(w, u.h2.sibling_list); - } - } - - if (wsi->upgraded_to_http2) { - /* remove pps */ - struct lws_h2_protocol_send *w = wsi->u.h2.h2n->pps, *w1; - while (w) { - w1 = wsi->u.h2.h2n->pps->next; - free(w); - w = w1; - } - wsi->u.h2.h2n->pps = NULL; - } - - if (wsi->http2_substream && wsi->u.h2.parent_wsi) { - lwsl_info(" %p: disentangling from siblings\n", wsi); - lws_start_foreach_llp(struct lws **, w, - wsi->u.h2.parent_wsi->u.h2.child_list) { - /* disconnect from siblings */ - if (*w == wsi) { - wsi2 = (*w)->u.h2.sibling_list; - (*w)->u.h2.sibling_list = NULL; - *w = wsi2; - lwsl_info(" %p disentangled from sibling %p\n", wsi, wsi2); - break; - } - } lws_end_foreach_llp(w, u.h2.sibling_list); - wsi->u.h2.parent_wsi->u.h2.child_count--; - wsi->u.h2.parent_wsi = NULL; - if (wsi->u.h2.pending_status_body) - lws_free_set_NULL(wsi->u.h2.pending_status_body); - } - - if (wsi->upgraded_to_http2 && wsi->u.h2.h2n && - wsi->u.h2.h2n->rx_scratch) - lws_free_set_NULL(wsi->u.h2.h2n->rx_scratch); -#endif - - if (wsi->mode == LWSCM_RAW_FILEDESC) { + if (wsi->role_ops == &role_ops_raw_file) { lws_remove_child_from_any_parent(wsi); - remove_wsi_socket_from_fds(wsi); - wsi->protocol->callback(wsi, - LWS_CALLBACK_RAW_CLOSE_FILE, + __remove_wsi_socket_from_fds(wsi); + wsi->protocol->callback(wsi, wsi->role_ops->close_cb[0], wsi->user_space, NULL, 0); goto async_close; } + wsi->wsistate_pre_close = wsi->wsistate; + #ifdef LWS_WITH_CGI - if (wsi->mode == LWSCM_CGI) { + if (wsi->role_ops == &role_ops_cgi) { /* we are not a network connection, but a handler for CGI io */ - if (wsi->parent && wsi->parent->cgi) { + if (wsi->parent && wsi->parent->http.cgi) { if (wsi->cgi_channel == LWS_STDOUT) lws_cgi_remove_and_kill(wsi->parent); /* end the binding between us and master */ - wsi->parent->cgi->stdwsi[(int)wsi->cgi_channel] = NULL; + wsi->parent->http.cgi->stdwsi[(int)wsi->cgi_channel] = NULL; } wsi->socket_is_permanently_unusable = 1; goto just_kill_connection; } - if (wsi->cgi) + if (wsi->http.cgi) lws_cgi_remove_and_kill(wsi); #endif #if !defined(LWS_NO_CLIENT) - if (wsi->mode == LWSCM_HTTP_CLIENT || - wsi->mode == LWSCM_WSCL_WAITING_CONNECT || - wsi->mode == LWSCM_WSCL_WAITING_PROXY_REPLY || - wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE || - wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE2 || - wsi->mode == LWSCM_WSCL_WAITING_SSL || - wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY || - wsi->mode == LWSCM_WSCL_WAITING_EXTENSION_CONNECT || - wsi->mode == LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY || - wsi->mode == LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY || - wsi->mode == LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY) - if (wsi->u.hdr.stash) - lws_free_set_NULL(wsi->u.hdr.stash); -#endif - - if (wsi->mode == LWSCM_RAW) { - wsi->protocol->callback(wsi, - LWS_CALLBACK_RAW_CLOSE, wsi->user_space, NULL, 0); + lws_client_stash_destroy(wsi); +#endif + + if (wsi->role_ops == &role_ops_raw_skt) { wsi->socket_is_permanently_unusable = 1; goto just_kill_connection; } +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + if (lwsi_role_http(wsi) && lwsi_role_server(wsi) && + wsi->http.fop_fd != NULL) + lws_vfs_file_close(&wsi->http.fop_fd); +#endif + + if (lwsi_state(wsi) == LRS_DEAD_SOCKET) + return; - if ((wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED || - wsi->mode == LWSCM_HTTP2_SERVING) && - wsi->u.http.fop_fd != NULL) { - lws_vfs_file_close(&wsi->u.http.fop_fd); - wsi->vhost->protocols->callback(wsi, - LWS_CALLBACK_CLOSED_HTTP, wsi->user_space, NULL, 0); - wsi->told_user_closed = 1; - } if (wsi->socket_is_permanently_unusable || reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY || - wsi->state == LWSS_SHUTDOWN) + lwsi_state(wsi) == LRS_SHUTDOWN) goto just_kill_connection; - wsi->state_pre_close = wsi->state; - - switch (wsi->state_pre_close) { - case LWSS_DEAD_SOCKET: + switch (lwsi_state_PRE_CLOSE(wsi)) { + case LRS_DEAD_SOCKET: return; /* we tried the polite way... */ - case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION: - case LWSS_AWAITING_CLOSE_ACK: + case LRS_WAITING_TO_SEND_CLOSE: + case LRS_AWAITING_CLOSE_ACK: + case LRS_RETURNED_CLOSE: goto just_kill_connection; - case LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE: + case LRS_FLUSHING_BEFORE_CLOSE: if (wsi->trunc_len) { lws_callback_on_writable(wsi); return; } - lwsl_info("%p: end FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi); + lwsl_info("%p: end LRS_FLUSHING_BEFORE_CLOSE\n", wsi); goto just_kill_connection; default: if (wsi->trunc_len) { - lwsl_info("%p: start FLUSHING_STORED_SEND_BEFORE_CLOSE\n", wsi); - wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE; - lws_set_timeout(wsi, PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5); + lwsl_info("%p: LRS_FLUSHING_BEFORE_CLOSE\n", wsi); + lwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE); + __lws_set_timeout(wsi, + PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE, 5); return; } break; } - if (wsi->mode == LWSCM_WSCL_WAITING_CONNECT || - wsi->mode == LWSCM_WSCL_ISSUE_HANDSHAKE) + if (lwsi_state(wsi) == LRS_WAITING_CONNECT || + lwsi_state(wsi) == LRS_H1C_ISSUE_HANDSHAKE) goto just_kill_connection; - if (!wsi->told_user_closed && - (wsi->mode == LWSCM_HTTP_SERVING || - wsi->mode == LWSCM_HTTP2_SERVING)) { - if (wsi->user_space) - wsi->vhost->protocols->callback(wsi, + if (!wsi->told_user_closed && lwsi_role_http(wsi) && + lwsi_role_server(wsi)) { + if (wsi->user_space && wsi->protocol && + wsi->protocol_bind_balance) { + wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL, wsi->user_space, NULL, 0); - wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP, - wsi->user_space, NULL, 0); - wsi->told_user_closed = 1; - } - - /* - * are his extensions okay with him closing? Eg he might be a mux - * parent and just his ch1 aspect is closing? - */ - - if (lws_ext_cb_active(wsi, LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE, NULL, 0) > 0) { - lwsl_ext("extension vetoed close\n"); - return; - } - - /* - * flush any tx pending from extensions, since we may send close packet - * if there are problems with send, just nuke the connection - */ - do { - ret = 0; - eff_buf.token = NULL; - eff_buf.token_len = 0; - - /* show every extension the new incoming data */ - - m = lws_ext_cb_active(wsi, - LWS_EXT_CB_FLUSH_PENDING_TX, &eff_buf, 0); - if (m < 0) { - lwsl_ext("Extension reports fatal error\n"); - goto just_kill_connection; + wsi->protocol_bind_balance = 0; } - if (m) - /* - * at least one extension told us he has more - * to spill, so we will go around again after - */ - ret = 1; - - /* assuming they left us something to send, send it */ - - if (eff_buf.token_len) - if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token, - eff_buf.token_len) != - eff_buf.token_len) { - lwsl_debug("close: ext spill failed\n"); - goto just_kill_connection; - } - } while (ret); + } /* * signal we are closing, lws_write will * add any necessary version-specific stuff. If the write fails, * no worries we are closing anyway. If we didn't initiate this * close, then our state has been changed to - * LWSS_RETURNED_CLOSE_ALREADY and we will skip this. + * LRS_RETURNED_CLOSE and we will skip this. * * Likewise if it's a second call to close this connection after we * sent the close indication to the peer already, we are in state - * LWSS_AWAITING_CLOSE_ACK and will skip doing this a second time. + * LRS_AWAITING_CLOSE_ACK and will skip doing this a second time. */ - if (wsi->state_pre_close == LWSS_ESTABLISHED && - (wsi->u.ws.close_in_ping_buffer_len || /* already a reason */ - (reason != LWS_CLOSE_STATUS_NOSTATUS && - (reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)))) { - lwsl_debug("sending close indication...\n"); - - /* if no prepared close reason, use 1000 and no aux data */ - if (!wsi->u.ws.close_in_ping_buffer_len) { - wsi->u.ws.close_in_ping_buffer_len = 2; - wsi->u.ws.ping_payload_buf[LWS_PRE] = - (reason >> 8) & 0xff; - wsi->u.ws.ping_payload_buf[LWS_PRE + 1] = - reason & 0xff; - } - -#if defined (LWS_WITH_ESP8266) - wsi->close_is_pending_send_completion = 1; -#endif - - lwsl_debug("waiting for chance to send close\n"); - wsi->waiting_to_send_close_frame = 1; - wsi->state = LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION; - lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 2); - lws_callback_on_writable(wsi); - + if (wsi->role_ops->close_via_role_protocol && + wsi->role_ops->close_via_role_protocol(wsi, reason)) return; - } just_kill_connection: + if (wsi->role_ops->close_kill_connection) + wsi->role_ops->close_kill_connection(wsi, reason); + lws_remove_child_from_any_parent(wsi); n = 0; - if (!wsi->told_user_closed && wsi->user_space) { - lwsl_debug("%s: %p: DROP_PROTOCOL %s\n", __func__, wsi, + if (!wsi->told_user_closed && wsi->user_space && + wsi->protocol_bind_balance) { + lwsl_debug("%s: %p: DROP_PROTOCOL %s\n", __func__, wsi, wsi->protocol->name); - wsi->protocol->callback(wsi, - LWS_CALLBACK_HTTP_DROP_PROTOCOL, + wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL, wsi->user_space, NULL, 0); + wsi->protocol_bind_balance = 0; } - if ((wsi->mode == LWSCM_WSCL_WAITING_SERVER_REPLY || - wsi->mode == LWSCM_WSCL_WAITING_CONNECT) && - !wsi->already_did_cce) { - wsi->vhost->protocols[0].callback(wsi, - LWS_CALLBACK_CLIENT_CONNECTION_ERROR, + if ((lwsi_state(wsi) == LRS_WAITING_SERVER_REPLY || + lwsi_state(wsi) == LRS_WAITING_CONNECT) && !wsi->already_did_cce) + wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); - } - if (wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) { - wsi->vhost->protocols[0].callback(wsi, - LWS_CALLBACK_CLOSED_CLIENT_HTTP, - wsi->user_space, NULL, 0); - wsi->told_user_closed = 1; - } - - -#if LWS_POSIX /* * Testing with ab shows that we have to stage the socket close when * the system is under stress... shutdown any further TX, change the @@ -616,55 +730,38 @@ just_kill_connection: * for the POLLIN to show a zero-size rx before coming back and doing * the actual close. */ - if (wsi->mode != LWSCM_RAW && - !(wsi->mode & LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP) && - wsi->state != LWSS_SHUTDOWN && - wsi->state != LWSS_CLIENT_UNCONNECTED && + if (wsi->role_ops != &role_ops_raw_skt && !lwsi_role_client(wsi) && + lwsi_state(wsi) != LRS_SHUTDOWN && + lwsi_state(wsi) != LRS_UNCONNECTED && reason != LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY && !wsi->socket_is_permanently_unusable) { -#ifdef LWS_OPENSSL_SUPPORT - if (lws_is_ssl(wsi) && wsi->ssl) { - n = SSL_shutdown(wsi->ssl); - /* - * If finished the SSL shutdown, then do socket - * shutdown, else need to retry SSL shutdown - */ - switch (n) { - case 0: - lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN); - break; - case 1: - n = shutdown(wsi->desc.sockfd, SHUT_WR); - break; - default: - if (SSL_want_read(wsi->ssl)) { - lws_change_pollfd(wsi, 0, LWS_POLLIN); - n = 0; - break; - } - if (SSL_want_write(wsi->ssl)) { - lws_change_pollfd(wsi, 0, LWS_POLLOUT); - n = 0; - break; - } - n = shutdown(wsi->desc.sockfd, SHUT_WR); - break; - } - } else + +#if defined(LWS_WITH_TLS) + if (lws_is_ssl(wsi) && wsi->tls.ssl) { + n = 0; + switch (__lws_tls_shutdown(wsi)) { + case LWS_SSL_CAPABLE_DONE: + case LWS_SSL_CAPABLE_ERROR: + case LWS_SSL_CAPABLE_MORE_SERVICE_READ: + case LWS_SSL_CAPABLE_MORE_SERVICE_WRITE: + case LWS_SSL_CAPABLE_MORE_SERVICE: + break; + } + } else #endif { - lwsl_info("%s: shutdown conn: %p (sock %d, state %d)\n", + lwsl_info("%s: shutdown conn: %p (sock %d, state 0x%x)\n", __func__, wsi, (int)(long)wsi->desc.sockfd, - wsi->state); + lwsi_state(wsi)); if (!wsi->socket_is_permanently_unusable && - lws_sockfd_valid(wsi->desc.sockfd)) { + lws_socket_is_valid(wsi->desc.sockfd)) { wsi->socket_is_permanently_unusable = 1; n = shutdown(wsi->desc.sockfd, SHUT_WR); } } if (n) - lwsl_debug("closing: shutdown (state %d) ret %d\n", - wsi->state, LWS_ERRNO); + lwsl_debug("closing: shutdown (state 0x%x) ret %d\n", + lwsi_state(wsi), LWS_ERRNO); /* * This causes problems on WINCE / ESP32 with disconnection @@ -673,199 +770,272 @@ just_kill_connection: #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP32) /* libuv: no event available to guarantee completion */ if (!wsi->socket_is_permanently_unusable && - lws_sockfd_valid(wsi->desc.sockfd) && - !LWS_LIBUV_ENABLED(context)) { - lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN); - wsi->state = LWSS_SHUTDOWN; - lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH, - context->timeout_secs); + lws_socket_is_valid(wsi->desc.sockfd) && + lwsi_state(wsi) != LRS_SHUTDOWN && + context->event_loop_ops->periodic_events_available) { + __lws_change_pollfd(wsi, LWS_POLLOUT, LWS_POLLIN); + lwsi_set_state(wsi, LRS_SHUTDOWN); + __lws_set_timeout(wsi, PENDING_TIMEOUT_SHUTDOWN_FLUSH, + context->timeout_secs); return; } #endif } -#endif lwsl_debug("%s: real just_kill_connection: %p (sockfd %d)\n", __func__, wsi, wsi->desc.sockfd); #ifdef LWS_WITH_HTTP_PROXY - if (wsi->rw) { - lws_rewrite_destroy(wsi->rw); - wsi->rw = NULL; + if (wsi->http.rw) { + lws_rewrite_destroy(wsi->http.rw); + wsi->http.rw = NULL; } #endif /* * we won't be servicing or receiving anything further from this guy * delete socket from the internal poll list if still present */ - lws_ssl_remove_wsi_from_buffered_list(wsi); - lws_remove_from_timeout_list(wsi); + __lws_ssl_remove_wsi_from_buffered_list(wsi); + __lws_remove_from_timeout_list(wsi); + lws_dll_lws_remove(&wsi->dll_hrtimer); + + /* don't repeat event loop stuff */ + if (wsi->told_event_loop_closed) + return; /* checking return redundant since we anyway close */ if (wsi->desc.sockfd != LWS_SOCK_INVALID) - remove_wsi_socket_from_fds(wsi); + __remove_wsi_socket_from_fds(wsi); else lws_same_vh_protocol_remove(wsi); -#if defined(LWS_WITH_ESP8266) - espconn_disconnect(wsi->desc.sockfd); -#endif - - wsi->state = LWSS_DEAD_SOCKET; - - lws_free_set_NULL(wsi->rxflow_buffer); - if (wsi->state_pre_close == LWSS_ESTABLISHED || - wsi->mode == LWSCM_WS_SERVING || - wsi->mode == LWSCM_WS_CLIENT) { - - if (wsi->u.ws.rx_draining_ext) { - struct lws **w = &pt->rx_draining_ext_list; - - wsi->u.ws.rx_draining_ext = 0; - /* remove us from context draining ext list */ - while (*w) { - if (*w == wsi) { - *w = wsi->u.ws.rx_draining_ext_list; - break; - } - w = &((*w)->u.ws.rx_draining_ext_list); - } - wsi->u.ws.rx_draining_ext_list = NULL; - } - - if (wsi->u.ws.tx_draining_ext) { - struct lws **w = &pt->tx_draining_ext_list; - - wsi->u.ws.tx_draining_ext = 0; - /* remove us from context draining ext list */ - while (*w) { - if (*w == wsi) { - *w = wsi->u.ws.tx_draining_ext_list; - break; - } - w = &((*w)->u.ws.tx_draining_ext_list); - } - wsi->u.ws.tx_draining_ext_list = NULL; - } - lws_free_set_NULL(wsi->u.ws.rx_ubuf); + lwsi_set_state(wsi, LRS_DEAD_SOCKET); + lws_buflist_destroy_all_segments(&wsi->buflist); + lws_dll_lws_remove(&wsi->dll_buflist); - if (wsi->trunc_alloc) - /* not going to be completed... nuke it */ - lws_free_set_NULL(wsi->trunc_alloc); - - wsi->u.ws.ping_payload_len = 0; - wsi->u.ws.ping_pending_flag = 0; - } + if (wsi->role_ops->close_role) + wsi->role_ops->close_role(pt, wsi); /* tell the user it's all over for this guy */ - if (!wsi->told_user_closed && - wsi->mode != LWSCM_RAW && wsi->protocol && - wsi->protocol->callback && - (wsi->state_pre_close == LWSS_ESTABLISHED || - wsi->state_pre_close == LWSS_HTTP2_ESTABLISHED || - wsi->state_pre_close == LWSS_HTTP_BODY || - wsi->state_pre_close == LWSS_HTTP || - wsi->state_pre_close == LWSS_RETURNED_CLOSE_ALREADY || - wsi->state_pre_close == LWSS_AWAITING_CLOSE_ACK || - wsi->state_pre_close == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION || - wsi->state_pre_close == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE || - (wsi->mode == LWSCM_WS_CLIENT && wsi->state_pre_close == LWSS_HTTP) || - (wsi->mode == LWSCM_WS_SERVING && wsi->state_pre_close == LWSS_HTTP))) { - lwsl_debug("calling back CLOSED %d %d\n", wsi->mode, wsi->state); - wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED, - wsi->user_space, NULL, 0); - } else if (wsi->mode == LWSCM_HTTP_SERVING_ACCEPTED) { - lwsl_debug("calling back CLOSED_HTTP\n"); - wsi->vhost->protocols->callback(wsi, LWS_CALLBACK_CLOSED_HTTP, - wsi->user_space, NULL, 0 ); - } else - lwsl_debug("not calling back closed mode=%d state=%d\n", - wsi->mode, wsi->state_pre_close); + if (lwsi_state_est_PRE_CLOSE(wsi) && !wsi->told_user_closed && + wsi->role_ops->close_cb[lwsi_role_server(wsi)]) { + const struct lws_protocols *pro = wsi->protocol; - /* deallocate any active extension contexts */ + if (!wsi->protocol) + pro = &wsi->vhost->protocols[0]; - if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0) - lwsl_warn("extension destruction failed\n"); - /* - * inform all extensions in case they tracked this guy out of band - * even though not active on him specifically - */ - if (lws_ext_cb_all_exts(context, wsi, - LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING, NULL, 0) < 0) - lwsl_warn("ext destroy wsi failed\n"); + pro->callback(wsi, + wsi->role_ops->close_cb[lwsi_role_server(wsi)], + wsi->user_space, NULL, 0); + wsi->told_user_closed = 1; + } async_close: wsi->socket_is_permanently_unusable = 1; -#ifdef LWS_WITH_LIBUV - if (!wsi->parent_carries_io && - lws_sockfd_valid(wsi->desc.sockfd)) - if (LWS_LIBUV_ENABLED(context)) { - if (wsi->listener) { - lwsl_debug("%s: stop listener poll\n", __func__); - uv_poll_stop(&wsi->w_read.uv_watcher); - } - lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", - __func__, wsi); - /* - * libuv has to do his own close handle processing - * asynchronously - */ - lws_libuv_closehandle(wsi); - + if (wsi->context->event_loop_ops->wsi_logical_close) + if (wsi->context->event_loop_ops->wsi_logical_close(wsi)) return; - } -#endif - lws_close_free_wsi_final(wsi); + __lws_close_free_wsi_final(wsi); } void -lws_close_free_wsi_final(struct lws *wsi) +__lws_close_free_wsi_final(struct lws *wsi) { int n; if (lws_socket_is_valid(wsi->desc.sockfd) && !lws_ssl_close(wsi)) { -#if LWS_POSIX n = compatible_close(wsi->desc.sockfd); if (n) lwsl_debug("closing: close ret %d\n", LWS_ERRNO); -#else - compatible_close(wsi->desc.sockfd); - (void)n; -#endif wsi->desc.sockfd = LWS_SOCK_INVALID; } /* outermost destroy notification for wsi (user_space still intact) */ - wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY, - wsi->user_space, NULL, 0); + if (wsi->vhost) + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY, + wsi->user_space, NULL, 0); #ifdef LWS_WITH_CGI - if (wsi->cgi) { + if (wsi->http.cgi) { for (n = 0; n < 3; n++) { - if (wsi->cgi->pipe_fds[n][!!(n == 0)] == 0) + if (wsi->http.cgi->pipe_fds[n][!!(n == 0)] == 0) lwsl_err("ZERO FD IN CGI CLOSE"); - if (wsi->cgi->pipe_fds[n][!!(n == 0)] >= 0) - close(wsi->cgi->pipe_fds[n][!!(n == 0)]); + if (wsi->http.cgi->pipe_fds[n][!!(n == 0)] >= 0) + close(wsi->http.cgi->pipe_fds[n][!!(n == 0)]); } - lws_free(wsi->cgi); + lws_free(wsi->http.cgi); } #endif - lws_free_wsi(wsi); + __lws_free_wsi(wsi); +} + + +void +lws_close_free_wsi(struct lws *wsi, enum lws_close_status reason, const char *caller) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + lws_pt_lock(pt, __func__); + __lws_close_free_wsi(wsi, reason, caller); + lws_pt_unlock(pt); +} + +/* lws_buflist */ + +int +lws_buflist_append_segment(struct lws_buflist **head, const uint8_t *buf, + size_t len) +{ + struct lws_buflist *nbuf; + int first = !*head; + void *p = *head; + int sanity = 1024; + + assert(buf); + assert(len); + + /* append at the tail */ + while (*head) { + if (!--sanity || head == &((*head)->next)) { + lwsl_err("%s: corrupt list points to self\n", __func__); + return -1; + } + head = &((*head)->next); + } + + lwsl_info("%s: len %u first %d %p\n", __func__, (uint32_t)len, first, p); + + nbuf = (struct lws_buflist *) + lws_malloc(sizeof(**head) + len, __func__); + if (!nbuf) { + lwsl_err("%s: OOM\n", __func__); + return -1; + } + + nbuf->len = len; + nbuf->pos = 0; + nbuf->next = NULL; + + p = (void *)nbuf->buf; + memcpy(p, buf, len); + + *head = nbuf; + + return first; /* returns 1 if first segment just created */ +} + +static int +lws_buflist_destroy_segment(struct lws_buflist **head) +{ + struct lws_buflist *old = *head; + + assert(*head); + *head = (*head)->next; + old->next = NULL; + lws_free(old); + + return !*head; /* returns 1 if last segment just destroyed */ +} + +void +lws_buflist_destroy_all_segments(struct lws_buflist **head) +{ + struct lws_buflist *p = *head, *p1; + + while (p) { + p1 = p->next; + p->next = NULL; + lws_free(p); + p = p1; + } + + *head = NULL; +} + +size_t +lws_buflist_next_segment_len(struct lws_buflist **head, uint8_t **buf) +{ + if (!*head) { + if (buf) + *buf = NULL; + + return 0; + } + + if (!(*head)->len && (*head)->next) + lws_buflist_destroy_segment(head); + + if (!*head) { + if (buf) + *buf = NULL; + + return 0; + } + + assert((*head)->pos < (*head)->len); + + if (buf) + *buf = (*head)->buf + (*head)->pos; + + return (*head)->len - (*head)->pos; } +int +lws_buflist_use_segment(struct lws_buflist **head, size_t len) +{ + assert(*head); + assert(len); + assert((*head)->pos + len <= (*head)->len); + + (*head)->pos += len; + if ((*head)->pos == (*head)->len) + lws_buflist_destroy_segment(head); + + if (!*head) + return 0; + + return (int)((*head)->len - (*head)->pos); +} + +void +lws_buflist_describe(struct lws_buflist **head, void *id) +{ + struct lws_buflist *old; + int n = 0; + + if (*head == NULL) + lwsl_notice("%p: buflist empty\n", id); + + while (*head) { + lwsl_notice("%p: %d: %llu / %llu (%llu left)\n", id, n, + (unsigned long long)(*head)->pos, + (unsigned long long)(*head)->len, + (unsigned long long)(*head)->len - (*head)->pos); + old = *head; + head = &((*head)->next); + if (*head == old) { + lwsl_err("%s: next points to self\n", __func__); + break; + } + n++; + } +} + +/* ... */ + LWS_VISIBLE LWS_EXTERN const char * lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len) { - int n = 0, sl = strlen(name); + int n = 0, sl = (int)strlen(name); while (lws_hdr_copy_fragment(wsi, buf, len, WSI_TOKEN_HTTP_URI_ARGS, n) >= 0) { @@ -879,7 +1049,7 @@ lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len) return NULL; } -#if LWS_POSIX && !defined(LWS_WITH_ESP32) +#if !defined(LWS_WITH_ESP32) LWS_VISIBLE int interface_to_sa(struct lws_vhost *vh, const char *ifname, struct sockaddr_in *addr, size_t addrlen) @@ -895,12 +1065,10 @@ interface_to_sa(struct lws_vhost *vh, const char *ifname, #endif #ifndef LWS_PLAT_OPTEE -#if LWS_POSIX static int lws_get_addresses(struct lws_vhost *vh, void *ads, char *name, int name_len, char *rip, int rip_len) { -#if LWS_POSIX struct addrinfo ai, *res; struct sockaddr_in addr4; @@ -921,8 +1089,8 @@ lws_get_addresses(struct lws_vhost *vh, void *ads, char *name, if (strncmp(rip, "::ffff:", 7) == 0) memmove(rip, rip + 7, strlen(rip) - 6); - getnameinfo((struct sockaddr *)ads, - sizeof(struct sockaddr_in6), name, name_len, NULL, 0, 0); + getnameinfo((struct sockaddr *)ads, sizeof(struct sockaddr_in6), + name, name_len, NULL, 0, 0); return 0; } else @@ -933,7 +1101,6 @@ lws_get_addresses(struct lws_vhost *vh, void *ads, char *name, memset(&ai, 0, sizeof ai); ai.ai_family = PF_UNSPEC; ai.ai_socktype = SOCK_STREAM; - ai.ai_flags = AI_CANONNAME; #if !defined(LWS_WITH_ESP32) if (getnameinfo((struct sockaddr *)ads, sizeof(struct sockaddr_in), @@ -966,24 +1133,12 @@ lws_get_addresses(struct lws_vhost *vh, void *ads, char *name, return -1; return 0; -#else - (void)vh; - (void)ads; - (void)name; - (void)name_len; - (void)rip; - (void)rip_len; - - return -1; -#endif } -#endif LWS_VISIBLE const char * lws_get_peer_simple(struct lws *wsi, char *name, int namelen) { -#if LWS_POSIX socklen_t len, olen; #ifdef LWS_WITH_IPV6 struct sockaddr_in6 sin6; @@ -992,10 +1147,7 @@ lws_get_peer_simple(struct lws *wsi, char *name, int namelen) int af = AF_INET; void *p, *q; -#if defined(LWS_WITH_HTTP2) - if (wsi->http2_substream) - wsi = wsi->u.h2.parent_wsi; -#endif + wsi = lws_get_network_wsi(wsi); if (wsi->parent_carries_io) wsi = wsi->parent; @@ -1021,13 +1173,6 @@ lws_get_peer_simple(struct lws *wsi, char *name, int namelen) } return lws_plat_inet_ntop(af, q, name, namelen); -#else -#if defined(LWS_WITH_ESP8266) - return lws_plat_get_peer_simple(wsi, name, namelen); -#else - return NULL; -#endif -#endif } #endif @@ -1036,7 +1181,6 @@ lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name, int name_len, char *rip, int rip_len) { #ifndef LWS_PLAT_OPTEE -#if LWS_POSIX socklen_t len; #ifdef LWS_WITH_IPV6 struct sockaddr_in6 sin6; @@ -1072,7 +1216,6 @@ lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name, bail: lws_latency(context, wsi, "lws_get_peer_addresses", ret, 1); #endif -#endif (void)wsi; (void)fd; (void)name; @@ -1112,6 +1255,12 @@ lws_protocol_get(struct lws *wsi) return wsi->protocol; } +LWS_VISIBLE const struct lws_udp * +lws_get_udp(const struct lws *wsi) +{ + return wsi->udp; +} + LWS_VISIBLE struct lws * lws_get_network_wsi(struct lws *wsi) { @@ -1119,11 +1268,11 @@ lws_get_network_wsi(struct lws *wsi) return NULL; #if defined(LWS_WITH_HTTP2) - if (!wsi->http2_substream) + if (!wsi->http2_substream && !wsi->client_h2_substream) return wsi; - while (wsi->u.h2.parent_wsi) - wsi = wsi->u.h2.parent_wsi; + while (wsi->h2.parent_wsi) + wsi = wsi->h2.parent_wsi; #endif return wsi; @@ -1209,6 +1358,29 @@ lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len) return 0; } +LWS_VISIBLE LWS_EXTERN int +lws_callback_vhost_protocols_vhost(struct lws_vhost *vh, int reason, void *in, + size_t len) +{ + int n; + struct lws *wsi = lws_zalloc(sizeof(*wsi), "fake wsi"); + + wsi->context = vh->context; + wsi->vhost = vh; + + for (n = 0; n < wsi->vhost->count_protocols; n++) { + wsi->protocol = &vh->protocols[n]; + if (wsi->protocol->callback(wsi, reason, NULL, in, len)) { + lws_free(wsi); + return 1; + } + } + + lws_free(wsi); + + return 0; +} + LWS_VISIBLE LWS_EXTERN void lws_set_fops(struct lws_context *context, const struct lws_plat_file_ops *fops) { @@ -1281,7 +1453,7 @@ lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path, pf = fops->next; while (pf) { n = 0; - while (n < ARRAY_SIZE(pf->fi) && pf->fi[n].sig) { + while (n < (int)ARRAY_SIZE(pf->fi) && pf->fi[n].sig) { if (p >= vfs_path + pf->fi[n].len) if (!strncmp(p - (pf->fi[n].len - 1), pf->fi[n].sig, @@ -1327,10 +1499,19 @@ lws_now_secs(void) return tv.tv_sec; } +LWS_VISIBLE LWS_EXTERN int +lws_compare_time_t(struct lws_context *context, time_t t1, time_t t2) +{ + if (t1 < context->time_discontiguity) + t1 += context->time_fixup; -#if LWS_POSIX + if (t2 < context->time_discontiguity) + t2 += context->time_fixup; -LWS_VISIBLE int + return (int)(t1 - t2); +} + +LWS_VISIBLE lws_sockfd_type lws_get_socket_fd(struct lws *wsi) { if (!wsi) @@ -1338,8 +1519,6 @@ lws_get_socket_fd(struct lws *wsi) return wsi->desc.sockfd; } -#endif - #ifdef LWS_LATENCY void lws_latency(struct lws_context *context, struct lws *wsi, const char *action, @@ -1384,8 +1563,14 @@ lws_latency(struct lws_context *context, struct lws *wsi, const char *action, LWS_VISIBLE int lws_rx_flow_control(struct lws *wsi, int _enable) { + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; int en = _enable; + // h2 ignores rx flow control atm + if (lwsi_role_h2(wsi) || wsi->http2_substream || + lwsi_role_h2_ENCAPSULATION(wsi)) + return 0; // !!! + lwsl_info("%s: %p 0x%x\n", __func__, wsi, _enable); if (!(_enable & LWS_RXFLOW_REASON_APPLIES)) { @@ -1398,6 +1583,8 @@ lws_rx_flow_control(struct lws *wsi, int _enable) en |= LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT; } + lws_pt_lock(pt, __func__); + /* any bit set in rxflow_bitmap DISABLEs rxflow control */ if (en & LWS_RXFLOW_REASON_APPLIES_ENABLE_BIT) wsi->rxflow_bitmap &= ~(en & 0xff); @@ -1406,16 +1593,23 @@ lws_rx_flow_control(struct lws *wsi, int _enable) if ((LWS_RXFLOW_PENDING_CHANGE | (!wsi->rxflow_bitmap)) == wsi->rxflow_change_to) - return 0; + goto skip; wsi->rxflow_change_to = LWS_RXFLOW_PENDING_CHANGE | !wsi->rxflow_bitmap; - lwsl_info("%s: 0x%p: bitmap 0x%x: en 0x%x, ch 0x%x\n", __func__, wsi, + lwsl_info("%s: %p: bitmap 0x%x: en 0x%x, ch 0x%x\n", __func__, wsi, wsi->rxflow_bitmap, en, wsi->rxflow_change_to); if (_enable & LWS_RXFLOW_REASON_FLAG_PROCESS_NOW || - !wsi->rxflow_will_be_applied) - return _lws_rx_flow_control(wsi); + !wsi->rxflow_will_be_applied) { + en = __lws_rx_flow_control(wsi); + lws_pt_unlock(pt); + + return en; + } + +skip: + lws_pt_unlock(pt); return 0; } @@ -1440,12 +1634,63 @@ lws_rx_flow_allow_all_protocol(const struct lws_context *context, } } +int +lws_broadcast(struct lws_context *context, int reason, void *in, size_t len) +{ + struct lws_vhost *v = context->vhost_list; + struct lws wsi; + int n, ret = 0; + + memset(&wsi, 0, sizeof(wsi)); + wsi.context = context; + + while (v) { + const struct lws_protocols *p = v->protocols; + wsi.vhost = v; + + for (n = 0; n < v->count_protocols; n++) { + wsi.protocol = p; + if (p->callback && + p->callback(&wsi, reason, NULL, in, len)) + ret |= 1; + p++; + } + v = v->vhost_next; + } + + return ret; +} + LWS_VISIBLE extern const char * lws_canonical_hostname(struct lws_context *context) { return (const char *)context->canonical_hostname; } +LWS_VISIBLE LWS_EXTERN const char * +lws_get_vhost_name(struct lws_vhost *vhost) +{ + return vhost->name; +} + +LWS_VISIBLE LWS_EXTERN int +lws_get_vhost_port(struct lws_vhost *vhost) +{ + return vhost->listen_port; +} + +LWS_VISIBLE LWS_EXTERN void * +lws_get_vhost_user(struct lws_vhost *vhost) +{ + return vhost->user; +} + +LWS_VISIBLE LWS_EXTERN const char * +lws_get_vhost_iface(struct lws_vhost *vhost) +{ + return vhost->iface; +} + int user_callback_handle_rxflow(lws_callback_function callback_function, struct lws *wsi, enum lws_callback_reasons reason, void *user, @@ -1457,20 +1702,15 @@ int user_callback_handle_rxflow(lws_callback_function callback_function, n = callback_function(wsi, reason, user, in, len); wsi->rxflow_will_be_applied = 0; if (!n) - n = _lws_rx_flow_control(wsi); + n = __lws_rx_flow_control(wsi); return n; } -#if defined(LWS_WITH_ESP8266) -#undef strchr -#define strchr ets_strchr -#endif - +#if !defined(LWS_WITHOUT_CLIENT) LWS_VISIBLE int lws_set_proxy(struct lws_vhost *vhost, const char *proxy) { -#if !defined(LWS_WITH_ESP8266) char *p; char authstring[96]; @@ -1481,15 +1721,15 @@ lws_set_proxy(struct lws_vhost *vhost, const char *proxy) if (!strncmp(proxy, "http://", 7)) proxy += 7; - p = strchr(proxy, '@'); + p = strrchr(proxy, '@'); if (p) { /* auth is around */ if ((unsigned int)(p - proxy) > sizeof(authstring) - 1) goto auth_too_long; - strncpy(authstring, proxy, p - proxy); + lws_strncpy(authstring, proxy, p - proxy + 1); // null termination not needed on input - if (lws_b64_encode_string(authstring, (p - proxy), + if (lws_b64_encode_string(authstring, lws_ptr_diff(p, proxy), vhost->proxy_basic_auth_token, sizeof vhost->proxy_basic_auth_token) < 0) goto auth_too_long; @@ -1500,39 +1740,38 @@ lws_set_proxy(struct lws_vhost *vhost, const char *proxy) } else vhost->proxy_basic_auth_token[0] = '\0'; - strncpy(vhost->http_proxy_address, proxy, - sizeof(vhost->http_proxy_address) - 1); - vhost->http_proxy_address[ - sizeof(vhost->http_proxy_address) - 1] = '\0'; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + lws_strncpy(vhost->http.http_proxy_address, proxy, + sizeof(vhost->http.http_proxy_address)); - p = strchr(vhost->http_proxy_address, ':'); - if (!p && !vhost->http_proxy_port) { + p = strchr(vhost->http.http_proxy_address, ':'); + if (!p && !vhost->http.http_proxy_port) { lwsl_err("http_proxy needs to be ads:port\n"); return -1; } else { if (p) { *p = '\0'; - vhost->http_proxy_port = atoi(p + 1); + vhost->http.http_proxy_port = atoi(p + 1); } } - lwsl_info(" Proxy %s:%u\n", vhost->http_proxy_address, - vhost->http_proxy_port); - + lwsl_info(" Proxy %s:%u\n", vhost->http.http_proxy_address, + vhost->http.http_proxy_port); +#endif return 0; auth_too_long: lwsl_err("proxy auth too long\n"); -#endif + return -1; } +#endif #if defined(LWS_WITH_SOCKS5) LWS_VISIBLE int lws_set_socks(struct lws_vhost *vhost, const char *socks) { -#if !defined(LWS_WITH_ESP8266) char *p_at, *p_colon; char user[96]; char password[96]; @@ -1543,7 +1782,7 @@ lws_set_socks(struct lws_vhost *vhost, const char *socks) vhost->socks_user[0] = '\0'; vhost->socks_password[0] = '\0'; - p_at = strchr(socks, '@'); + p_at = strrchr(socks, '@'); if (p_at) { /* auth is around */ if ((unsigned int)(p_at - socks) > (sizeof(user) + sizeof(password) - 2)) { @@ -1564,9 +1803,9 @@ lws_set_socks(struct lws_vhost *vhost, const char *socks) goto bail; } - strncpy(vhost->socks_user, socks, p_colon - socks); - strncpy(vhost->socks_password, p_colon + 1, - p_at - (p_colon + 1)); + lws_strncpy(vhost->socks_user, socks, p_colon - socks + 1); + lws_strncpy(vhost->socks_password, p_colon + 1, + p_at - (p_colon + 1) + 1); } lwsl_info(" Socks auth, user: %s, password: %s\n", @@ -1575,10 +1814,8 @@ lws_set_socks(struct lws_vhost *vhost, const char *socks) socks = p_at + 1; } - strncpy(vhost->socks_proxy_address, socks, - sizeof(vhost->socks_proxy_address) - 1); - vhost->socks_proxy_address[sizeof(vhost->socks_proxy_address) - 1] - = '\0'; + lws_strncpy(vhost->socks_proxy_address, socks, + sizeof(vhost->socks_proxy_address)); p_colon = strchr(vhost->socks_proxy_address, ':'); if (!p_colon && !vhost->socks_proxy_port) { @@ -1597,7 +1834,6 @@ lws_set_socks(struct lws_vhost *vhost, const char *socks) return 0; bail: -#endif return -1; } #endif @@ -1608,27 +1844,6 @@ lws_get_protocol(struct lws *wsi) return wsi->protocol; } -LWS_VISIBLE int -lws_is_final_fragment(struct lws *wsi) -{ - lwsl_info("%s: final %d, rx pk length %ld, draining %ld\n", __func__, - wsi->u.ws.final, (long)wsi->u.ws.rx_packet_length, - (long)wsi->u.ws.rx_draining_ext); - return wsi->u.ws.final && !wsi->u.ws.rx_packet_length && - !wsi->u.ws.rx_draining_ext; -} - -LWS_VISIBLE int -lws_is_first_fragment(struct lws *wsi) -{ - return wsi->u.ws.first_fragment; -} - -LWS_VISIBLE unsigned char -lws_get_reserved_bits(struct lws *wsi) -{ - return wsi->u.ws.rsv; -} int lws_ensure_user_space(struct lws *wsi) @@ -1639,7 +1854,8 @@ lws_ensure_user_space(struct lws *wsi) /* allocate the per-connection user memory (if any) */ if (wsi->protocol->per_session_data_size && !wsi->user_space) { - wsi->user_space = lws_zalloc(wsi->protocol->per_session_data_size, "user space"); + wsi->user_space = lws_zalloc( + wsi->protocol->per_session_data_size, "user space"); if (wsi->user_space == NULL) { lwsl_err("%s: OOM\n", __func__); return 1; @@ -1704,10 +1920,14 @@ lwsl_timestamp(int level, char *p, int len) (int)(now % 10000), log_level_names[n]); return n; } +#else + p[0] = '\0'; #endif + return 0; } +#ifndef LWS_PLAT_OPTEE static const char * const colours[] = { "[31;1m", /* LLL_ERR */ "[36;1m", /* LLL_WARN */ @@ -1722,17 +1942,14 @@ static const char * const colours[] = { "[30;1m", /* LLL_USER */ }; -#ifndef LWS_PLAT_OPTEE LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line) { -#if !defined(LWS_WITH_ESP8266) char buf[50]; - static char tty; + static char tty = 3; int n, m = ARRAY_SIZE(colours) - 1; if (!tty) tty = isatty(2) | 2; - lwsl_timestamp(level, buf, sizeof(buf)); if (tty == 3) { @@ -1746,17 +1963,12 @@ LWS_VISIBLE void lwsl_emit_stderr(int level, const char *line) fprintf(stderr, "%c%s%s%s%c[0m", 27, colours[m], buf, line, 27); } else fprintf(stderr, "%s%s", buf, line); -#endif } #endif LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl) { -#if defined(LWS_WITH_ESP8266) - char buf[128]; -#else char buf[256]; -#endif int n; if (!(log_level & filter)) @@ -1764,15 +1976,11 @@ LWS_VISIBLE void _lws_logv(int filter, const char *format, va_list vl) n = vsnprintf(buf, sizeof(buf) - 1, format, vl); (void)n; -#if defined(LWS_WITH_ESP8266) - buf[sizeof(buf) - 1] = '\0'; -#else /* vnsprintf returns what it would have written, even if truncated */ - if (n > sizeof(buf) - 1) + if (n > (int)sizeof(buf) - 1) n = sizeof(buf) - 1; if (n > 0) buf[n] = '\0'; -#endif lwsl_emit(filter, buf); } @@ -1810,6 +2018,12 @@ lwsl_hexdump_level(int hexdump_level, const void *vbuf, size_t len) if (!lwsl_visible(hexdump_level)) return; + if (!len) + return; + + if (!vbuf) + return; + _lws_log(hexdump_level, "\n"); for (n = 0; n < len;) { @@ -1852,19 +2066,19 @@ lwsl_hexdump(const void *vbuf, size_t len) LWS_VISIBLE int lws_is_ssl(struct lws *wsi) { -#ifdef LWS_OPENSSL_SUPPORT - return wsi->use_ssl; +#if defined(LWS_WITH_TLS) + return wsi->tls.use_ssl & LCCSCF_USE_SSL; #else (void)wsi; return 0; #endif } -#ifdef LWS_OPENSSL_SUPPORT -LWS_VISIBLE SSL* +#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS) +LWS_VISIBLE lws_tls_conn* lws_get_ssl(struct lws *wsi) { - return wsi->ssl; + return wsi->tls.ssl; } #endif @@ -1874,27 +2088,28 @@ lws_partial_buffered(struct lws *wsi) return !!wsi->trunc_len; } -LWS_VISIBLE size_t +LWS_VISIBLE lws_fileofs_t lws_get_peer_write_allowance(struct lws *wsi) { -#ifdef LWS_WITH_HTTP2 - /* only if we are using HTTP2 on this connection */ - if (wsi->mode != LWSCM_HTTP2_SERVING) - return -1; - - return lws_h2_tx_cr_get(wsi); -#else - (void)wsi; - return -1; -#endif + return wsi->role_ops->tx_credit(wsi); } LWS_VISIBLE void -lws_union_transition(struct lws *wsi, enum connection_mode mode) +lws_role_transition(struct lws *wsi, enum lwsi_role role, enum lwsi_state state, + struct lws_role_ops *ops) { - lwsl_debug("%s: %p: mode %d\n", __func__, wsi, mode); - memset(&wsi->u, 0, sizeof(wsi->u)); - wsi->mode = mode; +#if defined(_DEBUG) + const char *name = "(unset)"; +#endif + wsi->wsistate = role | state; + if (ops) + wsi->role_ops = ops; +#if defined(_DEBUG) + if (wsi->role_ops) + name = wsi->role_ops->name; + lwsl_debug("%s: %p: wsistate 0x%x, ops %s\n", __func__, wsi, + wsi->wsistate, name); +#endif } LWS_VISIBLE struct lws_plat_file_ops * @@ -1973,48 +2188,21 @@ lws_clear_child_pending_on_writable(struct lws *wsi) wsi->parent_pending_cb_on_writable = 0; } -LWS_VISIBLE LWS_EXTERN int -lws_get_close_length(struct lws *wsi) -{ - return wsi->u.ws.close_in_ping_buffer_len; -} - -LWS_VISIBLE LWS_EXTERN unsigned char * -lws_get_close_payload(struct lws *wsi) -{ - return &wsi->u.ws.ping_payload_buf[LWS_PRE]; -} - -LWS_VISIBLE LWS_EXTERN void -lws_close_reason(struct lws *wsi, enum lws_close_status status, - unsigned char *buf, size_t len) -{ - unsigned char *p, *start; - int budget = sizeof(wsi->u.ws.ping_payload_buf) - LWS_PRE; - - assert(wsi->mode == LWSCM_WS_SERVING || wsi->mode == LWSCM_WS_CLIENT); - - start = p = &wsi->u.ws.ping_payload_buf[LWS_PRE]; - - *p++ = (((int)status) >> 8) & 0xff; - *p++ = ((int)status) & 0xff; - - if (buf) - while (len-- && p < start + budget) - *p++ = *buf++; - - wsi->u.ws.close_in_ping_buffer_len = p - start; -} LWS_EXTERN int -_lws_rx_flow_control(struct lws *wsi) +__lws_rx_flow_control(struct lws *wsi) { struct lws *wsic = wsi->child_list; + // h2 ignores rx flow control atm + if (lwsi_role_h2(wsi) || wsi->http2_substream || + lwsi_role_h2_ENCAPSULATION(wsi)) + return 0; // !!! + /* if he has children, do those if they were changed */ while (wsic) { if (wsic->rxflow_change_to & LWS_RXFLOW_PENDING_CHANGE) - _lws_rx_flow_control(wsic); + __lws_rx_flow_control(wsic); wsic = wsic->sibling_list; } @@ -2024,13 +2212,13 @@ _lws_rx_flow_control(struct lws *wsi) return 0; /* stuff is still buffered, not ready to really accept new input */ - if (wsi->rxflow_buffer) { + if (lws_buflist_next_segment_len(&wsi->buflist, NULL)) { /* get ourselves called back to deal with stashed buffer */ lws_callback_on_writable(wsi); return 0; } - /* pending is cleared, we can change rxflow state */ + /* now the pending is cleared, we can change rxflow state */ wsi->rxflow_change_to &= ~LWS_RXFLOW_PENDING_CHANGE; @@ -2040,12 +2228,12 @@ _lws_rx_flow_control(struct lws *wsi) /* adjust the pollfd for this wsi */ if (wsi->rxflow_change_to & LWS_RXFLOW_ALLOW) { - if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { + if (__lws_change_pollfd(wsi, 0, LWS_POLLIN)) { lwsl_info("%s: fail\n", __func__); return -1; } } else - if (lws_change_pollfd(wsi, LWS_POLLIN, 0)) + if (__lws_change_pollfd(wsi, LWS_POLLIN, 0)) return -1; return 0; @@ -2162,14 +2350,14 @@ lws_parse_uri(char *p, const char **prot, const char **ads, int *port, return 0; } -#ifdef LWS_NO_EXTENSIONS +#if defined(LWS_WITHOUT_EXTENSIONS) /* we need to provide dummy callbacks for internal exts * so user code runs when faced with a lib compiled with * extensions disabled. */ -int +LWS_VISIBLE int lws_extension_callback_pm_deflate(struct lws_context *context, const struct lws_extension *ext, struct lws *wsi, @@ -2186,13 +2374,19 @@ lws_extension_callback_pm_deflate(struct lws_context *context, return 0; } + +LWS_EXTERN int +lws_set_extension_option(struct lws *wsi, const char *ext_name, + const char *opt_name, const char *opt_val) +{ + return -1; +} #endif LWS_EXTERN int lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, const char *iface) { -#if LWS_POSIX #ifdef LWS_WITH_UNIX_SOCK struct sockaddr_un serv_unix; #endif @@ -2204,6 +2398,9 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, socklen_t len = sizeof(struct sockaddr_storage); #endif int n; +#if !defined(LWS_WITH_ESP32) + int m; +#endif struct sockaddr_storage sin; struct sockaddr *v; @@ -2213,6 +2410,8 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, n = sizeof(struct sockaddr_un); bzero((char *) &serv_unix, sizeof(serv_unix)); serv_unix.sun_family = AF_UNIX; + if (!iface) + return -1; if (sizeof(serv_unix.sun_path) <= strlen(iface)) { lwsl_err("\"%s\" too long for UNIX domain socket\n", iface); @@ -2230,10 +2429,17 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, n = sizeof(struct sockaddr_in6); bzero((char *) &serv_addr6, sizeof(serv_addr6)); if (iface) { - if (interface_to_sa(vhost, iface, - (struct sockaddr_in *)v, n) < 0) { - lwsl_err("Unable to find if %s\n", iface); - return -1; + m = interface_to_sa(vhost, iface, + (struct sockaddr_in *)v, n); + if (m == LWS_ITOSA_NOT_USABLE) { + lwsl_info("%s: netif %s: Not usable\n", + __func__, iface); + return m; + } + if (m == LWS_ITOSA_NOT_EXIST) { + lwsl_info("%s: netif %s: Does not exist\n", + __func__, iface); + return m; } serv_addr6.sin6_scope_id = lws_get_addr_scope(iface); } @@ -2250,16 +2456,28 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, serv_addr4.sin_family = AF_INET; #if !defined(LWS_WITH_ESP32) - if (iface && - interface_to_sa(vhost, iface, - (struct sockaddr_in *)v, n) < 0) { - lwsl_err("Unable to find interface %s\n", iface); - return -1; + if (iface) { + m = interface_to_sa(vhost, iface, + (struct sockaddr_in *)v, n); + if (m == LWS_ITOSA_NOT_USABLE) { + lwsl_info("%s: netif %s: Not usable\n", + __func__, iface); + return m; + } + if (m == LWS_ITOSA_NOT_EXIST) { + lwsl_info("%s: netif %s: Does not exist\n", + __func__, iface); + return m; + } } #endif serv_addr4.sin_port = htons(port); } /* ipv4 */ + /* just checking for the interface extant */ + if (sockfd == LWS_SOCK_INVALID) + return 0; + n = bind(sockfd, v, n); #ifdef LWS_WITH_UNIX_SOCK if (n < 0 && LWS_UNIX_SOCK_ENABLED(vhost)) { @@ -2281,8 +2499,8 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, #endif #if defined(LWS_WITH_IPV6) port = (sin.ss_family == AF_INET6) ? - ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) : - ntohs(((struct sockaddr_in *) &sin)->sin_port); + ntohs(((struct sockaddr_in6 *) &sin)->sin6_port) : + ntohs(((struct sockaddr_in *) &sin)->sin_port); #else { struct sockaddr_in sain; @@ -2290,11 +2508,16 @@ lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, port = ntohs(sain.sin_port); } #endif -#endif return port; } +LWS_VISIBLE LWS_EXTERN int +lws_get_vhost_listen_port(struct lws_vhost *vhost) +{ + return vhost->listen_port; +} + #if defined(LWS_WITH_IPV6) LWS_EXTERN unsigned long lws_get_addr_scope(const char *ipaddr) @@ -2368,7 +2591,8 @@ lws_get_addr_scope(const char *ipaddr) while (adapter && !found) { addr = adapter->FirstUnicastAddress; while (addr && !found) { - if (addr->Address.lpSockaddr->sa_family == AF_INET6) { + if (addr->Address.lpSockaddr->sa_family == + AF_INET6) { sockaddr = (struct sockaddr_in6 *) (addr->Address.lpSockaddr); @@ -2395,18 +2619,73 @@ lws_get_addr_scope(const char *ipaddr) } #endif -LWS_EXTERN void -lws_restart_ws_ping_pong_timer(struct lws *wsi) +#if !defined(LWS_NO_SERVER) + +LWS_EXTERN struct lws * +lws_create_adopt_udp(struct lws_vhost *vhost, int port, int flags, + const char *protocol_name, struct lws *parent_wsi) { - if (!wsi->context->ws_ping_pong_interval) - return; - if (wsi->state != LWSS_ESTABLISHED) - return; + lws_sock_file_fd_type sock; + struct addrinfo h, *r, *rp; + struct lws *wsi = NULL; + char buf[16]; + int n; - wsi->u.ws.time_next_ping_check = (time_t)lws_now_secs() + - wsi->context->ws_ping_pong_interval; + memset(&h, 0, sizeof(h)); + h.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + h.ai_socktype = SOCK_DGRAM; + h.ai_protocol = IPPROTO_UDP; + h.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; + + lws_snprintf(buf, sizeof(buf), "%u", port); + n = getaddrinfo(NULL, buf, &h, &r); + if (n) { + lwsl_info("%s: getaddrinfo error: %s\n", __func__, + gai_strerror(n)); + goto bail; + } + + for (rp = r; rp; rp = rp->ai_next) { + sock.sockfd = socket(rp->ai_family, rp->ai_socktype, + rp->ai_protocol); + if (sock.sockfd >= 0) + break; + } + if (!rp) { + lwsl_err("%s: unable to create INET socket\n", __func__); + goto bail1; + } + + if ((flags & LWS_CAUDP_BIND) && bind(sock.sockfd, rp->ai_addr, +#if defined(_WIN32) + (int)rp->ai_addrlen +#else + rp->ai_addrlen +#endif + ) == -1) { + lwsl_err("%s: bind failed\n", __func__); + goto bail2; + } + + wsi = lws_adopt_descriptor_vhost(vhost, LWS_ADOPT_RAW_SOCKET_UDP, sock, + protocol_name, parent_wsi); + if (!wsi) + lwsl_err("%s: udp adoption failed\n", __func__); + +bail2: + if (!wsi) + close((int)sock.sockfd); +bail1: + freeaddrinfo(r); + +bail: + return wsi; } +#endif + + + static const char *hex = "0123456789ABCDEF"; LWS_VISIBLE LWS_EXTERN const char * @@ -2458,6 +2737,27 @@ lws_json_purify(char *escaped, const char *string, int len) return escaped; } +LWS_VISIBLE LWS_EXTERN void +lws_filename_purify_inplace(char *filename) +{ + while (*filename) { + + if (*filename == '.' && filename[1] == '.') { + *filename = '_'; + filename[1] = '_'; + } + + if (*filename == ':' || + *filename == '/' || + *filename == '\\' || + *filename == '$' || + *filename == '%') + *filename = '_'; + + filename++; + } +} + LWS_VISIBLE LWS_EXTERN const char * lws_urlencode(char *escaped, const char *string, int len) { @@ -2570,32 +2870,42 @@ lws_snprintf(char *str, size_t size, const char *format, ...) va_end(ap); if (n >= (int)size) - return size; + return (int)size; return n; } +char * +lws_strncpy(char *dest, const char *src, size_t size) +{ + strncpy(dest, src, size - 1); + dest[size - 1] = '\0'; + + return dest; +} + LWS_VISIBLE LWS_EXTERN int lws_is_cgi(struct lws *wsi) { #ifdef LWS_WITH_CGI - return !!wsi->cgi; + return !!wsi->http.cgi; #else return 0; #endif } +const struct lws_protocol_vhost_options * +lws_pvo_search(const struct lws_protocol_vhost_options *pvo, const char *name) +{ + while (pvo) { + if (!strcmp(pvo->name, name)) + break; + pvo = pvo->next; + } -#ifdef LWS_NO_EXTENSIONS -LWS_EXTERN int -lws_set_extension_option(struct lws *wsi, const char *ext_name, - const char *opt_name, const char *opt_val) -{ - return -1; + return pvo; } -#endif - void lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs) @@ -2619,11 +2929,34 @@ lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs) } } +const char * +lws_cmdline_option(int argc, const char **argv, const char *val) +{ + int n = (int)strlen(val), c = argc; + + while (--c > 0) { + + if (!strncmp(argv[c], val, n)) { + if (!*(argv[c] + n) && c < argc - 1) { + /* coverity treats unchecked argv as "tainted" */ + if (!argv[c + 1] || strlen(argv[c + 1]) > 1024) + return NULL; + return argv[c + 1]; + } + + return argv[c] + n; + } + } + + return NULL; +} + #ifdef LWS_WITH_SERVER_STATUS LWS_EXTERN int lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len) { +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) static const char * const prots[] = { "http://", "https://", @@ -2633,6 +2966,7 @@ lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len) ">https://", "callback://" }; +#endif char *orig = buf, *end = buf + len - 1, first = 1; int n = 0; @@ -2656,8 +2990,8 @@ lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len) " \"h2_subs\":\"%lu\"" , vh->name, vh->listen_port, -#ifdef LWS_OPENSSL_SUPPORT - vh->use_ssl, +#if defined(LWS_WITH_TLS) + vh->tls.use_ssl & LCCSCF_USE_SSL, #else 0, #endif @@ -2672,9 +3006,9 @@ lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len) vh->conn_stats.h2_alpn, vh->conn_stats.h2_subs ); - - if (vh->mount_list) { - const struct lws_http_mount *m = vh->mount_list; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + if (vh->http.mount_list) { + const struct lws_http_mount *m = vh->http.mount_list; buf += lws_snprintf(buf, end - buf, ",\n \"mounts\":["); while (m) { @@ -2705,7 +3039,7 @@ lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len) } buf += lws_snprintf(buf, end - buf, "\n ]"); } - +#endif if (vh->protocols) { n = 0; first = 1; @@ -2798,8 +3132,8 @@ lws_json_dump_context(const struct lws_context *context, char *buf, int len, " \"ah_wait_list\":\"%d\"\n" " }", pt->fds_count, - pt->ah_count_in_use, - pt->ah_wait_list_length); + pt->http.ah_count_in_use, + pt->http.ah_wait_list_length); } buf += lws_snprintf(buf, end - buf, "]"); @@ -2850,7 +3184,7 @@ lws_json_dump_context(const struct lws_context *context, char *buf, int len, #ifdef LWS_WITH_CGI for (n = 0; n < context->count_threads; n++) { pt = &context->pt[n]; - pcgi = &pt->cgi_list; + pcgi = &pt->http.cgi_list; while (*pcgi) { pcgi = &(*pcgi)->cgi_list; @@ -2898,63 +3232,117 @@ lws_stats_log_dump(struct lws_context *context) lwsl_notice("\n"); lwsl_notice("LWS internal statistics dump ----->\n"); - lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_CONNECTIONS)); - lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_CLOSE)); - lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_READ)); - lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_LWS_WRITE)); - lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_API_WRITE)); - lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITE_PARTIALS)); - lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_REQ)); - lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB_EFF_REQ)); - lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)); - lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN)); - lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_FAILED)); - lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)); - lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)); - lwsl_notice("LWSSTATS_C_PEER_LIMIT_AH_DENIED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_PEER_LIMIT_AH_DENIED)); - lwsl_notice("LWSSTATS_C_PEER_LIMIT_WSI_DENIED: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_PEER_LIMIT_WSI_DENIED)); - - lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_TIMEOUTS)); - lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_C_SERVICE_ENTRY)); - lwsl_notice("LWSSTATS_B_READ: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ)); - lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE)); - lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", (unsigned long long)lws_stats_get(context, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS)); - lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000); + lwsl_notice("LWSSTATS_C_CONNECTIONS: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_CONNECTIONS)); + lwsl_notice("LWSSTATS_C_API_CLOSE: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_API_CLOSE)); + lwsl_notice("LWSSTATS_C_API_READ: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_API_READ)); + lwsl_notice("LWSSTATS_C_API_LWS_WRITE: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_API_LWS_WRITE)); + lwsl_notice("LWSSTATS_C_API_WRITE: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_API_WRITE)); + lwsl_notice("LWSSTATS_C_WRITE_PARTIALS: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_WRITE_PARTIALS)); + lwsl_notice("LWSSTATS_C_WRITEABLE_CB_REQ: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_WRITEABLE_CB_REQ)); + lwsl_notice("LWSSTATS_C_WRITEABLE_CB_EFF_REQ: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_WRITEABLE_CB_EFF_REQ)); + lwsl_notice("LWSSTATS_C_WRITEABLE_CB: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_WRITEABLE_CB)); + lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN)); + lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_FAILED: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_SSL_CONNECTIONS_FAILED)); + lwsl_notice("LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)); + lwsl_notice("LWSSTATS_C_SSL_CONNS_HAD_RX: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_SSL_CONNS_HAD_RX)); + lwsl_notice("LWSSTATS_C_PEER_LIMIT_AH_DENIED: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_PEER_LIMIT_AH_DENIED)); + lwsl_notice("LWSSTATS_C_PEER_LIMIT_WSI_DENIED: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_PEER_LIMIT_WSI_DENIED)); + + lwsl_notice("LWSSTATS_C_TIMEOUTS: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_TIMEOUTS)); + lwsl_notice("LWSSTATS_C_SERVICE_ENTRY: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_C_SERVICE_ENTRY)); + lwsl_notice("LWSSTATS_B_READ: %8llu\n", + (unsigned long long)lws_stats_get(context, LWSSTATS_B_READ)); + lwsl_notice("LWSSTATS_B_WRITE: %8llu\n", + (unsigned long long)lws_stats_get(context, LWSSTATS_B_WRITE)); + lwsl_notice("LWSSTATS_B_PARTIALS_ACCEPTED_PARTS: %8llu\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_B_PARTIALS_ACCEPTED_PARTS)); + lwsl_notice("LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY: %8llums\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / 1000); if (lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) lwsl_notice(" Avg accept delay: %8llums\n", - (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / - lws_stats_get(context, LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000); - lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", (unsigned long long)lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / 1000); + (unsigned long long)(lws_stats_get(context, + LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY) / + lws_stats_get(context, + LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED)) / 1000); + lwsl_notice("LWSSTATS_MS_SSL_RX_DELAY: %8llums\n", + (unsigned long long)lws_stats_get(context, + LWSSTATS_MS_SSL_RX_DELAY) / 1000); if (lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) lwsl_notice(" Avg accept-rx delay: %8llums\n", - (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_SSL_RX_DELAY) / - lws_stats_get(context, LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000); + (unsigned long long)(lws_stats_get(context, + LWSSTATS_MS_SSL_RX_DELAY) / + lws_stats_get(context, + LWSSTATS_C_SSL_CONNS_HAD_RX)) / 1000); lwsl_notice("LWSSTATS_MS_WRITABLE_DELAY: %8lluus\n", - (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY)); + (unsigned long long)lws_stats_get(context, + LWSSTATS_MS_WRITABLE_DELAY)); lwsl_notice("LWSSTATS_MS_WORST_WRITABLE_DELAY: %8lluus\n", - (unsigned long long)lws_stats_get(context, LWSSTATS_MS_WORST_WRITABLE_DELAY)); + (unsigned long long)lws_stats_get(context, + LWSSTATS_MS_WORST_WRITABLE_DELAY)); if (lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB)) lwsl_notice(" Avg writable delay: %8lluus\n", - (unsigned long long)(lws_stats_get(context, LWSSTATS_MS_WRITABLE_DELAY) / + (unsigned long long)(lws_stats_get(context, + LWSSTATS_MS_WRITABLE_DELAY) / lws_stats_get(context, LWSSTATS_C_WRITEABLE_CB))); - lwsl_notice("Simultaneous SSL restriction: %8d/%d/%d\n", context->simultaneous_ssl, - context->simultaneous_ssl_restriction, context->ssl_gate_accepts); + lwsl_notice("Simultaneous SSL restriction: %8d/%d\n", + context->simultaneous_ssl, + context->simultaneous_ssl_restriction); - lwsl_notice("Live wsi: %8d\n", context->count_wsi_allocated); + lwsl_notice("Live wsi: %8d\n", + context->count_wsi_allocated); context->updated = 1; while (v) { - if (v->lserv_wsi) { + if (v->lserv_wsi && + v->lserv_wsi->position_in_fds_table != LWS_NO_FDS_POS) { - struct lws_context_per_thread *pt = &context->pt[(int)v->lserv_wsi->tsi]; + struct lws_context_per_thread *pt = + &context->pt[(int)v->lserv_wsi->tsi]; struct lws_pollfd *pfd; pfd = &pt->fds[v->lserv_wsi->position_in_fds_table]; lwsl_notice(" Listen port %d actual POLLIN: %d\n", - v->listen_port, (int)pfd->events & LWS_POLLIN); + v->listen_port, + (int)pfd->events & LWS_POLLIN); } v = v->vhost_next; @@ -2967,20 +3355,20 @@ lws_stats_log_dump(struct lws_context *context) lwsl_notice("PT %d\n", n + 1); - lws_pt_lock(pt); + lws_pt_lock(pt, __func__); lwsl_notice(" AH in use / max: %d / %d\n", - pt->ah_count_in_use, + pt->http.ah_count_in_use, context->max_http_header_pool); - wl = pt->ah_wait_list; + wl = pt->http.ah_wait_list; while (wl) { m++; - wl = wl->u.hdr.ah_wait_list; + wl = wl->ah_wait_list; } lwsl_notice(" AH wait list count / actual: %d / %d\n", - pt->ah_wait_list_length, m); + pt->http.ah_wait_list_length, m); lws_pt_unlock(pt); } @@ -3004,15 +3392,20 @@ lws_stats_log_dump(struct lws_context *context) for (n = 0; n < (int)context->pl_hash_elements; n++) { char buf[72]; - lws_start_foreach_llp(struct lws_peer **, peer, context->pl_hash_table[n]) { + lws_start_foreach_llp(struct lws_peer **, peer, + context->pl_hash_table[n]) { struct lws_peer *df = *peer; if (!lws_plat_inet_ntop(df->af, df->addr, buf, sizeof(buf) - 1)) strcpy(buf, "unknown"); - +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) lwsl_notice(" peer %s: count wsi: %d, count ah: %d\n", buf, df->count_wsi, df->count_ah); +#else + lwsl_notice(" peer %s: count wsi: %d\n", + buf, df->count_wsi); +#endif if (!--m) break; @@ -3028,23 +3421,23 @@ void lws_stats_atomic_bump(struct lws_context * context, struct lws_context_per_thread *pt, int index, uint64_t bump) { - lws_pt_lock(pt); + lws_pt_stats_lock(pt); context->lws_stats[index] += bump; if (index != LWSSTATS_C_SERVICE_ENTRY) context->updated = 1; - lws_pt_unlock(pt); + lws_pt_stats_unlock(pt); } void lws_stats_atomic_max(struct lws_context * context, struct lws_context_per_thread *pt, int index, uint64_t val) { - lws_pt_lock(pt); + lws_pt_stats_lock(pt); if (val > context->lws_stats[index]) { context->lws_stats[index] = val; context->updated = 1; } - lws_pt_unlock(pt); + lws_pt_stats_unlock(pt); } #endif diff --git a/thirdparty/libwebsockets/core/output.c b/thirdparty/libwebsockets/core/output.c new file mode 100644 index 0000000000..e2ff18ef27 --- /dev/null +++ b/thirdparty/libwebsockets/core/output.c @@ -0,0 +1,308 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +/* + * notice this returns number of bytes consumed, or -1 + */ +int lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len) +{ + struct lws_context *context = lws_get_context(wsi); + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + size_t real_len = len; + unsigned int n; + + // lwsl_hexdump_err(buf, len); + + /* + * Detect if we got called twice without going through the + * event loop to handle pending. This would be caused by either + * back-to-back writes in one WRITABLE (illegal) or calling lws_write() + * from outside the WRITABLE callback (illegal). + */ + if (wsi->could_have_pending) { + lwsl_hexdump_level(LLL_ERR, buf, len); + lwsl_err("** %p: vh: %s, prot: %s, role %s: " + "Illegal back-to-back write of %lu detected...\n", + wsi, wsi->vhost->name, wsi->protocol->name, + wsi->role_ops->name, + (unsigned long)len); + // assert(0); + + return -1; + } + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_WRITE, 1); + + if (!len) + return 0; + /* just ignore sends after we cleared the truncation buffer */ + if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE && !wsi->trunc_len) + return (int)len; + + if (wsi->trunc_len && (buf < wsi->trunc_alloc || + buf > (wsi->trunc_alloc + wsi->trunc_len + wsi->trunc_offset))) { + lwsl_hexdump_level(LLL_ERR, buf, len); + lwsl_err("** %p: vh: %s, prot: %s, Sending new %lu, pending truncated ...\n" + " It's illegal to do an lws_write outside of\n" + " the writable callback: fix your code\n", + wsi, wsi->vhost->name, wsi->protocol->name, + (unsigned long)len); + assert(0); + + return -1; + } + + if (!wsi->http2_substream && !lws_socket_is_valid(wsi->desc.sockfd)) + lwsl_warn("** error invalid sock but expected to send\n"); + + /* limit sending */ + if (wsi->protocol->tx_packet_size) + n = (int)wsi->protocol->tx_packet_size; + else { + n = (int)wsi->protocol->rx_buffer_size; + if (!n) + n = context->pt_serv_buf_size; + } + n += LWS_PRE + 4; + if (n > len) + n = (int)len; + + /* nope, send it on the socket directly */ + lws_latency_pre(context, wsi); + n = lws_ssl_capable_write(wsi, buf, n); + lws_latency(context, wsi, "send lws_issue_raw", n, n == len); + + /* something got written, it can have been truncated now */ + wsi->could_have_pending = 1; + + switch (n) { + case LWS_SSL_CAPABLE_ERROR: + /* we're going to close, let close know sends aren't possible */ + wsi->socket_is_permanently_unusable = 1; + return -1; + case LWS_SSL_CAPABLE_MORE_SERVICE: + /* + * nothing got sent, not fatal. Retry the whole thing later, + * ie, implying treat it was a truncated send so it gets + * retried + */ + n = 0; + break; + } + + /* + * we were already handling a truncated send? + */ + if (wsi->trunc_len) { + lwsl_info("%p partial adv %d (vs %ld)\n", wsi, n, (long)real_len); + wsi->trunc_offset += n; + wsi->trunc_len -= n; + + if (!wsi->trunc_len) { + lwsl_info("** %p partial send completed\n", wsi); + /* done with it, but don't free it */ + n = (int)real_len; + if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) { + lwsl_info("** %p signalling to close now\n", wsi); + return -1; /* retry closing now */ + } + } + /* always callback on writeable */ + lws_callback_on_writable(wsi); + + return n; + } + + if ((unsigned int)n == real_len) + /* what we just sent went out cleanly */ + return n; + + /* + * Newly truncated send. Buffer the remainder (it will get + * first priority next time the socket is writable). + */ + lwsl_debug("%p new partial sent %d from %lu total\n", wsi, n, + (unsigned long)real_len); + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITE_PARTIALS, 1); + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, n); + + /* + * - if we still have a suitable malloc lying around, use it + * - or, if too small, reallocate it + * - or, if no buffer, create it + */ + if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) { + lws_free(wsi->trunc_alloc); + + wsi->trunc_alloc_len = (unsigned int)(real_len - n); + wsi->trunc_alloc = lws_malloc(real_len - n, + "truncated send alloc"); + if (!wsi->trunc_alloc) { + lwsl_err("truncated send: unable to malloc %lu\n", + (unsigned long)(real_len - n)); + return -1; + } + } + wsi->trunc_offset = 0; + wsi->trunc_len = (unsigned int)(real_len - n); + memcpy(wsi->trunc_alloc, buf + n, real_len - n); + +#if !defined(LWS_WITH_ESP32) + if (lws_wsi_is_udp(wsi)) { + /* stash original destination for fulfilling UDP partials */ + wsi->udp->sa_pending = wsi->udp->sa; + wsi->udp->salen_pending = wsi->udp->salen; + } +#endif + + /* since something buffered, force it to get another chance to send */ + lws_callback_on_writable(wsi); + + return (int)real_len; +} + +LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len, + enum lws_write_protocol wp) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + if (wsi->parent_carries_io) { + struct lws_write_passthru pas; + + pas.buf = buf; + pas.len = len; + pas.wp = wp; + pas.wsi = wsi; + + if (wsi->parent->protocol->callback(wsi->parent, + LWS_CALLBACK_CHILD_WRITE_VIA_PARENT, + wsi->parent->user_space, + (void *)&pas, 0)) + return 1; + + return (int)len; + } + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_LWS_WRITE, 1); + + if ((int)len < 0) { + lwsl_err("%s: suspicious len int %d, ulong %lu\n", __func__, + (int)len, (unsigned long)len); + return -1; + } + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_WRITE, len); + +#ifdef LWS_WITH_ACCESS_LOG + wsi->http.access_log.sent += len; +#endif + if (wsi->vhost) + wsi->vhost->conn_stats.tx += len; + + assert(wsi->role_ops); + if (!wsi->role_ops->write_role_protocol) + return lws_issue_raw(wsi, buf, len); + + return wsi->role_ops->write_role_protocol(wsi, buf, len, &wp); +} + +LWS_VISIBLE int +lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + int n = 0; + + lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1); + + if (lws_wsi_is_udp(wsi)) { +#if !defined(LWS_WITH_ESP32) + wsi->udp->salen = sizeof(wsi->udp->sa); + n = recvfrom(wsi->desc.sockfd, (char *)buf, len, 0, + &wsi->udp->sa, &wsi->udp->salen); +#endif + } else + n = recv(wsi->desc.sockfd, (char *)buf, len, 0); + + if (n >= 0) { + if (wsi->vhost) + wsi->vhost->conn_stats.rx += n; + lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n); + + return n; + } + + if (LWS_ERRNO == LWS_EAGAIN || + LWS_ERRNO == LWS_EWOULDBLOCK || + LWS_ERRNO == LWS_EINTR) + return LWS_SSL_CAPABLE_MORE_SERVICE; + + lwsl_notice("error on reading from skt : %d\n", LWS_ERRNO); + return LWS_SSL_CAPABLE_ERROR; +} + +LWS_VISIBLE int +lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len) +{ + int n = 0; + + if (lws_wsi_is_udp(wsi)) { +#if !defined(LWS_WITH_ESP32) + if (wsi->trunc_len) + n = sendto(wsi->desc.sockfd, buf, len, 0, &wsi->udp->sa_pending, wsi->udp->salen_pending); + else + n = sendto(wsi->desc.sockfd, buf, len, 0, &wsi->udp->sa, wsi->udp->salen); +#endif + } else + n = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL); +// lwsl_info("%s: sent len %d result %d", __func__, len, n); + if (n >= 0) + return n; + + if (LWS_ERRNO == LWS_EAGAIN || + LWS_ERRNO == LWS_EWOULDBLOCK || + LWS_ERRNO == LWS_EINTR) { + if (LWS_ERRNO == LWS_EWOULDBLOCK) { + lws_set_blocking_send(wsi); + } + + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + + lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n", + len, wsi->desc.sockfd, n, LWS_ERRNO); + + return LWS_SSL_CAPABLE_ERROR; +} + +LWS_VISIBLE int +lws_ssl_pending_no_ssl(struct lws *wsi) +{ + (void)wsi; +#if defined(LWS_WITH_ESP32) + return 100; +#else + return 0; +#endif +} diff --git a/thirdparty/lws/pollfd.c b/thirdparty/libwebsockets/core/pollfd.c index 54a4a86057..2a632ce8ec 100644 --- a/thirdparty/lws/pollfd.c +++ b/thirdparty/libwebsockets/core/pollfd.c @@ -19,21 +19,31 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" int _lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa) { +#if !defined(LWS_WITH_LIBUV) && !defined(LWS_WITH_LIBEV) && !defined(LWS_WITH_LIBEVENT) + volatile struct lws_context_per_thread *vpt; +#endif struct lws_context_per_thread *pt; struct lws_context *context; int ret = 0, pa_events = 1; struct lws_pollfd *pfd; int sampled_tid, tid; - if (!wsi || wsi->position_in_fds_table < 0) + if (!wsi) + return 0; + + assert(wsi->position_in_fds_table == LWS_NO_FDS_POS || + wsi->position_in_fds_table >= 0); + + if (wsi->position_in_fds_table == LWS_NO_FDS_POS) return 0; - if (wsi->handling_pollout && !_and && _or == LWS_POLLOUT) { + if (((volatile struct lws *)wsi)->handling_pollout && + !_and && _or == LWS_POLLOUT) { /* * Happening alongside service thread handling POLLOUT. * The danger is when he is finished, he will disable POLLOUT, @@ -42,7 +52,7 @@ _lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa) * Instead of changing the fds, inform the service thread * what happened, and ask it to leave POLLOUT active on exit */ - wsi->leave_pollout_active = 1; + ((volatile struct lws *)wsi)->leave_pollout_active = 1; /* * by definition service thread is not in poll wait, so no need * to cancel service @@ -55,42 +65,106 @@ _lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa) context = wsi->context; pt = &context->pt[(int)wsi->tsi]; - assert(wsi->position_in_fds_table >= 0 && - wsi->position_in_fds_table < pt->fds_count); + + assert(wsi->position_in_fds_table < (int)pt->fds_count); + +#if !defined(LWS_WITH_LIBUV) && \ + !defined(LWS_WITH_LIBEV) && \ + !defined(LWS_WITH_LIBEVENT) + /* + * This only applies when we use the default poll() event loop. + * + * BSD can revert pa->events at any time, when the kernel decides to + * exit from poll(). We can't protect against it using locking. + * + * Therefore we must check first if the service thread is in poll() + * wait; if so, we know we must be being called from a foreign thread, + * and we must keep a strictly ordered list of changes we made instead + * of trying to apply them, since when poll() exits, which may happen + * at any time it would revert our changes. + * + * The plat code will apply them when it leaves the poll() wait + * before doing anything else. + */ + + vpt = (volatile struct lws_context_per_thread *)pt; + + vpt->foreign_spinlock = 1; + lws_memory_barrier(); + + if (vpt->inside_poll) { + struct lws_foreign_thread_pollfd *ftp, **ftp1; + /* + * We are certainly a foreign thread trying to change events + * while the service thread is in the poll() wait. + * + * Create a list of changes to be applied after poll() exit, + * instead of trying to apply them now. + */ + ftp = lws_malloc(sizeof(*ftp), "ftp"); + if (!ftp) { + vpt->foreign_spinlock = 0; + lws_memory_barrier(); + ret = -1; + goto bail; + } + + ftp->_and = _and; + ftp->_or = _or; + ftp->fd_index = wsi->position_in_fds_table; + ftp->next = NULL; + + /* place at END of list to maintain order */ + ftp1 = (struct lws_foreign_thread_pollfd **) + &vpt->foreign_pfd_list; + while (*ftp1) + ftp1 = &((*ftp1)->next); + + *ftp1 = ftp; + vpt->foreign_spinlock = 0; + lws_memory_barrier(); + lws_cancel_service_pt(wsi); + + return 0; + } + + vpt->foreign_spinlock = 0; + lws_memory_barrier(); +#endif pfd = &pt->fds[wsi->position_in_fds_table]; pa->fd = wsi->desc.sockfd; + lwsl_debug("%s: wsi %p: fd %d events %d -> %d\n", __func__, wsi, pa->fd, pfd->events, (pfd->events & ~_and) | _or); pa->prev_events = pfd->events; pa->events = pfd->events = (pfd->events & ~_and) | _or; if (wsi->http2_substream) return 0; - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CHANGE_MODE_POLL_FD, - wsi->user_space, (void *)pa, 0)) { + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, + LWS_CALLBACK_CHANGE_MODE_POLL_FD, + wsi->user_space, (void *)pa, 0)) { ret = -1; goto bail; } - if (_and & LWS_POLLIN) { - lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ); - lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ); - lws_libevent_io(wsi, LWS_EV_STOP | LWS_EV_READ); - } - if (_or & LWS_POLLIN) { - lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ); - lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ); - lws_libevent_io(wsi, LWS_EV_START | LWS_EV_READ); - } - if (_and & LWS_POLLOUT) { - lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); - lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); - lws_libevent_io(wsi, LWS_EV_STOP | LWS_EV_WRITE); - } - if (_or & LWS_POLLOUT) { - lws_libev_io(wsi, LWS_EV_START | LWS_EV_WRITE); - lws_libuv_io(wsi, LWS_EV_START | LWS_EV_WRITE); - lws_libevent_io(wsi, LWS_EV_START | LWS_EV_WRITE); + if (context->event_loop_ops->io) { + if (_and & LWS_POLLIN) + context->event_loop_ops->io(wsi, + LWS_EV_STOP | LWS_EV_READ); + + if (_or & LWS_POLLIN) + context->event_loop_ops->io(wsi, + LWS_EV_START | LWS_EV_READ); + + if (_and & LWS_POLLOUT) + context->event_loop_ops->io(wsi, + LWS_EV_STOP | LWS_EV_WRITE); + + if (_or & LWS_POLLOUT) + context->event_loop_ops->io(wsi, + LWS_EV_START | LWS_EV_WRITE); } /* @@ -100,20 +174,16 @@ _lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa) * ... and the service thread is waiting ... * then cancel it to force a restart with our changed events */ -#if LWS_POSIX pa_events = pa->prev_events != pa->events; -#endif if (pa_events) { - if (lws_plat_change_pollfd(context, wsi, pfd)) { lwsl_info("%s failed\n", __func__); ret = -1; goto bail; } - sampled_tid = context->service_tid; - if (sampled_tid) { + if (sampled_tid && wsi->vhost) { tid = wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_GET_THREAD_ID, NULL, NULL, 0); if (tid == -1) { @@ -124,34 +194,39 @@ _lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa) lws_cancel_service_pt(wsi); } } + bail: return ret; } #ifndef LWS_NO_SERVER +/* + * Enable or disable listen sockets on this pt globally... + * it's modulated according to the pt having space for a new accept. + */ static void -lws_accept_modulation(struct lws_context_per_thread *pt, int allow) +lws_accept_modulation(struct lws_context *context, + struct lws_context_per_thread *pt, int allow) { -// multithread listen seems broken -#if 0 struct lws_vhost *vh = context->vhost_list; struct lws_pollargs pa1; while (vh) { - if (allow) - _lws_change_pollfd(pt->wsi_listening, + if (vh->lserv_wsi) { + if (allow) + _lws_change_pollfd(vh->lserv_wsi, 0, LWS_POLLIN, &pa1); - else - _lws_change_pollfd(pt->wsi_listening, + else + _lws_change_pollfd(vh->lserv_wsi, LWS_POLLIN, 0, &pa1); + } vh = vh->vhost_next; } -#endif } #endif int -insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi) +__insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi) { struct lws_pollargs pa = { wsi->desc.sockfd, LWS_POLLIN, 0 }; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; @@ -167,52 +242,46 @@ insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi) return 1; } -#if !defined(_WIN32) && !defined(LWS_WITH_ESP8266) - if (wsi->desc.sockfd >= context->max_fds) { - lwsl_err("Socket fd %d is too high (%d)\n", - wsi->desc.sockfd, context->max_fds); +#if !defined(_WIN32) + if (wsi->desc.sockfd - lws_plat_socket_offset() >= context->max_fds) { + lwsl_err("Socket fd %d is too high (%d) offset %d\n", + wsi->desc.sockfd, context->max_fds, lws_plat_socket_offset()); return 1; } #endif assert(wsi); - assert(wsi->vhost); + assert(wsi->event_pipe || wsi->vhost); assert(lws_socket_is_valid(wsi->desc.sockfd)); - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *) &pa, 1)) return -1; - lws_pt_lock(pt); pt->count_conns++; insert_wsi(context, wsi); -#if defined(LWS_WITH_ESP8266) - if (wsi->position_in_fds_table == -1) -#endif - wsi->position_in_fds_table = pt->fds_count; + wsi->position_in_fds_table = pt->fds_count; pt->fds[wsi->position_in_fds_table].fd = wsi->desc.sockfd; -#if LWS_POSIX pt->fds[wsi->position_in_fds_table].events = LWS_POLLIN; -#else - pt->fds[wsi->position_in_fds_table].events = 0; -#endif pa.events = pt->fds[pt->fds_count].events; lws_plat_insert_socket_into_fds(context, wsi); /* external POLL support via protocol 0 */ - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_ADD_POLL_FD, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_ADD_POLL_FD, wsi->user_space, (void *) &pa, 0)) ret = -1; #ifndef LWS_NO_SERVER /* if no more room, defeat accepts on this thread */ if ((unsigned int)pt->fds_count == context->fd_limit_per_thread - 1) - lws_accept_modulation(pt, 0); + lws_accept_modulation(context, pt, 0); #endif - lws_pt_unlock(pt); - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *)&pa, 1)) ret = -1; @@ -220,15 +289,13 @@ insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi) } int -remove_wsi_socket_from_fds(struct lws *wsi) +__remove_wsi_socket_from_fds(struct lws *wsi) { struct lws_context *context = wsi->context; struct lws_pollargs pa = { wsi->desc.sockfd, 0, 0 }; -#if !defined(LWS_WITH_ESP8266) struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct lws *end_wsi; int v; -#endif int m, ret = 0; if (wsi->parent_carries_io) { @@ -236,15 +303,16 @@ remove_wsi_socket_from_fds(struct lws *wsi) return 0; } -#if !defined(_WIN32) && !defined(LWS_WITH_ESP8266) - if (wsi->desc.sockfd > context->max_fds) { +#if !defined(_WIN32) + if (wsi->desc.sockfd - lws_plat_socket_offset() > context->max_fds) { lwsl_err("fd %d too high (%d)\n", wsi->desc.sockfd, context->max_fds); return 1; } #endif - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, wsi->user_space, (void *)&pa, 1)) return -1; @@ -253,101 +321,114 @@ remove_wsi_socket_from_fds(struct lws *wsi) /* the guy who is to be deleted's slot index in pt->fds */ m = wsi->position_in_fds_table; -#if !defined(LWS_WITH_ESP8266) - lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE | - LWS_EV_PREPARE_DELETION); - lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE | - LWS_EV_PREPARE_DELETION); + /* these are the only valid possibilities for position_in_fds_table */ + assert(m == LWS_NO_FDS_POS || (m >= 0 && + (unsigned int)m < pt->fds_count)); - lws_pt_lock(pt); + if (context->event_loop_ops->io) + context->event_loop_ops->io(wsi, + LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE | + LWS_EV_PREPARE_DELETION); lwsl_debug("%s: wsi=%p, sock=%d, fds pos=%d, end guy pos=%d, endfd=%d\n", __func__, wsi, wsi->desc.sockfd, wsi->position_in_fds_table, pt->fds_count, pt->fds[pt->fds_count].fd); - /* have the last guy take up the now vacant slot */ - pt->fds[m] = pt->fds[pt->fds_count - 1]; -#endif - /* this decrements pt->fds_count */ - lws_plat_delete_socket_from_fds(context, wsi, m); -#if !defined(LWS_WITH_ESP8266) - v = (int) pt->fds[m].fd; - /* end guy's "position in fds table" is now the deletion guy's old one */ - end_wsi = wsi_from_fd(context, v); - if (!end_wsi) { - lwsl_err("no wsi found for sock fd %d at pos %d, pt->fds_count=%d\n", - (int)pt->fds[m].fd, m, pt->fds_count); - assert(0); - } else - end_wsi->position_in_fds_table = m; - - /* deletion guy's lws_lookup entry needs nuking */ - delete_from_fd(context, wsi->desc.sockfd); - /* removed wsi has no position any more */ - wsi->position_in_fds_table = -1; + if (m != LWS_NO_FDS_POS) { + + /* have the last guy take up the now vacant slot */ + pt->fds[m] = pt->fds[pt->fds_count - 1]; + /* this decrements pt->fds_count */ + lws_plat_delete_socket_from_fds(context, wsi, m); + v = (int) pt->fds[m].fd; + /* end guy's "position in fds table" is now the deletion guy's old one */ + end_wsi = wsi_from_fd(context, v); + if (!end_wsi) { + lwsl_err("no wsi for fd %d at pos %d, pt->fds_count=%d\n", + (int)pt->fds[m].fd, m, pt->fds_count); + assert(0); + } else + end_wsi->position_in_fds_table = m; + + /* deletion guy's lws_lookup entry needs nuking */ + delete_from_fd(context, wsi->desc.sockfd); + + /* removed wsi has no position any more */ + wsi->position_in_fds_table = LWS_NO_FDS_POS; + } /* remove also from external POLL support via protocol 0 */ - if (lws_socket_is_valid(wsi->desc.sockfd)) - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_DEL_POLL_FD, - wsi->user_space, (void *) &pa, 0)) - ret = -1; + if (lws_socket_is_valid(wsi->desc.sockfd) && wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_DEL_POLL_FD, + wsi->user_space, (void *) &pa, 0)) + ret = -1; + #ifndef LWS_NO_SERVER - if (!context->being_destroyed) - /* if this made some room, accept connects on this thread */ - if ((unsigned int)pt->fds_count < context->fd_limit_per_thread - 1) - lws_accept_modulation(pt, 1); + if (!context->being_destroyed && + /* if this made some room, accept connects on this thread */ + (unsigned int)pt->fds_count < context->fd_limit_per_thread - 1) + lws_accept_modulation(context, pt, 1); #endif - lws_pt_unlock(pt); - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 1)) ret = -1; -#endif + return ret; } int -lws_change_pollfd(struct lws *wsi, int _and, int _or) +__lws_change_pollfd(struct lws *wsi, int _and, int _or) { - struct lws_context_per_thread *pt; struct lws_context *context; struct lws_pollargs pa; int ret = 0; - if (!wsi || !wsi->protocol || wsi->position_in_fds_table < 0) - return 1; + if (!wsi || (!wsi->protocol && !wsi->event_pipe) || + wsi->position_in_fds_table == LWS_NO_FDS_POS) + return 0; context = lws_get_context(wsi); if (!context) return 1; - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, - wsi->user_space, (void *) &pa, 0)) + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_LOCK_POLL, + wsi->user_space, (void *) &pa, 0)) return -1; - pt = &context->pt[(int)wsi->tsi]; - - lws_pt_lock(pt); ret = _lws_change_pollfd(wsi, _and, _or, &pa); - lws_pt_unlock(pt); - if (wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, + if (wsi->vhost && + wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_UNLOCK_POLL, wsi->user_space, (void *) &pa, 0)) ret = -1; return ret; } +int +lws_change_pollfd(struct lws *wsi, int _and, int _or) +{ + struct lws_context_per_thread *pt; + int ret = 0; + + pt = &wsi->context->pt[(int)wsi->tsi]; + + lws_pt_lock(pt, __func__); + ret = __lws_change_pollfd(wsi, _and, _or); + lws_pt_unlock(pt); + + return ret; +} + LWS_VISIBLE int lws_callback_on_writable(struct lws *wsi) { struct lws_context_per_thread *pt; -#ifdef LWS_WITH_HTTP2 - struct lws *network_wsi, *wsi2; - int already; -#endif int n; - if (wsi->state == LWSS_SHUTDOWN) + if (lwsi_state(wsi) == LRS_SHUTDOWN) return 0; if (wsi->socket_is_permanently_unusable) @@ -375,72 +456,31 @@ lws_callback_on_writable(struct lws *wsi) #if defined(LWS_WITH_STATS) if (!wsi->active_writable_req_us) { wsi->active_writable_req_us = time_in_microseconds(); - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB_EFF_REQ, 1); + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_WRITEABLE_CB_EFF_REQ, 1); } #endif -#ifdef LWS_WITH_HTTP2 - lwsl_info("%s: %p\n", __func__, wsi); - - if (wsi->mode != LWSCM_HTTP2_SERVING) - goto network_sock; - if (wsi->u.h2.requested_POLLOUT) { - lwsl_info("already pending writable\n"); - return 1; + if (wsi->role_ops->callback_on_writable) { + if (wsi->role_ops->callback_on_writable(wsi)) + return 1; + wsi = lws_get_network_wsi(wsi); } - /* is this for DATA or for control messages? */ - if (wsi->upgraded_to_http2 && !wsi->u.h2.h2n->pps && - !lws_h2_tx_cr_get(wsi)) { - /* - * other side is not able to cope with us sending DATA - * anything so no matter if we have POLLOUT on our side if it's - * DATA we want to send. - * - * Delay waiting for our POLLOUT until peer indicates he has - * space for more using tx window command in http2 layer - */ - lwsl_notice("%s: %p: skint (%d)\n", __func__, wsi, wsi->u.h2.tx_cr); - wsi->u.h2.skint = 1; - return 0; - } - - wsi->u.h2.skint = 0; - network_wsi = lws_get_network_wsi(wsi); - already = network_wsi->u.h2.requested_POLLOUT; - - /* mark everybody above him as requesting pollout */ - - wsi2 = wsi; - while (wsi2) { - wsi2->u.h2.requested_POLLOUT = 1; - lwsl_info("mark %p pending writable\n", wsi2); - wsi2 = wsi2->u.h2.parent_wsi; - } - - /* for network action, act only on the network wsi */ - - wsi = network_wsi; - if (already) - return 1; -network_sock: -#endif - - if (lws_ext_cb_active(wsi, LWS_EXT_CB_REQUEST_ON_WRITEABLE, NULL, 0)) - return 1; - - if (wsi->position_in_fds_table < 0) { - lwsl_debug("%s: failed to find socket %d\n", __func__, wsi->desc.sockfd); + if (wsi->position_in_fds_table == LWS_NO_FDS_POS) { + lwsl_debug("%s: failed to find socket %d\n", __func__, + wsi->desc.sockfd); return -1; } - if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) + if (__lws_change_pollfd(wsi, 0, LWS_POLLOUT)) return -1; return 1; } + /* * stitch protocol choice into the vh protocol linked list * We always insert ourselves at the start of the list @@ -458,6 +498,8 @@ lws_same_vh_protocol_insert(struct lws *wsi, int n) lwsl_notice("Attempted to attach wsi twice to same vh prot\n"); } + lws_vhost_lock(wsi->vhost); + wsi->same_vh_protocol_prev = &wsi->vhost->same_vh_protocol_list[n]; /* old first guy is our next */ wsi->same_vh_protocol_next = wsi->vhost->same_vh_protocol_list[n]; @@ -468,6 +510,10 @@ lws_same_vh_protocol_insert(struct lws *wsi, int n) /* old first guy points back to us now */ wsi->same_vh_protocol_next->same_vh_protocol_prev = &wsi->same_vh_protocol_next; + + wsi->on_same_vh_list = 1; + + lws_vhost_unlock(wsi->vhost); } void @@ -482,6 +528,11 @@ lws_same_vh_protocol_remove(struct lws *wsi) */ lwsl_info("%s: removing same prot wsi %p\n", __func__, wsi); + if (!wsi->vhost || !wsi->on_same_vh_list) + return; + + lws_vhost_lock(wsi->vhost); + if (wsi->same_vh_protocol_prev) { assert (*(wsi->same_vh_protocol_prev) == wsi); lwsl_info("have prev %p, setting him to our next %p\n", @@ -493,13 +544,15 @@ lws_same_vh_protocol_remove(struct lws *wsi) } /* our next should point back to our prev */ - if (wsi->same_vh_protocol_next) { + if (wsi->same_vh_protocol_next) wsi->same_vh_protocol_next->same_vh_protocol_prev = wsi->same_vh_protocol_prev; - } wsi->same_vh_protocol_prev = NULL; wsi->same_vh_protocol_next = NULL; + wsi->on_same_vh_list = 0; + + lws_vhost_unlock(wsi->vhost); } @@ -523,7 +576,8 @@ lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost, assert(wsi->protocol == protocol); assert(*wsi->same_vh_protocol_prev == wsi); if (wsi->same_vh_protocol_next) - assert(wsi->same_vh_protocol_next->same_vh_protocol_prev == + assert(wsi->same_vh_protocol_next-> + same_vh_protocol_prev == &wsi->same_vh_protocol_next); lws_callback_on_writable(wsi); diff --git a/thirdparty/libwebsockets/core/private.h b/thirdparty/libwebsockets/core/private.h new file mode 100644 index 0000000000..d6b494ac8c --- /dev/null +++ b/thirdparty/libwebsockets/core/private.h @@ -0,0 +1,1751 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "lws_config.h" +#include "lws_config_private.h" + +#if defined(LWS_WITH_CGI) && defined(LWS_HAVE_VFORK) + #define _GNU_SOURCE +#endif + +#if defined(__COVERITY__) && !defined(LWS_COVERITY_WORKAROUND) + #define LWS_COVERITY_WORKAROUND + typedef float _Float32; + typedef float _Float64; + typedef float _Float128; + typedef float _Float32x; + typedef float _Float64x; + typedef float _Float128x; +#endif + +#ifdef LWS_HAVE_SYS_TYPES_H + #include <sys/types.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <ctype.h> +#include <limits.h> +#include <stdarg.h> +#include <inttypes.h> + +#if defined(LWS_WITH_ESP32) + #define MSG_NOSIGNAL 0 + #define SOMAXCONN 3 +#endif + +#define STORE_IN_ROM +#include <assert.h> +#if LWS_MAX_SMP > 1 + #include <pthread.h> +#endif + +#ifdef LWS_HAVE_SYS_STAT_H + #include <sys/stat.h> +#endif + +#if defined(WIN32) || defined(_WIN32) + + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + + #if (WINVER < 0x0501) + #undef WINVER + #undef _WIN32_WINNT + #define WINVER 0x0501 + #define _WIN32_WINNT WINVER + #endif + + #define LWS_NO_DAEMONIZE + #define LWS_ERRNO WSAGetLastError() + #define LWS_EAGAIN WSAEWOULDBLOCK + #define LWS_EALREADY WSAEALREADY + #define LWS_EINPROGRESS WSAEINPROGRESS + #define LWS_EINTR WSAEINTR + #define LWS_EISCONN WSAEISCONN + #define LWS_EWOULDBLOCK WSAEWOULDBLOCK + #define MSG_NOSIGNAL 0 + #define SHUT_RDWR SD_BOTH + #define SOL_TCP IPPROTO_TCP + #define SHUT_WR SD_SEND + + #define compatible_close(fd) closesocket(fd) + #define lws_set_blocking_send(wsi) wsi->sock_send_blocking = 1 + #define LWS_SOCK_INVALID (INVALID_SOCKET) + + #include <winsock2.h> + #include <ws2tcpip.h> + #include <windows.h> + #include <tchar.h> + #ifdef LWS_HAVE_IN6ADDR_H + #include <in6addr.h> + #endif + #include <mstcpip.h> + #include <io.h> + + #if !defined(LWS_HAVE_ATOLL) + #if defined(LWS_HAVE__ATOI64) + #define atoll _atoi64 + #else + #warning No atoll or _atoi64 available, using atoi + #define atoll atoi + #endif + #endif + + #ifndef __func__ + #define __func__ __FUNCTION__ + #endif + + #ifdef LWS_HAVE__VSNPRINTF + #define vsnprintf _vsnprintf + #endif + + /* we don't have an implementation for this on windows... */ + int kill(int pid, int sig); + int fork(void); + #ifndef SIGINT + #define SIGINT 2 + #endif + +#else /* not windows --> */ + + #include <fcntl.h> + #include <strings.h> + #include <unistd.h> + #include <sys/types.h> + + #ifndef __cplusplus + #include <errno.h> + #endif + #include <netdb.h> + #include <signal.h> + #include <sys/socket.h> + + #if defined(LWS_BUILTIN_GETIFADDRS) + #include "./misc/getifaddrs.h" + #else + #if !defined(LWS_WITH_ESP32) + #if defined(__HAIKU__) + #define _BSD_SOURCE + #endif + #include <ifaddrs.h> + #endif + #endif + #if defined (__ANDROID__) + #include <syslog.h> + #include <sys/resource.h> + #elif defined (__sun) || defined(__HAIKU__) || defined(__QNX__) + #include <syslog.h> + #else + #if !defined(LWS_WITH_ESP32) + #include <sys/syslog.h> + #endif + #endif + #include <netdb.h> + #if !defined(LWS_WITH_ESP32) + #include <sys/mman.h> + #include <sys/un.h> + #include <netinet/in.h> + #include <netinet/tcp.h> + #include <arpa/inet.h> + #include <poll.h> + #endif + #ifndef LWS_NO_FORK + #ifdef LWS_HAVE_SYS_PRCTL_H + #include <sys/prctl.h> + #endif + #endif + + #include <sys/time.h> + + #define LWS_ERRNO errno + #define LWS_EAGAIN EAGAIN + #define LWS_EALREADY EALREADY + #define LWS_EINPROGRESS EINPROGRESS + #define LWS_EINTR EINTR + #define LWS_EISCONN EISCONN + #define LWS_EWOULDBLOCK EWOULDBLOCK + + #define lws_set_blocking_send(wsi) + + #define LWS_SOCK_INVALID (-1) +#endif /* not windows */ + +#ifndef LWS_HAVE_BZERO + #ifndef bzero + #define bzero(b, len) (memset((b), '\0', (len)), (void) 0) + #endif +#endif + +#ifndef LWS_HAVE_STRERROR + #define strerror(x) "" +#endif + + +#define lws_socket_is_valid(x) (x != LWS_SOCK_INVALID) + +#include "libwebsockets.h" + +#include "tls/private.h" + +#if defined(WIN32) || defined(_WIN32) + #include <gettimeofday.h> + + #ifndef BIG_ENDIAN + #define BIG_ENDIAN 4321 /* to show byte order (taken from gcc) */ + #endif + #ifndef LITTLE_ENDIAN + #define LITTLE_ENDIAN 1234 + #endif + #ifndef BYTE_ORDER + #define BYTE_ORDER LITTLE_ENDIAN + #endif + + #undef __P + #ifndef __P + #if __STDC__ + #define __P(protos) protos + #else + #define __P(protos) () + #endif + #endif + +#else /* not windows */ + static inline int compatible_close(int fd) { return close(fd); } + + #include <sys/stat.h> + #include <sys/time.h> + + #if defined(__APPLE__) + #include <machine/endian.h> + #elif defined(__FreeBSD__) + #include <sys/endian.h> + #elif defined(__linux__) + #include <endian.h> + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__QNX__) + #include <gulliver.h> + #if defined(__LITTLEENDIAN__) + #define BYTE_ORDER __LITTLEENDIAN__ + #define LITTLE_ENDIAN __LITTLEENDIAN__ + #define BIG_ENDIAN 4321 /* to show byte order (taken from gcc); for suppres warning that BIG_ENDIAN is not defined. */ + #endif + #if defined(__BIGENDIAN__) + #define BYTE_ORDER __BIGENDIAN__ + #define LITTLE_ENDIAN 1234 /* to show byte order (taken from gcc); for suppres warning that LITTLE_ENDIAN is not defined. */ + #define BIG_ENDIAN __BIGENDIAN__ + #endif +#endif + +#if defined(__sun) && defined(__GNUC__) + + #include <arpa/nameser_compat.h> + + #if !defined (BYTE_ORDER) + #define BYTE_ORDER __BYTE_ORDER__ + #endif + + #if !defined(LITTLE_ENDIAN) + #define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ + #endif + + #if !defined(BIG_ENDIAN) + #define BIG_ENDIAN __ORDER_BIG_ENDIAN__ + #endif + +#endif /* sun + GNUC */ + +#if !defined(BYTE_ORDER) + #define BYTE_ORDER __BYTE_ORDER +#endif +#if !defined(LITTLE_ENDIAN) + #define LITTLE_ENDIAN __LITTLE_ENDIAN +#endif +#if !defined(BIG_ENDIAN) + #define BIG_ENDIAN __BIG_ENDIAN +#endif + + +/* + * Mac OSX as well as iOS do not define the MSG_NOSIGNAL flag, + * but happily have something equivalent in the SO_NOSIGPIPE flag. + */ +#ifdef __APPLE__ +#define MSG_NOSIGNAL SO_NOSIGPIPE +#endif + +/* + * Solaris 11.X only supports POSIX 2001, MSG_NOSIGNAL appears in + * POSIX 2008. + */ +#ifdef __sun + #define MSG_NOSIGNAL 0 +#endif + +#ifdef _WIN32 + #ifndef FD_HASHTABLE_MODULUS + #define FD_HASHTABLE_MODULUS 32 + #endif +#endif + +#ifndef LWS_DEF_HEADER_LEN +#define LWS_DEF_HEADER_LEN 4096 +#endif +#ifndef LWS_DEF_HEADER_POOL +#define LWS_DEF_HEADER_POOL 4 +#endif +#ifndef LWS_MAX_PROTOCOLS +#define LWS_MAX_PROTOCOLS 5 +#endif +#ifndef LWS_MAX_EXTENSIONS_ACTIVE +#define LWS_MAX_EXTENSIONS_ACTIVE 1 +#endif +#ifndef LWS_MAX_EXT_OFFERS +#define LWS_MAX_EXT_OFFERS 8 +#endif +#ifndef SPEC_LATEST_SUPPORTED +#define SPEC_LATEST_SUPPORTED 13 +#endif +#ifndef AWAITING_TIMEOUT +#define AWAITING_TIMEOUT 20 +#endif +#ifndef CIPHERS_LIST_STRING +#define CIPHERS_LIST_STRING "DEFAULT" +#endif +#ifndef LWS_SOMAXCONN +#define LWS_SOMAXCONN SOMAXCONN +#endif + +#define MAX_WEBSOCKET_04_KEY_LEN 128 + +#ifndef SYSTEM_RANDOM_FILEPATH +#define SYSTEM_RANDOM_FILEPATH "/dev/urandom" +#endif + +#define LWS_H2_RX_SCRATCH_SIZE 512 + + + +/* + * All lws_tls...() functions must return this type, converting the + * native backend result and doing the extra work to determine which one + * as needed. + * + * Native TLS backend return codes are NOT ALLOWED outside the backend. + * + * Non-SSL mode also uses these types. + */ +enum lws_ssl_capable_status { + LWS_SSL_CAPABLE_ERROR = -1, /* it failed */ + LWS_SSL_CAPABLE_DONE = 0, /* it succeeded */ + LWS_SSL_CAPABLE_MORE_SERVICE_READ = -2, /* retry WANT_READ */ + LWS_SSL_CAPABLE_MORE_SERVICE_WRITE = -3, /* retry WANT_WRITE */ + LWS_SSL_CAPABLE_MORE_SERVICE = -4, /* general retry */ +}; + +#if defined(__clang__) +#define lws_memory_barrier() __sync_synchronize() +#elif defined(__GNUC__) +#define lws_memory_barrier() __sync_synchronize() +#else +#define lws_memory_barrier() +#endif + +/* + * + * ------ roles ------ + * + */ + +#include "roles/private.h" + +/* null-terminated array of pointers to roles lws built with */ +extern const struct lws_role_ops *available_roles[]; + +#define LWS_FOR_EVERY_AVAILABLE_ROLE_START(xx) { \ + const struct lws_role_ops **ppxx = available_roles; \ + while (*ppxx) { \ + const struct lws_role_ops *xx = *ppxx++; + +#define LWS_FOR_EVERY_AVAILABLE_ROLE_END }} + +/* + * + * ------ event_loop ops ------ + * + */ + +#include "event-libs/private.h" + +/* enums of socks version */ +enum socks_version { + SOCKS_VERSION_4 = 4, + SOCKS_VERSION_5 = 5 +}; + +/* enums of subnegotiation version */ +enum socks_subnegotiation_version { + SOCKS_SUBNEGOTIATION_VERSION_1 = 1, +}; + +/* enums of socks commands */ +enum socks_command { + SOCKS_COMMAND_CONNECT = 1, + SOCKS_COMMAND_BIND = 2, + SOCKS_COMMAND_UDP_ASSOCIATE = 3 +}; + +/* enums of socks address type */ +enum socks_atyp { + SOCKS_ATYP_IPV4 = 1, + SOCKS_ATYP_DOMAINNAME = 3, + SOCKS_ATYP_IPV6 = 4 +}; + +/* enums of socks authentication methods */ +enum socks_auth_method { + SOCKS_AUTH_NO_AUTH = 0, + SOCKS_AUTH_GSSAPI = 1, + SOCKS_AUTH_USERNAME_PASSWORD = 2 +}; + +/* enums of subnegotiation status */ +enum socks_subnegotiation_status { + SOCKS_SUBNEGOTIATION_STATUS_SUCCESS = 0, +}; + +/* enums of socks request reply */ +enum socks_request_reply { + SOCKS_REQUEST_REPLY_SUCCESS = 0, + SOCKS_REQUEST_REPLY_FAILURE_GENERAL = 1, + SOCKS_REQUEST_REPLY_CONNECTION_NOT_ALLOWED = 2, + SOCKS_REQUEST_REPLY_NETWORK_UNREACHABLE = 3, + SOCKS_REQUEST_REPLY_HOST_UNREACHABLE = 4, + SOCKS_REQUEST_REPLY_CONNECTION_REFUSED = 5, + SOCKS_REQUEST_REPLY_TTL_EXPIRED = 6, + SOCKS_REQUEST_REPLY_COMMAND_NOT_SUPPORTED = 7, + SOCKS_REQUEST_REPLY_ATYP_NOT_SUPPORTED = 8 +}; + +/* enums used to generate socks messages */ +enum socks_msg_type { + /* greeting */ + SOCKS_MSG_GREETING, + /* credential, user name and password */ + SOCKS_MSG_USERNAME_PASSWORD, + /* connect command */ + SOCKS_MSG_CONNECT +}; + +enum { + LWS_RXFLOW_ALLOW = (1 << 0), + LWS_RXFLOW_PENDING_CHANGE = (1 << 1), +}; + +struct lws_ring { + void *buf; + void (*destroy_element)(void *element); + uint32_t buflen; + uint32_t element_len; + uint32_t head; + uint32_t oldest_tail; +}; + +struct lws_protocols; +struct lws; + +struct lws_io_watcher { +#ifdef LWS_WITH_LIBEV + struct lws_io_watcher_libev ev; +#endif +#ifdef LWS_WITH_LIBUV + struct lws_io_watcher_libuv uv; +#endif +#ifdef LWS_WITH_LIBEVENT + struct lws_io_watcher_libevent event; +#endif + struct lws_context *context; + + uint8_t actual_events; +}; + +struct lws_signal_watcher { +#ifdef LWS_WITH_LIBEV + struct lws_signal_watcher_libev ev; +#endif +#ifdef LWS_WITH_LIBUV + struct lws_signal_watcher_libuv uv; +#endif +#ifdef LWS_WITH_LIBEVENT + struct lws_signal_watcher_libevent event; +#endif + struct lws_context *context; +}; + +#ifdef _WIN32 +#define LWS_FD_HASH(fd) ((fd ^ (fd >> 8) ^ (fd >> 16)) % FD_HASHTABLE_MODULUS) +struct lws_fd_hashtable { + struct lws **wsi; + int length; +}; +#endif + +struct lws_foreign_thread_pollfd { + struct lws_foreign_thread_pollfd *next; + int fd_index; + int _and; + int _or; +}; + + +#define LWS_HRTIMER_NOWAIT (0x7fffffffffffffffll) + +/* + * so we can have n connections being serviced simultaneously, + * these things need to be isolated per-thread. + */ + +struct lws_context_per_thread { +#if LWS_MAX_SMP > 1 + pthread_mutex_t lock; + pthread_mutex_t lock_stats; + pthread_t lock_owner; + const char *last_lock_reason; +#endif + + struct lws_context *context; + + /* + * usable by anything in the service code, but only if the scope + * does not last longer than the service action (since next service + * of any socket can likewise use it and overwrite) + */ + unsigned char *serv_buf; + + struct lws_dll_lws dll_head_timeout; + struct lws_dll_lws dll_head_hrtimer; + struct lws_dll_lws dll_head_buflist; /* guys with pending rxflow */ + +#if defined(LWS_WITH_TLS) + struct lws_pt_tls tls; +#endif + + struct lws_pollfd *fds; + volatile struct lws_foreign_thread_pollfd * volatile foreign_pfd_list; +#ifdef _WIN32 + WSAEVENT *events; +#endif + lws_sockfd_type dummy_pipe_fds[2]; + struct lws *pipe_wsi; + + /* --- role based members --- */ + +#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_pt_role_ws ws; +#endif +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + struct lws_pt_role_http http; +#endif + + /* --- event library based members --- */ + +#if defined(LWS_WITH_LIBEV) + struct lws_pt_eventlibs_libev ev; +#endif +#if defined(LWS_WITH_LIBUV) + struct lws_pt_eventlibs_libuv uv; +#endif +#if defined(LWS_WITH_LIBEVENT) + struct lws_pt_eventlibs_libevent event; +#endif + +#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) + struct lws_signal_watcher w_sigint; +#endif + + /* --- */ + + unsigned long count_conns; + unsigned int fds_count; + + volatile unsigned char inside_poll; + volatile unsigned char foreign_spinlock; + + unsigned char tid; + + unsigned char lock_depth; + unsigned char inside_service:1; + unsigned char event_loop_foreign:1; + unsigned char event_loop_destroy_processing_done:1; +}; + +struct lws_conn_stats { + unsigned long long rx, tx; + unsigned long h1_conn, h1_trans, h2_trans, ws_upg, h2_alpn, h2_subs, + h2_upg, rejected; +}; + +void +lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs); + +struct lws_timed_vh_protocol { + struct lws_timed_vh_protocol *next; + const struct lws_protocols *protocol; + time_t time; + int reason; +}; + +/* + * virtual host -related context information + * vhostwide SSL context + * vhostwide proxy + * + * hierarchy: + * + * context -> vhost -> wsi + * + * incoming connection non-SSL vhost binding: + * + * listen socket -> wsi -> select vhost after first headers + * + * incoming connection SSL vhost binding: + * + * SSL SNI -> wsi -> bind after SSL negotiation + */ + + +struct lws_vhost { +#if !defined(LWS_WITHOUT_CLIENT) + char proxy_basic_auth_token[128]; +#endif +#if LWS_MAX_SMP > 1 + pthread_mutex_t lock; +#endif + +#if defined(LWS_ROLE_H2) + struct lws_vhost_role_h2 h2; +#endif +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + struct lws_vhost_role_http http; +#endif +#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_vhost_role_ws ws; +#endif + +#if defined(LWS_WITH_SOCKS5) + char socks_proxy_address[128]; + char socks_user[96]; + char socks_password[96]; +#endif +#if defined(LWS_WITH_LIBEV) + struct lws_io_watcher w_accept; +#endif + struct lws_conn_stats conn_stats; + struct lws_context *context; + struct lws_vhost *vhost_next; + + struct lws *lserv_wsi; + const char *name; + const char *iface; + +#if !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32) + int bind_iface; +#endif + const struct lws_protocols *protocols; + void **protocol_vh_privs; + const struct lws_protocol_vhost_options *pvo; + const struct lws_protocol_vhost_options *headers; + struct lws **same_vh_protocol_list; + struct lws_vhost *no_listener_vhost_list; +#if !defined(LWS_NO_CLIENT) + struct lws_dll_lws dll_active_client_conns; +#endif + +#if defined(LWS_WITH_TLS) + struct lws_vhost_tls tls; +#endif + + struct lws_timed_vh_protocol *timed_vh_protocol_list; + void *user; + + int listen_port; + +#if defined(LWS_WITH_SOCKS5) + unsigned int socks_proxy_port; +#endif + unsigned int options; + int count_protocols; + int ka_time; + int ka_probes; + int ka_interval; + int keepalive_timeout; + int timeout_secs_ah_idle; + +#ifdef LWS_WITH_ACCESS_LOG + int log_fd; +#endif + + unsigned int created_vhost_protocols:1; + unsigned int being_destroyed:1; + + unsigned char default_protocol_index; + unsigned char raw_protocol_index; +}; + +struct lws_deferred_free +{ + struct lws_deferred_free *next; + time_t deadline; + void *payload; +}; + +typedef union { +#ifdef LWS_WITH_IPV6 + struct sockaddr_in6 sa6; +#endif + struct sockaddr_in sa4; +} sockaddr46; + + +#if defined(LWS_WITH_PEER_LIMITS) +struct lws_peer { + struct lws_peer *next; + struct lws_peer *peer_wait_list; + + time_t time_created; + time_t time_closed_all; + + uint8_t addr[32]; + uint32_t hash; + uint32_t count_wsi; + uint32_t total_wsi; + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + struct lws_peer_role_http http; +#endif + + uint8_t af; +}; +#endif + +/* + * the rest is managed per-context, that includes + * + * - processwide single fd -> wsi lookup + * - contextwide headers pool + */ + +struct lws_context { + time_t last_timeout_check_s; + time_t last_ws_ping_pong_check_s; + time_t time_up; + time_t time_discontiguity; + time_t time_fixup; + const struct lws_plat_file_ops *fops; + struct lws_plat_file_ops fops_platform; + struct lws_context **pcontext_finalize; + + const struct lws_tls_ops *tls_ops; + +#if defined(LWS_WITH_HTTP2) + struct http2_settings set; +#endif +#if defined(LWS_WITH_ZIP_FOPS) + struct lws_plat_file_ops fops_zip; +#endif + struct lws_context_per_thread pt[LWS_MAX_SMP]; + struct lws_conn_stats conn_stats; +#if LWS_MAX_SMP > 1 + pthread_mutex_t lock; + int lock_depth; +#endif +#ifdef _WIN32 +/* different implementation between unix and windows */ + struct lws_fd_hashtable fd_hashtable[FD_HASHTABLE_MODULUS]; +#else + struct lws **lws_lookup; /* fd to wsi */ +#endif + struct lws_vhost *vhost_list; + struct lws_vhost *no_listener_vhost_list; + struct lws_vhost *vhost_pending_destruction_list; + struct lws_plugin *plugin_list; + struct lws_deferred_free *deferred_free_list; +#if defined(LWS_WITH_PEER_LIMITS) + struct lws_peer **pl_hash_table; + struct lws_peer *peer_wait_list; + time_t next_cull; +#endif + + void *external_baggage_free_on_destroy; + const struct lws_token_limits *token_limits; + void *user_space; + const struct lws_protocol_vhost_options *reject_service_keywords; + lws_reload_func deprecation_cb; + void (*eventlib_signal_cb)(void *event_lib_handle, int signum); + +#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP) + cap_value_t caps[4]; + char count_caps; +#endif + +#if defined(LWS_WITH_LIBEV) + struct lws_context_eventlibs_libev ev; +#endif +#if defined(LWS_WITH_LIBUV) + struct lws_context_eventlibs_libuv uv; +#endif +#if defined(LWS_WITH_LIBEVENT) + struct lws_context_eventlibs_libevent event; +#endif + struct lws_event_loop_ops *event_loop_ops; + + +#if defined(LWS_WITH_TLS) + struct lws_context_tls tls; +#endif + + char canonical_hostname[128]; + const char *server_string; + +#ifdef LWS_LATENCY + unsigned long worst_latency; + char worst_latency_info[256]; +#endif + +#if defined(LWS_WITH_STATS) + uint64_t lws_stats[LWSSTATS_SIZE]; + uint64_t last_dump; + int updated; +#endif +#if defined(LWS_WITH_ESP32) + unsigned long time_last_state_dump; + uint32_t last_free_heap; +#endif + + int max_fds; + int count_event_loop_static_asset_handles; + int started_with_parent; + int uid, gid; + + int fd_random; + + int count_wsi_allocated; + int count_cgi_spawned; + unsigned int options; + unsigned int fd_limit_per_thread; + unsigned int timeout_secs; + unsigned int pt_serv_buf_size; + int max_http_header_data; + int simultaneous_ssl_restriction; + int simultaneous_ssl; +#if defined(LWS_WITH_PEER_LIMITS) + uint32_t pl_hash_elements; /* protected by context->lock */ + uint32_t count_peers; /* protected by context->lock */ + unsigned short ip_limit_ah; + unsigned short ip_limit_wsi; +#endif + unsigned int deprecated:1; + unsigned int being_destroyed:1; + unsigned int being_destroyed1:1; + unsigned int being_destroyed2:1; + unsigned int requested_kill:1; + unsigned int protocol_init_done:1; + unsigned int doing_protocol_init:1; + unsigned int done_protocol_destroy_cb:1; + unsigned int finalize_destroy_after_internal_loops_stopped:1; + /* + * set to the Thread ID that's doing the service loop just before entry + * to poll indicates service thread likely idling in poll() + * volatile because other threads may check it as part of processing + * for pollfd event change. + */ + volatile int service_tid; + int service_tid_detected; + + short max_http_header_pool; + short count_threads; + short plugin_protocol_count; + short plugin_extension_count; + short server_string_len; + unsigned short ws_ping_pong_interval; + unsigned short deprecation_pending_listen_close_count; + + uint8_t max_fi; +}; + +int +lws_check_deferred_free(struct lws_context *context, int force); + +#define lws_get_context_protocol(ctx, x) ctx->vhost_list->protocols[x] +#define lws_get_vh_protocol(vh, x) vh->protocols[x] + +LWS_EXTERN void +__lws_close_free_wsi_final(struct lws *wsi); +LWS_EXTERN void +lws_libuv_closehandle(struct lws *wsi); +LWS_EXTERN int +lws_libuv_check_watcher_active(struct lws *wsi); + +LWS_VISIBLE LWS_EXTERN int +lws_plat_plugins_init(struct lws_context * context, const char * const *d); + +LWS_VISIBLE LWS_EXTERN int +lws_plat_plugins_destroy(struct lws_context * context); + +LWS_EXTERN void +lws_restart_ws_ping_pong_timer(struct lws *wsi); + +struct lws * +lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd); + +int +lws_jws_base64_enc(const char *in, size_t in_len, char *out, size_t out_max); + +void +lws_vhost_destroy1(struct lws_vhost *vh); + +enum { + LWS_EV_READ = (1 << 0), + LWS_EV_WRITE = (1 << 1), + LWS_EV_START = (1 << 2), + LWS_EV_STOP = (1 << 3), + + LWS_EV_PREPARE_DELETION = (1 << 31), +}; + + +#if defined(LWS_WITH_ESP32) +LWS_EXTERN int +lws_find_string_in_file(const char *filename, const char *string, int stringlen); +#endif + +#ifdef LWS_WITH_IPV6 +#define LWS_IPV6_ENABLED(vh) \ + (!lws_check_opt(vh->context->options, LWS_SERVER_OPTION_DISABLE_IPV6) && \ + !lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_IPV6)) +#else +#define LWS_IPV6_ENABLED(context) (0) +#endif + +#ifdef LWS_WITH_UNIX_SOCK +#define LWS_UNIX_SOCK_ENABLED(vhost) \ + (vhost->options & LWS_SERVER_OPTION_UNIX_SOCK) +#else +#define LWS_UNIX_SOCK_ENABLED(vhost) (0) +#endif + +enum uri_path_states { + URIPS_IDLE, + URIPS_SEEN_SLASH, + URIPS_SEEN_SLASH_DOT, + URIPS_SEEN_SLASH_DOT_DOT, +}; + +enum uri_esc_states { + URIES_IDLE, + URIES_SEEN_PERCENT, + URIES_SEEN_PERCENT_H1, +}; + + +#ifndef LWS_NO_CLIENT +struct client_info_stash { + char *address; + char *path; + char *host; + char *origin; + char *protocol; + char *method; + char *iface; + char *alpn; +}; +#endif + + +signed char char_to_hex(const char c); + + +struct lws_buflist { + struct lws_buflist *next; + + size_t len; + size_t pos; + + uint8_t buf[1]; /* true length of this is set by the oversize malloc */ +}; + +#define lws_wsi_is_udp(___wsi) (!!___wsi->udp) + +#define LWS_H2_FRAME_HEADER_LENGTH 9 + + +struct lws { + /* structs */ + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + struct _lws_http_mode_related http; +#endif +#if defined(LWS_ROLE_H2) + struct _lws_h2_related h2; +#endif +#if defined(LWS_ROLE_WS) + struct _lws_websocket_related *ws; /* allocated if we upgrade to ws */ +#endif + + const struct lws_role_ops *role_ops; + lws_wsi_state_t wsistate; + lws_wsi_state_t wsistate_pre_close; + + /* lifetime members */ + +#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) + struct lws_io_watcher w_read; +#endif +#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBEVENT) + struct lws_io_watcher w_write; +#endif + + /* pointers */ + + struct lws_context *context; + struct lws_vhost *vhost; + struct lws *parent; /* points to parent, if any */ + struct lws *child_list; /* points to first child */ + struct lws *sibling_list; /* subsequent children at same level */ + + const struct lws_protocols *protocol; + struct lws **same_vh_protocol_prev, *same_vh_protocol_next; + + struct lws_dll_lws dll_timeout; + struct lws_dll_lws dll_hrtimer; + struct lws_dll_lws dll_buflist; /* guys with pending rxflow */ + +#if defined(LWS_WITH_PEER_LIMITS) + struct lws_peer *peer; +#endif + + struct lws_udp *udp; +#ifndef LWS_NO_CLIENT + struct client_info_stash *stash; + char *client_hostname_copy; + struct lws_dll_lws dll_active_client_conns; + struct lws_dll_lws dll_client_transaction_queue_head; + struct lws_dll_lws dll_client_transaction_queue; +#endif + void *user_space; + void *opaque_parent_data; + + struct lws_buflist *buflist; + + /* truncated send handling */ + unsigned char *trunc_alloc; /* non-NULL means buffering in progress */ + +#if defined(LWS_WITH_TLS) + struct lws_lws_tls tls; +#endif + + lws_sock_file_fd_type desc; /* .filefd / .sockfd */ +#if defined(LWS_WITH_STATS) + uint64_t active_writable_req_us; +#if defined(LWS_WITH_TLS) + uint64_t accept_start_us; +#endif +#endif + + lws_usec_t pending_timer; /* hrtimer fires */ + time_t pending_timeout_set; /* second-resolution timeout start */ + +#ifdef LWS_LATENCY + unsigned long action_start; + unsigned long latency_start; +#endif + + /* ints */ +#define LWS_NO_FDS_POS (-1) + int position_in_fds_table; + unsigned int trunc_alloc_len; /* size of malloc */ + unsigned int trunc_offset; /* where we are in terms of spilling */ + unsigned int trunc_len; /* how much is buffered */ +#ifndef LWS_NO_CLIENT + int chunk_remaining; +#endif + unsigned int cache_secs; + + unsigned int hdr_parsing_completed:1; + unsigned int http2_substream:1; + unsigned int upgraded_to_http2:1; + unsigned int h2_stream_carries_ws:1; + unsigned int seen_nonpseudoheader:1; + unsigned int listener:1; + unsigned int user_space_externally_allocated:1; + unsigned int socket_is_permanently_unusable:1; + unsigned int rxflow_change_to:2; + unsigned int conn_stat_done:1; + unsigned int cache_reuse:1; + unsigned int cache_revalidate:1; + unsigned int cache_intermediaries:1; + unsigned int favoured_pollin:1; + unsigned int sending_chunked:1; + unsigned int interpreting:1; + unsigned int already_did_cce:1; + unsigned int told_user_closed:1; + unsigned int told_event_loop_closed:1; + unsigned int waiting_to_send_close_frame:1; + unsigned int close_needs_ack:1; + unsigned int ipv6:1; + unsigned int parent_carries_io:1; + unsigned int parent_pending_cb_on_writable:1; + unsigned int cgi_stdout_zero_length:1; + unsigned int seen_zero_length_recv:1; + unsigned int rxflow_will_be_applied:1; + unsigned int event_pipe:1; + unsigned int on_same_vh_list:1; + unsigned int handling_404:1; + unsigned int protocol_bind_balance:1; + + unsigned int could_have_pending:1; /* detect back-to-back writes */ + unsigned int outer_will_close:1; + +#ifdef LWS_WITH_ACCESS_LOG + unsigned int access_log_pending:1; +#endif +#ifndef LWS_NO_CLIENT + unsigned int do_ws:1; /* whether we are doing http or ws flow */ + unsigned int chunked:1; /* if the clientside connection is chunked */ + unsigned int client_rx_avail:1; + unsigned int client_http_body_pending:1; + unsigned int transaction_from_pipeline_queue:1; + unsigned int keepalive_active:1; + unsigned int keepalive_rejected:1; + unsigned int client_pipeline:1; + unsigned int client_h2_alpn:1; + unsigned int client_h2_substream:1; +#endif + +#ifdef _WIN32 + unsigned int sock_send_blocking:1; +#endif + +#ifndef LWS_NO_CLIENT + unsigned short c_port; +#endif + unsigned short pending_timeout_limit; + + /* chars */ + + char lws_rx_parse_state; /* enum lws_rx_parse_state */ + char rx_frame_type; /* enum lws_write_protocol */ + char pending_timeout; /* enum pending_timeout */ + char tsi; /* thread service index we belong to */ + char protocol_interpret_idx; + char redirects; + uint8_t rxflow_bitmap; +#ifdef LWS_WITH_CGI + char cgi_channel; /* which of stdin/out/err */ + char hdr_state; +#endif +#ifndef LWS_NO_CLIENT + char chunk_parser; /* enum lws_chunk_parser */ +#endif +#if defined(LWS_WITH_CGI) || !defined(LWS_NO_CLIENT) + char reason_bf; /* internal writeable callback reason bitfield */ +#endif +#if defined(LWS_WITH_STATS) && defined(LWS_WITH_TLS) + char seen_rx; +#endif + uint8_t ws_over_h2_count; + /* volatile to make sure code is aware other thread can change */ + volatile char handling_pollout; + volatile char leave_pollout_active; +}; + +#define lws_is_flowcontrolled(w) (!!(wsi->rxflow_bitmap)) + +void +lws_service_do_ripe_rxflow(struct lws_context_per_thread *pt); + +LWS_EXTERN int log_level; + +LWS_EXTERN int +lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, + const char *iface); + +#if defined(LWS_WITH_IPV6) +LWS_EXTERN unsigned long +lws_get_addr_scope(const char *ipaddr); +#endif + +LWS_EXTERN void +lws_close_free_wsi(struct lws *wsi, enum lws_close_status, const char *caller); +LWS_EXTERN void +__lws_close_free_wsi(struct lws *wsi, enum lws_close_status, const char *caller); + +LWS_EXTERN void +__lws_free_wsi(struct lws *wsi); + +LWS_EXTERN int +__remove_wsi_socket_from_fds(struct lws *wsi); +LWS_EXTERN int +lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len); + +#ifndef LWS_LATENCY +static inline void +lws_latency(struct lws_context *context, struct lws *wsi, const char *action, + int ret, int completion) { + do { + (void)context; (void)wsi; (void)action; (void)ret; + (void)completion; + } while (0); +} +static inline void +lws_latency_pre(struct lws_context *context, struct lws *wsi) { + do { (void)context; (void)wsi; } while (0); +} +#else +#define lws_latency_pre(_context, _wsi) lws_latency(_context, _wsi, NULL, 0, 0) +extern void +lws_latency(struct lws_context *context, struct lws *wsi, const char *action, + int ret, int completion); +#endif + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ws_client_rx_sm(struct lws *wsi, unsigned char c); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_parse(struct lws *wsi, unsigned char *buf, int *len); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_parse_urldecode(struct lws *wsi, uint8_t *_c); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_http_action(struct lws *wsi); + +LWS_EXTERN int +lws_b64_selftest(void); + +LWS_EXTERN int +lws_service_flag_pending(struct lws_context *context, int tsi); + +LWS_EXTERN int +lws_timed_callback_remove(struct lws_vhost *vh, struct lws_timed_vh_protocol *p); + +#if defined(_WIN32) +LWS_EXTERN struct lws * +wsi_from_fd(const struct lws_context *context, lws_sockfd_type fd); + +LWS_EXTERN int +insert_wsi(struct lws_context *context, struct lws *wsi); + +LWS_EXTERN int +delete_from_fd(struct lws_context *context, lws_sockfd_type fd); +#else +#define wsi_from_fd(A,B) A->lws_lookup[B - lws_plat_socket_offset()] +#define insert_wsi(A,B) assert(A->lws_lookup[B->desc.sockfd - lws_plat_socket_offset()] == 0); A->lws_lookup[B->desc.sockfd - lws_plat_socket_offset()]=B +#define delete_from_fd(A,B) A->lws_lookup[B - lws_plat_socket_offset()]=0 +#endif + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +__insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len); + +LWS_EXTERN void +lws_remove_from_timeout_list(struct lws *wsi); + +LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT +lws_client_connect_2(struct lws *wsi); + +LWS_VISIBLE struct lws * LWS_WARN_UNUSED_RESULT +lws_client_reset(struct lws **wsi, int ssl, const char *address, int port, + const char *path, const char *host); + +LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT +lws_create_new_server_wsi(struct lws_vhost *vhost, int fixed_tsi); + +LWS_EXTERN char * LWS_WARN_UNUSED_RESULT +lws_generate_client_handshake(struct lws *wsi, char *pkt); + +LWS_EXTERN int +lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd); + +LWS_EXTERN struct lws * +lws_client_connect_via_info2(struct lws *wsi); + + + +LWS_EXTERN void +lws_client_stash_destroy(struct lws *wsi); + +/* + * EXTENSIONS + */ + +#if defined(LWS_WITHOUT_EXTENSIONS) +#define lws_any_extension_handled(_a, _b, _c, _d) (0) +#define lws_ext_cb_active(_a, _b, _c, _d) (0) +#define lws_ext_cb_all_exts(_a, _b, _c, _d, _e) (0) +#define lws_issue_raw_ext_access lws_issue_raw +#define lws_context_init_extensions(_a, _b) +#endif + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_client_interpret_server_handshake(struct lws *wsi); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_issue_raw_ext_access(struct lws *wsi, unsigned char *buf, size_t len); + +LWS_EXTERN void +lws_role_transition(struct lws *wsi, enum lwsi_role role, enum lwsi_state state, + struct lws_role_ops *ops); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +user_callback_handle_rxflow(lws_callback_function, struct lws *wsi, + enum lws_callback_reasons reason, void *user, + void *in, size_t len); + +LWS_EXTERN int +lws_plat_socket_offset(void); + +LWS_EXTERN int +lws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd); + +LWS_EXTERN int +lws_plat_check_connection_error(struct lws *wsi); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_header_table_attach(struct lws *wsi, int autoservice); + +LWS_EXTERN int +lws_header_table_detach(struct lws *wsi, int autoservice); +LWS_EXTERN int +__lws_header_table_detach(struct lws *wsi, int autoservice); + +LWS_EXTERN void +lws_header_table_reset(struct lws *wsi, int autoservice); + +void +__lws_header_table_reset(struct lws *wsi, int autoservice); + +LWS_EXTERN char * LWS_WARN_UNUSED_RESULT +lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ensure_user_space(struct lws *wsi); + +LWS_EXTERN int +lws_change_pollfd(struct lws *wsi, int _and, int _or); + +#ifndef LWS_NO_SERVER + int _lws_vhost_init_server(const struct lws_context_creation_info *info, + struct lws_vhost *vhost); + LWS_EXTERN struct lws_vhost * + lws_select_vhost(struct lws_context *context, int port, const char *servername); + LWS_EXTERN int LWS_WARN_UNUSED_RESULT + lws_parse_ws(struct lws *wsi, unsigned char **buf, size_t len); + LWS_EXTERN void + lws_server_get_canonical_hostname(struct lws_context *context, + const struct lws_context_creation_info *info); +#else + #define _lws_vhost_init_server(_a, _b) (0) + #define lws_parse_ws(_a, _b, _c) (0) + #define lws_server_get_canonical_hostname(_a, _b) +#endif + +#ifndef LWS_NO_DAEMONIZE + LWS_EXTERN int get_daemonize_pid(); +#else + #define get_daemonize_pid() (0) +#endif + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +interface_to_sa(struct lws_vhost *vh, const char *ifname, + struct sockaddr_in *addr, size_t addrlen); +LWS_EXTERN void lwsl_emit_stderr(int level, const char *line); + +#if !defined(LWS_WITH_TLS) + #define LWS_SSL_ENABLED(context) (0) + #define lws_context_init_server_ssl(_a, _b) (0) + #define lws_ssl_destroy(_a) + #define lws_context_init_alpn(_a) + #define lws_ssl_capable_read lws_ssl_capable_read_no_ssl + #define lws_ssl_capable_write lws_ssl_capable_write_no_ssl + #define lws_ssl_pending lws_ssl_pending_no_ssl + #define lws_server_socket_service_ssl(_b, _c) (0) + #define lws_ssl_close(_a) (0) + #define lws_ssl_context_destroy(_a) + #define lws_ssl_SSL_CTX_destroy(_a) + #define lws_ssl_remove_wsi_from_buffered_list(_a) + #define __lws_ssl_remove_wsi_from_buffered_list(_a) + #define lws_context_init_ssl_library(_a) + #define lws_tls_check_all_cert_lifetimes(_a) + #define lws_tls_acme_sni_cert_destroy(_a) +#endif + + +#if LWS_MAX_SMP > 1 + +static LWS_INLINE void +lws_pt_mutex_init(struct lws_context_per_thread *pt) +{ + pthread_mutex_init(&pt->lock, NULL); + pthread_mutex_init(&pt->lock_stats, NULL); +} + +static LWS_INLINE void +lws_pt_mutex_destroy(struct lws_context_per_thread *pt) +{ + pthread_mutex_destroy(&pt->lock_stats); + pthread_mutex_destroy(&pt->lock); +} + +static LWS_INLINE void +lws_pt_lock(struct lws_context_per_thread *pt, const char *reason) +{ + if (pt->lock_owner == pthread_self()) { + pt->lock_depth++; + return; + } + pthread_mutex_lock(&pt->lock); + pt->last_lock_reason = reason; + pt->lock_owner = pthread_self(); + //lwsl_notice("tid %d: lock %s\n", pt->tid, reason); +} + +static LWS_INLINE void +lws_pt_unlock(struct lws_context_per_thread *pt) +{ + if (pt->lock_depth) { + pt->lock_depth--; + return; + } + pt->last_lock_reason = "free"; + pt->lock_owner = 0; + //lwsl_notice("tid %d: unlock %s\n", pt->tid, pt->last_lock_reason); + pthread_mutex_unlock(&pt->lock); +} + +static LWS_INLINE void +lws_pt_stats_lock(struct lws_context_per_thread *pt) +{ + pthread_mutex_lock(&pt->lock_stats); +} + +static LWS_INLINE void +lws_pt_stats_unlock(struct lws_context_per_thread *pt) +{ + pthread_mutex_unlock(&pt->lock_stats); +} + +static LWS_INLINE void +lws_context_lock(struct lws_context *context) +{ + pthread_mutex_lock(&context->lock); +} + +static LWS_INLINE void +lws_context_unlock(struct lws_context *context) +{ + pthread_mutex_unlock(&context->lock); +} + +static LWS_INLINE void +lws_vhost_lock(struct lws_vhost *vhost) +{ + pthread_mutex_lock(&vhost->lock); +} + +static LWS_INLINE void +lws_vhost_unlock(struct lws_vhost *vhost) +{ + pthread_mutex_unlock(&vhost->lock); +} + + +#else +#define lws_pt_mutex_init(_a) (void)(_a) +#define lws_pt_mutex_destroy(_a) (void)(_a) +#define lws_pt_lock(_a, b) (void)(_a) +#define lws_pt_unlock(_a) (void)(_a) +#define lws_context_lock(_a) (void)(_a) +#define lws_context_unlock(_a) (void)(_a) +#define lws_vhost_lock(_a) (void)(_a) +#define lws_vhost_unlock(_a) (void)(_a) +#define lws_pt_stats_lock(_a) (void)(_a) +#define lws_pt_stats_unlock(_a) (void)(_a) +#endif + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_pending_no_ssl(struct lws *wsi); + +int +lws_tls_check_cert_lifetime(struct lws_vhost *vhost); + +int lws_jws_selftest(void); + + +#ifndef LWS_NO_CLIENT +LWS_EXTERN int lws_client_socket_service(struct lws *wsi, + struct lws_pollfd *pollfd, + struct lws *wsi_conn); +LWS_EXTERN struct lws * +lws_client_wsi_effective(struct lws *wsi); +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_http_transaction_completed_client(struct lws *wsi); +#if !defined(LWS_WITH_TLS) + #define lws_context_init_client_ssl(_a, _b) (0) +#endif +LWS_EXTERN void +lws_decode_ssl_error(void); +#else +#define lws_context_init_client_ssl(_a, _b) (0) +#endif + +LWS_EXTERN int +__lws_rx_flow_control(struct lws *wsi); + +LWS_EXTERN int +_lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa); + +#ifndef LWS_NO_SERVER +LWS_EXTERN int +lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len); +#else +#define lws_server_socket_service(_b, _c) (0) +#define lws_handshake_server(_a, _b, _c) (0) +#endif + +#ifdef LWS_WITH_ACCESS_LOG +LWS_EXTERN int +lws_access_log(struct lws *wsi); +LWS_EXTERN void +lws_prepare_access_log_info(struct lws *wsi, char *uri_ptr, int meth); +#else +#define lws_access_log(_a) +#endif + +LWS_EXTERN int +lws_cgi_kill_terminated(struct lws_context_per_thread *pt); + +LWS_EXTERN void +lws_cgi_remove_and_kill(struct lws *wsi); + +int +lws_protocol_init(struct lws_context *context); + +int +lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p); + +const struct lws_http_mount * +lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len); + +/* + * custom allocator + */ +LWS_EXTERN void * +lws_realloc(void *ptr, size_t size, const char *reason); + +LWS_EXTERN void * LWS_WARN_UNUSED_RESULT +lws_zalloc(size_t size, const char *reason); + +#ifdef LWS_PLAT_OPTEE +void *lws_malloc(size_t size, const char *reason); +void lws_free(void *p); +#define lws_free_set_NULL(P) do { lws_free(P); (P) = NULL; } while(0) +#else +#define lws_malloc(S, R) lws_realloc(NULL, S, R) +#define lws_free(P) lws_realloc(P, 0, "lws_free") +#define lws_free_set_NULL(P) do { lws_realloc(P, 0, "free"); (P) = NULL; } while(0) +#endif + +int +lws_plat_pipe_create(struct lws *wsi); +int +lws_plat_pipe_signal(struct lws *wsi); +void +lws_plat_pipe_close(struct lws *wsi); +int +lws_create_event_pipes(struct lws_context *context); + +const struct lws_plat_file_ops * +lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path, + const char **vpath); + +/* lws_plat_ */ +LWS_EXTERN void +lws_plat_delete_socket_from_fds(struct lws_context *context, + struct lws *wsi, int m); +LWS_EXTERN void +lws_plat_insert_socket_into_fds(struct lws_context *context, + struct lws *wsi); +LWS_EXTERN void +lws_plat_service_periodic(struct lws_context *context); + +LWS_EXTERN int +lws_plat_change_pollfd(struct lws_context *context, struct lws *wsi, + struct lws_pollfd *pfd); +LWS_EXTERN void +lws_add_wsi_to_draining_ext_list(struct lws *wsi); +LWS_EXTERN void +lws_remove_wsi_from_draining_ext_list(struct lws *wsi); +LWS_EXTERN int +lws_plat_context_early_init(void); +LWS_EXTERN void +lws_plat_context_early_destroy(struct lws_context *context); +LWS_EXTERN void +lws_plat_context_late_destroy(struct lws_context *context); +LWS_EXTERN int +lws_poll_listen_fd(struct lws_pollfd *fd); +LWS_EXTERN int +lws_plat_service(struct lws_context *context, int timeout_ms); +LWS_EXTERN LWS_VISIBLE int +_lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi); +LWS_EXTERN int +lws_plat_init(struct lws_context *context, + const struct lws_context_creation_info *info); +LWS_EXTERN void +lws_plat_drop_app_privileges(const struct lws_context_creation_info *info); +LWS_EXTERN unsigned long long +time_in_microseconds(void); +LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT +lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt); +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_plat_inet_pton(int af, const char *src, void *dst); + +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len); +LWS_EXTERN int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, + lws_filepos_t *amount); + + +LWS_EXTERN void +lws_same_vh_protocol_remove(struct lws *wsi); +LWS_EXTERN void +lws_same_vh_protocol_insert(struct lws *wsi, int n); + +LWS_EXTERN int +lws_broadcast(struct lws_context *context, int reason, void *in, size_t len); + +#if defined(LWS_WITH_STATS) + void + lws_stats_atomic_bump(struct lws_context * context, + struct lws_context_per_thread *pt, int index, uint64_t bump); + void + lws_stats_atomic_max(struct lws_context * context, + struct lws_context_per_thread *pt, int index, uint64_t val); +#else + static inline uint64_t lws_stats_atomic_bump(struct lws_context * context, + struct lws_context_per_thread *pt, int index, uint64_t bump) { + (void)context; (void)pt; (void)index; (void)bump; return 0; } + static inline uint64_t lws_stats_atomic_max(struct lws_context * context, + struct lws_context_per_thread *pt, int index, uint64_t val) { + (void)context; (void)pt; (void)index; (void)val; return 0; } +#endif + +/* socks */ +void socks_generate_msg(struct lws *wsi, enum socks_msg_type type, + ssize_t *msg_len); + +#if defined(LWS_WITH_PEER_LIMITS) +void +lws_peer_track_wsi_close(struct lws_context *context, struct lws_peer *peer); +int +lws_peer_confirm_ah_attach_ok(struct lws_context *context, struct lws_peer *peer); +void +lws_peer_track_ah_detach(struct lws_context *context, struct lws_peer *peer); +void +lws_peer_cull_peer_wait_list(struct lws_context *context); +struct lws_peer * +lws_get_or_create_peer(struct lws_vhost *vhost, lws_sockfd_type sockfd); +void +lws_peer_add_wsi(struct lws_context *context, struct lws_peer *peer, + struct lws *wsi); +void +lws_peer_dump_from_wsi(struct lws *wsi); +#endif + + +void +__lws_remove_from_timeout_list(struct lws *wsi); + +lws_usec_t +__lws_hrtimer_service(struct lws_context_per_thread *pt); + +void +__lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs); +int +__lws_change_pollfd(struct lws *wsi, int _and, int _or); + + +int +lws_callback_as_writeable(struct lws *wsi); +int +lws_buflist_aware_read(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_tokens *ebuf); +int +lws_buflist_aware_consume(struct lws *wsi, struct lws_tokens *ebuf, int used, + int buffered); + + +char * +lws_generate_client_ws_handshake(struct lws *wsi, char *p); +int +lws_client_ws_upgrade(struct lws *wsi, const char **cce); +int +lws_create_client_ws_object(struct lws_client_connect_info *i, struct lws *wsi); +int +lws_alpn_comma_to_openssl(const char *comma, uint8_t *os, int len); +int +lws_role_call_alpn_negotiated(struct lws *wsi, const char *alpn); +int +lws_tls_server_conn_alpn(struct lws *wsi); + +int +lws_ws_client_rx_sm_block(struct lws *wsi, unsigned char **buf, size_t len); +void +lws_destroy_event_pipe(struct lws *wsi); +void +lws_context_destroy2(struct lws_context *context); + +#ifdef __cplusplus +}; +#endif diff --git a/thirdparty/libwebsockets/core/service.c b/thirdparty/libwebsockets/core/service.c new file mode 100644 index 0000000000..6523058814 --- /dev/null +++ b/thirdparty/libwebsockets/core/service.c @@ -0,0 +1,987 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +int +lws_callback_as_writeable(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + int n, m; + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1); +#if defined(LWS_WITH_STATS) + if (wsi->active_writable_req_us) { + uint64_t ul = time_in_microseconds() - + wsi->active_writable_req_us; + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_MS_WRITABLE_DELAY, ul); + lws_stats_atomic_max(wsi->context, pt, + LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); + wsi->active_writable_req_us = 0; + } +#endif + + n = wsi->role_ops->writeable_cb[lwsi_role_server(wsi)]; + + m = user_callback_handle_rxflow(wsi->protocol->callback, + wsi, (enum lws_callback_reasons) n, + wsi->user_space, NULL, 0); + + return m; +} + +LWS_VISIBLE int +lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd) +{ + volatile struct lws *vwsi = (volatile struct lws *)wsi; + int n; + + //lwsl_notice("%s: %p\n", __func__, wsi); + + vwsi->leave_pollout_active = 0; + vwsi->handling_pollout = 1; + /* + * if another thread wants POLLOUT on us, from here on while + * handling_pollout is set, he will only set leave_pollout_active. + * If we are going to disable POLLOUT, we will check that first. + */ + wsi->could_have_pending = 0; /* clear back-to-back write detection */ + + /* + * user callback is lowest priority to get these notifications + * actually, since other pending things cannot be disordered + * + * Priority 1: pending truncated sends are incomplete ws fragments + * If anything else sent first the protocol would be + * corrupted. + */ + + if (wsi->trunc_len) { + //lwsl_notice("%s: completing partial\n", __func__); + if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset, + wsi->trunc_len) < 0) { + lwsl_info("%s signalling to close\n", __func__); + goto bail_die; + } + /* leave POLLOUT active either way */ + goto bail_ok; + } else + if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) { + wsi->socket_is_permanently_unusable = 1; + goto bail_die; /* retry closing now */ + } + +#ifdef LWS_WITH_CGI + /* + * A cgi master's wire protocol remains h1 or h2. He is just getting + * his data from his child cgis. + */ + if (wsi->http.cgi) { + /* also one shot */ + if (pollfd) + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_info("failed at set pollfd\n"); + return 1; + } + goto user_service_go_again; + } +#endif + + /* if we got here, we should have wire protocol ops set on the wsi */ + assert(wsi->role_ops); + + if (!wsi->role_ops->handle_POLLOUT) + goto bail_ok; + + switch ((wsi->role_ops->handle_POLLOUT)(wsi)) { + case LWS_HP_RET_BAIL_OK: + goto bail_ok; + case LWS_HP_RET_BAIL_DIE: + goto bail_die; + case LWS_HP_RET_USER_SERVICE: + break; + default: + assert(0); + } + + /* one shot */ + + if (wsi->parent_carries_io) { + vwsi->handling_pollout = 0; + vwsi->leave_pollout_active = 0; + + return lws_callback_as_writeable(wsi); + } + + if (pollfd) { + int eff = vwsi->leave_pollout_active; + + if (!eff) { + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_info("failed at set pollfd\n"); + goto bail_die; + } + } + + vwsi->handling_pollout = 0; + + /* cannot get leave_pollout_active set after the above */ + if (!eff && wsi->leave_pollout_active) { + /* + * got set inbetween sampling eff and clearing + * handling_pollout, force POLLOUT on + */ + lwsl_debug("leave_pollout_active\n"); + if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) { + lwsl_info("failed at set pollfd\n"); + goto bail_die; + } + } + + vwsi->leave_pollout_active = 0; + } + + if (lwsi_role_client(wsi) && + !wsi->hdr_parsing_completed && + lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS && + lwsi_state(wsi) != LRS_ISSUE_HTTP_BODY + ) + goto bail_ok; + + +#ifdef LWS_WITH_CGI +user_service_go_again: +#endif + + if (wsi->role_ops->perform_user_POLLOUT) { + if (wsi->role_ops->perform_user_POLLOUT(wsi) == -1) + goto bail_die; + else + goto bail_ok; + } + + lwsl_debug("%s: %p: non mux: wsistate 0x%x, ops %s\n", __func__, wsi, + wsi->wsistate, wsi->role_ops->name); + + vwsi = (volatile struct lws *)wsi; + vwsi->leave_pollout_active = 0; + + n = lws_callback_as_writeable(wsi); + vwsi->handling_pollout = 0; + + if (vwsi->leave_pollout_active) + lws_change_pollfd(wsi, 0, LWS_POLLOUT); + + return n; + + /* + * since these don't disable the POLLOUT, they are always doing the + * right thing for leave_pollout_active whether it was set or not. + */ + +bail_ok: + vwsi->handling_pollout = 0; + vwsi->leave_pollout_active = 0; + + return 0; + +bail_die: + vwsi->handling_pollout = 0; + vwsi->leave_pollout_active = 0; + + return -1; +} + +static int +__lws_service_timeout_check(struct lws *wsi, time_t sec) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + int n = 0; + + (void)n; + + /* + * if we went beyond the allowed time, kill the + * connection + */ + if (wsi->dll_timeout.prev && + lws_compare_time_t(wsi->context, sec, wsi->pending_timeout_set) > + wsi->pending_timeout_limit) { + + if (wsi->desc.sockfd != LWS_SOCK_INVALID && + wsi->position_in_fds_table >= 0) + n = pt->fds[wsi->position_in_fds_table].events; + + lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_TIMEOUTS, 1); + + /* no need to log normal idle keepalive timeout */ + if (wsi->pending_timeout != PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE) +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + lwsl_info("wsi %p: TIMEDOUT WAITING on %d " + "(did hdr %d, ah %p, wl %d, pfd " + "events %d) %llu vs %llu\n", + (void *)wsi, wsi->pending_timeout, + wsi->hdr_parsing_completed, wsi->http.ah, + pt->http.ah_wait_list_length, n, + (unsigned long long)sec, + (unsigned long long)wsi->pending_timeout_limit); +#if defined(LWS_WITH_CGI) + if (wsi->http.cgi) + lwsl_notice("CGI timeout: %s\n", wsi->http.cgi->summary); +#endif +#else + lwsl_info("wsi %p: TIMEDOUT WAITING on %d ", (void *)wsi, + wsi->pending_timeout); +#endif + + /* + * Since he failed a timeout, he already had a chance to do + * something and was unable to... that includes situations like + * half closed connections. So process this "failed timeout" + * close as a violent death and don't try to do protocol + * cleanup like flush partials. + */ + wsi->socket_is_permanently_unusable = 1; + if (lwsi_state(wsi) == LRS_WAITING_SSL && wsi->protocol) + wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, + wsi->user_space, + (void *)"Timed out waiting SSL", 21); + + __lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "timeout"); + + return 1; + } + + return 0; +} + +int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + uint8_t *buffered; + size_t blen; + int ret = 0, m; + + /* his RX is flowcontrolled, don't send remaining now */ + blen = lws_buflist_next_segment_len(&wsi->buflist, &buffered); + if (blen) { + if (buf >= buffered && buf + len <= buffered + blen) { + /* rxflow while we were spilling prev rxflow */ + lwsl_info("%s: staying in rxflow buf\n", __func__); + + return 1; + } + ret = 1; + } + + /* a new rxflow, buffer it and warn caller */ + + m = lws_buflist_append_segment(&wsi->buflist, buf + n, len - n); + + if (m < 0) + return -1; + if (m) { + lwsl_debug("%s: added %p to rxflow list\n", __func__, wsi); + lws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist); + } + + return ret; +} + +/* this is used by the platform service code to stop us waiting for network + * activity in poll() when we have something that already needs service + */ + +LWS_VISIBLE LWS_EXTERN int +lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi) +{ + struct lws_context_per_thread *pt = &context->pt[tsi]; + + /* Figure out if we really want to wait in poll() + * We only need to wait if really nothing already to do and we have + * to wait for something from network + */ +#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS) + /* 1) if we know we are draining rx ext, do not wait in poll */ + if (pt->ws.rx_draining_ext_list) + return 0; +#endif + + /* 2) if we know we have non-network pending data, do not wait in poll */ + + if (pt->context->tls_ops && + pt->context->tls_ops->fake_POLLIN_for_buffered) + if (pt->context->tls_ops->fake_POLLIN_for_buffered(pt)) + return 0; + + /* 3) If there is any wsi with rxflow buffered and in a state to process + * it, we should not wait in poll + */ + + lws_start_foreach_dll(struct lws_dll_lws *, d, pt->dll_head_buflist.next) { + struct lws *wsi = lws_container_of(d, struct lws, dll_buflist); + + if (lwsi_state(wsi) != LRS_DEFERRING_ACTION) + return 0; + + } lws_end_foreach_dll(d); + + return timeout_ms; +} + +/* + * POLLIN said there is something... we must read it, and either use it; or + * if other material already in the buflist append it and return the buflist + * head material. + */ +int +lws_buflist_aware_read(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_tokens *ebuf) +{ + int n, prior = (int)lws_buflist_next_segment_len(&wsi->buflist, NULL); + + ebuf->token = (char *)pt->serv_buf; + ebuf->len = lws_ssl_capable_read(wsi, pt->serv_buf, + wsi->context->pt_serv_buf_size); + + if (ebuf->len == LWS_SSL_CAPABLE_MORE_SERVICE && prior) + goto get_from_buflist; + + if (ebuf->len <= 0) + return 0; + + /* nothing in buflist already? Then just use what we read */ + + if (!prior) + return 0; + + /* stash what we read */ + + n = lws_buflist_append_segment(&wsi->buflist, (uint8_t *)ebuf->token, + ebuf->len); + if (n < 0) + return -1; + if (n) { + lwsl_debug("%s: added %p to rxflow list\n", __func__, wsi); + lws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist); + } + + /* get the first buflist guy in line */ + +get_from_buflist: + + ebuf->len = (int)lws_buflist_next_segment_len(&wsi->buflist, + (uint8_t **)&ebuf->token); + + return 1; /* came from buflist */ +} + +int +lws_buflist_aware_consume(struct lws *wsi, struct lws_tokens *ebuf, int used, + int buffered) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + int m; + + /* it's in the buflist; we didn't use any */ + + if (!used && buffered) + return 0; + + if (used && buffered) { + m = lws_buflist_use_segment(&wsi->buflist, used); + lwsl_info("%s: draining rxflow: used %d, next %d\n", + __func__, used, m); + if (m) + return 0; + + lwsl_info("%s: removed %p from dll_buflist\n", __func__, wsi); + lws_dll_lws_remove(&wsi->dll_buflist); + + return 0; + } + + /* any remainder goes on the buflist */ + + if (used != ebuf->len) { + m = lws_buflist_append_segment(&wsi->buflist, + (uint8_t *)ebuf->token + used, + ebuf->len - used); + if (m < 0) + return 1; /* OOM */ + if (m) { + lwsl_debug("%s: added %p to rxflow list\n", __func__, wsi); + lws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist); + } + } + + return 0; +} + +void +lws_service_do_ripe_rxflow(struct lws_context_per_thread *pt) +{ + struct lws_pollfd pfd; + + if (!pt->dll_head_buflist.next) + return; + + /* + * service all guys with pending rxflow that reached a state they can + * accept the pending data + */ + + lws_pt_lock(pt, __func__); + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + pt->dll_head_buflist.next) { + struct lws *wsi = lws_container_of(d, struct lws, dll_buflist); + + pfd.events = LWS_POLLIN; + pfd.revents = LWS_POLLIN; + pfd.fd = -1; + + lwsl_debug("%s: rxflow processing: %p 0x%x\n", __func__, wsi, + wsi->wsistate); + + if (!lws_is_flowcontrolled(wsi) && + lwsi_state(wsi) != LRS_DEFERRING_ACTION && + (wsi->role_ops->handle_POLLIN)(pt, wsi, &pfd) == + LWS_HPI_RET_PLEASE_CLOSE_ME) + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "close_and_handled"); + + } lws_end_foreach_dll_safe(d, d1); + + lws_pt_unlock(pt); +} + +/* + * guys that need POLLIN service again without waiting for network action + * can force POLLIN here if not flowcontrolled, so they will get service. + * + * Return nonzero if anybody got their POLLIN faked + */ +int +lws_service_flag_pending(struct lws_context *context, int tsi) +{ + struct lws_context_per_thread *pt = &context->pt[tsi]; + +#if defined(LWS_WITH_TLS) + struct lws *wsi, *wsi_next; +#endif + int forced = 0; + + lws_pt_lock(pt, __func__); + + /* + * 1) If there is any wsi with a buflist and in a state to process + * it, we should not wait in poll + */ + + lws_start_foreach_dll(struct lws_dll_lws *, d, pt->dll_head_buflist.next) { + struct lws *wsi = lws_container_of(d, struct lws, dll_buflist); + + if (lwsi_state(wsi) != LRS_DEFERRING_ACTION) { + forced = 1; + break; + } + } lws_end_foreach_dll(d); + +#if defined(LWS_ROLE_WS) + forced |= role_ops_ws.service_flag_pending(context, tsi); +#endif + +#if defined(LWS_WITH_TLS) + /* + * 2) For all guys with buffered SSL read data already saved up, if they + * are not flowcontrolled, fake their POLLIN status so they'll get + * service to use up the buffered incoming data, even though their + * network socket may have nothing + */ + wsi = pt->tls.pending_read_list; + while (wsi) { + wsi_next = wsi->tls.pending_read_list_next; + pt->fds[wsi->position_in_fds_table].revents |= + pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; + if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) { + forced = 1; + /* + * he's going to get serviced now, take him off the + * list of guys with buffered SSL. If he still has some + * at the end of the service, he'll get put back on the + * list then. + */ + __lws_ssl_remove_wsi_from_buffered_list(wsi); + } + + wsi = wsi_next; + } +#endif + + lws_pt_unlock(pt); + + return forced; +} + +static int +lws_service_periodic_checks(struct lws_context *context, + struct lws_pollfd *pollfd, int tsi) +{ + struct lws_context_per_thread *pt = &context->pt[tsi]; + lws_sockfd_type our_fd = 0, tmp_fd; + struct lws *wsi; + int timed_out = 0; + time_t now; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + struct allocated_headers *ah; + int m; +#endif + + if (!context->protocol_init_done) + if (lws_protocol_init(context)) + return -1; + + time(&now); + + /* + * handle case that system time was uninitialized when lws started + * at boot, and got initialized a little later + */ + if (context->time_up < 1464083026 && now > 1464083026) + context->time_up = now; + + if (context->last_timeout_check_s && + now - context->last_timeout_check_s > 100) { + /* + * There has been a discontiguity. Any stored time that is + * less than context->time_discontiguity should have context-> + * time_fixup added to it. + * + * Some platforms with no RTC will experience this as a normal + * event when ntp sets their clock, but we can have started + * long before that with a 0-based unix time. + */ + + context->time_discontiguity = now; + context->time_fixup = now - context->last_timeout_check_s; + + lwsl_notice("time discontiguity: at old time %llus, " + "new time %llus: +%llus\n", + (unsigned long long)context->last_timeout_check_s, + (unsigned long long)context->time_discontiguity, + (unsigned long long)context->time_fixup); + + context->last_timeout_check_s = now - 1; + } + + if (!lws_compare_time_t(context, context->last_timeout_check_s, now)) + return 0; + + context->last_timeout_check_s = now; + +#if defined(LWS_WITH_STATS) + if (!tsi && now - context->last_dump > 10) { + lws_stats_log_dump(context); + context->last_dump = now; + } +#endif + + lws_plat_service_periodic(context); + lws_check_deferred_free(context, 0); + +#if defined(LWS_WITH_PEER_LIMITS) + lws_peer_cull_peer_wait_list(context); +#endif + + /* retire unused deprecated context */ +#if !defined(LWS_PLAT_OPTEE) && !defined(LWS_WITH_ESP32) +#if !defined(_WIN32) + if (context->deprecated && !context->count_wsi_allocated) { + lwsl_notice("%s: ending deprecated context\n", __func__); + kill(getpid(), SIGINT); + return 0; + } +#endif +#endif + /* global timeout check once per second */ + + if (pollfd) + our_fd = pollfd->fd; + + /* + * Phase 1: check every wsi on the timeout check list + */ + + lws_pt_lock(pt, __func__); + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + context->pt[tsi].dll_head_timeout.next) { + wsi = lws_container_of(d, struct lws, dll_timeout); + tmp_fd = wsi->desc.sockfd; + if (__lws_service_timeout_check(wsi, now)) { + /* he did time out... */ + if (tmp_fd == our_fd) + /* it was the guy we came to service! */ + timed_out = 1; + /* he's gone, no need to mark as handled */ + } + } lws_end_foreach_dll_safe(d, d1); + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + /* + * Phase 2: double-check active ah timeouts independent of wsi + * timeout status + */ + + ah = pt->http.ah_list; + while (ah) { + int len; + char buf[256]; + const unsigned char *c; + + if (!ah->in_use || !ah->wsi || !ah->assigned || + (ah->wsi->vhost && + lws_compare_time_t(context, now, ah->assigned) < + ah->wsi->vhost->timeout_secs_ah_idle + 360)) { + ah = ah->next; + continue; + } + + /* + * a single ah session somehow got held for + * an unreasonable amount of time. + * + * Dump info on the connection... + */ + wsi = ah->wsi; + buf[0] = '\0'; +#if !defined(LWS_PLAT_OPTEE) + lws_get_peer_simple(wsi, buf, sizeof(buf)); +#else + buf[0] = '\0'; +#endif + lwsl_notice("ah excessive hold: wsi %p\n" + " peer address: %s\n" + " ah pos %u\n", + wsi, buf, ah->pos); + buf[0] = '\0'; + m = 0; + do { + c = lws_token_to_string(m); + if (!c) + break; + if (!(*c)) + break; + + len = lws_hdr_total_length(wsi, m); + if (!len || len > (int)sizeof(buf) - 1) { + m++; + continue; + } + + if (lws_hdr_copy(wsi, buf, + sizeof buf, m) > 0) { + buf[sizeof(buf) - 1] = '\0'; + + lwsl_notice(" %s = %s\n", + (const char *)c, buf); + } + m++; + } while (1); + + /* explicitly detach the ah */ + lws_header_table_detach(wsi, 0); + + /* ... and then drop the connection */ + + m = 0; + if (wsi->desc.sockfd == our_fd) { + m = timed_out; + + /* it was the guy we came to service! */ + timed_out = 1; + } + + if (!m) /* if he didn't already timeout */ + __lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "excessive ah"); + + ah = pt->http.ah_list; + } +#endif + lws_pt_unlock(pt); + +#if 0 + { + char s[300], *p = s; + + for (n = 0; n < context->count_threads; n++) + p += sprintf(p, " %7lu (%5d), ", + context->pt[n].count_conns, + context->pt[n].fds_count); + + lwsl_notice("load: %s\n", s); + } +#endif + /* + * Phase 3: vhost / protocol timer callbacks + */ + + wsi = NULL; + lws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) { + struct lws_timed_vh_protocol *nx; + if (v->timed_vh_protocol_list) { + lws_start_foreach_ll(struct lws_timed_vh_protocol *, + q, v->timed_vh_protocol_list) { + if (now >= q->time) { + if (!wsi) + wsi = lws_zalloc(sizeof(*wsi), "cbwsi"); + wsi->context = context; + wsi->vhost = v; + wsi->protocol = q->protocol; + lwsl_debug("timed cb: vh %s, protocol %s, reason %d\n", v->name, q->protocol->name, q->reason); + q->protocol->callback(wsi, q->reason, NULL, NULL, 0); + nx = q->next; + lws_timed_callback_remove(v, q); + q = nx; + continue; /* we pointed ourselves to the next from the now-deleted guy */ + } + } lws_end_foreach_ll(q, next); + } + } lws_end_foreach_ll(v, vhost_next); + if (wsi) + lws_free(wsi); + + /* + * Phase 4: check for unconfigured vhosts due to required + * interface missing before + */ + + lws_context_lock(context); + lws_start_foreach_llp(struct lws_vhost **, pv, + context->no_listener_vhost_list) { + struct lws_vhost *v = *pv; + lwsl_debug("deferred iface: checking if on vh %s\n", (*pv)->name); + if (_lws_vhost_init_server(NULL, *pv) == 0) { + /* became happy */ + lwsl_notice("vh %s: became connected\n", v->name); + *pv = v->no_listener_vhost_list; + v->no_listener_vhost_list = NULL; + break; + } + } lws_end_foreach_llp(pv, no_listener_vhost_list); + lws_context_unlock(context); + + /* + * Phase 5: role periodic checks + */ +#if defined(LWS_ROLE_WS) + role_ops_ws.periodic_checks(context, tsi, now); +#endif +#if defined(LWS_ROLE_CGI) + role_ops_cgi.periodic_checks(context, tsi, now); +#endif + + /* + * Phase 6: check the remaining cert lifetime daily + */ + + if (context->tls_ops && + context->tls_ops->periodic_housekeeping) + context->tls_ops->periodic_housekeeping(context, now); + + return timed_out; +} + +LWS_VISIBLE int +lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd, + int tsi) +{ + struct lws_context_per_thread *pt = &context->pt[tsi]; + struct lws *wsi; + + if (!context || context->being_destroyed1) + return -1; + + /* the socket we came to service timed out, nothing to do */ + if (lws_service_periodic_checks(context, pollfd, tsi) || !pollfd) + return 0; + + /* no, here to service a socket descriptor */ + wsi = wsi_from_fd(context, pollfd->fd); + if (!wsi) + /* not lws connection ... leave revents alone and return */ + return 0; + + /* + * so that caller can tell we handled, past here we need to + * zero down pollfd->revents after handling + */ + + /* handle session socket closed */ + + if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) && + (pollfd->revents & LWS_POLLHUP)) { + wsi->socket_is_permanently_unusable = 1; + lwsl_debug("Session Socket %p (fd=%d) dead\n", + (void *)wsi, pollfd->fd); + + goto close_and_handled; + } + +#ifdef _WIN32 + if (pollfd->revents & LWS_POLLOUT) + wsi->sock_send_blocking = FALSE; +#endif + + if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) && + (pollfd->revents & LWS_POLLHUP)) { + lwsl_debug("pollhup\n"); + wsi->socket_is_permanently_unusable = 1; + goto close_and_handled; + } + +#if defined(LWS_WITH_TLS) + if (lwsi_state(wsi) == LRS_SHUTDOWN && + lws_is_ssl(wsi) && wsi->tls.ssl) { + switch (__lws_tls_shutdown(wsi)) { + case LWS_SSL_CAPABLE_DONE: + case LWS_SSL_CAPABLE_ERROR: + goto close_and_handled; + + case LWS_SSL_CAPABLE_MORE_SERVICE_READ: + case LWS_SSL_CAPABLE_MORE_SERVICE_WRITE: + case LWS_SSL_CAPABLE_MORE_SERVICE: + goto handled; + } + } +#endif + wsi->could_have_pending = 0; /* clear back-to-back write detection */ + + /* okay, what we came here to do... */ + + /* if we got here, we should have wire protocol ops set on the wsi */ + assert(wsi->role_ops); + + // lwsl_notice("%s: %s: wsistate 0x%x\n", __func__, wsi->role_ops->name, + // wsi->wsistate); + + switch ((wsi->role_ops->handle_POLLIN)(pt, wsi, pollfd)) { + case LWS_HPI_RET_WSI_ALREADY_DIED: + return 1; + case LWS_HPI_RET_HANDLED: + break; + case LWS_HPI_RET_PLEASE_CLOSE_ME: +close_and_handled: + lwsl_debug("%p: Close and handled\n", wsi); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "close_and_handled"); +#if defined(_DEBUG) && defined(LWS_WITH_LIBUV) + /* + * confirm close has no problem being called again while + * it waits for libuv service to complete the first async + * close + */ + if (context->event_loop_ops == &event_loop_ops_uv) + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "close_and_handled uv repeat test"); +#endif + /* + * pollfd may point to something else after the close + * due to pollfd swapping scheme on delete on some platforms + * we can't clear revents now because it'd be the wrong guy's + * revents + */ + return 1; + default: + assert(0); + } +#if defined(LWS_WITH_TLS) +handled: +#endif + pollfd->revents = 0; + + lws_pt_lock(pt, __func__); + __lws_hrtimer_service(pt); + lws_pt_unlock(pt); + + return 0; +} + +LWS_VISIBLE int +lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd) +{ + return lws_service_fd_tsi(context, pollfd, 0); +} + +LWS_VISIBLE int +lws_service(struct lws_context *context, int timeout_ms) +{ + struct lws_context_per_thread *pt = &context->pt[0]; + int n; + + if (!context) + return 1; + + pt->inside_service = 1; + + if (context->event_loop_ops->run_pt) { + /* we are configured for an event loop */ + context->event_loop_ops->run_pt(context, 0); + + pt->inside_service = 0; + + return 1; + } + n = lws_plat_service(context, timeout_ms); + + pt->inside_service = 0; + + return n; +} + +LWS_VISIBLE int +lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi) +{ + struct lws_context_per_thread *pt = &context->pt[tsi]; + int n; + + pt->inside_service = 1; + + if (context->event_loop_ops->run_pt) { + /* we are configured for an event loop */ + context->event_loop_ops->run_pt(context, tsi); + + pt->inside_service = 0; + + return 1; + } + + n = _lws_plat_service_tsi(context, timeout_ms, tsi); + + pt->inside_service = 0; + + return n; +} diff --git a/thirdparty/libwebsockets/event-libs/poll/poll.c b/thirdparty/libwebsockets/event-libs/poll/poll.c new file mode 100644 index 0000000000..09af5b15d8 --- /dev/null +++ b/thirdparty/libwebsockets/event-libs/poll/poll.c @@ -0,0 +1,43 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h if LWS_ROLE_WS + */ + +#include <core/private.h> + +struct lws_event_loop_ops event_loop_ops_poll = { + /* name */ "poll", + /* init_context */ NULL, + /* destroy_context1 */ NULL, + /* destroy_context2 */ NULL, + /* init_vhost_listen_wsi */ NULL, + /* init_pt */ NULL, + /* wsi_logical_close */ NULL, + /* check_client_connect_ok */ NULL, + /* close_handle_manually */ NULL, + /* accept */ NULL, + /* io */ NULL, + /* run */ NULL, + /* destroy_pt */ NULL, + /* destroy wsi */ NULL, + + /* periodic_events_available */ 1, +};
\ No newline at end of file diff --git a/thirdparty/libwebsockets/event-libs/poll/private.h b/thirdparty/libwebsockets/event-libs/poll/private.h new file mode 100644 index 0000000000..ca313ebfb0 --- /dev/null +++ b/thirdparty/libwebsockets/event-libs/poll/private.h @@ -0,0 +1,23 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + */ + +extern struct lws_event_loop_ops event_loop_ops_poll; diff --git a/thirdparty/libwebsockets/event-libs/private.h b/thirdparty/libwebsockets/event-libs/private.h new file mode 100644 index 0000000000..c36d39c8c2 --- /dev/null +++ b/thirdparty/libwebsockets/event-libs/private.h @@ -0,0 +1,74 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h + */ + +struct lws_event_loop_ops { + const char *name; + /* event loop-specific context init during context creation */ + int (*init_context)(struct lws_context *context, + const struct lws_context_creation_info *info); + /* called during lws_destroy_context */ + int (*destroy_context1)(struct lws_context *context); + /* called during lws_destroy_context2 */ + int (*destroy_context2)(struct lws_context *context); + /* init vhost listening wsi */ + int (*init_vhost_listen_wsi)(struct lws *wsi); + /* init the event loop for a pt */ + int (*init_pt)(struct lws_context *context, void *_loop, int tsi); + /* called at end of first phase of close_free_wsi() */ + int (*wsi_logical_close)(struct lws *wsi); + /* return nonzero if client connect not allowed */ + int (*check_client_connect_ok)(struct lws *wsi); + /* close handle manually */ + void (*close_handle_manually)(struct lws *wsi); + /* event loop accept processing */ + void (*accept)(struct lws *wsi); + /* control wsi active events */ + void (*io)(struct lws *wsi, int flags); + /* run the event loop for a pt */ + void (*run_pt)(struct lws_context *context, int tsi); + /* called before pt is destroyed */ + void (*destroy_pt)(struct lws_context *context, int tsi); + /* called just before wsi is freed */ + void (*destroy_wsi)(struct lws *wsi); + + unsigned int periodic_events_available:1; +}; + +/* bring in event libs private declarations */ + +#if defined(LWS_WITH_POLL) +#include "event-libs/poll/private.h" +#endif + +#if defined(LWS_WITH_LIBUV) +#include "event-libs/libuv/private.h" +#endif + +#if defined(LWS_WITH_LIBEVENT) +#include "event-libs/libevent/private.h" +#endif + +#if defined(LWS_WITH_LIBEV) +#include "event-libs/libev/private.h" +#endif + diff --git a/thirdparty/lws/libwebsockets.h b/thirdparty/libwebsockets/libwebsockets.h index 460c732602..7ae563d582 100644 --- a/thirdparty/lws/libwebsockets.h +++ b/thirdparty/libwebsockets/libwebsockets.h @@ -1,7 +1,7 @@ /* * libwebsockets - small server side websockets and web server implementation * - * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com> + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -27,25 +27,21 @@ #ifdef __cplusplus #include <cstddef> #include <cstdarg> -# + extern "C" { #else #include <stdarg.h> #endif +#include <string.h> +#include <stdlib.h> + #include "lws_config.h" /* * CARE: everything using cmake defines needs to be below here */ -#if defined(LWS_WITH_ESP8266) -struct sockaddr_in; -#define LWS_POSIX 0 -#else -#define LWS_POSIX 1 -#endif - #if defined(LWS_HAS_INTPTR_T) #include <stdint.h> #define lws_intptr_t intptr_t @@ -62,6 +58,7 @@ typedef unsigned long long lws_intptr_t; #include <ws2tcpip.h> #include <stddef.h> #include <basetsd.h> +#include <io.h> #ifndef _WIN32_WCE #include <fcntl.h> #else @@ -99,25 +96,18 @@ typedef unsigned long long lws_intptr_t; #define LWS_O_CREAT _O_CREAT #define LWS_O_TRUNC _O_TRUNC -#if !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1900) /* Visual Studio 2015 already defines this in <stdio.h> */ -#define lws_snprintf _snprintf -#endif - #ifndef __func__ #define __func__ __FUNCTION__ #endif -#if !defined(__MINGW32__) &&(!defined(_MSC_VER) || _MSC_VER < 1900) && !defined(snprintf) -#define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__) -#endif - #else /* NOT WIN32 */ #include <unistd.h> #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP) #include <sys/capability.h> #endif -#if defined(__NetBSD__) || defined(__FreeBSD__) +#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__QNX__) || defined(__OpenBSD__) +#include <sys/socket.h> #include <netinet/in.h> #endif @@ -127,7 +117,7 @@ typedef unsigned long long lws_intptr_t; #define LWS_O_CREAT O_CREAT #define LWS_O_TRUNC O_TRUNC -#if !defined(LWS_WITH_ESP8266) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32) +#if !defined(LWS_PLAT_OPTEE) && !defined(OPTEE_TA) && !defined(LWS_WITH_ESP32) #include <poll.h> #include <netdb.h> #define LWS_INVALID_FILE -1 @@ -166,7 +156,7 @@ typedef unsigned long long lws_intptr_t; #endif -#ifdef LWS_WITH_LIBEV +#if defined(LWS_WITH_LIBEV) #include <ev.h> #endif /* LWS_WITH_LIBEV */ #ifdef LWS_WITH_LIBUV @@ -175,7 +165,7 @@ typedef unsigned long long lws_intptr_t; #include <uv-version.h> #endif #endif /* LWS_WITH_LIBUV */ -#ifdef LWS_WITH_LIBEVENT +#if defined(LWS_WITH_LIBEVENT) #include <event2/event.h> #endif /* LWS_WITH_LIBEVENT */ @@ -192,13 +182,34 @@ typedef unsigned long long lws_intptr_t; #endif #endif -#ifdef LWS_OPENSSL_SUPPORT +#if defined(LWS_WITH_TLS) #ifdef USE_WOLFSSL #ifdef USE_OLD_CYASSL +#ifdef _WIN32 +/* + * Include user-controlled settings for windows from + * <wolfssl-root>/IDE/WIN/user_settings.h + */ +#include <IDE/WIN/user_settings.h> +#include <cyassl/ctaocrypt/settings.h> +#else +#include <cyassl/options.h> +#endif #include <cyassl/openssl/ssl.h> #include <cyassl/error-ssl.h> + #else +#ifdef _WIN32 +/* + * Include user-controlled settings for windows from + * <wolfssl-root>/IDE/WIN/user_settings.h + */ +#include <IDE/WIN/user_settings.h> +#include <wolfssl/wolfcrypt/settings.h> +#else +#include <wolfssl/options.h> +#endif #include <wolfssl/openssl/ssl.h> #include <wolfssl/error-ssl.h> #endif /* not USE_OLD_CYASSL */ @@ -210,14 +221,60 @@ typedef unsigned long long lws_intptr_t; #define MBEDTLS_CONFIG_FILE <mbedtls/esp_config.h> #endif #include <mbedtls/ssl.h> -#endif +#else #include <openssl/ssl.h> #if !defined(LWS_WITH_MBEDTLS) #include <openssl/err.h> #endif +#endif #endif /* not USE_WOLFSSL */ #endif +/* + * Helpers for pthread mutex in user code... if lws is built for + * multiple service threads, these resolve to pthread mutex + * operations. In the case LWS_MAX_SMP is 1 (the default), they + * are all NOPs and no pthread type or api is referenced. + */ + +#if LWS_MAX_SMP > 1 + +#include <pthread.h> + +#define lws_pthread_mutex(name) pthread_mutex_t name; + +static LWS_INLINE void +lws_pthread_mutex_init(pthread_mutex_t *lock) +{ + pthread_mutex_init(lock, NULL); +} + +static LWS_INLINE void +lws_pthread_mutex_destroy(pthread_mutex_t *lock) +{ + pthread_mutex_destroy(lock); +} + +static LWS_INLINE void +lws_pthread_mutex_lock(pthread_mutex_t *lock) +{ + pthread_mutex_lock(lock); +} + +static LWS_INLINE void +lws_pthread_mutex_unlock(pthread_mutex_t *lock) +{ + pthread_mutex_unlock(lock); +} + +#else +#define lws_pthread_mutex(name) +#define lws_pthread_mutex_init(_a) +#define lws_pthread_mutex_destroy(_a) +#define lws_pthread_mutex_lock(_a) +#define lws_pthread_mutex_unlock(_a) +#endif + #define CONTEXT_PORT_NO_LISTEN -1 #define CONTEXT_PORT_NO_LISTEN_SERVER -2 @@ -280,10 +337,6 @@ lwsl_timestamp(int level, char *p, int len); * active */ -#if defined(LWS_WITH_ESP8266) -#undef _DEBUG -#endif - #ifdef _DEBUG #if defined(LWS_WITH_NO_LOGS) /* notice, warn and log are always compiled in */ @@ -313,14 +366,20 @@ lwsl_timestamp(int level, char *p, int len); #endif +#define lwsl_hexdump_err(...) lwsl_hexdump_level(LLL_ERR, __VA_ARGS__) +#define lwsl_hexdump_warn(...) lwsl_hexdump_level(LLL_WARN, __VA_ARGS__) +#define lwsl_hexdump_notice(...) lwsl_hexdump_level(LLL_NOTICE, __VA_ARGS__) +#define lwsl_hexdump_info(...) lwsl_hexdump_level(LLL_INFO, __VA_ARGS__) +#define lwsl_hexdump_debug(...) lwsl_hexdump_level(LLL_DEBUG, __VA_ARGS__) + /** - * lwsl_hexdump() - helper to hexdump a buffer + * lwsl_hexdump_level() - helper to hexdump a buffer at a selected debug level * * \param level: one of LLL_ constants - * \param buf: buffer start to dump + * \param vbuf: buffer start to dump * \param len: length of buffer to dump * - * If \p level is visible, does a nice hexdump -C style dump of \p buf for + * If \p level is visible, does a nice hexdump -C style dump of \p vbuf for * \p len bytes. This can be extremely convenient while debugging. */ LWS_VISIBLE LWS_EXTERN void @@ -396,12 +455,13 @@ lwsl_visible(int level); #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M))) #endif - struct lws; #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #endif +typedef int64_t lws_usec_t; + /* api change list for user code to test against */ #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG @@ -422,7 +482,7 @@ struct lws; #if defined(_WIN32) typedef SOCKET lws_sockfd_type; typedef HANDLE lws_filefd_type; -#define lws_sockfd_valid(sfd) (!!sfd) + struct lws_pollfd { lws_sockfd_type fd; /**< file descriptor */ SHORT events; /**< which events to respond to */ @@ -434,77 +494,11 @@ struct lws_pollfd { #else -#if defined(LWS_WITH_ESP8266) - -#include <user_interface.h> -#include <espconn.h> - -typedef struct espconn * lws_sockfd_type; -typedef void * lws_filefd_type; -#define lws_sockfd_valid(sfd) (!!sfd) -struct pollfd { - lws_sockfd_type fd; /**< fd related to */ - short events; /**< which POLL... events to respond to */ - short revents; /**< which POLL... events occurred */ -}; -#define POLLIN 0x0001 -#define POLLPRI 0x0002 -#define POLLOUT 0x0004 -#define POLLERR 0x0008 -#define POLLHUP 0x0010 -#define POLLNVAL 0x0020 - -struct lws_vhost; - -lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh); -void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi); - -#include <os_type.h> -#include <osapi.h> -#include "ets_sys.h" - -int ets_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3); -#define snprintf ets_snprintf - -typedef os_timer_t uv_timer_t; -typedef void uv_cb_t(uv_timer_t *); - -void os_timer_disarm(void *); -void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *); - -void ets_timer_arm_new(os_timer_t *, int, int, int); - -//void os_timer_arm(os_timer_t *, int, int); - -#define UV_VERSION_MAJOR 1 - -#define lws_uv_getloop(a, b) (NULL) - -static inline void uv_timer_init(void *l, uv_timer_t *t) -{ - (void)l; - memset(t, 0, sizeof(*t)); - os_timer_disarm(t); -} - -static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep) -{ - os_timer_setfn(t, (os_timer_func_t *)cb, t); - /* ms, repeat */ - os_timer_arm(t, first, !!rep); -} - -static inline void uv_timer_stop(uv_timer_t *t) -{ - os_timer_disarm(t); -} - -#else #if defined(LWS_WITH_ESP32) typedef int lws_sockfd_type; typedef int lws_filefd_type; -#define lws_sockfd_valid(sfd) (sfd >= 0) + struct pollfd { lws_sockfd_type fd; /**< fd related to */ short events; /**< which POLL... events to respond to */ @@ -638,13 +632,14 @@ struct lws_esp32 { char model[16]; char group[16]; char role[16]; - char ssid[4][16]; - char password[4][32]; - char active_ssid[32]; + char ssid[4][64]; + char password[4][64]; + char active_ssid[64]; char access_pw[16]; char hostname[32]; char mac[20]; - mdns_server_t *mdns; + char le_dns[64]; + char le_email[64]; char region; char inet; char conn_ap; @@ -656,6 +651,11 @@ struct lws_esp32 { void *scan_consumer_arg; struct lws_group_member *first; int extant_group_members; + + char acme; + char upload; + + volatile char button_is_down; }; struct lws_esp32_image { @@ -702,8 +702,6 @@ extern void lws_esp32_leds_timer_cb(TimerHandle_t th); #else typedef int lws_sockfd_type; typedef int lws_filefd_type; -#define lws_sockfd_valid(sfd) (sfd >= 0) -#endif #endif #define lws_pollfd pollfd @@ -830,6 +828,8 @@ enum lws_close_status { connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified). */ + LWS_CLOSE_STATUS_CLIENT_TRANSACTION_DONE = 2000, + /****** add new things just above ---^ ******/ LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999, @@ -858,37 +858,6 @@ struct lws_context; /* needed even with extensions disabled for create context */ struct lws_extension; -/*! \defgroup lwsmeta lws-meta - * - * ##lws-meta protocol - * - * The protocol wraps other muxed connections inside one tcp connection. - * - * Commands are assigned from 0x41 up (so they are valid unicode) - */ -///@{ - -enum lws_meta_commands { - LWS_META_CMD_OPEN_SUBCHANNEL = 'A', - /**< Client requests to open new subchannel - */ - LWS_META_CMD_OPEN_RESULT, - /**< Result of client request to open new subchannel */ - LWS_META_CMD_CLOSE_NOTIFY, - /**< Notification of subchannel closure */ - LWS_META_CMD_CLOSE_RQ, - /**< client requests to close a subchannel */ - LWS_META_CMD_WRITE, - /**< connection writes something to specific channel index */ - - /****** add new things just above ---^ ******/ -}; - -/* channel numbers are transported offset by 0x20 so they are valid unicode */ - -#define LWS_META_TRANSPORT_OFFSET 0x20 - -///@} /*! \defgroup usercb User Callback * @@ -908,16 +877,388 @@ struct lws_ssl_info { int ret; }; +enum lws_cert_update_state { + LWS_CUS_IDLE, + LWS_CUS_STARTING, + LWS_CUS_SUCCESS, + LWS_CUS_FAILED, + + LWS_CUS_CREATE_KEYS, + LWS_CUS_REG, + LWS_CUS_AUTH, + LWS_CUS_CHALLENGE, + LWS_CUS_CREATE_REQ, + LWS_CUS_REQ, + LWS_CUS_CONFIRM, + LWS_CUS_ISSUE, +}; + +enum { + LWS_TLS_REQ_ELEMENT_COUNTRY, + LWS_TLS_REQ_ELEMENT_STATE, + LWS_TLS_REQ_ELEMENT_LOCALITY, + LWS_TLS_REQ_ELEMENT_ORGANIZATION, + LWS_TLS_REQ_ELEMENT_COMMON_NAME, + LWS_TLS_REQ_ELEMENT_EMAIL, + + LWS_TLS_REQ_ELEMENT_COUNT, + + LWS_TLS_SET_DIR_URL = LWS_TLS_REQ_ELEMENT_COUNT, + LWS_TLS_SET_AUTH_PATH, + LWS_TLS_SET_CERT_PATH, + LWS_TLS_SET_KEY_PATH, + + LWS_TLS_TOTAL_COUNT +}; + +struct lws_acme_cert_aging_args { + struct lws_vhost *vh; + const char *element_overrides[LWS_TLS_TOTAL_COUNT]; /* NULL = use pvo */ +}; + /* * NOTE: These public enums are part of the abi. If you want to add one, * add it at where specified so existing users are unaffected. */ /** enum lws_callback_reasons - reason you're getting a protocol callback */ enum lws_callback_reasons { + + /* --------------------------------------------------------------------- + * ----- Callbacks related to wsi and protocol binding lifecycle ----- + */ + + LWS_CALLBACK_PROTOCOL_INIT = 27, + /**< One-time call per protocol, per-vhost using it, so it can + * do initial setup / allocations etc */ + + LWS_CALLBACK_PROTOCOL_DESTROY = 28, + /**< One-time call per protocol, per-vhost using it, indicating + * this protocol won't get used at all after this callback, the + * vhost is getting destroyed. Take the opportunity to + * deallocate everything that was allocated by the protocol. */ + + LWS_CALLBACK_WSI_CREATE = 29, + /**< outermost (earliest) wsi create notification to protocols[0] */ + + LWS_CALLBACK_WSI_DESTROY = 30, + /**< outermost (latest) wsi destroy notification to protocols[0] */ + + LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49, + /**< By default, all HTTP handling is done in protocols[0]. + * However you can bind different protocols (by name) to + * different parts of the URL space using callback mounts. This + * callback occurs in the new protocol when a wsi is bound + * to that protocol. Any protocol allocation related to the + * http transaction processing should be created then. + * These specific callbacks are necessary because with HTTP/1.1, + * a single connection may perform at series of different + * transactions at different URLs, thus the lifetime of the + * protocol bind is just for one transaction, not connection. */ + + LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50, + /**< This is called when a transaction is unbound from a protocol. + * It indicates the connection completed its transaction and may + * do something different now. Any protocol allocation related + * to the http transaction processing should be destroyed. */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to Server TLS ----- + */ + + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21, + /**< if configured for + * including OpenSSL support, this callback allows your user code + * to perform extra SSL_CTX_load_verify_locations() or similar + * calls to direct OpenSSL where to find certificates the client + * can use to confirm the remote server identity. user is the + * OpenSSL SSL_CTX* */ + + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22, + /**< if configured for + * including OpenSSL support, this callback allows your user code + * to load extra certificates into the server which allow it to + * verify the validity of certificates returned by clients. user + * is the server's OpenSSL SSL_CTX* and in is the lws_vhost */ + + LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23, + /**< if the libwebsockets vhost was created with the option + * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this + * callback is generated during OpenSSL verification of the cert + * sent from the client. It is sent to protocol[0] callback as + * no protocol has been negotiated on the connection yet. + * Notice that the libwebsockets context and wsi are both NULL + * during this callback. See + * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html + * to understand more detail about the OpenSSL callback that + * generates this libwebsockets callback and the meanings of the + * arguments passed. In this callback, user is the x509_ctx, + * in is the ssl pointer and len is preverify_ok + * Notice that this callback maintains libwebsocket return + * conventions, return 0 to mean the cert is OK or 1 to fail it. + * This also means that if you don't handle this callback then + * the default callback action of returning 0 allows the client + * certificates. */ + + LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37, + /**< if configured for including OpenSSL support but no private key + * file has been specified (ssl_private_key_filepath is NULL), this is + * called to allow the user to set the private key directly via + * libopenssl and perform further operations if required; this might be + * useful in situations where the private key is not directly accessible + * by the OS, for example if it is stored on a smartcard. + * user is the server's OpenSSL SSL_CTX* */ + + LWS_CALLBACK_SSL_INFO = 67, + /**< SSL connections only. An event you registered an + * interest in at the vhost has occurred on a connection + * using the vhost. in is a pointer to a + * struct lws_ssl_info containing information about the + * event*/ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to Client TLS ----- + */ + + LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58, + /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION + * this callback is called during OpenSSL verification of the cert + * sent from the server to the client. It is sent to protocol[0] + * callback as no protocol has been negotiated on the connection yet. + * Notice that the wsi is set because lws_client_connect_via_info was + * successful. + * + * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html + * to understand more detail about the OpenSSL callback that + * generates this libwebsockets callback and the meanings of the + * arguments passed. In this callback, user is the x509_ctx, + * in is the ssl pointer and len is preverify_ok. + * + * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be + * overruled and cert shall be accepted as ok, + * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be + * called and return value must be 0 to mean the cert is OK; + * returning 1 will fail the cert in any case. + * + * This also means that if you don't handle this callback then + * the default callback action of returning 0 will not accept the + * certificate in case of a validation error decided by the SSL lib. + * + * This is expected and secure behaviour when validating certificates. + * + * Note: LCCSCF_ALLOW_SELFSIGNED and + * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this + * callback being implemented. + */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to HTTP Server ----- + */ + + LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19, + /**< A new client has been accepted by the ws server. This + * callback allows setting any relevant property to it. Because this + * happens immediately after the instantiation of a new client, + * there's no websocket protocol selected yet so this callback is + * issued only to protocol 0. Only wsi is defined, pointing to the + * new client, and the return value is ignored. */ + + LWS_CALLBACK_HTTP = 12, + /**< an http request has come from a client that is not + * asking to upgrade the connection to a websocket + * one. This is a chance to serve http content, + * for example, to send a script to the client + * which will then open the websockets connection. + * in points to the URI path requested and + * lws_serve_http_file() makes it very + * simple to send back a file to the client. + * Normally after sending the file you are done + * with the http connection, since the rest of the + * activity will come by websockets from the script + * that was delivered by http, so you will want to + * return 1; to close and free up the connection. */ + + LWS_CALLBACK_HTTP_BODY = 13, + /**< the next len bytes data from the http + * request body HTTP connection is now available in in. */ + + LWS_CALLBACK_HTTP_BODY_COMPLETION = 14, + /**< the expected amount of http request body has been delivered */ + + LWS_CALLBACK_HTTP_FILE_COMPLETION = 15, + /**< a file requested to be sent down http link has completed. */ + + LWS_CALLBACK_HTTP_WRITEABLE = 16, + /**< you can write more down the http protocol link now. */ + + LWS_CALLBACK_CLOSED_HTTP = 5, + /**< when a HTTP (non-websocket) session ends */ + + LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18, + /**< called when the request has + * been received and parsed from the client, but the response is + * not sent yet. Return non-zero to disallow the connection. + * user is a pointer to the connection user space allocation, + * in is the URI, eg, "/" + * In your handler you can use the public APIs + * lws_hdr_total_length() / lws_hdr_copy() to access all of the + * headers using the header enums lws_token_indexes from + * libwebsockets.h to check for and read the supported header + * presence and content before deciding to allow the http + * connection to proceed or to kill the connection. */ + + LWS_CALLBACK_ADD_HEADERS = 53, + /**< This gives your user code a chance to add headers to a server + * transaction bound to your protocol. `in` points to a + * `struct lws_process_html_args` describing a buffer and length + * you can add headers into using the normal lws apis. + * + * (see LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to add headers to + * a client transaction) + * + * Only `args->p` and `args->len` are valid, and `args->p` should + * be moved on by the amount of bytes written, if any. Eg + * + * case LWS_CALLBACK_ADD_HEADERS: + * + * struct lws_process_html_args *args = + * (struct lws_process_html_args *)in; + * + * if (lws_add_http_header_by_name(wsi, + * (unsigned char *)"set-cookie:", + * (unsigned char *)cookie, cookie_len, + * (unsigned char **)&args->p, + * (unsigned char *)args->p + args->max_len)) + * return 1; + * + * break; + */ + + LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51, + /**< This gives the user code a chance to forbid an http access. + * `in` points to a `struct lws_process_html_args`, which + * describes the URL, and a bit mask describing the type of + * authentication required. If the callback returns nonzero, + * the transaction ends with HTTP_STATUS_UNAUTHORIZED. */ + + LWS_CALLBACK_PROCESS_HTML = 52, + /**< This gives your user code a chance to mangle outgoing + * HTML. `in` points to a `struct lws_process_html_args` + * which describes the buffer containing outgoing HTML. + * The buffer may grow up to `.max_len` (currently +128 + * bytes per buffer). + */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to HTTP Client ----- + */ + + LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44, + /**< The HTTP client connection has succeeded, and is now + * connected to the server */ + + LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45, + /**< The HTTP client connection is closing */ + + LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48, + /**< This is generated by lws_http_client_read() used to drain + * incoming data. In the case the incoming data was chunked, it will + * be split into multiple smaller callbacks for each chunk block, + * removing the chunk headers. If not chunked, it will appear all in + * one callback. */ + + LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46, + /**< This simply indicates data was received on the HTTP client + * connection. It does NOT drain or provide the data. + * This exists to neatly allow a proxying type situation, + * where this incoming data will go out on another connection. + * If the outgoing connection stalls, we should stall processing + * the incoming data. So a handler for this in that case should + * simply set a flag to indicate there is incoming data ready + * and ask for a writeable callback on the outgoing connection. + * In the writable callback he can check the flag and then get + * and drain the waiting incoming data using lws_http_client_read(). + * This will use callbacks to LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ + * to get and drain the incoming data, where it should be sent + * back out on the outgoing connection. */ + LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47, + /**< The client transaction completed... at the moment this + * is the same as closing since transaction pipelining on + * client side is not yet supported. */ + + LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57, + /**< when doing an HTTP type client connection, you can call + * lws_client_http_body_pending(wsi, 1) from + * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks + * sending the HTTP headers. + * + * From this callback, when you have sent everything, you should let + * lws know by calling lws_client_http_body_pending(wsi, 0) + */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to Websocket Server ----- + */ + LWS_CALLBACK_ESTABLISHED = 0, /**< (VH) after the server completes a handshake with an incoming * client. If you built the library with ssl support, in is a - * pointer to the ssl struct associated with the connection or NULL.*/ + * pointer to the ssl struct associated with the connection or NULL. + * + * b0 of len is set if the connection was made using ws-over-h2 + */ + + LWS_CALLBACK_CLOSED = 4, + /**< when the websocket session ends */ + + LWS_CALLBACK_SERVER_WRITEABLE = 11, + /**< See LWS_CALLBACK_CLIENT_WRITEABLE */ + + LWS_CALLBACK_RECEIVE = 6, + /**< data has appeared for this server endpoint from a + * remote client, it can be found at *in and is + * len bytes long */ + + LWS_CALLBACK_RECEIVE_PONG = 7, + /**< servers receive PONG packets with this callback reason */ + + LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38, + /**< The peer has sent an unsolicited Close WS packet. in and + * len are the optional close code (first 2 bytes, network + * order) and the optional additional information which is not + * defined in the standard, and may be a string or non human-readable + * data. + * If you return 0 lws will echo the close and then close the + * connection. If you return nonzero lws will just close the + * connection. */ + + LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20, + /**< called when the handshake has + * been received and parsed from the client, but the response is + * not sent yet. Return non-zero to disallow the connection. + * user is a pointer to the connection user space allocation, + * in is the requested protocol name + * In your handler you can use the public APIs + * lws_hdr_total_length() / lws_hdr_copy() to access all of the + * headers using the header enums lws_token_indexes from + * libwebsockets.h to check for and read the supported header + * presence and content before deciding to allow the handshake + * to proceed or to kill the connection. */ + + LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25, + /**< When the server handshake code + * sees that it does support a requested extension, before + * accepting the extension by additing to the list sent back to + * the client it gives this callback just to check that it's okay + * to use that extension. It calls back to the requested protocol + * and with in being the extension name, len is 0 and user is + * valid. Note though at this time the ESTABLISHED callback hasn't + * happened yet so if you initialize user content there, user + * content during this callback might not be useful for anything. */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to Websocket Client ----- + */ + LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1, /**< the request client connection has been unable to complete a * handshake with the remote server. If in is non-NULL, you can @@ -962,6 +1303,7 @@ enum lws_callback_reasons { * "HS: SO_SNDBUF failed" * "HS: Rejected at CLIENT_ESTABLISHED" */ + LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2, /**< this is the last chance for the client user code to examine the * http headers and decide to reject the connection. If the @@ -969,131 +1311,14 @@ enum lws_callback_reasons { * client (url, etc) it needs to copy it out at * this point since it will be destroyed before * the CLIENT_ESTABLISHED call */ + LWS_CALLBACK_CLIENT_ESTABLISHED = 3, - /**< after your client connection completed - * a handshake with the remote server */ - LWS_CALLBACK_CLOSED = 4, - /**< when the websocket session ends */ - LWS_CALLBACK_CLOSED_HTTP = 5, - /**< when a HTTP (non-websocket) session ends */ - LWS_CALLBACK_RECEIVE = 6, - /**< data has appeared for this server endpoint from a - * remote client, it can be found at *in and is - * len bytes long */ - LWS_CALLBACK_RECEIVE_PONG = 7, - /**< servers receive PONG packets with this callback reason */ - LWS_CALLBACK_CLIENT_RECEIVE = 8, - /**< data has appeared from the server for the client connection, it - * can be found at *in and is len bytes long */ - LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9, - /**< clients receive PONG packets with this callback reason */ - LWS_CALLBACK_CLIENT_WRITEABLE = 10, - /**< If you call lws_callback_on_writable() on a connection, you will - * get one of these callbacks coming when the connection socket - * is able to accept another write packet without blocking. - * If it already was able to take another packet without blocking, - * you'll get this callback at the next call to the service loop - * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE - * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */ - LWS_CALLBACK_SERVER_WRITEABLE = 11, - /**< See LWS_CALLBACK_CLIENT_WRITEABLE */ - LWS_CALLBACK_HTTP = 12, - /**< an http request has come from a client that is not - * asking to upgrade the connection to a websocket - * one. This is a chance to serve http content, - * for example, to send a script to the client - * which will then open the websockets connection. - * in points to the URI path requested and - * lws_serve_http_file() makes it very - * simple to send back a file to the client. - * Normally after sending the file you are done - * with the http connection, since the rest of the - * activity will come by websockets from the script - * that was delivered by http, so you will want to - * return 1; to close and free up the connection. */ - LWS_CALLBACK_HTTP_BODY = 13, - /**< the next len bytes data from the http - * request body HTTP connection is now available in in. */ - LWS_CALLBACK_HTTP_BODY_COMPLETION = 14, - /**< the expected amount of http request body has been delivered */ - LWS_CALLBACK_HTTP_FILE_COMPLETION = 15, - /**< a file requested to be sent down http link has completed. */ - LWS_CALLBACK_HTTP_WRITEABLE = 16, - /**< you can write more down the http protocol link now. */ - LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17, - /**< called when a client connects to - * the server at network level; the connection is accepted but then - * passed to this callback to decide whether to hang up immediately - * or not, based on the client IP. in contains the connection - * socket's descriptor. Since the client connection information is - * not available yet, wsi still pointing to the main server socket. - * Return non-zero to terminate the connection before sending or - * receiving anything. Because this happens immediately after the - * network connection from the client, there's no websocket protocol - * selected yet so this callback is issued only to protocol 0. */ - LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18, - /**< called when the request has - * been received and parsed from the client, but the response is - * not sent yet. Return non-zero to disallow the connection. - * user is a pointer to the connection user space allocation, - * in is the URI, eg, "/" - * In your handler you can use the public APIs - * lws_hdr_total_length() / lws_hdr_copy() to access all of the - * headers using the header enums lws_token_indexes from - * libwebsockets.h to check for and read the supported header - * presence and content before deciding to allow the http - * connection to proceed or to kill the connection. */ - LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19, - /**< A new client just had - * been connected, accepted, and instantiated into the pool. This - * callback allows setting any relevant property to it. Because this - * happens immediately after the instantiation of a new client, - * there's no websocket protocol selected yet so this callback is - * issued only to protocol 0. Only wsi is defined, pointing to the - * new client, and the return value is ignored. */ - LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20, - /**< called when the handshake has - * been received and parsed from the client, but the response is - * not sent yet. Return non-zero to disallow the connection. - * user is a pointer to the connection user space allocation, - * in is the requested protocol name - * In your handler you can use the public APIs - * lws_hdr_total_length() / lws_hdr_copy() to access all of the - * headers using the header enums lws_token_indexes from - * libwebsockets.h to check for and read the supported header - * presence and content before deciding to allow the handshake - * to proceed or to kill the connection. */ - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21, - /**< if configured for - * including OpenSSL support, this callback allows your user code - * to perform extra SSL_CTX_load_verify_locations() or similar - * calls to direct OpenSSL where to find certificates the client - * can use to confirm the remote server identity. user is the - * OpenSSL SSL_CTX* */ - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22, - /**< if configured for - * including OpenSSL support, this callback allows your user code - * to load extra certificates into the server which allow it to - * verify the validity of certificates returned by clients. user - * is the server's OpenSSL SSL_CTX* */ - LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23, - /**< if the libwebsockets vhost was created with the option - * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this - * callback is generated during OpenSSL verification of the cert - * sent from the client. It is sent to protocol[0] callback as - * no protocol has been negotiated on the connection yet. - * Notice that the libwebsockets context and wsi are both NULL - * during this callback. See - * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html - * to understand more detail about the OpenSSL callback that - * generates this libwebsockets callback and the meanings of the - * arguments passed. In this callback, user is the x509_ctx, - * in is the ssl pointer and len is preverify_ok - * Notice that this callback maintains libwebsocket return - * conventions, return 0 to mean the cert is OK or 1 to fail it. - * This also means that if you don't handle this callback then - * the default callback action of returning 0 allows the client - * certificates. */ + /**< after your client connection completed the websocket upgrade + * handshake with the remote server */ + + LWS_CALLBACK_CLIENT_CLOSED = 75, + /**< when a client websocket session ends */ + LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24, /**< this callback happens * when a client handshake is being compiled. user is NULL, @@ -1117,19 +1342,30 @@ enum lws_callback_reasons { * optional, if you don't handle it everything is fine. * * Notice the callback is coming to protocols[0] all the time, - * because there is no specific protocol negotiated yet. */ - LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25, - /**< When the server handshake code - * sees that it does support a requested extension, before - * accepting the extension by additing to the list sent back to - * the client it gives this callback just to check that it's okay - * to use that extension. It calls back to the requested protocol - * and with in being the extension name, len is 0 and user is - * valid. Note though at this time the ESTABLISHED callback hasn't - * happened yet so if you initialize user content there, user - * content during this callback might not be useful for anything. */ + * because there is no specific protocol negotiated yet. + * + * See LWS_CALLBACK_ADD_HEADERS for adding headers to server + * transactions. + */ + + LWS_CALLBACK_CLIENT_RECEIVE = 8, + /**< data has appeared from the server for the client connection, it + * can be found at *in and is len bytes long */ + + LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9, + /**< clients receive PONG packets with this callback reason */ + + LWS_CALLBACK_CLIENT_WRITEABLE = 10, + /**< If you call lws_callback_on_writable() on a connection, you will + * get one of these callbacks coming when the connection socket + * is able to accept another write packet without blocking. + * If it already was able to take another packet without blocking, + * you'll get this callback at the next call to the service loop + * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE + * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */ + LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26, - /**< When a client + /**< When a ws client * connection is being prepared to start a handshake to a server, * each supported extension is checked with protocols[0] callback * with this reason, giving the user code a chance to suppress the @@ -1137,18 +1373,32 @@ enum lws_callback_reasons { * unhandled, by default 0 will be returned and the extension * support included in the header to the server. Notice this * callback comes to protocols[0]. */ - LWS_CALLBACK_PROTOCOL_INIT = 27, - /**< One-time call per protocol, per-vhost using it, so it can - * do initial setup / allocations etc */ - LWS_CALLBACK_PROTOCOL_DESTROY = 28, - /**< One-time call per protocol, per-vhost using it, indicating - * this protocol won't get used at all after this callback, the - * vhost is getting destroyed. Take the opportunity to - * deallocate everything that was allocated by the protocol. */ - LWS_CALLBACK_WSI_CREATE = 29, - /**< outermost (earliest) wsi create notification to protocols[0] */ - LWS_CALLBACK_WSI_DESTROY = 30, - /**< outermost (latest) wsi destroy notification to protocols[0] */ + + LWS_CALLBACK_WS_EXT_DEFAULTS = 39, + /**< Gives client connections an opportunity to adjust negotiated + * extension defaults. `user` is the extension name that was + * negotiated (eg, "permessage-deflate"). `in` points to a + * buffer and `len` is the buffer size. The user callback can + * set the buffer to a string describing options the extension + * should parse. Or just ignore for defaults. */ + + + LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17, + /**< called when a client connects to + * the server at network level; the connection is accepted but then + * passed to this callback to decide whether to hang up immediately + * or not, based on the client IP. in contains the connection + * socket's descriptor. Since the client connection information is + * not available yet, wsi still pointing to the main server socket. + * Return non-zero to terminate the connection before sending or + * receiving anything. Because this happens immediately after the + * network connection from the client, there's no websocket protocol + * selected yet so this callback is issued only to protocol 0. */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to external poll loop integration ----- + */ + LWS_CALLBACK_GET_THREAD_ID = 31, /**< lws can accept callback when writable requests from other * threads, if you implement this callback and return an opaque @@ -1171,12 +1421,14 @@ enum lws_callback_reasons { * * If you are using the internal lws polling / event loop * you can just ignore these callbacks. */ + LWS_CALLBACK_DEL_POLL_FD = 33, /**< This callback happens when a socket descriptor * needs to be removed from an external polling array. in is * again the struct lws_pollargs containing the fd member * to be removed. If you are using the internal polling * loop, you can just ignore it. */ + LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34, /**< This callback happens when lws wants to modify the events for * a connection. @@ -1185,6 +1437,7 @@ enum lws_callback_reasons { * the prev_events member. * If you are using the internal polling loop, you can just ignore * it. */ + LWS_CALLBACK_LOCK_POLL = 35, /**< These allow the external poll changes driven * by lws to participate in an external thread locking @@ -1197,135 +1450,46 @@ enum lws_callback_reasons { * len == 1 allows external threads to be synchronized against * wsi lifecycle changes if it acquires the same lock for the * duration of wsi dereference from the other thread context. */ + LWS_CALLBACK_UNLOCK_POLL = 36, /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */ - LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37, - /**< if configured for including OpenSSL support but no private key - * file has been specified (ssl_private_key_filepath is NULL), this is - * called to allow the user to set the private key directly via - * libopenssl and perform further operations if required; this might be - * useful in situations where the private key is not directly accessible - * by the OS, for example if it is stored on a smartcard. - * user is the server's OpenSSL SSL_CTX* */ - LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38, - /**< The peer has sent an unsolicited Close WS packet. in and - * len are the optional close code (first 2 bytes, network - * order) and the optional additional information which is not - * defined in the standard, and may be a string or non-human- readable data. - * If you return 0 lws will echo the close and then close the - * connection. If you return nonzero lws will just close the - * connection. */ - - LWS_CALLBACK_WS_EXT_DEFAULTS = 39, - /**< Gives client connections an opportunity to adjust negotiated - * extension defaults. `user` is the extension name that was - * negotiated (eg, "permessage-deflate"). `in` points to a - * buffer and `len` is the buffer size. The user callback can - * set the buffer to a string describing options the extension - * should parse. Or just ignore for defaults. */ + /* --------------------------------------------------------------------- + * ----- Callbacks related to CGI serving ----- + */ LWS_CALLBACK_CGI = 40, /**< CGI: CGI IO events on stdin / out / err are sent here on * protocols[0]. The provided `lws_callback_http_dummy()` * handles this and the callback should be directed there if * you use CGI. */ + LWS_CALLBACK_CGI_TERMINATED = 41, /**< CGI: The related CGI process ended, this is called before * the wsi is closed. Used to, eg, terminate chunking. * The provided `lws_callback_http_dummy()` * handles this and the callback should be directed there if * you use CGI. The child PID that terminated is in len. */ + LWS_CALLBACK_CGI_STDIN_DATA = 42, /**< CGI: Data is, to be sent to the CGI process stdin, eg from * a POST body. The provided `lws_callback_http_dummy()` * handles this and the callback should be directed there if * you use CGI. */ + LWS_CALLBACK_CGI_STDIN_COMPLETED = 43, /**< CGI: no more stdin is coming. The provided * `lws_callback_http_dummy()` handles this and the callback * should be directed there if you use CGI. */ - LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44, - /**< The HTTP client connection has succeeded, and is now - * connected to the server */ - LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45, - /**< The HTTP client connection is closing */ - LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46, - /**< This simply indicates data was received on the HTTP client - * connection. It does NOT drain or provide the data. - * This exists to neatly allow a proxying type situation, - * where this incoming data will go out on another connection. - * If the outgoing connection stalls, we should stall processing - * the incoming data. So a handler for this in that case should - * simply set a flag to indicate there is incoming data ready - * and ask for a writeable callback on the outgoing connection. - * In the writable callback he can check the flag and then get - * and drain the waiting incoming data using lws_http_client_read(). - * This will use callbacks to LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ - * to get and drain the incoming data, where it should be sent - * back out on the outgoing connection. */ - LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47, - /**< The client transaction completed... at the moment this - * is the same as closing since transaction pipelining on - * client side is not yet supported. */ - LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48, - /**< This is generated by lws_http_client_read() used to drain - * incoming data. In the case the incoming data was chunked, - * it will be split into multiple smaller callbacks for each - * chunk block, removing the chunk headers. If not chunked, - * it will appear all in one callback. */ - LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49, - /**< By default, all HTTP handling is done in protocols[0]. - * However you can bind different protocols (by name) to - * different parts of the URL space using callback mounts. This - * callback occurs in the new protocol when a wsi is bound - * to that protocol. Any protocol allocation related to the - * http transaction processing should be created then. - * These specific callbacks are necessary because with HTTP/1.1, - * a single connection may perform at series of different - * transactions at different URLs, thus the lifetime of the - * protocol bind is just for one transaction, not connection. */ - LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50, - /**< This is called when a transaction is unbound from a protocol. - * It indicates the connection completed its transaction and may - * do something different now. Any protocol allocation related - * to the http transaction processing should be destroyed. */ - LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51, - /**< This gives the user code a chance to forbid an http access. - * `in` points to a `struct lws_process_html_args`, which - * describes the URL, and a bit mask describing the type of - * authentication required. If the callback returns nonzero, - * the transaction ends with HTTP_STATUS_UNAUTHORIZED. */ - LWS_CALLBACK_PROCESS_HTML = 52, - /**< This gives your user code a chance to mangle outgoing - * HTML. `in` points to a `struct lws_process_html_args` - * which describes the buffer containing outgoing HTML. - * The buffer may grow up to `.max_len` (currently +128 - * bytes per buffer). - * */ - LWS_CALLBACK_ADD_HEADERS = 53, - /**< This gives your user code a chance to add headers to a - * transaction bound to your protocol. `in` points to a - * `struct lws_process_html_args` describing a buffer and length - * you can add headers into using the normal lws apis. - * - * Only `args->p` and `args->len` are valid, and `args->p` should - * be moved on by the amount of bytes written, if any. Eg - * - * case LWS_CALLBACK_ADD_HEADERS: - * - * struct lws_process_html_args *args = - * (struct lws_process_html_args *)in; - * - * if (lws_add_http_header_by_name(wsi, - * (unsigned char *)"set-cookie:", - * (unsigned char *)cookie, cookie_len, - * (unsigned char **)&args->p, - * (unsigned char *)args->p + args->max_len)) - * return 1; - * - * break; + + LWS_CALLBACK_CGI_PROCESS_ATTACH = 70, + /**< CGI: Sent when the CGI process is spawned for the wsi. The + * len parameter is the PID of the child process */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to Generic Sessions ----- */ + LWS_CALLBACK_SESSION_INFO = 54, /**< This is only generated by user code using generic sessions. * It's used to get a `struct lws_session_info` filled in by @@ -1335,85 +1499,103 @@ enum lws_callback_reasons { LWS_CALLBACK_GS_EVENT = 55, /**< Indicates an event happened to the Generic Sessions session. * `in` contains a `struct lws_gs_event_args` describing the event. */ + LWS_CALLBACK_HTTP_PMO = 56, /**< per-mount options for this connection, called before * the normal LWS_CALLBACK_HTTP when the mount has per-mount * options. */ - LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57, - /**< when doing an HTTP type client connection, you can call - * lws_client_http_body_pending(wsi, 1) from - * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks - * sending the HTTP headers. - * - * From this callback, when you have sent everything, you should let - * lws know by calling lws_client_http_body_pending(wsi, 0) - */ - LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION = 58, - /**< Similar to LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION - * this callback is called during OpenSSL verification of the cert - * sent from the server to the client. It is sent to protocol[0] - * callback as no protocol has been negotiated on the connection yet. - * Notice that the wsi is set because lws_client_connect_via_info was - * successful. - * - * See http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html - * to understand more detail about the OpenSSL callback that - * generates this libwebsockets callback and the meanings of the - * arguments passed. In this callback, user is the x509_ctx, - * in is the ssl pointer and len is preverify_ok. - * - * THIS IS NOT RECOMMENDED BUT if a cert validation error shall be - * overruled and cert shall be accepted as ok, - * X509_STORE_CTX_set_error((X509_STORE_CTX*)user, X509_V_OK); must be - * called and return value must be 0 to mean the cert is OK; - * returning 1 will fail the cert in any case. - * - * This also means that if you don't handle this callback then - * the default callback action of returning 0 will not accept the - * certificate in case of a validation error decided by the SSL lib. - * - * This is expected and secure behaviour when validating certificates. - * - * Note: LCCSCF_ALLOW_SELFSIGNED and - * LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK still work without this - * callback being implemented. + + /* --------------------------------------------------------------------- + * ----- Callbacks related to RAW sockets ----- */ + LWS_CALLBACK_RAW_RX = 59, /**< RAW mode connection RX */ + LWS_CALLBACK_RAW_CLOSE = 60, /**< RAW mode connection is closing */ + LWS_CALLBACK_RAW_WRITEABLE = 61, /**< RAW mode connection may be written */ + LWS_CALLBACK_RAW_ADOPT = 62, /**< RAW mode connection was adopted (equivalent to 'wsi created') */ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to RAW file handles ----- + */ + LWS_CALLBACK_RAW_ADOPT_FILE = 63, /**< RAW mode file was adopted (equivalent to 'wsi created') */ + LWS_CALLBACK_RAW_RX_FILE = 64, - /**< RAW mode file has something to read */ + /**< This is the indication the RAW mode file has something to read. + * This doesn't actually do the read of the file and len is always + * 0... your code should do the read having been informed there is + * something to read now. */ + LWS_CALLBACK_RAW_WRITEABLE_FILE = 65, /**< RAW mode file is writeable */ + LWS_CALLBACK_RAW_CLOSE_FILE = 66, /**< RAW mode wsi that adopted a file is closing */ - LWS_CALLBACK_SSL_INFO = 67, - /**< SSL connections only. An event you registered an - * interest in at the vhost has occurred on a connection - * using the vhost. in is a pointer to a - * struct lws_ssl_info containing information about the - * event*/ + + /* --------------------------------------------------------------------- + * ----- Callbacks related to generic wsi events ----- + */ + + LWS_CALLBACK_TIMER = 73, + /**< When the time elapsed after a call to + * lws_set_timer_usecs(wsi, usecs) is up, the wsi will get one of + * these callbacks. The deadline can be continuously extended into the + * future by later calls to lws_set_timer_usecs() before the deadline + * expires, or cancelled by lws_set_timer_usecs(wsi, -1); + * See the note on lws_set_timer_usecs() about which event loops are + * supported. */ + + LWS_CALLBACK_EVENT_WAIT_CANCELLED = 71, + /**< This is sent to every protocol of every vhost in response + * to lws_cancel_service() or lws_cancel_service_pt(). This + * callback is serialized in the lws event loop normally, even + * if the lws_cancel_service[_pt]() call was from a different + * thread. */ + + LWS_CALLBACK_CHILD_CLOSING = 69, + /**< Sent to parent to notify them a child is closing / being + * destroyed. in is the child wsi. + */ + LWS_CALLBACK_CHILD_WRITE_VIA_PARENT = 68, /**< Child has been marked with parent_carries_io attribute, so * lws_write directs the to this callback at the parent, * in is a struct lws_write_passthru containing the args * the lws_write() was called with. */ - LWS_CALLBACK_CHILD_CLOSING = 69, - /**< Sent to parent to notify them a child is closing / being - * destroyed. in is the child wsi. + + /* --------------------------------------------------------------------- + * ----- Callbacks related to TLS certificate management ----- */ - LWS_CALLBACK_CGI_PROCESS_ATTACH = 70, - /**< CGI: Sent when the CGI process is spawned for the wsi. The - * len parameter is the PID of the child process */ + + LWS_CALLBACK_VHOST_CERT_AGING = 72, + /**< When a vhost TLS cert has its expiry checked, this callback + * is broadcast to every protocol of every vhost in case the + * protocol wants to take some action with this information. + * \p in is a pointer to a struct lws_acme_cert_aging_args, + * and \p len is the number of days left before it expires, as + * a (ssize_t). In the struct lws_acme_cert_aging_args, vh + * points to the vhost the cert aging information applies to, + * and element_overrides[] is an optional way to update information + * from the pvos... NULL in an index means use the information from + * from the pvo for the cert renewal, non-NULL in the array index + * means use that pointer instead for the index. */ + + LWS_CALLBACK_VHOST_CERT_UPDATE = 74, + /**< When a vhost TLS cert is being updated, progress is + * reported to the vhost in question here, including completion + * and failure. in points to optional JSON, and len represents the + * connection state using enum lws_cert_update_state */ + /****** add new things just above ---^ ******/ @@ -1448,6 +1630,8 @@ lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason, #define LWS_CB_REASON_AUX_BF__CGI_HEADERS 8 ///@} +struct lws_vhost; + /*! \defgroup generic hash * ## Generic Hash related functions * @@ -1459,7 +1643,7 @@ lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason, */ ///@{ -#ifdef LWS_OPENSSL_SUPPORT +#if defined(LWS_WITH_TLS) #if defined(LWS_WITH_MBEDTLS) #include <mbedtls/sha1.h> @@ -1467,9 +1651,20 @@ lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason, #include <mbedtls/sha512.h> #endif -#define LWS_GENHASH_TYPE_SHA1 0 -#define LWS_GENHASH_TYPE_SHA256 1 -#define LWS_GENHASH_TYPE_SHA512 2 +enum lws_genhash_types { + LWS_GENHASH_TYPE_SHA1, + LWS_GENHASH_TYPE_SHA256, + LWS_GENHASH_TYPE_SHA384, + LWS_GENHASH_TYPE_SHA512, +}; + +enum lws_genhmac_types { + LWS_GENHMAC_TYPE_SHA256, + LWS_GENHMAC_TYPE_SHA384, + LWS_GENHMAC_TYPE_SHA512, +}; + +#define LWS_GENHASH_LARGEST 64 struct lws_genhash_ctx { uint8_t type; @@ -1477,7 +1672,8 @@ struct lws_genhash_ctx { union { mbedtls_sha1_context sha1; mbedtls_sha256_context sha256; - mbedtls_sha512_context sha512; + mbedtls_sha512_context sha512; /* 384 also uses this */ + const mbedtls_md_info_t *hmac; } u; #else const EVP_MD *evp_type; @@ -1485,6 +1681,17 @@ struct lws_genhash_ctx { #endif }; +struct lws_genhmac_ctx { + uint8_t type; +#if defined(LWS_WITH_MBEDTLS) + const mbedtls_md_info_t *hmac; + mbedtls_md_context_t ctx; +#else + const EVP_MD *evp_type; + EVP_MD_CTX *ctx; +#endif +}; + /** lws_genhash_size() - get hash size in bytes * * \param type: one of LWS_GENHASH_TYPE_... @@ -1492,7 +1699,16 @@ struct lws_genhash_ctx { * Returns number of bytes in this type of hash */ LWS_VISIBLE LWS_EXTERN size_t LWS_WARN_UNUSED_RESULT -lws_genhash_size(int type); +lws_genhash_size(enum lws_genhash_types type); + +/** lws_genhmac_size() - get hash size in bytes + * + * \param type: one of LWS_GENHASH_TYPE_... + * + * Returns number of bytes in this type of hmac + */ +LWS_VISIBLE LWS_EXTERN size_t LWS_WARN_UNUSED_RESULT +lws_genhmac_size(enum lws_genhmac_types type); /** lws_genhash_init() - prepare your struct lws_genhash_ctx for use * @@ -1502,7 +1718,7 @@ lws_genhash_size(int type); * Initializes the hash context for the type you requested */ LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_genhash_init(struct lws_genhash_ctx *ctx, int type); +lws_genhash_init(struct lws_genhash_ctx *ctx, enum lws_genhash_types type); /** lws_genhash_update() - digest len bytes of the buffer starting at in * @@ -1529,10 +1745,386 @@ lws_genhash_update(struct lws_genhash_ctx *ctx, const void *in, size_t len); LWS_VISIBLE LWS_EXTERN int lws_genhash_destroy(struct lws_genhash_ctx *ctx, void *result); +/** lws_genhmac_init() - prepare your struct lws_genhmac_ctx for use + * + * \param ctx: your struct lws_genhmac_ctx + * \param type: one of LWS_GENHMAC_TYPE_... + * \param key: pointer to the start of the HMAC key + * \param key_len: length of the HMAC key + * + * Initializes the hash context for the type you requested + * + * If the return is nonzero, it failed and there is nothing needing to be + * destroyed. + */ +int +lws_genhmac_init(struct lws_genhmac_ctx *ctx, enum lws_genhmac_types type, + const uint8_t *key, size_t key_len); + +/** lws_genhmac_update() - digest len bytes of the buffer starting at in + * + * \param ctx: your struct lws_genhmac_ctx + * \param in: start of the bytes to digest + * \param len: count of bytes to digest + * + * Updates the state of your hash context to reflect digesting len bytes from in + * + * If the return is nonzero, it failed and needs destroying. + */ +int +lws_genhmac_update(struct lws_genhmac_ctx *ctx, const void *in, size_t len); + +/** lws_genhmac_destroy() - copy out the result digest and destroy the ctx + * + * \param ctx: your struct lws_genhmac_ctx + * \param result: NULL, or where to copy the result hash + * + * Finalizes the hash and copies out the digest. Destroys any allocations such + * that ctx can safely go out of scope after calling this. + * + * NULL result is supported so that you can destroy the ctx cleanly on error + * conditions, where there is no valid result. + */ +int +lws_genhmac_destroy(struct lws_genhmac_ctx *ctx, void *result); +///@} + +/*! \defgroup generic RSA + * ## Generic RSA related functions + * + * Lws provides generic RSA functions that abstract the ones + * provided by whatever OpenSSL library you are linking against. + * + * It lets you use the same code if you build against mbedtls or OpenSSL + * for example. + */ +///@{ + +enum enum_jwk_tok { + JWK_KEY_E, + JWK_KEY_N, + JWK_KEY_D, + JWK_KEY_P, + JWK_KEY_Q, + JWK_KEY_DP, + JWK_KEY_DQ, + JWK_KEY_QI, + JWK_KTY, /* also serves as count of real elements */ + JWK_KEY, +}; + +#define LWS_COUNT_RSA_ELEMENTS JWK_KTY + +struct lws_genrsa_ctx { +#if defined(LWS_WITH_MBEDTLS) + mbedtls_rsa_context *ctx; +#else + BIGNUM *bn[LWS_COUNT_RSA_ELEMENTS]; + RSA *rsa; #endif +}; + +struct lws_genrsa_element { + uint8_t *buf; + uint16_t len; +}; + +struct lws_genrsa_elements { + struct lws_genrsa_element e[LWS_COUNT_RSA_ELEMENTS]; +}; + +/** lws_jwk_destroy_genrsa_elements() - Free allocations in genrsa_elements + * + * \param el: your struct lws_genrsa_elements + * + * This is a helper for user code making use of struct lws_genrsa_elements + * where the elements are allocated on the heap, it frees any non-NULL + * buf element and sets the buf to NULL. + * + * NB: lws_genrsa_public_... apis do not need this as they take care of the key + * creation and destruction themselves. + */ +LWS_VISIBLE LWS_EXTERN void +lws_jwk_destroy_genrsa_elements(struct lws_genrsa_elements *el); + +/** lws_genrsa_public_decrypt_create() - Create RSA public decrypt context + * + * \param ctx: your struct lws_genrsa_ctx + * \param el: struct prepared with key element data + * + * Creates an RSA context with a public key associated with it, formed from + * the key elements in \p el. + * + * Returns 0 for OK or nonzero for error. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_create(struct lws_genrsa_ctx *ctx, struct lws_genrsa_elements *el); + +/** lws_genrsa_new_keypair() - Create new RSA keypair + * + * \param context: your struct lws_context (may be used for RNG) + * \param ctx: your struct lws_genrsa_ctx + * \param el: struct to get the new key element data allocated into it + * \param bits: key size, eg, 4096 + * + * Creates a new RSA context and generates a new keypair into it, with \p bits + * bits. + * + * Returns 0 for OK or nonzero for error. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_new_keypair(struct lws_context *context, struct lws_genrsa_ctx *ctx, + struct lws_genrsa_elements *el, int bits); + +/** lws_genrsa_public_decrypt() - Perform RSA public decryption + * + * \param ctx: your struct lws_genrsa_ctx + * \param in: encrypted input + * \param in_len: length of encrypted input + * \param out: decrypted output + * \param out_max: size of output buffer + * + * Performs the decryption. + * + * Returns <0 for error, or length of decrypted data. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_public_decrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in, + size_t in_len, uint8_t *out, size_t out_max); + +/** lws_genrsa_public_verify() - Perform RSA public verification + * + * \param ctx: your struct lws_genrsa_ctx + * \param in: unencrypted payload (usually a recomputed hash) + * \param hash_type: one of LWS_GENHASH_TYPE_ + * \param sig: pointer to the signature we received with the payload + * \param sig_len: length of the signature we are checking in bytes + * + * Returns <0 for error, or 0 if signature matches the payload + key. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_public_verify(struct lws_genrsa_ctx *ctx, const uint8_t *in, + enum lws_genhash_types hash_type, + const uint8_t *sig, size_t sig_len); + +/** lws_genrsa_public_sign() - Create RSA signature + * + * \param ctx: your struct lws_genrsa_ctx + * \param in: precomputed hash + * \param hash_type: one of LWS_GENHASH_TYPE_ + * \param sig: pointer to buffer to take signature + * \param sig_len: length of the buffer (must be >= length of key N) + * + * Returns <0 for error, or 0 for success. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_public_sign(struct lws_genrsa_ctx *ctx, const uint8_t *in, + enum lws_genhash_types hash_type, uint8_t *sig, + size_t sig_len); + +/** lws_genrsa_public_decrypt_destroy() - Destroy RSA public decrypt context + * + * \param ctx: your struct lws_genrsa_ctx + * + * Destroys any allocations related to \p ctx. + * + * This and related APIs operate identically with OpenSSL or mbedTLS backends. + */ +LWS_VISIBLE LWS_EXTERN void +lws_genrsa_destroy(struct lws_genrsa_ctx *ctx); +/** lws_genrsa_render_pkey_asn1() - Exports public or private key to ASN1/DER + * + * \param ctx: your struct lws_genrsa_ctx + * \param _private: 0 = public part only, 1 = all parts of the key + * \param pkey_asn1: pointer to buffer to take the ASN1 + * \param pkey_asn1_len: max size of the pkey_asn1_len + * + * Returns length of pkey_asn1 written, or -1 for error. + */ +LWS_VISIBLE LWS_EXTERN int +lws_genrsa_render_pkey_asn1(struct lws_genrsa_ctx *ctx, int _private, + uint8_t *pkey_asn1, size_t pkey_asn1_len); ///@} +/*! \defgroup jwk JSON Web Keys + * ## JSON Web Keys API + * + * Lws provides an API to parse JSON Web Keys into a struct lws_genrsa_elements. + * + * "oct" and "RSA" type keys are supported. For "oct" keys, they are held in + * the "e" member of the struct lws_genrsa_elements. + * + * Keys elements are allocated on the heap. You must destroy the allocations + * in the struct lws_genrsa_elements by calling + * lws_jwk_destroy_genrsa_elements() when you are finished with it. + */ +///@{ + +struct lws_jwk { + char keytype[5]; /**< "oct" or "RSA" */ + struct lws_genrsa_elements el; /**< OCTet key is in el.e */ +}; + +/** lws_jwk_import() - Create a JSON Web key from the textual representation + * + * \param s: the JWK object to create + * \param in: a single JWK JSON stanza in utf-8 + * \param len: the length of the JWK JSON stanza in bytes + * + * Creates an lws_jwk struct filled with data from the JSON representation. + * "oct" and "rsa" key types are supported. + * + * For "oct" type keys, it is loaded into el.e. + */ +LWS_VISIBLE LWS_EXTERN int +lws_jwk_import(struct lws_jwk *s, const char *in, size_t len); + +/** lws_jwk_destroy() - Destroy a JSON Web key + * + * \param s: the JWK object to destroy + * + * All allocations in the lws_jwk are destroyed + */ +LWS_VISIBLE LWS_EXTERN void +lws_jwk_destroy(struct lws_jwk *s); + +/** lws_jwk_export() - Export a JSON Web key to a textual representation + * + * \param s: the JWK object to export + * \param _private: 0 = just export public parts, 1 = export everything + * \param p: the buffer to write the exported JWK to + * \param len: the length of the buffer \p p in bytes + * + * Returns length of the used part of the buffer if OK, or -1 for error. + * + * Serializes the content of the JWK into a char buffer. + */ +LWS_VISIBLE LWS_EXTERN int +lws_jwk_export(struct lws_jwk *s, int _private, char *p, size_t len); + +/** lws_jwk_load() - Import a JSON Web key from a file + * + * \param s: the JWK object to load into + * \param filename: filename to load from + * + * Returns 0 for OK or -1 for failure + */ +LWS_VISIBLE int +lws_jwk_load(struct lws_jwk *s, const char *filename); + +/** lws_jwk_save() - Export a JSON Web key to a file + * + * \param s: the JWK object to save from + * \param filename: filename to save to + * + * Returns 0 for OK or -1 for failure + */ +LWS_VISIBLE int +lws_jwk_save(struct lws_jwk *s, const char *filename); + +/** lws_jwk_rfc7638_fingerprint() - jwk to RFC7638 compliant fingerprint + * + * \param s: the JWK object to fingerprint + * \param digest32: buffer to take 32-byte digest + * + * Returns 0 for OK or -1 for failure + */ +LWS_VISIBLE int +lws_jwk_rfc7638_fingerprint(struct lws_jwk *s, char *digest32); +///@} + + +/*! \defgroup jws JSON Web Signature + * ## JSON Web Signature API + * + * Lws provides an API to check and create RFC7515 JSON Web Signatures + * + * SHA256/384/512 HMAC, and RSA 256/384/512 are supported. + * + * The API uses your TLS library crypto, but works exactly the same no matter + * what you TLS backend is. + */ +///@{ + +LWS_VISIBLE LWS_EXTERN int +lws_jws_confirm_sig(const char *in, size_t len, struct lws_jwk *jwk); + +/** + * lws_jws_sign_from_b64() - add b64 sig to b64 hdr + payload + * + * \param b64_hdr: protected header encoded in b64, may be NULL + * \param hdr_len: bytes in b64 coding of protected header + * \param b64_pay: payload encoded in b64 + * \param pay_len: bytes in b64 coding of payload + * \param b64_sig: buffer to write the b64 encoded signature into + * \param sig_len: max bytes we can write at b64_sig + * \param hash_type: one of LWS_GENHASH_TYPE_SHA[256|384|512] + * \param jwk: the struct lws_jwk containing the signing key + * + * This adds a b64-coded JWS signature of the b64-encoded protected header + * and b64-encoded payload, at \p b64_sig. The signature will be as large + * as the N element of the RSA key when the RSA key is used, eg, 512 bytes for + * a 4096-bit key, and then b64-encoding on top. + * + * In some special cases, there is only payload to sign and no header, in that + * case \p b64_hdr may be NULL, and only the payload will be hashed before + * signing. + * + * Returns the length of the encoded signature written to \p b64_sig, or -1. + */ +LWS_VISIBLE LWS_EXTERN int +lws_jws_sign_from_b64(const char *b64_hdr, size_t hdr_len, const char *b64_pay, + size_t pay_len, char *b64_sig, size_t sig_len, + enum lws_genhash_types hash_type, struct lws_jwk *jwk); + +/** + * lws_jws_create_packet() - add b64 sig to b64 hdr + payload + * + * \param jwk: the struct lws_jwk containing the signing key + * \param payload: unencoded payload JSON + * \param len: length of unencoded payload JSON + * \param nonce: Nonse string to include in protected header + * \param out: buffer to take signed packet + * \param out_len: size of \p out buffer + * + * This creates a "flattened" JWS packet from the jwk and the plaintext + * payload, and signs it. The packet is written into \p out. + * + * This does the whole packet assembly and signing, calling through to + * lws_jws_sign_from_b64() as part of the process. + * + * Returns the length written to \p out, or -1. + */ +LWS_VISIBLE LWS_EXTERN int +lws_jws_create_packet(struct lws_jwk *jwk, const char *payload, size_t len, + const char *nonce, char *out, size_t out_len); + +/** + * lws_jws_base64_enc() - encode input data into b64url data + * + * \param in: the incoming plaintext + * \param in_len: the length of the incoming plaintext in bytes + * \param out: the buffer to store the b64url encoded data to + * \param out_max: the length of \p out in bytes + * + * Returns either -1 if problems, or the number of bytes written to \p out. + */ +LWS_VISIBLE LWS_EXTERN int +lws_jws_base64_enc(const char *in, size_t in_len, char *out, size_t out_max); +///@} +#endif + /*! \defgroup extensions Extension related functions * ##Extension releated functions * @@ -1548,27 +2140,10 @@ lws_genhash_destroy(struct lws_genhash_ctx *ctx, void *result); * add it at where specified so existing users are unaffected. */ enum lws_extension_callback_reasons { - LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0, - LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1, - LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2, - LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3, LWS_EXT_CB_CONSTRUCT = 4, LWS_EXT_CB_CLIENT_CONSTRUCT = 5, - LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6, - LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7, LWS_EXT_CB_DESTROY = 8, - LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9, - LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10, - LWS_EXT_CB_PACKET_RX_PREPARSE = 11, LWS_EXT_CB_PACKET_TX_PRESEND = 12, - LWS_EXT_CB_PACKET_TX_DO_SEND = 13, - LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14, - LWS_EXT_CB_FLUSH_PENDING_TX = 15, - LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16, - LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17, - LWS_EXT_CB_1HZ = 18, - LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19, - LWS_EXT_CB_IS_WRITEABLE = 20, LWS_EXT_CB_PAYLOAD_TX = 21, LWS_EXT_CB_PAYLOAD_RX = 22, LWS_EXT_CB_OPTION_DEFAULT = 23, @@ -1646,18 +2221,6 @@ struct lws_ext_option_arg { * user data is deleted. This same callback is used whether you * are in client or server instantiation context. * - * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on - * a connection, and a packet of data arrived at the connection, - * it is passed to this callback to give the extension a chance to - * change the data, eg, decompress it. user is pointing to the - * extension's private connection context data, in is pointing - * to an lws_tokens struct, it consists of a char * pointer called - * token, and an int called token_len. At entry, these are - * set to point to the received buffer and set to the content - * length. If the extension will grow the content, it should use - * a new buffer allocated in its private user context data and - * set the pointed-to lws_tokens members to point to its buffer. - * * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the * extension a chance to change websocket data just before it will @@ -1697,16 +2260,6 @@ LWS_VISIBLE LWS_EXTERN int lws_set_extension_option(struct lws *wsi, const char *ext_name, const char *opt_name, const char *opt_val); -#ifndef LWS_NO_EXTENSIONS -/* lws_get_internal_extensions() - DEPRECATED - * - * \Deprecated There is no longer a set internal extensions table. The table is provided - * by user code along with application-specific settings. See the test - * client and server for how to do. - */ -static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension * -lws_get_internal_extensions(void) { return NULL; } - /** * lws_ext_parse_options() - deal with parsing negotiated extension options * @@ -1721,7 +2274,6 @@ LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi, void *ext_user, const struct lws_ext_options *opts, const char *o, int len); -#endif /** lws_extension_callback_pm_deflate() - extension for RFC7692 * @@ -1785,8 +2337,8 @@ struct lws_protocols { * be able to consume it all without having to return to the event * loop. That is supported in lws. * - * If .tx_packet_size is 0, this also controls how much may be sent at once - * for backwards compatibility. + * If .tx_packet_size is 0, this also controls how much may be sent at + * once for backwards compatibility. */ unsigned int id; /**< ignored by lws, but useful to contain user information bound @@ -1811,8 +2363,6 @@ struct lws_protocols { * This is part of the ABI, don't needlessly break compatibility */ }; -struct lws_vhost; - /** * lws_vhost_name_to_protocol() - get vhost's protocol object from its name * @@ -1894,6 +2444,17 @@ lws_adjust_protocol_psds(struct lws *wsi, size_t new_size); LWS_VISIBLE LWS_EXTERN int lws_finalize_startup(struct lws_context *context); +/** + * lws_pvo_search() - helper to find a named pvo in a linked-list + * + * \param pvo: the first pvo in the linked-list + * \param name: the name of the pvo to return if found + * + * Returns NULL, or a pointer to the name pvo in the linked-list + */ +LWS_VISIBLE LWS_EXTERN const struct lws_protocol_vhost_options * +lws_pvo_search(const struct lws_protocol_vhost_options *pvo, const char *name); + LWS_VISIBLE LWS_EXTERN int lws_protocol_init(struct lws_context *context); @@ -2088,6 +2649,17 @@ enum lws_context_options { * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS callback, which * provides the vhost SSL_CTX * in the user parameter. */ + LWS_SERVER_OPTION_SKIP_PROTOCOL_INIT = (1 << 25), + /**< (VH) You probably don't want this. It forces this vhost to not + * call LWS_CALLBACK_PROTOCOL_INIT on its protocols. It's used in the + * special case of a temporary vhost bound to a single protocol. + */ + LWS_SERVER_OPTION_IGNORE_MISSING_CERT = (1 << 26), + /**< (VH) Don't fail if the vhost TLS cert or key are missing, just + * continue. The vhost won't be able to serve anything, but if for + * example the ACME plugin was configured to fetch a cert, this lets + * you bootstrap your vhost from having no cert to start with. + */ /****** add new things just above ---^ ******/ }; @@ -2110,7 +2682,11 @@ struct lws_context_creation_info { /**< VHOST: Port to listen on. Use CONTEXT_PORT_NO_LISTEN to suppress * listening for a client. Use CONTEXT_PORT_NO_LISTEN_SERVER if you are * writing a server but you are using \ref sock-adopt instead of the - * built-in listener */ + * built-in listener. + * + * You can also set port to 0, in which case the kernel will pick + * a random port that is not already in use. You can find out what + * port the vhost is listening on using lws_get_vhost_listen_port() */ const char *iface; /**< VHOST: NULL to bind the listen socket to all interfaces, or the * interface name, eg, "eth2" @@ -2191,12 +2767,12 @@ struct lws_context_creation_info { int ka_interval; /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes * attempt */ -#ifdef LWS_OPENSSL_SUPPORT +#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS) SSL_CTX *provided_client_ssl_ctx; /**< CONTEXT: If non-null, swap out libwebsockets ssl - * implementation for the one provided by provided_ssl_ctx. - * Libwebsockets no longer is responsible for freeing the context - * if this option is selected. */ + * implementation for the one provided by provided_ssl_ctx. + * Libwebsockets no longer is responsible for freeing the context + * if this option is selected. */ #else /* maintain structure layout either way */ void *provided_client_ssl_ctx; /**< dummy if ssl disabled */ #endif @@ -2207,9 +2783,10 @@ struct lws_context_creation_info { short max_http_header_pool; /**< CONTEXT: The max number of connections with http headers that * can be processed simultaneously (the corresponding memory is - * allocated for the lifetime of the context). If the pool is - * busy new incoming connections must wait for accept until one - * becomes free. */ + * allocated and deallocated dynamically as needed). If the pool is + * fully busy new incoming connections must wait for accept until one + * becomes free. 0 = allow as many ah as number of availble fds for + * the process */ unsigned int count_threads; /**< CONTEXT: how many contexts to create in an array, 0 = 1 */ @@ -2372,13 +2949,42 @@ struct lws_context_creation_info { * given here. */ uint32_t http2_settings[7]; - /**< CONTEXT: after context creation http2_settings[1] thru [6] have - * been set to the lws platform default values. - * VHOST: if http2_settings[0] is nonzero, the values given in + /**< VHOST: if http2_settings[0] is nonzero, the values given in * http2_settings[1]..[6] are used instead of the lws * platform default values. * Just leave all at 0 if you don't care. */ + const char *error_document_404; + /**< VHOST: If non-NULL, when asked to serve a non-existent file, + * lws attempts to server this url path instead. Eg, + * "/404.html" */ + const char *alpn; + /**< CONTEXT: If non-NULL, default list of advertised alpn, comma- + * separated + * + * VHOST: If non-NULL, per-vhost list of advertised alpn, comma- + * separated + */ + void **foreign_loops; + /**< CONTEXT: This is ignored if the context is not being started with + * an event loop, ie, .options has a flag like + * LWS_SERVER_OPTION_LIBUV. + * + * NULL indicates lws should start its own even loop for + * each service thread, and deal with closing the loops + * when the context is destroyed. + * + * Non-NULL means it points to an array of external + * ("foreign") event loops that are to be used in turn for + * each service thread. In the default case of 1 service + * thread, it can just point to one foreign event loop. + */ + void (*signal_cb)(void *event_lib_handle, int signum); + /**< CONTEXT: NULL: default signal handling. Otherwise this receives + * the signal handler callback. event_lib_handle is the + * native event library signal handle, eg uv_signal_t * + * for libuv. + */ /* Add new things just above here ---^ * This is part of the ABI, don't needlessly break compatibility @@ -2387,8 +2993,14 @@ struct lws_context_creation_info { * members added above will see 0 (default) even if the app * was not built against the newer headers. */ + struct lws_context **pcontext; + /**< CONTEXT: if non-NULL, at the end of context destroy processing, + * the pointer pointed to by pcontext is written with NULL. You can + * use this to let foreign event loops know that lws context destruction + * is fully completed. + */ - void *_unused[8]; /**< dummy */ + void *_unused[4]; /**< dummy */ }; /** @@ -2426,7 +3038,8 @@ struct lws_context_creation_info { * one place; they're all handled in the user callback. */ LWS_VISIBLE LWS_EXTERN struct lws_context * -lws_create_context(struct lws_context_creation_info *info); +lws_create_context(const struct lws_context_creation_info *info); + /** * lws_context_destroy() - Destroy the websocket context @@ -2439,9 +3052,6 @@ lws_create_context(struct lws_context_creation_info *info); LWS_VISIBLE LWS_EXTERN void lws_context_destroy(struct lws_context *context); -LWS_VISIBLE LWS_EXTERN void -lws_context_destroy2(struct lws_context *context); - typedef int (*lws_reload_func)(void); /** @@ -2529,7 +3139,7 @@ struct lws_vhost; */ LWS_VISIBLE LWS_EXTERN struct lws_vhost * lws_create_vhost(struct lws_context *context, - struct lws_context_creation_info *info); + const struct lws_context_creation_info *info); /** * lws_vhost_destroy() - Destroy a vhost (virtual server context) @@ -2598,6 +3208,38 @@ LWS_VISIBLE LWS_EXTERN struct lws_vhost * lws_get_vhost(struct lws *wsi); /** + * lws_get_vhost_name() - returns the name of a vhost + * + * \param vhost: which vhost + */ +LWS_VISIBLE LWS_EXTERN const char * +lws_get_vhost_name(struct lws_vhost *vhost); + +/** + * lws_get_vhost_port() - returns the port a vhost listens on, or -1 + * + * \param vhost: which vhost + */ +LWS_VISIBLE LWS_EXTERN int +lws_get_vhost_port(struct lws_vhost *vhost); + +/** + * lws_get_vhost_user() - returns the user pointer for the vhost + * + * \param vhost: which vhost + */ +LWS_VISIBLE LWS_EXTERN void * +lws_get_vhost_user(struct lws_vhost *vhost); + +/** + * lws_get_vhost_iface() - returns the binding for the vhost listen socket + * + * \param vhost: which vhost + */ +LWS_VISIBLE LWS_EXTERN const char * +lws_get_vhost_iface(struct lws_vhost *vhost); + +/** * lws_json_dump_vhost() - describe vhost state and stats in JSON * * \param vh: the vhost @@ -2748,7 +3390,16 @@ enum lws_client_connect_ssl_connection_flags { LCCSCF_USE_SSL = (1 << 0), LCCSCF_ALLOW_SELFSIGNED = (1 << 1), LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2), - LCCSCF_ALLOW_EXPIRED = (1 << 3) + LCCSCF_ALLOW_EXPIRED = (1 << 3), + + LCCSCF_PIPELINE = (1 << 16), + /**< Serialize / pipeline multiple client connections + * on a single connection where possible. + * + * HTTP/1.0: possible if Keep-Alive: yes sent by server + * HTTP/1.1: always possible... uses pipelining + * HTTP/2: always possible... uses parallel streams + * */ }; /** struct lws_client_connect_info - parameters to connect with when using @@ -2762,7 +3413,7 @@ struct lws_client_connect_info { int port; /**< remote port to connect to */ int ssl_connection; - /**< nonzero for ssl */ + /**< 0, or a combination of LCCSCF_ flags */ const char *path; /**< uri path */ const char *host; @@ -2779,7 +3430,9 @@ struct lws_client_connect_info { /**< UNUSED... provide in info.extensions at context creation time */ const char *method; /**< if non-NULL, do this http method instead of ws[s] upgrade. - * use "GET" to be a simple http client connection */ + * use "GET" to be a simple http client connection. "RAW" gets + * you a connected socket that lws itself will leave alone once + * connected. */ struct lws *parent_wsi; /**< if another wsi is responsible for this connection, give it here. * this is used to make sure if the parent closes so do any @@ -2805,6 +3458,13 @@ struct lws_client_connect_info { const char *iface; /**< NULL to allow routing on any interface, or interface name or IP * to bind the socket to */ + const char *local_protocol_name; + /**< NULL: .protocol is used both to select the local protocol handler + * to bind to and as the list of remote ws protocols we could + * accept. + * non-NULL: this protocol name is used to bind the connection to + * the local protocol handler. .protocol is used for the + * list of remote ws protocols we could accept */ /* Add new things just above here ---^ * This is part of the ABI, don't needlessly break compatibility @@ -2813,6 +3473,12 @@ struct lws_client_connect_info { * members added above will see 0 (default) even if the app * was not built against the newer headers. */ + const char *alpn; + /* NULL: allow lws default ALPN list, from vhost if present or from + * list of roles built into lws + * non-NULL: require one from provided comma-separated list of alpn + * tokens + */ void *_unused[4]; /**< dummy */ }; @@ -2938,6 +3604,10 @@ lws_http_client_read(struct lws *wsi, char **buf, int *len); * \param wsi: client connection * * Returns the last server response code, eg, 200 for client http connections. + * + * You should capture this during the LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP + * callback, because after that the memory reserved for storing the related + * headers is freed and this value is lost. */ LWS_VISIBLE LWS_EXTERN unsigned int lws_http_client_http_response(struct lws *wsi); @@ -3030,15 +3700,8 @@ lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi); * on one thread * \param wsi: Cancel service on the thread this wsi is serviced by * - * This function lets a call to lws_service() waiting for a timeout - * immediately return. - * - * It works by creating a phony event and then swallowing it silently. - * - * The reason it may be needed is when waiting in poll(), changes to - * the event masks are ignored by the OS until poll() is reentered. This - * lets you halt the poll() wait and make the reentry happen immediately - * instead of having the wait out the rest of the poll timeout. + * Same as lws_cancel_service(), but targets a single service thread, the one + * the wsi belongs to. You probably want to use lws_cancel_service() instead. */ LWS_VISIBLE LWS_EXTERN void lws_cancel_service_pt(struct lws *wsi); @@ -3047,12 +3710,13 @@ lws_cancel_service_pt(struct lws *wsi); * lws_cancel_service() - Cancel wait for new pending socket activity * \param context: Websocket context * - * This function let a call to lws_service() waiting for a timeout - * immediately return. + * This function creates an immediate "synchronous interrupt" to the lws poll() + * wait or event loop. As soon as possible in the serialzed service sequencing, + * a LWS_CALLBACK_EVENT_WAIT_CANCELLED callback is sent to every protocol on + * every vhost. * - * What it basically does is provide a fake event that will be swallowed, - * so the wait in poll() is ended. That's useful because poll() doesn't - * attend to changes in POLLIN/OUT/ERR until it re-enters the wait. + * lws_cancel_service() may be called from another thread while the context + * exists, and its effect will be immediately serialized. */ LWS_VISIBLE LWS_EXTERN void lws_cancel_service(struct lws_context *context); @@ -3235,6 +3899,7 @@ struct lws_process_html_args { int len; /**< length of the original data at p */ int max_len; /**< maximum length we can grow the data to */ int final; /**< set if this is the last chunk of the file */ + int chunked; /**< 0 == unchunked, 1 == produce chunk headers (incompatible with HTTP/2) */ }; typedef const char *(*lws_process_html_state_cb)(void *data, int index); @@ -3296,12 +3961,12 @@ lws_chunked_html_process(struct lws_process_html_args *args, /** struct lws_tokens * you need these to look at headers that have been parsed if using the * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum - * list below is absent, .token = NULL and token_len = 0. Otherwise .token - * points to .token_len chars containing that header content. + * list below is absent, .token = NULL and len = 0. Otherwise .token + * points to .len chars containing that header content. */ struct lws_tokens { char *token; /**< pointer to start of the token */ - int token_len; /**< length of the token's value */ + int len; /**< length of the token's value */ }; /* enum lws_token_indexes @@ -3399,6 +4064,10 @@ enum lws_token_indexes { WSI_TOKEN_CONNECT = 81, WSI_TOKEN_HEAD_URI = 82, WSI_TOKEN_TE = 83, + WSI_TOKEN_REPLAY_NONCE = 84, + WSI_TOKEN_COLON_PROTOCOL = 85, + WSI_TOKEN_X_AUTH_TOKEN = 86, + /****** add new things just above ---^ ******/ /* use token storage to stash these internally, not for @@ -3411,6 +4080,7 @@ enum lws_token_indexes { _WSI_TOKEN_CLIENT_ORIGIN, _WSI_TOKEN_CLIENT_METHOD, _WSI_TOKEN_CLIENT_IFACE, + _WSI_TOKEN_CLIENT_ALPN, /* always last real token index*/ WSI_TOKEN_COUNT, @@ -3605,6 +4275,54 @@ lws_add_http_header_content_length(struct lws *wsi, LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT lws_finalize_http_header(struct lws *wsi, unsigned char **p, unsigned char *end); + +/** + * lws_finalize_write_http_header() - Helper finializing and writing http headers + * + * \param wsi: the connection to check + * \param start: pointer to the start of headers in the buffer, eg &buf[LWS_PRE] + * \param p: pointer to current position in buffer pointer + * \param end: pointer to end of buffer + * + * Terminates the headers correctly accoring to the protocol in use (h1 / h2) + * and writes the headers. Returns nonzero for error. + */ +LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_finalize_write_http_header(struct lws *wsi, unsigned char *start, + unsigned char **p, unsigned char *end); + +#define LWS_ILLEGAL_HTTP_CONTENT_LEN ((lws_filepos_t)-1ll) + +/** + * lws_add_http_common_headers() - Helper preparing common http headers + * + * \param wsi: the connection to check + * \param code: an HTTP code like 200, 404 etc (see enum http_status) + * \param content_type: the content type, like "text/html" + * \param content_len: the content length, in bytes + * \param p: pointer to current position in buffer pointer + * \param end: pointer to end of buffer + * + * Adds the initial response code, so should be called first. + * + * Code may additionally take OR'd flags: + * + * LWSAHH_FLAG_NO_SERVER_NAME: don't apply server name header this time + * + * This helper just calls public apis to simplify adding headers that are + * commonly needed. If it doesn't fit your case, or you want to add additional + * headers just call the public apis directly yourself for what you want. + * + * You can miss out the content length header by providing the constant + * LWS_ILLEGAL_HTTP_CONTENT_LEN for the content_len. + * + * It does not call lws_finalize_http_header(), to allow you to add further + * headers after calling this. You will need to call that yourself at the end. + */ +LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_add_http_common_headers(struct lws *wsi, unsigned int code, + const char *content_type, lws_filepos_t content_len, + unsigned char **p, unsigned char *end); ///@} /** \defgroup form-parsing Form Parsing @@ -3787,7 +4505,7 @@ lws_return_http_status(struct lws *wsi, unsigned int code, const char *html_body); /** - * lws_http_redirect() - write http redirect into buffer + * lws_http_redirect() - write http redirect out on wsi * * \param wsi: websocket connection * \param code: HTTP response code (eg, 301) @@ -3795,6 +4513,8 @@ lws_return_http_status(struct lws *wsi, unsigned int code, * \param len: length of loc * \param p: pointer current position in buffer (updated as we write) * \param end: pointer to end of buffer + * + * Returns amount written, or < 0 indicating fatal write failure. */ LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len, @@ -3845,30 +4565,29 @@ lws_sql_purify(char *escaped, const char *string, int len); */ LWS_VISIBLE LWS_EXTERN const char * lws_json_purify(char *escaped, const char *string, int len); -///@} -/*! \defgroup ev libev helpers +/** + * lws_filename_purify_inplace() - replace scary filename chars with underscore * - * ##libev helpers + * \param filename: filename to be purified * - * APIs specific to libev event loop itegration + * Replace scary characters in the filename (it should not be a path) + * with underscore, so it's safe to use. */ -///@{ - -#ifdef LWS_WITH_LIBEV -typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents); +LWS_VISIBLE LWS_EXTERN void +lws_filename_purify_inplace(char *filename); LWS_VISIBLE LWS_EXTERN int -lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint, - lws_ev_signal_cb_t *cb); - +lws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf, + int len); LWS_VISIBLE LWS_EXTERN int -lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi); +lws_plat_write_file(const char *filename, void *buf, int len); -LWS_VISIBLE LWS_EXTERN void -lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents); -#endif /* LWS_WITH_LIBEV */ +LWS_VISIBLE LWS_EXTERN int +lws_plat_read_file(const char *filename, void *buf, int len); +LWS_VISIBLE LWS_EXTERN int +lws_plat_recommended_rsa_bits(void); ///@} /*! \defgroup uv libuv helpers @@ -3879,60 +4598,38 @@ lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents); */ ///@{ #ifdef LWS_WITH_LIBUV -LWS_VISIBLE LWS_EXTERN int -lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint, - uv_signal_cb cb); - -LWS_VISIBLE LWS_EXTERN void -lws_libuv_run(const struct lws_context *context, int tsi); - -LWS_VISIBLE LWS_EXTERN void -lws_libuv_stop(struct lws_context *context); - -LWS_VISIBLE LWS_EXTERN void -lws_libuv_stop_without_kill(const struct lws_context *context, int tsi); - -LWS_VISIBLE LWS_EXTERN int -lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi); +/* + * Any direct libuv allocations in lws protocol handlers must participate in the + * lws reference counting scheme. Two apis are provided: + * + * - lws_libuv_static_refcount_add(handle, context) to mark the handle with + * a pointer to the context and increment the global uv object counter + * + * - lws_libuv_static_refcount_del() which should be used as the close callback + * for your own libuv objects declared in the protocol scope. + * + * Using the apis allows lws to detach itself from a libuv loop completely + * cleanly and at the moment all of its libuv objects have completed close. + */ LWS_VISIBLE LWS_EXTERN uv_loop_t * lws_uv_getloop(struct lws_context *context, int tsi); LWS_VISIBLE LWS_EXTERN void -lws_uv_sigint_cb(uv_signal_t *watcher, int signum); +lws_libuv_static_refcount_add(uv_handle_t *, struct lws_context *context); LWS_VISIBLE LWS_EXTERN void -lws_close_all_handles_in_loop(uv_loop_t *loop); -#endif /* LWS_WITH_LIBUV */ -///@} - -/*! \defgroup event libevent helpers - * - * ##libevent helpers - * - * APIs specific to libevent event loop itegration - */ -///@{ - -#ifdef LWS_WITH_LIBEVENT -typedef void (lws_event_signal_cb_t) (evutil_socket_t sock_fd, short revents, - void *ctx); - -LWS_VISIBLE LWS_EXTERN int -lws_event_sigint_cfg(struct lws_context *context, int use_event_sigint, - lws_event_signal_cb_t cb); - -LWS_VISIBLE LWS_EXTERN int -lws_event_initloop(struct lws_context *context, struct event_base *loop, - int tsi); +lws_libuv_static_refcount_del(uv_handle_t *); -LWS_VISIBLE LWS_EXTERN void -lws_event_sigint_cb(evutil_socket_t sock_fd, short revents, - void *ctx); -#endif /* LWS_WITH_LIBEVENT */ +#endif /* LWS_WITH_LIBUV */ +#if defined(LWS_WITH_ESP32) +#define lws_libuv_static_refcount_add(_a, _b) +#define lws_libuv_static_refcount_del NULL +#endif ///@} + /*! \defgroup timeout Connection timeouts APIs related to setting connection timeouts @@ -3951,7 +4648,7 @@ enum pending_timeout { PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4, PENDING_TIMEOUT_AWAITING_PING = 5, PENDING_TIMEOUT_CLOSE_ACK = 6, - PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7, + PENDING_TIMEOUT_UNUSED1 = 7, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8, PENDING_TIMEOUT_SSL_ACCEPT = 9, PENDING_TIMEOUT_HTTP_CONTENT = 10, @@ -3970,6 +4667,9 @@ enum pending_timeout { PENDING_TIMEOUT_KILLED_BY_PARENT = 23, PENDING_TIMEOUT_CLOSE_SEND = 24, PENDING_TIMEOUT_HOLDING_AH = 25, + PENDING_TIMEOUT_UDP_IDLE = 26, + PENDING_TIMEOUT_CLIENT_CONN_IDLE = 27, + PENDING_TIMEOUT_LAGGING = 28, /****** add new things just above ---^ ******/ @@ -4003,6 +4703,60 @@ enum pending_timeout { */ LWS_VISIBLE LWS_EXTERN void lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs); + +#define LWS_SET_TIMER_USEC_CANCEL ((lws_usec_t)-1ll) +#define LWS_USEC_PER_SEC (1000000ll) + +/** + * lws_set_timer_usecs() - schedules a callback on the wsi in the future + * + * \param wsi: Websocket connection instance + * \param usecs: LWS_SET_TIMER_USEC_CANCEL removes any existing scheduled + * callback, otherwise number of microseconds in the future + * the callback will occur at. + * + * NOTE: event loop support for this: + * + * default poll() loop: yes + * libuv event loop: yes + * libev: not implemented (patch welcome) + * libevent: not implemented (patch welcome) + * + * After the deadline expires, the wsi will get a callback of type + * LWS_CALLBACK_TIMER and the timer is exhausted. The deadline may be + * continuously deferred by further calls to lws_set_timer_usecs() with a later + * deadline, or cancelled by lws_set_timer_usecs(wsi, -1). + * + * If the timer should repeat, lws_set_timer_usecs() must be called again from + * LWS_CALLBACK_TIMER. + * + * Accuracy depends on the platform and the load on the event loop or system... + * all that's guaranteed is the callback will come after the requested wait + * period. + */ +LWS_VISIBLE LWS_EXTERN void +lws_set_timer_usecs(struct lws *wsi, lws_usec_t usecs); + +/* + * lws_timed_callback_vh_protocol() - calls back a protocol on a vhost after + * the specified delay + * + * \param vh: the vhost to call back + * \param protocol: the protocol to call back + * \param reason: callback reason + * \param secs: how many seconds in the future to do the callback. Set to + * -1 to cancel the timer callback. + * + * Callback the specified protocol with a fake wsi pointing to the specified + * vhost and protocol, with the specified reason, at the specified time in the + * future. + * + * Returns 0 if OK. + */ +LWS_VISIBLE LWS_EXTERN int +lws_timed_callback_vh_protocol(struct lws_vhost *vh, + const struct lws_protocols *prot, + int reason, int secs); ///@} /*! \defgroup sending-data Sending data @@ -4011,7 +4765,7 @@ lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs); */ //@{ #if !defined(LWS_SIZEOFPTR) -#define LWS_SIZEOFPTR (sizeof (void *)) +#define LWS_SIZEOFPTR ((int)sizeof (void *)) #endif #if defined(__x86_64__) @@ -4027,6 +4781,8 @@ lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs); #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE #define LWS_SEND_BUFFER_POST_PADDING 0 +#define LWS_WRITE_RAW LWS_WRITE_HTTP + /* * NOTE: These public enums are part of the abi. If you want to add one, * add it at where specified so existing users are unaffected. @@ -4185,6 +4941,23 @@ lws_write(struct lws *wsi, unsigned char *buf, size_t len, /* helper for case where buffer may be const */ #define lws_write_http(wsi, buf, len) \ lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP) + +/* helper for multi-frame ws message flags */ +static inline int +lws_write_ws_flags(int initial, int is_start, int is_end) +{ + int r; + + if (is_start) + r = initial; + else + r = LWS_WRITE_CONTINUATION; + + if (!is_end) + r |= LWS_WRITE_NO_FIN; + + return r; +} ///@} /** \defgroup callback-when-writeable Callback when writeable @@ -4324,9 +5097,31 @@ lws_callback_all_protocol_vhost_args(struct lws_vhost *vh, * - Which: connections using this protocol on same VHOST as wsi ONLY * - When: now * - What: reason + * + * This is deprecated since v2.5, use lws_callback_vhost_protocols_vhost() + * which takes the pointer to the vhost directly without using or needing the + * wsi. */ LWS_VISIBLE LWS_EXTERN int -lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len); +lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len) +LWS_WARN_DEPRECATED; + +/** + * lws_callback_vhost_protocols_vhost() - Callback all protocols enabled on a vhost + * with the given reason + * + * \param vh: vhost that will get callbacks + * \param reason: Callback reason index + * \param in: in argument to callback + * \param len: len argument to callback + * + * - Which: connections using this protocol on same VHOST as wsi ONLY + * - When: now + * - What: reason + */ +LWS_VISIBLE LWS_EXTERN int +lws_callback_vhost_protocols_vhost(struct lws_vhost *vh, int reason, void *in, + size_t len); LWS_VISIBLE LWS_EXTERN int lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, @@ -4335,11 +5130,11 @@ lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason, /** * lws_get_socket_fd() - returns the socket file descriptor * - * You will not need this unless you are doing something special + * This is needed to use sendto() on UDP raw sockets * * \param wsi: Websocket connection instance */ -LWS_VISIBLE LWS_EXTERN int +LWS_VISIBLE LWS_EXTERN lws_sockfd_type lws_get_socket_fd(struct lws *wsi); /** @@ -4363,7 +5158,7 @@ lws_get_socket_fd(struct lws *wsi); * automatically, so this number reflects the situation at the peer or * intermediary dynamically. */ -LWS_VISIBLE LWS_EXTERN size_t +LWS_VISIBLE LWS_EXTERN lws_fileofs_t lws_get_peer_write_allowance(struct lws *wsi); ///@} @@ -4422,19 +5217,22 @@ lws_rx_flow_allow_all_protocol(const struct lws_context *context, /** * lws_remaining_packet_payload() - Bytes to come before "overall" - * rx packet is complete + * rx fragment is complete * \param wsi: Websocket instance (available from user callback) * - * This function is intended to be called from the callback if the - * user code is interested in "complete packets" from the client. - * libwebsockets just passes through payload as it comes and issues a buffer - * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE - * callback handler can use this API to find out if the buffer it has just - * been given is the last piece of a "complete packet" from the client -- - * when that is the case lws_remaining_packet_payload() will return - * 0. + * This tracks how many bytes are left in the current ws fragment, according + * to the ws length given in the fragment header. + * + * If the message was in a single fragment, and there is no compression, this + * is the same as "how much data is left to read for this message". * - * Many protocols won't care becuse their packets are always small. + * However, if the message is being sent in multiple fragments, this will + * reflect the unread amount of the current **fragment**, not the message. With + * ws, it is legal to not know the length of the message before it completes. + * + * Additionally if the message is sent via the negotiated permessage-deflate + * extension, this number only tells the amount of **compressed** data left to + * be read, since that is the only information available at the ws layer. */ LWS_VISIBLE LWS_EXTERN size_t lws_remaining_packet_payload(struct lws *wsi); @@ -4488,8 +5286,10 @@ typedef enum { LWS_ADOPT_ALLOW_SSL = 4, /* flag: if set requires LWS_ADOPT_SOCKET */ LWS_ADOPT_WS_PARENTIO = 8, /* flag: ws mode parent handles IO * if given must be only flag - * wsi put directly into ws mode - */ + * wsi put directly into ws mode */ + LWS_ADOPT_FLAG_UDP = 16, /* flag: socket is UDP */ + + LWS_ADOPT_RAW_SOCKET_UDP = LWS_ADOPT_SOCKET | LWS_ADOPT_FLAG_UDP, } lws_adoption_type; typedef union { @@ -4497,6 +5297,16 @@ typedef union { lws_filefd_type filefd; } lws_sock_file_fd_type; +#if !defined(LWS_WITH_ESP32) +struct lws_udp { + struct sockaddr sa; + socklen_t salen; + + struct sockaddr sa_pending; + socklen_t salen_pending; +}; +#endif + /* * lws_adopt_descriptor_vhost() - adopt foreign socket or file descriptor * if socket descriptor, should already have been accepted from listen socket @@ -4573,6 +5383,24 @@ lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd, LWS_VISIBLE LWS_EXTERN struct lws * lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd, const char *readbuf, size_t len); + +#define LWS_CAUDP_BIND 1 + +/** + * lws_create_adopt_udp() - create, bind and adopt a UDP socket + * + * \param vhost: lws vhost + * \param port: UDP port to bind to, -1 means unbound + * \param flags: 0 or LWS_CAUDP_NO_BIND + * \param protocol_name: Name of protocol on vhost to bind wsi to + * \param parent_wsi: NULL or parent wsi new wsi will be a child of + * + * Either returns new wsi bound to accept_fd, or closes accept_fd and + * returns NULL, having cleaned up any new wsi pieces. + * */ +LWS_VISIBLE LWS_EXTERN struct lws * +lws_create_adopt_udp(struct lws_vhost *vhost, int port, int flags, + const char *protocol_name, struct lws *parent_wsi); ///@} /** \defgroup net Network related helper APIs @@ -4624,17 +5452,31 @@ lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name, */ LWS_VISIBLE LWS_EXTERN const char * lws_get_peer_simple(struct lws *wsi, char *name, int namelen); -#if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) + + +#define LWS_ITOSA_NOT_EXIST -1 +#define LWS_ITOSA_NOT_USABLE -2 +#define LWS_ITOSA_USABLE 0 +#if !defined(LWS_WITH_ESP32) /** * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct * - * \param ipv6: Allow IPV6 addresses + * \param ipv6: Allow IPV6 addresses * \param ifname: Interface name or IP - * \param addr: struct sockaddr_in * to be written + * \param addr: struct sockaddr_in * to be written * \param addrlen: Length of addr * * This converts a textual network interface name to a sockaddr usable by - * other network functions + * other network functions. + * + * If the network interface doesn't exist, it will return LWS_ITOSA_NOT_EXIST. + * + * If the network interface is not usable, eg ethernet cable is removed, it + * may logically exist but not have any IP address. As such it will return + * LWS_ITOSA_NOT_USABLE. + * + * If the network interface exists and is usable, it will return + * LWS_ITOSA_USABLE. */ LWS_VISIBLE LWS_EXTERN int lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, @@ -4702,6 +5544,13 @@ lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, type it = &(start); \ while (*(it)) { +#define lws_start_foreach_llp_safe(type, it, start, nxt)\ +{ \ + type it = &(start); \ + type next; \ + while (*(it)) { \ + next = &((*(it))->nxt); \ + /** * lws_end_foreach_llp(): linkedlist pointer iterator helper end * @@ -4717,6 +5566,170 @@ lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, } \ } +#define lws_end_foreach_llp_safe(it) \ + it = next; \ + } \ +} + +#define lws_ll_fwd_insert(\ + ___new_object, /* pointer to new object */ \ + ___m_list, /* member for next list object ptr */ \ + ___list_head /* list head */ \ + ) {\ + ___new_object->___m_list = ___list_head; \ + ___list_head = ___new_object; \ + } + +#define lws_ll_fwd_remove(\ + ___type, /* type of listed object */ \ + ___m_list, /* member for next list object ptr */ \ + ___target, /* object to remove from list */ \ + ___list_head /* list head */ \ + ) { \ + lws_start_foreach_llp(___type **, ___ppss, ___list_head) { \ + if (*___ppss == ___target) { \ + *___ppss = ___target->___m_list; \ + break; \ + } \ + } lws_end_foreach_llp(___ppss, ___m_list); \ + } + +/* + * doubly linked-list + */ + +struct lws_dll { /* abstract */ + struct lws_dll *prev; + struct lws_dll *next; +}; + +/* + * these all point to the composed list objects... you have to use the + * lws_container_of() helper to recover the start of the containing struct + */ + +LWS_VISIBLE LWS_EXTERN void +lws_dll_add_front(struct lws_dll *d, struct lws_dll *phead); + +LWS_VISIBLE LWS_EXTERN void +lws_dll_remove(struct lws_dll *d); + +struct lws_dll_lws { /* typed as struct lws * */ + struct lws_dll_lws *prev; + struct lws_dll_lws *next; +}; + +#define lws_dll_is_null(___dll) (!(___dll)->prev && !(___dll)->next) + +static inline void +lws_dll_lws_add_front(struct lws_dll_lws *_a, struct lws_dll_lws *_head) +{ + lws_dll_add_front((struct lws_dll *)_a, (struct lws_dll *)_head); +} + +static inline void +lws_dll_lws_remove(struct lws_dll_lws *_a) +{ + lws_dll_remove((struct lws_dll *)_a); +} + +/* + * these are safe against the current container object getting deleted, + * since the hold his next in a temp and go to that next. ___tmp is + * the temp. + */ + +#define lws_start_foreach_dll_safe(___type, ___it, ___tmp, ___start) \ +{ \ + ___type ___it = ___start; \ + while (___it) { \ + ___type ___tmp = (___it)->next; + +#define lws_end_foreach_dll_safe(___it, ___tmp) \ + ___it = ___tmp; \ + } \ +} + +#define lws_start_foreach_dll(___type, ___it, ___start) \ +{ \ + ___type ___it = ___start; \ + while (___it) { + +#define lws_end_foreach_dll(___it) \ + ___it = (___it)->next; \ + } \ +} + +struct lws_buflist; + +/** + * lws_buflist_append_segment(): add buffer to buflist at head + * + * \param head: list head + * \param buf: buffer to stash + * \param len: length of buffer to stash + * + * Returns -1 on OOM, 1 if this was the first segment on the list, and 0 if + * it was a subsequent segment. + */ +LWS_VISIBLE LWS_EXTERN int +lws_buflist_append_segment(struct lws_buflist **head, const uint8_t *buf, + size_t len); +/** + * lws_buflist_next_segment_len(): number of bytes left in current segment + * + * \param head: list head + * \param buf: if non-NULL, *buf is written with the address of the start of + * the remaining data in the segment + * + * Returns the number of bytes left in the current segment. 0 indicates + * that the buflist is empty (there are no segments on the buflist). + */ +LWS_VISIBLE LWS_EXTERN size_t +lws_buflist_next_segment_len(struct lws_buflist **head, uint8_t **buf); +/** + * lws_buflist_use_segment(): remove len bytes from the current segment + * + * \param head: list head + * \param len: number of bytes to mark as used + * + * If len is less than the remaining length of the current segment, the position + * in the current segment is simply advanced and it returns. + * + * If len uses up the remaining length of the current segment, then the segment + * is deleted and the list head moves to the next segment if any. + * + * Returns the number of bytes left in the current segment. 0 indicates + * that the buflist is empty (there are no segments on the buflist). + */ +LWS_VISIBLE LWS_EXTERN int +lws_buflist_use_segment(struct lws_buflist **head, size_t len); +/** + * lws_buflist_destroy_all_segments(): free all segments on the list + * + * \param head: list head + * + * This frees everything on the list unconditionally. *head is always + * NULL after this. + */ +LWS_VISIBLE LWS_EXTERN void +lws_buflist_destroy_all_segments(struct lws_buflist **head); + +void +lws_buflist_describe(struct lws_buflist **head, void *id); + +/** + * lws_ptr_diff(): helper to report distance between pointers as an int + * + * \param head: the pointer with the larger address + * \param tail: the pointer with the smaller address + * + * This helper gives you an int representing the number of bytes further + * forward the first pointer is compared to the second pointer. + */ +#define lws_ptr_diff(head, tail) \ + ((int)((char *)(head) - (char *)(tail))) + /** * lws_snprintf(): snprintf that truncates the returned length too * @@ -4732,6 +5745,19 @@ LWS_VISIBLE LWS_EXTERN int lws_snprintf(char *str, size_t size, const char *format, ...) LWS_FORMAT(3); /** + * lws_strncpy(): strncpy that guarantees NUL on truncated copy + * + * \param dest: destination buffer + * \param src: source buffer + * \param size: bytes left in destination buffer + * + * This lets you correctly truncate buffers by concatenating lengths, if you + * reach the limit the reported length doesn't exceed the limit. + */ +LWS_VISIBLE LWS_EXTERN char * +lws_strncpy(char *dest, const char *src, size_t size); + +/** * lws_get_random(): fill a buffer with platform random data * * \param context: the lws context @@ -4797,6 +5823,25 @@ lws_set_wsi_user(struct lws *wsi, void *user); LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT lws_parse_uri(char *p, const char **prot, const char **ads, int *port, const char **path); +/** + * lws_cmdline_option(): simple commandline parser + * + * \param argc: count of argument strings + * \param argv: argument strings + * \param val: string to find + * + * Returns NULL if the string \p val is not found in the arguments. + * + * If it is found, then it returns a pointer to the next character after \p val. + * So if \p val is "-d", then for the commandlines "myapp -d15" and + * "myapp -d 15", in both cases the return will point to the "15". + * + * In the case there is no argument, like "myapp -d", the return will + * either point to the '\\0' at the end of -d, or to the start of the + * next argument, ie, will be non-NULL. + */ +LWS_VISIBLE LWS_EXTERN const char * +lws_cmdline_option(int argc, const char **argv, const char *val); /** * lws_now_secs(): return seconds since 1970-1-1 @@ -4805,6 +5850,26 @@ LWS_VISIBLE LWS_EXTERN unsigned long lws_now_secs(void); /** + * lws_compare_time_t(): return relationship between two time_t + * + * \param context: struct lws_context + * \param t1: time_t 1 + * \param t2: time_t 2 + * + * returns <0 if t2 > t1; >0 if t1 > t2; or == 0 if t1 == t2. + * + * This is aware of clock discontiguities that may have affected either t1 or + * t2 and adapts the comparison for them. + * + * For the discontiguity detection to work, you must avoid any arithmetic on + * the times being compared. For example to have a timeout that triggers + * 15s from when it was set, store the time it was set and compare like + * `if (lws_compare_time_t(context, now, set_time) > 15)` + */ +LWS_VISIBLE LWS_EXTERN int +lws_compare_time_t(struct lws_context *context, time_t t1, time_t t2); + +/** * lws_get_context - Allow getting lws_context from a Websocket connection * instance * @@ -4817,6 +5882,18 @@ LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT lws_get_context(const struct lws *wsi); /** + * lws_get_vhost_listen_port - Find out the port number a vhost is listening on + * + * In the case you passed 0 for the port number at context creation time, you + * can discover the port number that was actually chosen for the vhost using + * this api. + * + * \param vhost: Vhost to get listen port from + */ +LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_get_vhost_listen_port(struct lws_vhost *vhost); + +/** * lws_get_count_threads(): how many service threads the context uses * * \param context: the lws context @@ -4848,6 +5925,16 @@ LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT lws_get_child(const struct lws *wsi); /** + * lws_get_udp() - get wsi's udp struct + * + * \param wsi: lws connection + * + * Returns NULL or pointer to the wsi's UDP-specific information + */ +LWS_VISIBLE LWS_EXTERN const struct lws_udp * LWS_WARN_UNUSED_RESULT +lws_get_udp(const struct lws *wsi); + +/** * lws_parent_carries_io() - mark wsi as needing to send messages via parent * * \param wsi: child lws connection @@ -4887,14 +5974,6 @@ lws_get_close_payload(struct lws *wsi); LWS_VISIBLE LWS_EXTERN struct lws *lws_get_network_wsi(struct lws *wsi); -/* - * \deprecated DEPRECATED Note: this is not normally needed as a user api. - * It's provided in case it is - * useful when integrating with other app poll loop service code. - */ -LWS_VISIBLE LWS_EXTERN int -lws_read(struct lws *wsi, unsigned char *buf, lws_filepos_t len); - /** * lws_set_allocator() - custom allocator support * @@ -4992,7 +6071,18 @@ lws_is_ssl(struct lws *wsi); LWS_VISIBLE LWS_EXTERN int lws_is_cgi(struct lws *wsi); -#ifdef LWS_OPENSSL_SUPPORT + +struct lws_wifi_scan { /* generic wlan scan item */ + struct lws_wifi_scan *next; + char ssid[32]; + int32_t rssi; /* divide by .count to get db */ + uint8_t bssid[6]; + uint8_t count; + uint8_t channel; + uint8_t authmode; +}; + +#if defined(LWS_WITH_TLS) && !defined(LWS_WITH_MBEDTLS) /** * lws_get_ssl() - Return wsi's SSL context structure * \param wsi: websocket connection @@ -5002,6 +6092,160 @@ lws_is_cgi(struct lws *wsi); LWS_VISIBLE LWS_EXTERN SSL* lws_get_ssl(struct lws *wsi); #endif + +enum lws_tls_cert_info { + LWS_TLS_CERT_INFO_VALIDITY_FROM, + /**< fills .time with the time_t the cert validity started from */ + LWS_TLS_CERT_INFO_VALIDITY_TO, + /**< fills .time with the time_t the cert validity ends at */ + LWS_TLS_CERT_INFO_COMMON_NAME, + /**< fills up to len bytes of .ns.name with the cert common name */ + LWS_TLS_CERT_INFO_ISSUER_NAME, + /**< fills up to len bytes of .ns.name with the cert issuer name */ + LWS_TLS_CERT_INFO_USAGE, + /**< fills verified with a bitfield asserting the valid uses */ + LWS_TLS_CERT_INFO_VERIFIED, + /**< fills .verified with a bool representing peer cert validity, + * call returns -1 if no cert */ + LWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY, + /**< the certificate's public key, as an opaque bytestream. These + * opaque bytestreams can only be compared with each other using the + * same tls backend, ie, OpenSSL or mbedTLS. The different backends + * produce different, incompatible representations for the same cert. + */ +}; + +union lws_tls_cert_info_results { + unsigned int verified; + time_t time; + unsigned int usage; + struct { + int len; + /* KEEP LAST... notice the [64] is only there because + * name[] is not allowed in a union. The actual length of + * name[] is arbitrary and is passed into the api using the + * len parameter. Eg + * + * char big[1024]; + * union lws_tls_cert_info_results *buf = + * (union lws_tls_cert_info_results *)big; + * + * lws_tls_peer_cert_info(wsi, type, buf, sizeof(big) - + * sizeof(*buf) + sizeof(buf->ns.name)); + */ + char name[64]; + } ns; +}; + +/** + * lws_tls_peer_cert_info() - get information from the peer's TLS cert + * + * \param wsi: the connection to query + * \param type: one of LWS_TLS_CERT_INFO_ + * \param buf: pointer to union to take result + * \param len: when result is a string, the true length of buf->ns.name[] + * + * lws_tls_peer_cert_info() lets you get hold of information from the peer + * certificate. + * + * Return 0 if there is a result in \p buf, or -1 indicating there was no cert + * or another problem. + * + * This function works the same no matter if the TLS backend is OpenSSL or + * mbedTLS. + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_peer_cert_info(struct lws *wsi, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len); + +/** + * lws_tls_vhost_cert_info() - get information from the vhost's own TLS cert + * + * \param vhost: the vhost to query + * \param type: one of LWS_TLS_CERT_INFO_ + * \param buf: pointer to union to take result + * \param len: when result is a string, the true length of buf->ns.name[] + * + * lws_tls_vhost_cert_info() lets you get hold of information from the vhost + * certificate. + * + * Return 0 if there is a result in \p buf, or -1 indicating there was no cert + * or another problem. + * + * This function works the same no matter if the TLS backend is OpenSSL or + * mbedTLS. + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_vhost_cert_info(struct lws_vhost *vhost, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len); + +/** + * lws_tls_acme_sni_cert_create() - creates a temp selfsigned cert + * and attaches to a vhost + * + * \param vhost: the vhost to acquire the selfsigned cert + * \param san_a: SAN written into the certificate + * \param san_b: second SAN written into the certificate + * + * + * Returns 0 if created and attached to the vhost. Returns -1 if problems and + * frees all allocations before returning. + * + * On success, any allocations are destroyed at vhost destruction automatically. + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a, + const char *san_b); + +/** + * lws_tls_acme_sni_csr_create() - creates a CSR and related private key PEM + * + * \param context: lws_context used for random + * \param elements: array of LWS_TLS_REQ_ELEMENT_COUNT const char * + * \param csr: buffer that will get the b64URL(ASN-1 CSR) + * \param csr_len: max length of the csr buffer + * \param privkey_pem: pointer to pointer allocated to hold the privkey_pem + * \param privkey_len: pointer to size_t set to the length of the privkey_pem + * + * Creates a CSR according to the information in \p elements, and a private + * RSA key used to sign the CSR. + * + * The outputs are the b64URL(ASN-1 CSR) into csr, and the PEM private key into + * privkey_pem. + * + * Notice that \p elements points to an array of const char *s pointing to the + * information listed in the enum above. If an entry is NULL or an empty + * string, the element is set to "none" in the CSR. + * + * Returns 0 on success or nonzero for failure. + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[], + uint8_t *csr, size_t csr_len, char **privkey_pem, + size_t *privkey_len); + +/** + * lws_tls_cert_updated() - update every vhost using the given cert path + * + * \param context: our lws_context + * \param certpath: the filepath to the certificate + * \param keypath: the filepath to the private key of the certificate + * \param mem_cert: copy of the cert in memory + * \param len_mem_cert: length of the copy of the cert in memory + * \param mem_privkey: copy of the private key in memory + * \param len_mem_privkey: length of the copy of the private key in memory + * + * Checks every vhost to see if it is the using certificate described by the + * the given filepaths. If so, it attempts to update the vhost ssl_ctx to use + * the new certificate. + * + * Returns 0 on success or nonzero for failure. + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_cert_updated(struct lws_context *context, const char *certpath, + const char *keypath, + const char *mem_cert, size_t len_mem_cert, + const char *mem_privkey, size_t len_mem_privkey); ///@} /** \defgroup lws_ring LWS Ringbuffer APIs @@ -5226,6 +6470,65 @@ lws_ring_next_linear_insert_range(struct lws_ring *ring, void **start, */ LWS_VISIBLE LWS_EXTERN void lws_ring_bump_head(struct lws_ring *ring, size_t bytes); + +LWS_VISIBLE LWS_EXTERN void +lws_ring_dump(struct lws_ring *ring, uint32_t *tail); + +/* + * This is a helper that combines the common pattern of needing to consume + * some ringbuffer elements, move the consumer tail on, and check if that + * has moved any ringbuffer elements out of scope, because it was the last + * consumer that had not already consumed them. + * + * Elements that go out of scope because the oldest tail is now after them + * get garbage-collected by calling the destroy_element callback on them + * defined when the ringbuffer was created. + */ + +#define lws_ring_consume_and_update_oldest_tail(\ + ___ring, /* the lws_ring object */ \ + ___type, /* type of objects with tails */ \ + ___ptail, /* ptr to tail of obj with tail doing consuming */ \ + ___count, /* count of payload objects being consumed */ \ + ___list_head, /* head of list of objects with tails */ \ + ___mtail, /* member name of tail in ___type */ \ + ___mlist /* member name of next list member ptr in ___type */ \ + ) { \ + int ___n, ___m; \ + \ + ___n = lws_ring_get_oldest_tail(___ring) == *(___ptail); \ + lws_ring_consume(___ring, ___ptail, NULL, ___count); \ + if (___n) { \ + uint32_t ___oldest; \ + ___n = 0; \ + ___oldest = *(___ptail); \ + lws_start_foreach_llp(___type **, ___ppss, ___list_head) { \ + ___m = lws_ring_get_count_waiting_elements( \ + ___ring, &(*___ppss)->tail); \ + if (___m >= ___n) { \ + ___n = ___m; \ + ___oldest = (*___ppss)->tail; \ + } \ + } lws_end_foreach_llp(___ppss, ___mlist); \ + \ + lws_ring_update_oldest_tail(___ring, ___oldest); \ + } \ +} + +/* + * This does the same as the lws_ring_consume_and_update_oldest_tail() + * helper, but for the simpler case there is only one consumer, so one + * tail, and that tail is always the oldest tail. + */ + +#define lws_ring_consume_single_tail(\ + ___ring, /* the lws_ring object */ \ + ___ptail, /* ptr to tail of obj with tail doing consuming */ \ + ___count /* count of payload objects being consumed */ \ + ) { \ + lws_ring_consume(___ring, ___ptail, NULL, ___count); \ + lws_ring_update_oldest_tail(___ring, *(___ptail)); \ +} ///@} /** \defgroup sha SHA and B64 helpers @@ -5262,16 +6565,40 @@ lws_SHA1(const unsigned char *d, size_t n, unsigned char *md); LWS_VISIBLE LWS_EXTERN int lws_b64_encode_string(const char *in, int in_len, char *out, int out_size); /** + * lws_b64_encode_string_url(): encode a string into base 64 + * + * \param in: incoming buffer + * \param in_len: length of incoming buffer + * \param out: result buffer + * \param out_size: length of result buffer + * + * Encodes a string using b64 with the "URL" variant (+ -> -, and / -> _) + */ +LWS_VISIBLE LWS_EXTERN int +lws_b64_encode_string_url(const char *in, int in_len, char *out, int out_size); +/** * lws_b64_decode_string(): decode a string from base 64 * * \param in: incoming buffer * \param out: result buffer * \param out_size: length of result buffer * - * Decodes a string using b64 + * Decodes a NUL-terminated string using b64 */ LWS_VISIBLE LWS_EXTERN int lws_b64_decode_string(const char *in, char *out, int out_size); +/** + * lws_b64_decode_string_len(): decode a string from base 64 + * + * \param in: incoming buffer + * \param in_len: length of incoming buffer + * \param out: result buffer + * \param out_size: length of result buffer + * + * Decodes a range of chars using b64 + */ +LWS_VISIBLE LWS_EXTERN int +lws_b64_decode_string_len(const char *in, int in_len, char *out, int out_size); ///@} @@ -5727,6 +7054,248 @@ lws_email_destroy(struct lws_email *email); #endif //@} + +/** \defgroup lejp JSON parser + * ##JSON parsing related functions + * \ingroup lwsapi + * + * LEJP is an extremely lightweight JSON stream parser included in lws. + */ +//@{ +struct lejp_ctx; + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(_x) (sizeof(_x) / sizeof(_x[0])) +#endif +#define LWS_ARRAY_SIZE(_x) (sizeof(_x) / sizeof(_x[0])) +#define LEJP_FLAG_WS_KEEP 64 +#define LEJP_FLAG_WS_COMMENTLINE 32 + +enum lejp_states { + LEJP_IDLE = 0, + LEJP_MEMBERS = 1, + LEJP_M_P = 2, + LEJP_MP_STRING = LEJP_FLAG_WS_KEEP | 3, + LEJP_MP_STRING_ESC = LEJP_FLAG_WS_KEEP | 4, + LEJP_MP_STRING_ESC_U1 = LEJP_FLAG_WS_KEEP | 5, + LEJP_MP_STRING_ESC_U2 = LEJP_FLAG_WS_KEEP | 6, + LEJP_MP_STRING_ESC_U3 = LEJP_FLAG_WS_KEEP | 7, + LEJP_MP_STRING_ESC_U4 = LEJP_FLAG_WS_KEEP | 8, + LEJP_MP_DELIM = 9, + LEJP_MP_VALUE = 10, + LEJP_MP_VALUE_NUM_INT = LEJP_FLAG_WS_KEEP | 11, + LEJP_MP_VALUE_NUM_EXP = LEJP_FLAG_WS_KEEP | 12, + LEJP_MP_VALUE_TOK = LEJP_FLAG_WS_KEEP | 13, + LEJP_MP_COMMA_OR_END = 14, + LEJP_MP_ARRAY_END = 15, +}; + +enum lejp_reasons { + LEJP_CONTINUE = -1, + LEJP_REJECT_IDLE_NO_BRACE = -2, + LEJP_REJECT_MEMBERS_NO_CLOSE = -3, + LEJP_REJECT_MP_NO_OPEN_QUOTE = -4, + LEJP_REJECT_MP_STRING_UNDERRUN = -5, + LEJP_REJECT_MP_ILLEGAL_CTRL = -6, + LEJP_REJECT_MP_STRING_ESC_ILLEGAL_ESC = -7, + LEJP_REJECT_ILLEGAL_HEX = -8, + LEJP_REJECT_MP_DELIM_MISSING_COLON = -9, + LEJP_REJECT_MP_DELIM_BAD_VALUE_START = -10, + LEJP_REJECT_MP_VAL_NUM_INT_NO_FRAC = -11, + LEJP_REJECT_MP_VAL_NUM_FORMAT = -12, + LEJP_REJECT_MP_VAL_NUM_EXP_BAD_EXP = -13, + LEJP_REJECT_MP_VAL_TOK_UNKNOWN = -14, + LEJP_REJECT_MP_C_OR_E_UNDERF = -15, + LEJP_REJECT_MP_C_OR_E_NOTARRAY = -16, + LEJP_REJECT_MP_ARRAY_END_MISSING = -17, + LEJP_REJECT_STACK_OVERFLOW = -18, + LEJP_REJECT_MP_DELIM_ISTACK = -19, + LEJP_REJECT_NUM_TOO_LONG = -20, + LEJP_REJECT_MP_C_OR_E_NEITHER = -21, + LEJP_REJECT_UNKNOWN = -22, + LEJP_REJECT_CALLBACK = -23 +}; + +#define LEJP_FLAG_CB_IS_VALUE 64 + +enum lejp_callbacks { + LEJPCB_CONSTRUCTED = 0, + LEJPCB_DESTRUCTED = 1, + + LEJPCB_START = 2, + LEJPCB_COMPLETE = 3, + LEJPCB_FAILED = 4, + + LEJPCB_PAIR_NAME = 5, + + LEJPCB_VAL_TRUE = LEJP_FLAG_CB_IS_VALUE | 6, + LEJPCB_VAL_FALSE = LEJP_FLAG_CB_IS_VALUE | 7, + LEJPCB_VAL_NULL = LEJP_FLAG_CB_IS_VALUE | 8, + LEJPCB_VAL_NUM_INT = LEJP_FLAG_CB_IS_VALUE | 9, + LEJPCB_VAL_NUM_FLOAT = LEJP_FLAG_CB_IS_VALUE | 10, + LEJPCB_VAL_STR_START = 11, /* notice handle separately */ + LEJPCB_VAL_STR_CHUNK = LEJP_FLAG_CB_IS_VALUE | 12, + LEJPCB_VAL_STR_END = LEJP_FLAG_CB_IS_VALUE | 13, + + LEJPCB_ARRAY_START = 14, + LEJPCB_ARRAY_END = 15, + + LEJPCB_OBJECT_START = 16, + LEJPCB_OBJECT_END = 17 +}; + +/** + * _lejp_callback() - User parser actions + * \param ctx: LEJP context + * \param reason: Callback reason + * + * Your user callback is associated with the context at construction time, + * and receives calls as the parsing progresses. + * + * All of the callbacks may be ignored and just return 0. + * + * The reasons it might get called, found in @reason, are: + * + * LEJPCB_CONSTRUCTED: The context was just constructed... you might want to + * perform one-time allocation for the life of the context. + * + * LEJPCB_DESTRUCTED: The context is being destructed... if you made any + * allocations at construction-time, you can free them now + * + * LEJPCB_START: Parsing is beginning at the first byte of input + * + * LEJPCB_COMPLETE: Parsing has completed successfully. You'll get a 0 or + * positive return code from lejp_parse indicating the + * amount of unused bytes left in the input buffer + * + * LEJPCB_FAILED: Parsing failed. You'll get a negative error code + * returned from lejp_parse + * + * LEJPCB_PAIR_NAME: When a "name":"value" pair has had the name parsed, + * this callback occurs. You can find the new name at + * the end of ctx->path[] + * + * LEJPCB_VAL_TRUE: The "true" value appeared + * + * LEJPCB_VAL_FALSE: The "false" value appeared + * + * LEJPCB_VAL_NULL: The "null" value appeared + * + * LEJPCB_VAL_NUM_INT: A string representing an integer is in ctx->buf + * + * LEJPCB_VAL_NUM_FLOAT: A string representing a float is in ctx->buf + * + * LEJPCB_VAL_STR_START: We are starting to parse a string, no data yet + * + * LEJPCB_VAL_STR_CHUNK: We parsed LEJP_STRING_CHUNK -1 bytes of string data in + * ctx->buf, which is as much as we can buffer, so we are + * spilling it. If all your strings are less than + * LEJP_STRING_CHUNK - 1 bytes, you will never see this + * callback. + * + * LEJPCB_VAL_STR_END: String parsing has completed, the last chunk of the + * string is in ctx->buf. + * + * LEJPCB_ARRAY_START: An array started + * + * LEJPCB_ARRAY_END: An array ended + * + * LEJPCB_OBJECT_START: An object started + * + * LEJPCB_OBJECT_END: An object ended + */ +LWS_EXTERN signed char _lejp_callback(struct lejp_ctx *ctx, char reason); + +typedef signed char (*lejp_callback)(struct lejp_ctx *ctx, char reason); + +#ifndef LEJP_MAX_DEPTH +#define LEJP_MAX_DEPTH 12 +#endif +#ifndef LEJP_MAX_INDEX_DEPTH +#define LEJP_MAX_INDEX_DEPTH 5 +#endif +#ifndef LEJP_MAX_PATH +#define LEJP_MAX_PATH 128 +#endif +#ifndef LEJP_STRING_CHUNK +/* must be >= 30 to assemble floats */ +#define LEJP_STRING_CHUNK 255 +#endif + +enum num_flags { + LEJP_SEEN_MINUS = (1 << 0), + LEJP_SEEN_POINT = (1 << 1), + LEJP_SEEN_POST_POINT = (1 << 2), + LEJP_SEEN_EXP = (1 << 3) +}; + +struct _lejp_stack { + char s; /* lejp_state stack*/ + char p; /* path length */ + char i; /* index array length */ + char b; /* user bitfield */ +}; + +struct lejp_ctx { + + /* sorted by type for most compact alignment + * + * pointers + */ + + signed char (*callback)(struct lejp_ctx *ctx, char reason); + void *user; + const char * const *paths; + + /* arrays */ + + struct _lejp_stack st[LEJP_MAX_DEPTH]; + uint16_t i[LEJP_MAX_INDEX_DEPTH]; /* index array */ + uint16_t wild[LEJP_MAX_INDEX_DEPTH]; /* index array */ + char path[LEJP_MAX_PATH]; + char buf[LEJP_STRING_CHUNK]; + + /* int */ + + uint32_t line; + + /* short */ + + uint16_t uni; + + /* char */ + + uint8_t npos; + uint8_t dcount; + uint8_t f; + uint8_t sp; /* stack head */ + uint8_t ipos; /* index stack depth */ + uint8_t ppos; + uint8_t count_paths; + uint8_t path_match; + uint8_t path_match_len; + uint8_t wildcount; +}; + +LWS_VISIBLE LWS_EXTERN void +lejp_construct(struct lejp_ctx *ctx, + signed char (*callback)(struct lejp_ctx *ctx, char reason), + void *user, const char * const *paths, unsigned char paths_count); + +LWS_VISIBLE LWS_EXTERN void +lejp_destruct(struct lejp_ctx *ctx); + +LWS_VISIBLE LWS_EXTERN int +lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len); + +LWS_VISIBLE LWS_EXTERN void +lejp_change_callback(struct lejp_ctx *ctx, + signed char (*callback)(struct lejp_ctx *ctx, char reason)); + +LWS_VISIBLE LWS_EXTERN int +lejp_get_wildcard(struct lejp_ctx *ctx, int wildcard, char *dest, int len); +//@} + /* * Stats are all uint64_t numbers that start at 0. * Index names here have the convention @@ -5775,9 +7344,9 @@ LWS_VISIBLE LWS_EXTERN void lws_stats_log_dump(struct lws_context *context); #else static LWS_INLINE uint64_t -lws_stats_get(struct lws_context *context, int index) { return 0; } +lws_stats_get(struct lws_context *context, int index) { (void)context; (void)index; return 0; } static LWS_INLINE void -lws_stats_log_dump(struct lws_context *context) { } +lws_stats_log_dump(struct lws_context *context) { (void)context; } #endif #ifdef __cplusplus diff --git a/thirdparty/lws/lws_config.h b/thirdparty/libwebsockets/lws_config.h index 6005d94ec6..7185a806a5 100644 --- a/thirdparty/lws/lws_config.h +++ b/thirdparty/libwebsockets/lws_config.h @@ -14,6 +14,12 @@ #define LWS_INSTALL_DATADIR "/usr/local/share" +#define LWS_ROLE_H1 +#define LWS_ROLE_WS +#define LWS_ROLE_RAW +/* #undef LWS_ROLE_H2 */ +/* #undef LWS_ROLE_CGI */ + /* Define to 1 to use wolfSSL/CyaSSL as a replacement for OpenSSL. * LWS_OPENSSL_SUPPORT needs to be set also for this to work. */ /* #undef USE_WOLFSSL */ @@ -25,26 +31,26 @@ #define LWS_WITH_MBEDTLS /* #undef LWS_WITH_POLARSSL */ -/* #undef LWS_WITH_ESP8266 */ /* #undef LWS_WITH_ESP32 */ /* #undef LWS_WITH_PLUGINS */ /* #undef LWS_WITH_NO_LOGS */ /* The Libwebsocket version */ -#define LWS_LIBRARY_VERSION "2.4.2" +#define LWS_LIBRARY_VERSION "3.0.0" -#define LWS_LIBRARY_VERSION_MAJOR 2 -#define LWS_LIBRARY_VERSION_MINOR 4 -#define LWS_LIBRARY_VERSION_PATCH 2 +#define LWS_LIBRARY_VERSION_MAJOR 3 +#define LWS_LIBRARY_VERSION_MINOR 0 +#define LWS_LIBRARY_VERSION_PATCH 0 /* LWS_LIBRARY_VERSION_NUMBER looks like 1005001 for e.g. version 1.5.1 */ #define LWS_LIBRARY_VERSION_NUMBER (LWS_LIBRARY_VERSION_MAJOR*1000000)+(LWS_LIBRARY_VERSION_MINOR*1000)+LWS_LIBRARY_VERSION_PATCH /* The current git commit hash that we're building from */ -#define LWS_BUILD_HASH "8964ce9db75a98e463dfafd2e89f2bc8a95ec6ed" +#define LWS_BUILD_HASH "v2.0.0-948-geaa935a8" -/* Build with OpenSSL support */ +/* Build with OpenSSL support ... alias of LWS_WITH_TLS for compatibility*/ #define LWS_OPENSSL_SUPPORT +#define LWS_WITH_TLS /* The client should load and trust CA root certs it finds in the OS */ /* #undef LWS_SSL_CLIENT_USE_OS_CA_CERTS */ @@ -53,7 +59,13 @@ /* #undef LWS_OPENSSL_CLIENT_CERTS "../share" */ /* Turn off websocket extensions */ -/* #undef LWS_NO_EXTENSIONS */ +#define LWS_WITHOUT_EXTENSIONS + +/* notice if client or server gone */ +/* #undef LWS_WITHOUT_SERVER */ +/* #undef LWS_WITHOUT_CLIENT */ + +#define LWS_WITH_POLL /* Enable libev io loop */ /* #undef LWS_WITH_LIBEV */ @@ -99,8 +111,11 @@ /* #undef LWS_HAVE_SSL_CTX_set1_param */ #define LWS_HAVE_X509_VERIFY_PARAM_set1_host /* #undef LWS_HAVE_RSA_SET0_KEY */ +/* #undef LWS_HAVE_X509_get_key_usage */ +/* #undef LWS_HAVE_SSL_CTX_get0_certificate */ /* #undef LWS_HAVE_UV_VERSION_H */ +/* #undef LWS_HAVE_PTHREAD_H */ /* CGI apis */ /* #undef LWS_WITH_CGI */ @@ -112,7 +127,7 @@ /* #undef LWS_WITH_HTTP_PROXY */ /* HTTP Ranges support */ -#define LWS_WITH_RANGES +/* #undef LWS_WITH_RANGES */ /* Http access log support */ /* #undef LWS_WITH_ACCESS_LOG */ @@ -134,7 +149,7 @@ /* #undef LWS_PLAT_OPTEE */ /* ZIP FOPS */ -#define LWS_WITH_ZIP_FOPS +/* #undef LWS_WITH_ZIP_FOPS */ #define LWS_HAVE_STDINT_H /* #undef LWS_AVOID_SIGPIPE_IGN */ @@ -151,11 +166,26 @@ /* #undef LWS_HAVE__ATOI64 */ /* #undef LWS_HAVE__STAT32I64 */ +/* #undef LWS_WITH_JWS */ +/* #undef LWS_WITH_ACME */ +/* #undef LWS_WITH_SELFTESTS */ + +#if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__OpenBSD__) +#define LWS_HAVE_MALLOC_H +#endif + +#if !defined(IPHONE_ENABLED) && !defined(OSX_ENABLED) +#define LWS_HAVE_PIPE2 +#endif + /* OpenSSL various APIs */ #define LWS_HAVE_TLS_CLIENT_METHOD /* #undef LWS_HAVE_TLSV1_2_CLIENT_METHOD */ /* #undef LWS_HAVE_SSL_SET_INFO_CALLBACK */ +/* #undef LWS_HAVE_SSL_EXTRA_CHAIN_CERTS */ +/* #undef LWS_HAVE_SSL_get0_alpn_selected */ +/* #undef LWS_HAVE_SSL_set_alpn_protos */ #define LWS_HAS_INTPTR_T diff --git a/thirdparty/lws/lws_config_private.h b/thirdparty/libwebsockets/lws_config_private.h index 475d1bd3f8..9d04078fef 100644 --- a/thirdparty/lws/lws_config_private.h +++ b/thirdparty/libwebsockets/lws_config_private.h @@ -100,6 +100,8 @@ /* Define to 1 if you have the <unistd.h> header file. */ #define LWS_HAVE_UNISTD_H +#define LWS_HAVE_TCP_USER_TIMEOUT + /* Define to 1 if you have the `vfork' function. */ #define LWS_HAVE_VFORK diff --git a/thirdparty/lws/misc/base64-decode.c b/thirdparty/libwebsockets/misc/base64-decode.c index c8f11d21b8..64b84d78fa 100644 --- a/thirdparty/lws/misc/base64-decode.c +++ b/thirdparty/libwebsockets/misc/base64-decode.c @@ -40,15 +40,18 @@ #include <stdio.h> #include <string.h> -#include "private-libwebsockets.h" +#include "core/private.h" -static const char encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +static const char encode_orig[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char encode_url[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789-_"; static const char decode[] = "|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW" "$$$$$$XYZ[\\]^_`abcdefghijklmnopq"; -LWS_VISIBLE int -lws_b64_encode_string(const char *in, int in_len, char *out, int out_size) +static int +_lws_b64_encode_string(const char *encode, const char *in, int in_len, + char *out, int out_size) { unsigned char triple[3]; int i; @@ -89,26 +92,47 @@ lws_b64_encode_string(const char *in, int in_len, char *out, int out_size) return done; } +LWS_VISIBLE int +lws_b64_encode_string(const char *in, int in_len, char *out, int out_size) +{ + return _lws_b64_encode_string(encode_orig, in, in_len, out, out_size); +} + +LWS_VISIBLE int +lws_b64_encode_string_url(const char *in, int in_len, char *out, int out_size) +{ + return _lws_b64_encode_string(encode_url, in, in_len, out, out_size); +} + /* * returns length of decoded string in out, or -1 if out was too small * according to out_size + * + * Only reads up to in_len chars, otherwise if in_len is -1 on entry reads until + * the first NUL in the input. */ -LWS_VISIBLE int -lws_b64_decode_string(const char *in, char *out, int out_size) +static int +_lws_b64_decode_string(const char *in, int in_len, char *out, int out_size) { int len, i, c = 0, done = 0; unsigned char v, quad[4]; - while (*in) { + while (in_len && *in) { len = 0; - for (i = 0; i < 4 && *in; i++) { + for (i = 0; i < 4 && in_len && *in; i++) { v = 0; c = 0; - while (*in && !v) { + while (in_len && *in && !v) { c = v = *in++; + in_len--; + /* support the url base64 variant too */ + if (v == '-') + c = v = '+'; + if (v == '_') + c = v = '/'; v = (v < 43 || v > 122) ? 0 : decode[v - 43]; if (v) v = (v == '$') ? 0 : v - 61; @@ -131,7 +155,7 @@ lws_b64_decode_string(const char *in, char *out, int out_size) * bytes." (wikipedia) */ - if (!*in && c == '=') + if ((!in_len || !*in) && c == '=') len--; if (len >= 2) @@ -152,6 +176,18 @@ lws_b64_decode_string(const char *in, char *out, int out_size) return done; } +LWS_VISIBLE int +lws_b64_decode_string(const char *in, char *out, int out_size) +{ + return _lws_b64_decode_string(in, -1, out, out_size); +} + +LWS_VISIBLE int +lws_b64_decode_string_len(const char *in, int in_len, char *out, int out_size) +{ + return _lws_b64_decode_string(in, in_len, out, out_size); +} + #if 0 int lws_b64_selftest(void) diff --git a/thirdparty/lws/misc/getifaddrs.c b/thirdparty/libwebsockets/misc/getifaddrs.c index 4f42ab4595..735b899f48 100644 --- a/thirdparty/lws/misc/getifaddrs.c +++ b/thirdparty/libwebsockets/misc/getifaddrs.c @@ -43,7 +43,7 @@ #include <string.h> #include <sys/ioctl.h> #include <unistd.h> -#include "private-libwebsockets.h" +#include "core/private.h" #ifdef LWS_HAVE_SYS_SOCKIO_H #include <sys/sockio.h> diff --git a/thirdparty/lws/misc/getifaddrs.h b/thirdparty/libwebsockets/misc/getifaddrs.h index d26670c082..d26670c082 100644 --- a/thirdparty/lws/misc/getifaddrs.h +++ b/thirdparty/libwebsockets/misc/getifaddrs.h diff --git a/thirdparty/lws/misc/lejp.c b/thirdparty/libwebsockets/misc/lejp.c index 38efa8b122..00d350f81e 100644 --- a/thirdparty/lws/misc/lejp.c +++ b/thirdparty/libwebsockets/misc/lejp.c @@ -1,14 +1,26 @@ /* * Lightweight Embedded JSON Parser * - * Copyright (C) 2013 Andy Green <andy@warmcat.com> - * This code is licensed under LGPL 2.1 - * http://www.gnu.org/licenses/lgpl-2.1.html + * Copyright (C) 2013-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA */ +#include <libwebsockets.h> #include <string.h> -#include "lejp.h" - #include <stdio.h> /** @@ -148,7 +160,8 @@ lejp_get_wildcard(struct lejp_ctx *ctx, int wildcard, char *dest, int len) n = ctx->wild[wildcard]; - while (--len && n < ctx->ppos && (n == ctx->wild[wildcard] || ctx->path[n] != '.')) + while (--len && n < ctx->ppos && + (n == ctx->wild[wildcard] || ctx->path[n] != '.')) *dest++ = ctx->path[n++]; *dest = '\0'; @@ -186,7 +199,6 @@ lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len) while (len--) { c = *json++; - s = ctx->st[ctx->sp].s; /* skip whitespace unless we should care */ @@ -411,6 +423,26 @@ lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len) } goto add_stack_level; + case ']': + /* pop */ + ctx->sp--; + if (ctx->st[ctx->sp].s != LEJP_MP_ARRAY_END) { + ret = LEJP_REJECT_MP_C_OR_E_NOTARRAY; + goto reject; + } + /* drop the path [n] bit */ + ctx->ppos = ctx->st[ctx->sp - 1].p; + ctx->ipos = ctx->st[ctx->sp - 1].i; + ctx->path[ctx->ppos] = '\0'; + if (ctx->path_match && + ctx->ppos <= ctx->path_match_len) + /* + * we shrank the path to be + * smaller than the matching point + */ + ctx->path_match = 0; + goto array_end; + case 't': /* true */ ctx->uni = 0; ctx->st[ctx->sp].s = LEJP_MP_VALUE_TOK; @@ -582,8 +614,10 @@ lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len) goto reject; } /* drop the path [n] bit */ - ctx->ppos = ctx->st[ctx->sp - 1].p; - ctx->ipos = ctx->st[ctx->sp - 1].i; + if (ctx->sp) { + ctx->ppos = ctx->st[ctx->sp - 1].p; + ctx->ipos = ctx->st[ctx->sp - 1].i; + } ctx->path[ctx->ppos] = '\0'; if (ctx->path_match && ctx->ppos <= ctx->path_match_len) @@ -609,8 +643,10 @@ lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len) } /* pop */ ctx->sp--; - ctx->ppos = ctx->st[ctx->sp - 1].p; - ctx->ipos = ctx->st[ctx->sp - 1].i; + if (ctx->sp) { + ctx->ppos = ctx->st[ctx->sp - 1].p; + ctx->ipos = ctx->st[ctx->sp - 1].i; + } ctx->path[ctx->ppos] = '\0'; if (ctx->path_match && ctx->ppos <= ctx->path_match_len) @@ -631,6 +667,7 @@ lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len) goto reject; case LEJP_MP_ARRAY_END: +array_end: ctx->path[ctx->ppos] = '\0'; if (c == ',') { /* increment this stack level's index */ diff --git a/thirdparty/lws/misc/sha-1.c b/thirdparty/libwebsockets/misc/sha-1.c index 50205a0100..2e4db52693 100644 --- a/thirdparty/lws/misc/sha-1.c +++ b/thirdparty/libwebsockets/misc/sha-1.c @@ -32,7 +32,7 @@ * implemented by Jun-ichiro itojun Itoh <itojun@itojun.org> */ -#include "private-libwebsockets.h" +#include "core/private.h" #ifdef LWS_HAVE_SYS_TYPES_H #include <sys/types.h> diff --git a/thirdparty/lws/plat/lws-plat-unix.c b/thirdparty/libwebsockets/plat/lws-plat-unix.c index a51e67bb81..bacc6af647 100644 --- a/thirdparty/lws/plat/lws-plat-unix.c +++ b/thirdparty/libwebsockets/plat/lws-plat-unix.c @@ -19,7 +19,8 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#define _GNU_SOURCE +#include "core/private.h" #include <pwd.h> #include <grp.h> @@ -29,6 +30,56 @@ #endif #include <dirent.h> +int +lws_plat_socket_offset(void) +{ + return 0; +} + +int +lws_plat_pipe_create(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + +#if defined(LWS_HAVE_PIPE2) + return pipe2(pt->dummy_pipe_fds, O_NONBLOCK); +#else + return pipe(pt->dummy_pipe_fds); +#endif +} + +int +lws_plat_pipe_signal(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + char buf = 0; + int n; + + n = write(pt->dummy_pipe_fds[1], &buf, 1); + + return n != 1; +} + +void +lws_plat_pipe_close(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + if (pt->dummy_pipe_fds[0] && pt->dummy_pipe_fds[0] != -1) + close(pt->dummy_pipe_fds[0]); + if (pt->dummy_pipe_fds[1] && pt->dummy_pipe_fds[1] != -1) + close(pt->dummy_pipe_fds[1]); + + pt->dummy_pipe_fds[0] = pt->dummy_pipe_fds[1] = -1; +} + +#ifdef __QNX__ +# include "netinet/tcp_var.h" +# define TCP_KEEPINTVL TCPCTL_KEEPINTVL +# define TCP_KEEPIDLE TCPCTL_KEEPIDLE +# define TCP_KEEPCNT TCPCTL_KEEPCNT +#endif + unsigned long long time_in_microseconds(void) { struct timeval tv; @@ -52,6 +103,10 @@ lws_send_pipe_choked(struct lws *wsi) #if defined(LWS_WITH_HTTP2) wsi_eff = lws_get_network_wsi(wsi); #endif + + /* the fact we checked implies we avoided back-to-back writes */ + wsi_eff->could_have_pending = 0; + /* treat the fact we got a truncated send pending as if we're choked */ if (wsi_eff->trunc_len) return 1; @@ -77,29 +132,6 @@ lws_poll_listen_fd(struct lws_pollfd *fd) return poll(fd, 1, 0); } -LWS_VISIBLE void -lws_cancel_service_pt(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - char buf = 0; - - if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1) - lwsl_err("Cannot write to dummy pipe"); -} - -LWS_VISIBLE void -lws_cancel_service(struct lws_context *context) -{ - struct lws_context_per_thread *pt = &context->pt[0]; - char buf = 0, m = context->count_threads; - - while (m--) { - if (write(pt->dummy_pipe_fds[1], &buf, sizeof(buf)) != 1) - lwsl_err("Cannot write to dummy pipe"); - pt++; - } -} - LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line) { int syslog_level = LOG_DEBUG; @@ -124,9 +156,10 @@ LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line) LWS_VISIBLE LWS_EXTERN int _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) { + volatile struct lws_foreign_thread_pollfd *ftp, *next; + volatile struct lws_context_per_thread *vpt; struct lws_context_per_thread *pt; int n = -1, m, c; - char buf; /* stay dead once we are dead */ @@ -134,15 +167,15 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) return 1; pt = &context->pt[tsi]; + vpt = (volatile struct lws_context_per_thread *)pt; lws_stats_atomic_bump(context, pt, LWSSTATS_C_SERVICE_ENTRY, 1); if (timeout_ms < 0) goto faked_service; - lws_libev_run(context, tsi); - lws_libuv_run(context, tsi); - lws_libevent_run(context, tsi); + if (context->event_loop_ops->run_pt) + context->event_loop_ops->run_pt(context, tsi); if (!context->service_tid_detected) { struct lws _lws; @@ -169,15 +202,73 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) timeout_ms = 0; } + if (timeout_ms) { + lws_pt_lock(pt, __func__); + /* don't stay in poll wait longer than next hr timeout */ + lws_usec_t t = __lws_hrtimer_service(pt); + if ((lws_usec_t)timeout_ms * 1000 > t) + timeout_ms = t / 1000; + lws_pt_unlock(pt); + } + + vpt->inside_poll = 1; + lws_memory_barrier(); n = poll(pt->fds, pt->fds_count, timeout_ms); + vpt->inside_poll = 0; + lws_memory_barrier(); -#ifdef LWS_OPENSSL_SUPPORT - if (!n && !pt->rx_draining_ext_list && - !lws_ssl_anybody_has_buffered_read_tsi(context, tsi)) { -#else - if (!pt->rx_draining_ext_list && !n) /* poll timeout */ { + /* Collision will be rare and brief. Just spin until it completes */ + while (vpt->foreign_spinlock) + ; + + /* + * At this point we are not inside a foreign thread pollfd change, + * and we have marked ourselves as outside the poll() wait. So we + * are the only guys that can modify the lws_foreign_thread_pollfd + * list on the pt. Drain the list and apply the changes to the + * affected pollfds in the correct order. + */ + + lws_pt_lock(pt, __func__); + + ftp = vpt->foreign_pfd_list; + //lwsl_notice("cleared list %p\n", ftp); + while (ftp) { + struct lws *wsi; + struct lws_pollfd *pfd; + + next = ftp->next; + pfd = &vpt->fds[ftp->fd_index]; + if (lws_socket_is_valid(pfd->fd)) { + wsi = wsi_from_fd(context, pfd->fd); + if (wsi) + __lws_change_pollfd(wsi, ftp->_and, ftp->_or); + } + lws_free((void *)ftp); + ftp = next; + } + vpt->foreign_pfd_list = NULL; + lws_memory_barrier(); + + /* we have come out of a poll wait... check the hrtimer list */ + + __lws_hrtimer_service(pt); + + lws_pt_unlock(pt); + + m = 0; +#if defined(LWS_ROLE_WS) && !defined(LWS_WITHOUT_EXTENSIONS) + m |= !!pt->ws.rx_draining_ext_list; #endif + + if (pt->context->tls_ops && + pt->context->tls_ops->fake_POLLIN_for_buffered) + m |= pt->context->tls_ops->fake_POLLIN_for_buffered(pt); + + if (!m && !n) { /* nothing to do */ lws_service_fd_tsi(context, NULL, tsi); + lws_service_do_ripe_rxflow(pt); + return 0; } @@ -194,18 +285,12 @@ faked_service: c = n; /* any socket with events to service? */ - for (n = 0; n < pt->fds_count && c; n++) { + for (n = 0; n < (int)pt->fds_count && c; n++) { if (!pt->fds[n].revents) continue; c--; - if (pt->fds[n].fd == pt->dummy_pipe_fds[0]) { - if (read(pt->fds[n].fd, &buf, 1) != 1) - lwsl_err("Cannot read from dummy pipe."); - continue; - } - m = lws_service_fd_tsi(context, &pt->fds[n], tsi); if (m < 0) return -1; @@ -214,6 +299,8 @@ faked_service: n--; } + lws_service_do_ripe_rxflow(pt); + return 0; } @@ -262,6 +349,14 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, int fd) */ #else /* set the keepalive conditions we want on it too */ + +#if defined(LWS_HAVE_TCP_USER_TIMEOUT) + optval = 1000 * (vhost->ka_time + + (vhost->ka_interval * vhost->ka_probes)); + if (setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, + (const void *)&optval, optlen) < 0) + return 1; +#endif optval = vhost->ka_time; if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (const void *)&optval, optlen) < 0) @@ -292,7 +387,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, int fd) /* Disable Nagle */ optval = 1; -#if defined (__sun) +#if defined (__sun) || defined(__QNX__) if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0) return 1; #elif !defined(__APPLE__) && \ @@ -317,7 +412,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, int fd) #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP) static void -_lws_plat_apply_caps(int mode, cap_value_t *cv, int count) +_lws_plat_apply_caps(int mode, const cap_value_t *cv, int count) { cap_t caps; @@ -334,7 +429,7 @@ _lws_plat_apply_caps(int mode, cap_value_t *cv, int count) #endif LWS_VISIBLE void -lws_plat_drop_app_privileges(struct lws_context_creation_info *info) +lws_plat_drop_app_privileges(const struct lws_context_creation_info *info) { #if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP) int n; @@ -449,8 +544,8 @@ lws_plat_plugins_init(struct lws_context * context, const char * const *d) } plugin->list = context->plugin_list; context->plugin_list = plugin; - strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1); - plugin->name[sizeof(plugin->name) - 1] = '\0'; + lws_strncpy(plugin->name, namelist[i]->d_name, + sizeof(plugin->name)); plugin->l = l; plugin->caps = lcaps; context->plugin_protocol_count += lcaps.count_protocols; @@ -543,9 +638,6 @@ lws_plat_context_early_destroy(struct lws_context *context) LWS_VISIBLE void lws_plat_context_late_destroy(struct lws_context *context) { - struct lws_context_per_thread *pt = &context->pt[0]; - int m = context->count_threads; - #ifdef LWS_WITH_PLUGINS if (context->plugin_list) lws_plat_plugins_destroy(context); @@ -554,13 +646,6 @@ lws_plat_context_late_destroy(struct lws_context *context) if (context->lws_lookup) lws_free(context->lws_lookup); - while (m--) { - if (pt->dummy_pipe_fds[0]) - close(pt->dummy_pipe_fds[0]); - if (pt->dummy_pipe_fds[1]) - close(pt->dummy_pipe_fds[1]); - pt++; - } if (!context->fd_random) lwsl_err("ZERO RANDOM FD\n"); if (context->fd_random != LWS_INVALID_FILE) @@ -573,7 +658,7 @@ LWS_VISIBLE int lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, size_t addrlen) { - int rc = -1; + int rc = LWS_ITOSA_NOT_EXIST; struct ifaddrs *ifr; struct ifaddrs *ifc; @@ -586,12 +671,19 @@ lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, if (!ifc->ifa_addr) continue; - lwsl_info(" interface %s vs %s\n", ifc->ifa_name, ifname); + lwsl_debug(" interface %s vs %s (fam %d) ipv6 %d\n", ifc->ifa_name, ifname, ifc->ifa_addr->sa_family, ipv6); if (strcmp(ifc->ifa_name, ifname)) continue; switch (ifc->ifa_addr->sa_family) { +#if defined(AF_PACKET) + case AF_PACKET: + /* interface exists but is not usable */ + rc = LWS_ITOSA_NOT_USABLE; + continue; +#endif + case AF_INET: #ifdef LWS_WITH_IPV6 if (ipv6) { @@ -619,20 +711,20 @@ lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr, default: continue; } - rc = 0; + rc = LWS_ITOSA_USABLE; } freeifaddrs(ifr); - if (rc == -1) { + if (rc) { /* check if bind to IP address */ #ifdef LWS_WITH_IPV6 if (inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1) - rc = 0; + rc = LWS_ITOSA_USABLE; else #endif if (inet_pton(AF_INET, ifname, &addr->sin_addr) == 1) - rc = 0; + rc = LWS_ITOSA_USABLE; } return rc; @@ -643,9 +735,8 @@ lws_plat_insert_socket_into_fds(struct lws_context *context, struct lws *wsi) { struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - lws_libev_io(wsi, LWS_EV_START | LWS_EV_READ); - lws_libuv_io(wsi, LWS_EV_START | LWS_EV_READ); - lws_libevent_io(wsi, LWS_EV_START | LWS_EV_READ); + if (context->event_loop_ops->io) + context->event_loop_ops->io(wsi, LWS_EV_START | LWS_EV_READ); pt->fds[pt->fds_count++].revents = 0; } @@ -656,9 +747,9 @@ lws_plat_delete_socket_from_fds(struct lws_context *context, { struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - lws_libev_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); - lws_libuv_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); - lws_libevent_io(wsi, LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); + if (context->event_loop_ops->io) + context->event_loop_ops->io(wsi, + LWS_EV_STOP | LWS_EV_READ | LWS_EV_WRITE); pt->fds_count--; } @@ -739,7 +830,8 @@ _lws_plat_file_seek_cur(lws_fop_fd_t fop_fd, lws_fileofs_t offset) { lws_fileofs_t r; - if (offset > 0 && offset > fop_fd->len - fop_fd->pos) + if (offset > 0 && + offset > (lws_fileofs_t)fop_fd->len - (lws_fileofs_t)fop_fd->pos) offset = fop_fd->len - fop_fd->pos; if ((lws_fileofs_t)fop_fd->pos + offset < 0) @@ -793,13 +885,11 @@ _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount, return 0; } - LWS_VISIBLE int lws_plat_init(struct lws_context *context, - struct lws_context_creation_info *info) + const struct lws_context_creation_info *info) { - struct lws_context_per_thread *pt = &context->pt[0]; - int n = context->count_threads, fd; + int fd; /* master context has the global fd lookup array */ context->lws_lookup = lws_zalloc(sizeof(struct lws *) * @@ -821,26 +911,6 @@ lws_plat_init(struct lws_context *context, return 1; } - if (!lws_libev_init_fd_table(context) && - !lws_libuv_init_fd_table(context) && - !lws_libevent_init_fd_table(context)) { - /* otherwise libev/uv/event handled it instead */ - - while (n--) { - if (pipe(pt->dummy_pipe_fds)) { - lwsl_err("Unable to create pipe\n"); - return 1; - } - - /* use the read end of pipe as first item */ - pt->fds[0].fd = pt->dummy_pipe_fds[0]; - pt->fds[0].events = LWS_POLLIN; - pt->fds[0].revents = 0; - pt->fds_count = 1; - pt++; - } - } - #ifdef LWS_WITH_PLUGINS if (info->plugin_dirs) lws_plat_plugins_init(context, info->plugin_dirs); @@ -848,3 +918,52 @@ lws_plat_init(struct lws_context *context, return 0; } + +LWS_VISIBLE int +lws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf, + int len) +{ + int n; + + n = write(fd, buf, len); + + fsync(fd); + lseek(fd, 0, SEEK_SET); + + return n != len; +} + +LWS_VISIBLE int +lws_plat_write_file(const char *filename, void *buf, int len) +{ + int m, fd; + + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); + + if (fd == -1) + return 1; + + m = write(fd, buf, len); + close(fd); + + return m != len; +} + +LWS_VISIBLE int +lws_plat_read_file(const char *filename, void *buf, int len) +{ + int n, fd = open(filename, O_RDONLY); + if (fd == -1) + return -1; + + n = read(fd, buf, len); + close(fd); + + return n; +} + +LWS_VISIBLE int +lws_plat_recommended_rsa_bits(void) +{ + return 4096; +} diff --git a/thirdparty/lws/plat/lws-plat-win.c b/thirdparty/libwebsockets/plat/lws-plat-win.c index f5b178ce85..948db62896 100644 --- a/thirdparty/lws/plat/lws-plat-win.c +++ b/thirdparty/libwebsockets/plat/lws-plat-win.c @@ -1,7 +1,34 @@ #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #endif -#include "private-libwebsockets.h" +#include "core/private.h" + +int +lws_plat_socket_offset(void) +{ + return 0; +} + +int +lws_plat_pipe_create(struct lws *wsi) +{ + return 1; +} + +int +lws_plat_pipe_signal(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + WSASetEvent(pt->events[0]); /* trigger the cancel event */ + + return 0; +} + +void +lws_plat_pipe_close(struct lws *wsi) +{ +} unsigned long long time_in_microseconds() @@ -19,9 +46,10 @@ time_in_microseconds() #endif /* - * As per Windows documentation for FILETIME, copy the resulting FILETIME structure to a - * ULARGE_INTEGER structure using memcpy (using memcpy instead of direct assignment can - * prevent alignment faults on 64-bit Windows). + * As per Windows documentation for FILETIME, copy the resulting + * FILETIME structure to a ULARGE_INTEGER structure using memcpy + * (using memcpy instead of direct assignment can prevent alignment + * faults on 64-bit Windows). */ memcpy(&datetime, &filetime, sizeof(datetime)); @@ -81,7 +109,7 @@ delete_from_fd(struct lws_context *context, lws_sockfd_type fd) if (context->fd_hashtable[h].wsi[n]->desc.sockfd == fd) { while (n < context->fd_hashtable[h].length) { context->fd_hashtable[h].wsi[n] = - context->fd_hashtable[h].wsi[n + 1]; + context->fd_hashtable[h].wsi[n + 1]; n++; } context->fd_hashtable[h].length--; @@ -94,8 +122,8 @@ delete_from_fd(struct lws_context *context, lws_sockfd_type fd) return 1; } -LWS_VISIBLE int lws_get_random(struct lws_context *context, - void *buf, int len) +LWS_VISIBLE int +lws_get_random(struct lws_context *context, void *buf, int len) { int n; char *p = (char *)buf; @@ -106,16 +134,25 @@ LWS_VISIBLE int lws_get_random(struct lws_context *context, return n; } -LWS_VISIBLE int lws_send_pipe_choked(struct lws *wsi) -{ +LWS_VISIBLE int +lws_send_pipe_choked(struct lws *wsi) +{ struct lws *wsi_eff = wsi; + +#if defined(LWS_WITH_HTTP2) + wsi_eff = lws_get_network_wsi(wsi); +#endif + /* the fact we checked implies we avoided back-to-back writes */ + wsi_eff->could_have_pending = 0; + /* treat the fact we got a truncated send pending as if we're choked */ - if (wsi->trunc_len) + if (wsi_eff->trunc_len) return 1; - return (int)wsi->sock_send_blocking; + return (int)wsi_eff->sock_send_blocking; } -LWS_VISIBLE int lws_poll_listen_fd(struct lws_pollfd *fd) +LWS_VISIBLE int +lws_poll_listen_fd(struct lws_pollfd *fd) { fd_set readfds; struct timeval tv = { 0, 0 }; @@ -125,29 +162,11 @@ LWS_VISIBLE int lws_poll_listen_fd(struct lws_pollfd *fd) FD_ZERO(&readfds); FD_SET(fd->fd, &readfds); - return select(fd->fd + 1, &readfds, NULL, NULL, &tv); + return select(((int)fd->fd) + 1, &readfds, NULL, NULL, &tv); } LWS_VISIBLE void -lws_cancel_service(struct lws_context *context) -{ - struct lws_context_per_thread *pt = &context->pt[0]; - int n = context->count_threads; - - while (n--) { - WSASetEvent(pt->events[0]); - pt++; - } -} - -LWS_VISIBLE void -lws_cancel_service_pt(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - WSASetEvent(pt->events[0]); -} - -LWS_VISIBLE void lwsl_emit_syslog(int level, const char *line) +lwsl_emit_syslog(int level, const char *line) { lwsl_emit_stderr(level, line); } @@ -182,9 +201,8 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) context->service_tid_detected = 1; } - if (timeout_ms < 0) - { - if (lws_service_flag_pending(context, tsi)) { + if (timeout_ms < 0) { + if (lws_service_flag_pending(context, tsi)) { /* any socket with events to service? */ for (n = 0; n < (int)pt->fds_count; n++) { if (!pt->fds[n].revents) @@ -201,6 +219,9 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) return 0; } + if (context->event_loop_ops->run_pt) + context->event_loop_ops->run_pt(context, tsi); + for (i = 0; i < pt->fds_count; ++i) { pfd = &pt->fds[i]; @@ -220,6 +241,9 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) if (n) i--; + /* + * any wsi has truncated, force him signalled + */ if (wsi->trunc_len) WSASetEvent(pt->events[0]); } @@ -236,29 +260,44 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) timeout_ms = 0; } - ev = WSAWaitForMultipleEvents( 1, pt->events , FALSE, timeout_ms, FALSE); + if (timeout_ms) { + lws_pt_lock(pt, __func__); + /* don't stay in poll wait longer than next hr timeout */ + lws_usec_t t = __lws_hrtimer_service(pt); + + if ((lws_usec_t)timeout_ms * 1000 > t) + timeout_ms = (int)(t / 1000); + lws_pt_unlock(pt); + } + + ev = WSAWaitForMultipleEvents(1, pt->events, FALSE, timeout_ms, FALSE); if (ev == WSA_WAIT_EVENT_0) { - unsigned int eIdx; + unsigned int eIdx, err; WSAResetEvent(pt->events[0]); + if (pt->context->tls_ops && + pt->context->tls_ops->fake_POLLIN_for_buffered) + pt->context->tls_ops->fake_POLLIN_for_buffered(pt); + for (eIdx = 0; eIdx < pt->fds_count; ++eIdx) { - if (WSAEnumNetworkEvents(pt->fds[eIdx].fd, 0, &networkevents) == SOCKET_ERROR) { - lwsl_err("WSAEnumNetworkEvents() failed with error %d\n", LWS_ERRNO); + if (WSAEnumNetworkEvents(pt->fds[eIdx].fd, 0, + &networkevents) == SOCKET_ERROR) { + lwsl_err("WSAEnumNetworkEvents() failed " + "with error %d\n", LWS_ERRNO); return -1; } pfd = &pt->fds[eIdx]; pfd->revents = (short)networkevents.lNetworkEvents; + err = networkevents.iErrorCode[FD_CONNECT_BIT]; + if ((networkevents.lNetworkEvents & FD_CONNECT) && - networkevents.iErrorCode[FD_CONNECT_BIT] && - networkevents.iErrorCode[FD_CONNECT_BIT] != LWS_EALREADY && - networkevents.iErrorCode[FD_CONNECT_BIT] != LWS_EINPROGRESS && - networkevents.iErrorCode[FD_CONNECT_BIT] != LWS_EWOULDBLOCK && - networkevents.iErrorCode[FD_CONNECT_BIT] != WSAEINVAL) { - lwsl_debug("Unable to connect errno=%d\n", - networkevents.iErrorCode[FD_CONNECT_BIT]); + err && err != LWS_EALREADY && + err != LWS_EINPROGRESS && err != LWS_EWOULDBLOCK && + err != WSAEINVAL) { + lwsl_debug("Unable to connect errno=%d\n", err); pfd->revents |= LWS_POLLHUP; } @@ -269,21 +308,19 @@ _lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi) } /* if something closed, retry this slot */ if (pfd->revents & LWS_POLLHUP) - --eIdx; + --eIdx; - if( pfd->revents != 0 ) { + if (pfd->revents) lws_service_fd_tsi(context, pfd, tsi); - - } } } context->service_tid = 0; - if (ev == WSA_WAIT_TIMEOUT) { + if (ev == WSA_WAIT_TIMEOUT) lws_service_fd(context, NULL); - } - return 0;; + + return 0; } LWS_VISIBLE int @@ -309,7 +346,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd) /* enable keepalive on this socket */ optval = 1; if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, - (const char *)&optval, optlen) < 0) + (const char *)&optval, optlen) < 0) return 1; alive.onoff = TRUE; @@ -317,7 +354,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd) alive.keepaliveinterval = vhost->ka_interval; if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), - NULL, 0, &dwBytesRet, NULL, NULL)) + NULL, 0, &dwBytesRet, NULL, NULL)) return 1; } @@ -343,7 +380,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd) } LWS_VISIBLE void -lws_plat_drop_app_privileges(struct lws_context_creation_info *info) +lws_plat_drop_app_privileges(const struct lws_context_creation_info *info) { } @@ -406,7 +443,7 @@ lws_interface_to_sa(int ipv6, if (ipv6) { if (lws_plat_inet_pton(AF_INET6, ifname, &addr6->sin6_addr) == 1) { - return 0; + return LWS_ITOSA_USABLE; } } #endif @@ -420,11 +457,11 @@ lws_interface_to_sa(int ipv6, } if (address == INADDR_NONE) - return -1; + return LWS_ITOSA_NOT_EXIST; - addr->sin_addr.s_addr = (lws_intptr_t)address; + addr->sin_addr.s_addr = (unsigned long)(lws_intptr_t)address; - return 0; + return LWS_ITOSA_USABLE; } LWS_VISIBLE void @@ -542,7 +579,7 @@ LWS_VISIBLE int lws_plat_inet_pton(int af, const char *src, void *dst) { WCHAR *buffer; - DWORD bufferlen = strlen(src) + 1; + DWORD bufferlen = (int)strlen(src) + 1; BOOL ok = FALSE; buffer = lws_malloc(bufferlen * 2, "inet_pton"); @@ -692,7 +729,7 @@ _lws_plat_file_write(lws_fop_fd_t fop_fd, lws_filepos_t *amount, LWS_VISIBLE int lws_plat_init(struct lws_context *context, - struct lws_context_creation_info *info) + const struct lws_context_creation_info *info) { struct lws_context_per_thread *pt = &context->pt[0]; int i, n = context->count_threads; @@ -715,7 +752,7 @@ lws_plat_init(struct lws_context *context, } pt->fds_count = 0; - pt->events[0] = WSACreateEvent(); + pt->events[0] = WSACreateEvent(); /* the cancel event */ pt++; } @@ -743,3 +780,50 @@ int fork(void) exit(0); } +LWS_VISIBLE int +lws_plat_write_cert(struct lws_vhost *vhost, int is_key, int fd, void *buf, + int len) +{ + int n; + + n = write(fd, buf, len); + + lseek(fd, 0, SEEK_SET); + + return n != len; +} + +LWS_VISIBLE int +lws_plat_write_file(const char *filename, void *buf, int len) +{ + int m, fd; + + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600); + + if (fd == -1) + return -1; + + m = write(fd, buf, len); + close(fd); + + return m != len; +} + +LWS_VISIBLE int +lws_plat_read_file(const char *filename, void *buf, int len) +{ + int n, fd = open(filename, O_RDONLY); + if (fd == -1) + return -1; + + n = read(fd, buf, len); + close(fd); + + return n; +} + +LWS_VISIBLE int +lws_plat_recommended_rsa_bits(void) +{ + return 4096; +} diff --git a/thirdparty/libwebsockets/roles/h1/ops-h1.c b/thirdparty/libwebsockets/roles/h1/ops-h1.c new file mode 100644 index 0000000000..d3b16f4d1f --- /dev/null +++ b/thirdparty/libwebsockets/roles/h1/ops-h1.c @@ -0,0 +1,687 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +#ifndef min +#define min(a, b) ((a) < (b) ? (a) : (b)) +#endif + + +/* + * We have to take care about parsing because the headers may be split + * into multiple fragments. They may contain unknown headers with arbitrary + * argument lengths. So, we parse using a single-character at a time state + * machine that is completely independent of packet size. + * + * Returns <0 for error or length of chars consumed from buf (up to len) + */ + +int +lws_read_h1(struct lws *wsi, unsigned char *buf, lws_filepos_t len) +{ + unsigned char *last_char, *oldbuf = buf; + lws_filepos_t body_chunk_len; + size_t n; + + // lwsl_notice("%s: h1 path: wsi state 0x%x\n", __func__, lwsi_state(wsi)); + + switch (lwsi_state(wsi)) { + + case LRS_ISSUING_FILE: + return 0; + + case LRS_ESTABLISHED: + + if (lwsi_role_ws(wsi)) + goto ws_mode; + + if (lwsi_role_client(wsi)) + break; + + wsi->hdr_parsing_completed = 0; + + /* fallthru */ + + case LRS_HEADERS: + if (!wsi->http.ah) { + lwsl_err("%s: LRS_HEADERS: NULL ah\n", __func__); + assert(0); + } + lwsl_parser("issuing %d bytes to parser\n", (int)len); +#if defined(LWS_ROLE_WS) && !defined(LWS_NO_CLIENT) + if (lws_ws_handshake_client(wsi, &buf, (size_t)len)) + goto bail; +#endif + last_char = buf; + if (lws_handshake_server(wsi, &buf, (size_t)len)) + /* Handshake indicates this session is done. */ + goto bail; + + /* we might have transitioned to RAW */ + if (wsi->role_ops == &role_ops_raw_skt || + wsi->role_ops == &role_ops_raw_file) + /* we gave the read buffer to RAW handler already */ + goto read_ok; + + /* + * It's possible that we've exhausted our data already, or + * rx flow control has stopped us dealing with this early, + * but lws_handshake_server doesn't update len for us. + * Figure out how much was read, so that we can proceed + * appropriately: + */ + len -= (buf - last_char); +// lwsl_debug("%s: thinks we have used %ld\n", __func__, (long)len); + + if (!wsi->hdr_parsing_completed) + /* More header content on the way */ + goto read_ok; + + switch (lwsi_state(wsi)) { + case LRS_ESTABLISHED: + case LRS_HEADERS: + goto read_ok; + case LRS_ISSUING_FILE: + goto read_ok; + case LRS_BODY: + wsi->http.rx_content_remain = + wsi->http.rx_content_length; + if (wsi->http.rx_content_remain) + goto http_postbody; + + /* there is no POST content */ + goto postbody_completion; + default: + break; + } + break; + + case LRS_BODY: +http_postbody: + lwsl_debug("%s: http post body: remain %d\n", __func__, + (int)wsi->http.rx_content_remain); + while (len && wsi->http.rx_content_remain) { + /* Copy as much as possible, up to the limit of: + * what we have in the read buffer (len) + * remaining portion of the POST body (content_remain) + */ + body_chunk_len = min(wsi->http.rx_content_remain, len); + wsi->http.rx_content_remain -= body_chunk_len; + len -= body_chunk_len; +#ifdef LWS_WITH_CGI + if (wsi->http.cgi) { + struct lws_cgi_args args; + + args.ch = LWS_STDIN; + args.stdwsi = &wsi->http.cgi->stdwsi[0]; + args.data = buf; + args.len = body_chunk_len; + + /* returns how much used */ + n = user_callback_handle_rxflow( + wsi->protocol->callback, + wsi, LWS_CALLBACK_CGI_STDIN_DATA, + wsi->user_space, + (void *)&args, 0); + if ((int)n < 0) + goto bail; + } else { +#endif + n = wsi->protocol->callback(wsi, + LWS_CALLBACK_HTTP_BODY, wsi->user_space, + buf, (size_t)body_chunk_len); + if (n) + goto bail; + n = (size_t)body_chunk_len; +#ifdef LWS_WITH_CGI + } +#endif + buf += n; + + if (wsi->http.rx_content_remain) { + lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, + wsi->context->timeout_secs); + break; + } + /* he sent all the content in time */ +postbody_completion: +#ifdef LWS_WITH_CGI + /* + * If we're running a cgi, we can't let him off the + * hook just because he sent his POST data + */ + if (wsi->http.cgi) + lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, + wsi->context->timeout_secs); + else +#endif + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); +#ifdef LWS_WITH_CGI + if (!wsi->http.cgi) +#endif + { + lwsl_info("HTTP_BODY_COMPLETION: %p (%s)\n", + wsi, wsi->protocol->name); + n = wsi->protocol->callback(wsi, + LWS_CALLBACK_HTTP_BODY_COMPLETION, + wsi->user_space, NULL, 0); + if (n) + goto bail; + + if (wsi->http2_substream) + lwsi_set_state(wsi, LRS_ESTABLISHED); + } + + break; + } + break; + + case LRS_AWAITING_CLOSE_ACK: + case LRS_WAITING_TO_SEND_CLOSE: + case LRS_SHUTDOWN: + +ws_mode: +#if !defined(LWS_NO_CLIENT) && defined(LWS_ROLE_WS) + // lwsl_notice("%s: ws_mode\n", __func__); + if (lws_ws_handshake_client(wsi, &buf, (size_t)len)) + goto bail; +#endif +#if defined(LWS_ROLE_WS) + if (lwsi_role_ws(wsi) && lwsi_role_server(wsi) && + /* + * for h2 we are on the swsi + */ + lws_parse_ws(wsi, &buf, (size_t)len) < 0) { + lwsl_info("%s: lws_parse_ws bailed\n", __func__); + goto bail; + } +#endif + // lwsl_notice("%s: ws_mode: buf moved on by %d\n", __func__, + // lws_ptr_diff(buf, oldbuf)); + break; + + case LRS_DEFERRING_ACTION: + lwsl_debug("%s: LRS_DEFERRING_ACTION\n", __func__); + break; + + case LRS_SSL_ACK_PENDING: + break; + + case LRS_DEAD_SOCKET: + lwsl_err("%s: Unhandled state LRS_DEAD_SOCKET\n", __func__); + goto bail; + // assert(0); + /* fallthru */ + + default: + lwsl_err("%s: Unhandled state %d\n", __func__, lwsi_state(wsi)); + assert(0); + goto bail; + } + +read_ok: + /* Nothing more to do for now */ +// lwsl_info("%s: %p: read_ok, used %ld (len %d, state %d)\n", __func__, +// wsi, (long)(buf - oldbuf), (int)len, wsi->state); + + return lws_ptr_diff(buf, oldbuf); + +bail: + /* + * h2 / h2-ws calls us recursively in + * + * lws_read_h1()-> + * lws_h2_parser()-> + * lws_read_h1() + * + * pattern, having stripped the h2 framing in the middle. + * + * When taking down the whole connection, make sure that only the + * outer lws_read() does the wsi close. + */ + if (!wsi->outer_will_close) + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "lws_read_h1 bail"); + + return -1; +} +#if !defined(LWS_NO_SERVER) +static int +lws_h1_server_socket_service(struct lws *wsi, struct lws_pollfd *pollfd) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct lws_tokens ebuf; + int n, buffered; + + if (lwsi_state(wsi) == LRS_DEFERRING_ACTION) + goto try_pollout; + + /* any incoming data ready? */ + + if (!(pollfd->revents & pollfd->events & LWS_POLLIN)) + goto try_pollout; + + /* + * If we previously just did POLLIN when IN and OUT were signaled + * (because POLLIN processing may have used up the POLLOUT), don't let + * that happen twice in a row... next time we see the situation favour + * POLLOUT + */ + + if (wsi->favoured_pollin && + (pollfd->revents & pollfd->events & LWS_POLLOUT)) { + // lwsl_notice("favouring pollout\n"); + wsi->favoured_pollin = 0; + goto try_pollout; + } + + /* + * We haven't processed that the tunnel is set up yet, so + * defer reading + */ + + if (lwsi_state(wsi) == LRS_SSL_ACK_PENDING) + return LWS_HPI_RET_HANDLED; + + /* these states imply we MUST have an ah attached */ + + if ((lwsi_state(wsi) == LRS_ESTABLISHED || + lwsi_state(wsi) == LRS_ISSUING_FILE || + lwsi_state(wsi) == LRS_HEADERS || + lwsi_state(wsi) == LRS_BODY)) { + + if (!wsi->http.ah && lws_header_table_attach(wsi, 0)) { + lwsl_info("%s: wsi %p: ah not available\n", __func__, wsi); + goto try_pollout; + } + + /* + * We got here because there was specifically POLLIN... + * regardless of our buflist state, we need to get it, + * and either use it, or append to the buflist and use + * buflist head material. + * + * We will not notice a connection close until the buflist is + * exhausted and we tried to do a read of some kind. + */ + + buffered = lws_buflist_aware_read(pt, wsi, &ebuf); + switch (ebuf.len) { + case 0: + lwsl_info("%s: read 0 len a\n", __func__); + wsi->seen_zero_length_recv = 1; + lws_change_pollfd(wsi, LWS_POLLIN, 0); +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* + * autobahn requires us to win the race between close + * and draining the extensions + */ + if (wsi->ws && + (wsi->ws->rx_draining_ext || wsi->ws->tx_draining_ext)) + goto try_pollout; +#endif + /* + * normally, we respond to close with logically closing + * our side immediately + */ + goto fail; + + case LWS_SSL_CAPABLE_ERROR: + goto fail; + case LWS_SSL_CAPABLE_MORE_SERVICE: + goto try_pollout; + } + + /* just ignore incoming if waiting for close */ + if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) { + lwsl_notice("%s: just ignoring\n", __func__); + goto try_pollout; + } + + if (lwsi_state(wsi) == LRS_ISSUING_FILE) { + // lwsl_notice("stashing: wsi %p: bd %d\n", wsi, buffered); + if (lws_buflist_aware_consume(wsi, &ebuf, 0, buffered)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + + goto try_pollout; + } + + /* + * Otherwise give it to whoever wants it according to the + * connection state + */ +#if defined(LWS_ROLE_H2) + if (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY) + n = lws_read_h2(wsi, (uint8_t *)ebuf.token, ebuf.len); + else +#endif + n = lws_read_h1(wsi, (uint8_t *)ebuf.token, ebuf.len); + if (n < 0) /* we closed wsi */ + return LWS_HPI_RET_WSI_ALREADY_DIED; + + lwsl_debug("%s: consumed %d\n", __func__, n); + + if (lws_buflist_aware_consume(wsi, &ebuf, n, buffered)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + + /* + * during the parsing our role changed to something non-http, + * so the ah has no further meaning + */ + + if (wsi->http.ah && + !lwsi_role_h1(wsi) && + !lwsi_role_h2(wsi) && + !lwsi_role_cgi(wsi)) + lws_header_table_detach(wsi, 0); + + /* + * He may have used up the writability above, if we will defer + * POLLOUT processing in favour of POLLIN, note it + */ + + if (pollfd->revents & LWS_POLLOUT) + wsi->favoured_pollin = 1; + + return LWS_HPI_RET_HANDLED; + } + + /* + * He may have used up the writability above, if we will defer POLLOUT + * processing in favour of POLLIN, note it + */ + + if (pollfd->revents & LWS_POLLOUT) + wsi->favoured_pollin = 1; + +try_pollout: + + /* this handles POLLOUT for http serving fragments */ + + if (!(pollfd->revents & LWS_POLLOUT)) + return LWS_HPI_RET_HANDLED; + + /* one shot */ + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_notice("%s a\n", __func__); + goto fail; + } + + /* clear back-to-back write detection */ + wsi->could_have_pending = 0; + + if (lwsi_state(wsi) == LRS_DEFERRING_ACTION) { + lwsl_debug("%s: LRS_DEFERRING_ACTION now writable\n", __func__); + + lwsi_set_state(wsi, LRS_ESTABLISHED); + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_info("failed at set pollfd\n"); + goto fail; + } + } + + if (!wsi->hdr_parsing_completed) + return LWS_HPI_RET_HANDLED; + + if (lwsi_state(wsi) != LRS_ISSUING_FILE) { + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_WRITEABLE_CB, 1); +#if defined(LWS_WITH_STATS) + if (wsi->active_writable_req_us) { + uint64_t ul = time_in_microseconds() - + wsi->active_writable_req_us; + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_MS_WRITABLE_DELAY, ul); + lws_stats_atomic_max(wsi->context, pt, + LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); + wsi->active_writable_req_us = 0; + } +#endif + + n = user_callback_handle_rxflow(wsi->protocol->callback, wsi, + LWS_CALLBACK_HTTP_WRITEABLE, + wsi->user_space, NULL, 0); + if (n < 0) { + lwsl_info("writeable_fail\n"); + goto fail; + } + + return LWS_HPI_RET_HANDLED; + } + + /* >0 == completion, <0 == error + * + * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when + * it's done. That's the case even if we just completed the + * send, so wait for that. + */ + n = lws_serve_http_file_fragment(wsi); + if (n < 0) + goto fail; + + return LWS_HPI_RET_HANDLED; + + +fail: + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, + "server socket svc fail"); + + return LWS_HPI_RET_WSI_ALREADY_DIED; +} +#endif + +static int +rops_handle_POLLIN_h1(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ + +// lwsl_notice("%s: %p: wsistate 0x%x %s, revents 0x%x\n", __func__, wsi, +// wsi->wsistate, wsi->role_ops->name, pollfd->revents); + +#ifdef LWS_WITH_CGI + if (wsi->http.cgi && (pollfd->revents & LWS_POLLOUT)) { + if (lws_handle_POLLOUT_event(wsi, pollfd)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + + return LWS_HPI_RET_HANDLED; + } +#endif + + if (lws_is_flowcontrolled(wsi)) + /* We cannot deal with any kind of new RX because we are + * RX-flowcontrolled. + */ + return LWS_HPI_RET_HANDLED; + +#if !defined(LWS_NO_SERVER) + if (!lwsi_role_client(wsi)) { + int n; + + lwsl_debug("%s: %p: wsistate 0x%x\n", __func__, wsi, wsi->wsistate); + n = lws_h1_server_socket_service(wsi, pollfd); + if (n != LWS_HPI_RET_HANDLED) + return n; + if (lwsi_state(wsi) != LRS_SSL_INIT) + if (lws_server_socket_service_ssl(wsi, LWS_SOCK_INVALID)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + + return LWS_HPI_RET_HANDLED; + } +#endif + +#ifndef LWS_NO_CLIENT + if ((pollfd->revents & LWS_POLLIN) && + wsi->hdr_parsing_completed && !wsi->told_user_closed) { + + /* + * In SSL mode we get POLLIN notification about + * encrypted data in. + * + * But that is not necessarily related to decrypted + * data out becoming available; in may need to perform + * other in or out before that happens. + * + * simply mark ourselves as having readable data + * and turn off our POLLIN + */ + wsi->client_rx_avail = 1; + lws_change_pollfd(wsi, LWS_POLLIN, 0); + + //lwsl_notice("calling back %s\n", wsi->protocol->name); + + /* let user code know, he'll usually ask for writeable + * callback and drain / re-enable it there + */ + if (user_callback_handle_rxflow( + wsi->protocol->callback, + wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP, + wsi->user_space, NULL, 0)) { + lwsl_info("RECEIVE_CLIENT_HTTP closed it\n"); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + return LWS_HPI_RET_HANDLED; + } +#endif + +// if (lwsi_state(wsi) == LRS_ESTABLISHED) +// return LWS_HPI_RET_HANDLED; + +#if !defined(LWS_NO_CLIENT) + if ((pollfd->revents & LWS_POLLOUT) && + lws_handle_POLLOUT_event(wsi, pollfd)) { + lwsl_debug("POLLOUT event closed it\n"); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + if (lws_client_socket_service(wsi, pollfd, NULL)) + return LWS_HPI_RET_WSI_ALREADY_DIED; +#endif + + return LWS_HPI_RET_HANDLED; +} + +int rops_handle_POLLOUT_h1(struct lws *wsi) +{ + if (lwsi_state(wsi) == LRS_ISSUE_HTTP_BODY) + return LWS_HP_RET_USER_SERVICE; + + if (lwsi_role_client(wsi)) + return LWS_HP_RET_USER_SERVICE; + + return LWS_HP_RET_BAIL_OK; +} + +static int +rops_write_role_protocol_h1(struct lws *wsi, unsigned char *buf, size_t len, + enum lws_write_protocol *wp) +{ +#if 0 + /* if not in a state to send stuff, then just send nothing */ + + if ((lwsi_state(wsi) != LRS_RETURNED_CLOSE && + lwsi_state(wsi) != LRS_WAITING_TO_SEND_CLOSE && + lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK)) { + //assert(0); + lwsl_debug("binning %d %d\n", lwsi_state(wsi), *wp); + return 0; + } +#endif + + return lws_issue_raw(wsi, (unsigned char *)buf, len); +} + +static int +rops_alpn_negotiated_h1(struct lws *wsi, const char *alpn) +{ + lwsl_debug("%s: client %d\n", __func__, lwsi_role_client(wsi)); +#if !defined(LWS_NO_CLIENT) + if (lwsi_role_client(wsi)) { + /* + * If alpn asserts it is http/1.1, server support for KA is + * mandatory. + * + * Knowing this lets us proceed with sending pipelined headers + * before we received the first response headers. + */ + wsi->keepalive_active = 1; + } +#endif + + return 0; +} + +static int +rops_destroy_role_h1(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct allocated_headers *ah; + + /* we may not have an ah, but may be on the waiting list... */ + lwsl_info("%s: ah det due to close\n", __func__); + __lws_header_table_detach(wsi, 0); + + ah = pt->http.ah_list; + + while (ah) { + if (ah->in_use && ah->wsi == wsi) { + lwsl_err("%s: ah leak: wsi %p\n", __func__, wsi); + ah->in_use = 0; + ah->wsi = NULL; + pt->http.ah_count_in_use--; + break; + } + ah = ah->next; + } + + return 0; +} + +struct lws_role_ops role_ops_h1 = { + /* role name */ "h1", + /* alpn id */ "http/1.1", + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ NULL, + /* destroy_vhost */ NULL, + /* periodic_checks */ NULL, + /* service_flag_pending */ NULL, + /* handle_POLLIN */ rops_handle_POLLIN_h1, + /* handle_POLLOUT */ rops_handle_POLLOUT_h1, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ NULL, + /* tx_credit */ NULL, + /* write_role_protocol */ rops_write_role_protocol_h1, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ rops_alpn_negotiated_h1, + /* close_via_role_protocol */ NULL, + /* close_role */ NULL, + /* close_kill_connection */ NULL, + /* destroy_role */ rops_destroy_role_h1, + /* writeable cb clnt, srv */ { LWS_CALLBACK_CLIENT_HTTP_WRITEABLE, + LWS_CALLBACK_HTTP_WRITEABLE }, + /* close cb clnt, srv */ { LWS_CALLBACK_CLOSED_CLIENT_HTTP, + LWS_CALLBACK_CLOSED_HTTP }, + /* file_handle */ 0, +}; diff --git a/thirdparty/libwebsockets/roles/h1/private.h b/thirdparty/libwebsockets/roles/h1/private.h new file mode 100644 index 0000000000..3f53954d33 --- /dev/null +++ b/thirdparty/libwebsockets/roles/h1/private.h @@ -0,0 +1,27 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h if LWS_ROLE_H1 + * + * Most of the h1 business is defined in the h1 / h2 common roles/http dir + */ + +extern struct lws_role_ops role_ops_h1; +#define lwsi_role_h1(wsi) (wsi->role_ops == &role_ops_h1) diff --git a/thirdparty/lws/client/client-handshake.c b/thirdparty/libwebsockets/roles/http/client/client-handshake.c index c2720d9283..4830fc9eca 100644 --- a/thirdparty/lws/client/client-handshake.c +++ b/thirdparty/libwebsockets/roles/http/client/client-handshake.c @@ -1,4 +1,4 @@ -#include "private-libwebsockets.h" +#include "core/private.h" static int lws_getaddrinfo46(struct lws *wsi, const char *ads, struct addrinfo **result) @@ -20,7 +20,6 @@ lws_getaddrinfo46(struct lws *wsi, const char *ads, struct addrinfo **result) { hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; - hints.ai_flags = AI_CANONNAME; } return getaddrinfo(ads, NULL, &hints, result); @@ -29,15 +28,20 @@ lws_getaddrinfo46(struct lws *wsi, const char *ads, struct addrinfo **result) struct lws * lws_client_connect_2(struct lws *wsi) { - sockaddr46 sa46; - struct addrinfo *result; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + const char *adsin; + struct lws *wsi_piggyback = NULL; struct lws_pollfd pfd; - const char *cce = "", *iface; - int n, port; ssize_t plen = 0; +#endif + struct addrinfo *result; const char *ads; + sockaddr46 sa46; + int n, port; + const char *cce = "", *iface; + const char *meth = NULL; #ifdef LWS_WITH_IPV6 char ipv6only = lws_check_opt(wsi->vhost->options, LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY | @@ -48,24 +52,148 @@ lws_client_connect_2(struct lws *wsi) #endif #endif - lwsl_client("%s\n", __func__); + lwsl_client("%s: %p\n", __func__, wsi); - if (!wsi->u.hdr.ah) { +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + if (!wsi->http.ah) { cce = "ah was NULL at cc2"; lwsl_err("%s\n", cce); goto oom4; } + /* we can only piggyback GET or POST */ + + meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD); + if (meth && strcmp(meth, "GET") && strcmp(meth, "POST")) + goto create_new_conn; + + /* we only pipeline connections that said it was okay */ + + if (!wsi->client_pipeline) + goto create_new_conn; + + /* + * let's take a look first and see if there are any already-active + * client connections we can piggy-back on. + */ + + adsin = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS); + + lws_vhost_lock(wsi->vhost); /* ----------------------------------- { */ + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + wsi->vhost->dll_active_client_conns.next) { + struct lws *w = lws_container_of(d, struct lws, + dll_active_client_conns); + + lwsl_debug("%s: check %s %s %d %d\n", __func__, adsin, + w->client_hostname_copy, wsi->c_port, w->c_port); + + if (w != wsi && w->client_hostname_copy && + !strcmp(adsin, w->client_hostname_copy) && +#if defined(LWS_WITH_TLS) + (wsi->tls.use_ssl & LCCSCF_USE_SSL) == + (w->tls.use_ssl & LCCSCF_USE_SSL) && +#endif + wsi->c_port == w->c_port) { + + /* someone else is already connected to the right guy */ + + /* do we know for a fact pipelining won't fly? */ + if (w->keepalive_rejected) { + lwsl_info("defeating pipelining due to no " + "keepalive on server\n"); + lws_vhost_unlock(wsi->vhost); /* } ---------- */ + goto create_new_conn; + } +#if defined (LWS_WITH_HTTP2) + /* + * h2: in usable state already: just use it without + * going through the queue + */ + if (w->client_h2_alpn && + (lwsi_state(w) == LRS_H2_WAITING_TO_SEND_HEADERS || + lwsi_state(w) == LRS_ESTABLISHED)) { + + lwsl_info("%s: just join h2 directly\n", + __func__); + + wsi->client_h2_alpn = 1; + lws_wsi_h2_adopt(w, wsi); + lws_vhost_unlock(wsi->vhost); /* } ---------- */ + + return wsi; + } +#endif + + lwsl_info("applying %p to txn queue on %p (wsistate 0x%x)\n", + wsi, w, w->wsistate); + /* + * ...let's add ourselves to his transaction queue... + * we are adding ourselves at the HEAD + */ + lws_dll_lws_add_front(&wsi->dll_client_transaction_queue, + &w->dll_client_transaction_queue_head); + + /* + * h1: pipeline our headers out on him, + * and wait for our turn at client transaction_complete + * to take over parsing the rx. + */ + + wsi_piggyback = w; + + lws_vhost_unlock(wsi->vhost); /* } ---------- */ + goto send_hs; + } + + } lws_end_foreach_dll_safe(d, d1); + + lws_vhost_unlock(wsi->vhost); /* } ---------------------------------- */ + +create_new_conn: +#endif + + /* + * clients who will create their own fresh connection keep a copy of + * the hostname they originally connected to, in case other connections + * want to use it too + */ + + if (!wsi->client_hostname_copy) + wsi->client_hostname_copy = + strdup(lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_PEER_ADDRESS)); + + /* + * If we made our own connection, and we're doing a method that can take + * a pipeline, we are an "active client connection". + * + * Add ourselves to the vhost list of those so that others can + * piggyback on our transaction queue + */ + + if (meth && (!strcmp(meth, "GET") || !strcmp(meth, "POST")) && + lws_dll_is_null(&wsi->dll_client_transaction_queue) && + lws_dll_is_null(&wsi->dll_active_client_conns)) { + lws_vhost_lock(wsi->vhost); + lws_dll_lws_add_front(&wsi->dll_active_client_conns, + &wsi->vhost->dll_active_client_conns); + lws_vhost_unlock(wsi->vhost); + } + /* * start off allowing ipv6 on connection if vhost allows it */ wsi->ipv6 = LWS_IPV6_ENABLED(wsi->vhost); +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + /* Decide what it is we need to connect to: * * Priority 1: connect to http proxy */ - if (wsi->vhost->http_proxy_port) { + if (wsi->vhost->http.http_proxy_port) { plen = sprintf((char *)pt->serv_buf, "CONNECT %s:%u HTTP/1.0\x0d\x0a" "User-agent: libwebsockets\x0d\x0a", @@ -78,8 +206,11 @@ lws_client_connect_2(struct lws *wsi) wsi->vhost->proxy_basic_auth_token); plen += sprintf((char *)pt->serv_buf + plen, "\x0d\x0a"); - ads = wsi->vhost->http_proxy_address; - port = wsi->vhost->http_proxy_port; + ads = wsi->vhost->http.http_proxy_address; + port = wsi->vhost->http.http_proxy_port; +#else + if (0) { +#endif #if defined(LWS_WITH_SOCKS5) @@ -104,12 +235,14 @@ lws_client_connect_2(struct lws *wsi) * to whatever we decided to connect to */ - lwsl_notice("%s: %p: address %s\n", __func__, wsi, ads); + lwsl_info("%s: %p: address %s\n", __func__, wsi, ads); n = lws_getaddrinfo46(wsi, ads, &result); #ifdef LWS_WITH_IPV6 if (wsi->ipv6) { + struct sockaddr_in6 *sa6 = + ((struct sockaddr_in6 *)result->ai_addr); if (n) { /* lws_getaddrinfo46 failed, there is no usable result */ @@ -138,11 +271,10 @@ lws_client_connect_2(struct lws *wsi) break; case AF_INET6: - memcpy(&sa46.sa6.sin6_addr, - &((struct sockaddr_in6 *)result->ai_addr)->sin6_addr, + memcpy(&sa46.sa6.sin6_addr, &sa6->sin6_addr, sizeof(struct in6_addr)); - sa46.sa6.sin6_scope_id = ((struct sockaddr_in6 *)result->ai_addr)->sin6_scope_id; - sa46.sa6.sin6_flowinfo = ((struct sockaddr_in6 *)result->ai_addr)->sin6_flowinfo; + sa46.sa6.sin6_scope_id = sa6->sin6_scope_id; + sa46.sa6.sin6_flowinfo = sa6->sin6_flowinfo; break; default: lwsl_err("Unknown address family\n"); @@ -211,14 +343,11 @@ lws_client_connect_2(struct lws *wsi) if (!lws_socket_is_valid(wsi->desc.sockfd)) { -#if defined(LWS_WITH_LIBUV) - if (LWS_LIBUV_ENABLED(context)) - if (lws_libuv_check_watcher_active(wsi)) { - lwsl_warn("Waiting for libuv watcher to close\n"); - cce = "waiting for libuv watcher to close"; - goto oom4; - } -#endif + if (wsi->context->event_loop_ops->check_client_connect_ok && + wsi->context->event_loop_ops->check_client_connect_ok(wsi)) { + cce = "waiting for event loop watcher to close"; + goto oom4; + } #ifdef LWS_WITH_IPV6 if (wsi->ipv6) @@ -240,13 +369,12 @@ lws_client_connect_2(struct lws *wsi) goto oom4; } - wsi->mode = LWSCM_WSCL_WAITING_CONNECT; + lwsi_set_state(wsi, LRS_WAITING_CONNECT); - lws_libev_accept(wsi, wsi->desc); - lws_libuv_accept(wsi, wsi->desc); - lws_libevent_accept(wsi, wsi->desc); + if (wsi->context->event_loop_ops->accept) + wsi->context->event_loop_ops->accept(wsi); - if (insert_wsi_socket_into_fds(context, wsi)) { + if (__insert_wsi_socket_into_fds(wsi->context, wsi)) { compatible_close(wsi->desc.sockfd); cce = "insert wsi failed"; goto oom4; @@ -328,10 +456,11 @@ lws_client_connect_2(struct lws *wsi) lwsl_client("connected\n"); +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) /* we are connected to server, or proxy */ /* http proxy */ - if (wsi->vhost->http_proxy_port) { + if (wsi->vhost->http.http_proxy_port) { /* * OK from now on we talk via the proxy, so connect to that @@ -340,11 +469,11 @@ lws_client_connect_2(struct lws *wsi) * leaving old string/frag there but unreferenced) */ if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, - wsi->vhost->http_proxy_address)) + wsi->vhost->http.http_proxy_address)) goto failed; - wsi->c_port = wsi->vhost->http_proxy_port; + wsi->c_port = wsi->vhost->http.http_proxy_port; - n = send(wsi->desc.sockfd, (char *)pt->serv_buf, plen, + n = send(wsi->desc.sockfd, (char *)pt->serv_buf, (int)plen, MSG_NOSIGNAL); if (n < 0) { lwsl_debug("ERROR writing to proxy socket\n"); @@ -355,10 +484,11 @@ lws_client_connect_2(struct lws *wsi) lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE, AWAITING_TIMEOUT); - wsi->mode = LWSCM_WSCL_WAITING_PROXY_REPLY; + lwsi_set_state(wsi, LRS_WAITING_PROXY_REPLY); return wsi; } +#endif #if defined(LWS_WITH_SOCKS5) /* socks proxy */ else if (wsi->vhost->socks_proxy_port) { @@ -373,72 +503,105 @@ lws_client_connect_2(struct lws *wsi) lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY, AWAITING_TIMEOUT); - wsi->mode = LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY; + lwsi_set_state(wsi, LRS_WAITING_SOCKS_GREETING_REPLY); return wsi; } #endif +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) +send_hs: - /* - * provoke service to issue the handshake directly - * we need to do it this way because in the proxy case, this is the - * next state and executed only if and when we get a good proxy - * response inside the state machine... but notice in SSL case this - * may not have sent anything yet with 0 return, and won't until some - * many retries from main loop. To stop that becoming endless, - * cover with a timeout. - */ + if (wsi_piggyback && + !lws_dll_is_null(&wsi->dll_client_transaction_queue)) { + /* + * We are pipelining on an already-established connection... + * we can skip tls establishment. + */ + + lwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE2); + + /* + * we can't send our headers directly, because they have to + * be sent when the parent is writeable. The parent will check + * for anybody on his client transaction queue that is in + * LRS_H1C_ISSUE_HANDSHAKE2, and let them write. + * + * If we are trying to do this too early, before the master + * connection has written his own headers, then it will just + * wait in the queue until it's possible to send them. + */ + lws_callback_on_writable(wsi_piggyback); + lwsl_info("%s: wsi %p: waiting to send headers (parent state %x)\n", + __func__, wsi, lwsi_state(wsi_piggyback)); + } else { + lwsl_info("%s: wsi %p: client creating own connection\n", + __func__, wsi); - lws_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, - AWAITING_TIMEOUT); + /* we are making our own connection */ + lwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE); + + /* + * provoke service to issue the handshake directly. + * + * we need to do it this way because in the proxy case, this is + * the next state and executed only if and when we get a good + * proxy response inside the state machine... but notice in + * SSL case this may not have sent anything yet with 0 return, + * and won't until many retries from main loop. To stop that + * becoming endless, cover with a timeout. + */ - wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE; - pfd.fd = wsi->desc.sockfd; - pfd.events = LWS_POLLIN; - pfd.revents = LWS_POLLIN; + lws_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, + AWAITING_TIMEOUT); - n = lws_service_fd(context, &pfd); - if (n < 0) { - cce = "first service failed"; - goto failed; - } - if (n) /* returns 1 on failure after closing wsi */ - return NULL; + pfd.fd = wsi->desc.sockfd; + pfd.events = LWS_POLLIN; + pfd.revents = LWS_POLLIN; + n = lws_service_fd(context, &pfd); + if (n < 0) { + cce = "first service failed"; + goto failed; + } + if (n) /* returns 1 on failure after closing wsi */ + return NULL; + } +#endif return wsi; oom4: - /* we're closing, losing some rx is OK */ - lws_header_table_force_to_detachable_state(wsi); - - if (wsi->mode == LWSCM_HTTP_CLIENT || - wsi->mode == LWSCM_HTTP_CLIENT_ACCEPTED || - wsi->mode == LWSCM_WSCL_WAITING_CONNECT) { - wsi->vhost->protocols[0].callback(wsi, + if (lwsi_role_client(wsi) && lwsi_state_est(wsi)) { + wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, (void *)cce, strlen(cce)); wsi->already_did_cce = 1; } /* take care that we might be inserted in fds already */ - if (wsi->position_in_fds_table != -1) + if (wsi->position_in_fds_table != LWS_NO_FDS_POS) goto failed1; lws_remove_from_timeout_list(wsi); +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) lws_header_table_detach(wsi, 0); +#endif + lws_client_stash_destroy(wsi); + lws_free_set_NULL(wsi->client_hostname_copy); lws_free(wsi); return NULL; failed: - wsi->vhost->protocols[0].callback(wsi, + wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, (void *)cce, strlen(cce)); wsi->already_did_cce = 1; failed1: - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "client_connect2"); return NULL; } +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + /** * lws_client_reset() - retarget a connected wsi to start over with a new connection (ie, redirect) * this only works if still in HTTP, ie, not upgraded yet @@ -452,7 +615,8 @@ LWS_VISIBLE struct lws * lws_client_reset(struct lws **pwsi, int ssl, const char *address, int port, const char *path, const char *host) { - char origin[300] = "", protocol[300] = "", method[32] = "", iface[16] = "", *p; + char origin[300] = "", protocol[300] = "", method[32] = "", + iface[16] = "", alpn[32] = "", *p; struct lws *wsi = *pwsi; if (wsi->redirects == 3) { @@ -463,49 +627,42 @@ lws_client_reset(struct lws **pwsi, int ssl, const char *address, int port, p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN); if (p) - strncpy(origin, p, sizeof(origin) - 1); + lws_strncpy(origin, p, sizeof(origin)); p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); if (p) - strncpy(protocol, p, sizeof(protocol) - 1); + lws_strncpy(protocol, p, sizeof(protocol)); p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD); if (p) - strncpy(method, p, sizeof(method) - 1); + lws_strncpy(method, p, sizeof(method)); p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_IFACE); if (p) - strncpy(method, p, sizeof(iface) - 1); + lws_strncpy(iface, p, sizeof(iface)); + + p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ALPN); + if (p) + lws_strncpy(alpn, p, sizeof(alpn)); lwsl_info("redirect ads='%s', port=%d, path='%s', ssl = %d\n", address, port, path, ssl); /* close the connection by hand */ -#ifdef LWS_OPENSSL_SUPPORT +#if defined(LWS_WITH_TLS) lws_ssl_close(wsi); #endif -#ifdef LWS_WITH_LIBUV - if (LWS_LIBUV_ENABLED(wsi->context)) { - lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi); - /* - * libuv has to do his own close handle processing asynchronously - * but once it starts we can do everything else synchronously, - * including trash wsi->desc.sockfd since it took a copy. - * - * When it completes it will call compatible_close() - */ - lws_libuv_closehandle_manually(wsi); - } else -#else - compatible_close(wsi->desc.sockfd); -#endif + if (wsi->context->event_loop_ops->close_handle_manually) + wsi->context->event_loop_ops->close_handle_manually(wsi); + else + compatible_close(wsi->desc.sockfd); - remove_wsi_socket_from_fds(wsi); + __remove_wsi_socket_from_fds(wsi); -#ifdef LWS_OPENSSL_SUPPORT - wsi->use_ssl = ssl; +#if defined(LWS_WITH_TLS) + wsi->tls.use_ssl = ssl; #else if (ssl) { lwsl_err("%s: not configured for ssl\n", __func__); @@ -514,12 +671,12 @@ lws_client_reset(struct lws **pwsi, int ssl, const char *address, int port, #endif wsi->desc.sockfd = LWS_SOCK_INVALID; - wsi->state = LWSS_CLIENT_UNCONNECTED; + lwsi_set_state(wsi, LRS_UNCONNECTED); wsi->protocol = NULL; wsi->pending_timeout = NO_PENDING_TIMEOUT; wsi->c_port = port; wsi->hdr_parsing_completed = 0; - _lws_header_table_reset(wsi->u.hdr.ah); + _lws_header_table_reset(wsi->http.ah); if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address)) return NULL; @@ -544,6 +701,10 @@ lws_client_reset(struct lws **pwsi, int ssl, const char *address, int port, if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE, iface)) return NULL; + if (alpn[0]) + if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ALPN, + alpn)) + return NULL; origin[0] = '/'; strncpy(&origin[1], path, sizeof(origin) - 2); @@ -683,26 +844,68 @@ html_parser_cb(const hubbub_token *token, void *pw) } #endif +#endif + +static char * +lws_strdup(const char *s) +{ + char *d = lws_malloc(strlen(s) + 1, "strdup"); + + if (d) + strcpy(d, s); + + return d; +} + +void +lws_client_stash_destroy(struct lws *wsi) +{ + if (!wsi || !wsi->stash) + return; + + lws_free_set_NULL(wsi->stash->address); + lws_free_set_NULL(wsi->stash->path); + lws_free_set_NULL(wsi->stash->host); + lws_free_set_NULL(wsi->stash->origin); + lws_free_set_NULL(wsi->stash->protocol); + lws_free_set_NULL(wsi->stash->method); + lws_free_set_NULL(wsi->stash->iface); + lws_free_set_NULL(wsi->stash->alpn); + + lws_free_set_NULL(wsi->stash); +} + LWS_VISIBLE struct lws * lws_client_connect_via_info(struct lws_client_connect_info *i) { struct lws *wsi; - int v = SPEC_LATEST_SUPPORTED; const struct lws_protocols *p; + const char *local = i->protocol; if (i->context->requested_kill) return NULL; if (!i->context->protocol_init_done) lws_protocol_init(i->context); + /* + * If we have .local_protocol_name, use it to select the + * local protocol handler to bind to. Otherwise use .protocol if + * http[s]. + */ + if (i->local_protocol_name) + local = i->local_protocol_name; wsi = lws_zalloc(sizeof(struct lws), "client wsi"); if (wsi == NULL) goto bail; wsi->context = i->context; +#if defined(LWS_ROLE_H1) /* assert the mode and union status (hdr) clearly */ - lws_union_transition(wsi, LWSCM_HTTP_CLIENT); + lws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, &role_ops_h1); +#else + lws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, &role_ops_raw_skt); +#endif wsi->desc.sockfd = LWS_SOCK_INVALID; /* 1) fill up the wsi with stuff from the connect_info as far as it @@ -710,26 +913,52 @@ lws_client_connect_via_info(struct lws_client_connect_info *i) * not even be able to get ahold of an ah at this point. */ - /* -1 means just use latest supported */ - if (i->ietf_version_or_minus_one != -1 && i->ietf_version_or_minus_one) - v = i->ietf_version_or_minus_one; + if (!i->method) /* ie, ws */ +#if defined(LWS_ROLE_WS) + if (lws_create_client_ws_object(i, wsi)) + return NULL; +#else + return NULL; +#endif - wsi->ietf_spec_revision = v; wsi->user_space = NULL; - wsi->state = LWSS_CLIENT_UNCONNECTED; wsi->pending_timeout = NO_PENDING_TIMEOUT; - wsi->position_in_fds_table = -1; + wsi->position_in_fds_table = LWS_NO_FDS_POS; wsi->c_port = i->port; wsi->vhost = i->vhost; if (!wsi->vhost) wsi->vhost = i->context->vhost_list; + if (!wsi->vhost) { + lwsl_err("At least one vhost in the context is required\n"); + + goto bail; + } + wsi->protocol = &wsi->vhost->protocols[0]; + wsi->client_pipeline = !!(i->ssl_connection & LCCSCF_PIPELINE); - /* for http[s] connection, allow protocol selection by name */ + /* reasonable place to start */ + lws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, +#if defined(LWS_ROLE_H1) + &role_ops_h1); +#else + &role_ops_raw_skt); +#endif - if (i->method && i->vhost && i->protocol) { - p = lws_vhost_name_to_protocol(i->vhost, i->protocol); + /* + * 1) for http[s] connection, allow protocol selection by name + * 2) for ws[s], if local_protocol_name given also use it for + * local protocol binding... this defeats the server + * protocol negotiation if so + * + * Otherwise leave at protocols[0]... the server will tell us + * which protocol we are associated with since we can give it a + * list. + */ + if (/*(i->method || i->local_protocol_name) && */local) { + lwsl_info("binding to %s\n", local); + p = lws_vhost_name_to_protocol(wsi->vhost, local); if (p) wsi->protocol = p; } @@ -745,10 +974,10 @@ lws_client_connect_via_info(struct lws_client_connect_info *i) if (lws_ensure_user_space(wsi)) goto bail; -#ifdef LWS_OPENSSL_SUPPORT - wsi->use_ssl = i->ssl_connection; +#if defined(LWS_WITH_TLS) + wsi->tls.use_ssl = i->ssl_connection; #else - if (i->ssl_connection) { + if (i->ssl_connection & LCCSCF_USE_SSL) { lwsl_err("libwebsockets not configured for ssl\n"); goto bail; } @@ -760,47 +989,63 @@ lws_client_connect_via_info(struct lws_client_connect_info *i) * things pointed to have gone out of scope. */ - wsi->u.hdr.stash = lws_malloc(sizeof(*wsi->u.hdr.stash), "client stash"); - if (!wsi->u.hdr.stash) { + wsi->stash = lws_zalloc(sizeof(*wsi->stash), "client stash"); + if (!wsi->stash) { lwsl_err("%s: OOM\n", __func__); - goto bail; + goto bail1; } - wsi->u.hdr.stash->origin[0] = '\0'; - wsi->u.hdr.stash->protocol[0] = '\0'; - wsi->u.hdr.stash->method[0] = '\0'; - wsi->u.hdr.stash->iface[0] = '\0'; - - strncpy(wsi->u.hdr.stash->address, i->address, - sizeof(wsi->u.hdr.stash->address) - 1); - strncpy(wsi->u.hdr.stash->path, i->path, - sizeof(wsi->u.hdr.stash->path) - 1); - strncpy(wsi->u.hdr.stash->host, i->host, - sizeof(wsi->u.hdr.stash->host) - 1); - if (i->origin) - strncpy(wsi->u.hdr.stash->origin, i->origin, - sizeof(wsi->u.hdr.stash->origin) - 1); - if (i->protocol) - strncpy(wsi->u.hdr.stash->protocol, i->protocol, - sizeof(wsi->u.hdr.stash->protocol) - 1); - if (i->method) - strncpy(wsi->u.hdr.stash->method, i->method, - sizeof(wsi->u.hdr.stash->method) - 1); - if (i->iface) - strncpy(wsi->u.hdr.stash->iface, i->iface, - sizeof(wsi->u.hdr.stash->iface) - 1); - - wsi->u.hdr.stash->address[sizeof(wsi->u.hdr.stash->address) - 1] = '\0'; - wsi->u.hdr.stash->path[sizeof(wsi->u.hdr.stash->path) - 1] = '\0'; - wsi->u.hdr.stash->host[sizeof(wsi->u.hdr.stash->host) - 1] = '\0'; - wsi->u.hdr.stash->origin[sizeof(wsi->u.hdr.stash->origin) - 1] = '\0'; - wsi->u.hdr.stash->protocol[sizeof(wsi->u.hdr.stash->protocol) - 1] = '\0'; - wsi->u.hdr.stash->method[sizeof(wsi->u.hdr.stash->method) - 1] = '\0'; - wsi->u.hdr.stash->iface[sizeof(wsi->u.hdr.stash->iface) - 1] = '\0'; + wsi->stash->address = lws_strdup(i->address); + wsi->stash->path = lws_strdup(i->path); + wsi->stash->host = lws_strdup(i->host); + + if (!wsi->stash->address || !wsi->stash->path || !wsi->stash->host) + goto bail1; + + if (i->origin) { + wsi->stash->origin = lws_strdup(i->origin); + if (!wsi->stash->origin) + goto bail1; + } + if (i->protocol) { + wsi->stash->protocol = lws_strdup(i->protocol); + if (!wsi->stash->protocol) + goto bail1; + } + if (i->method) { + wsi->stash->method = lws_strdup(i->method); + if (!wsi->stash->method) + goto bail1; + } + if (i->iface) { + wsi->stash->iface = lws_strdup(i->iface); + if (!wsi->stash->iface) + goto bail1; + } + /* + * For ws, default to http/1.1 only. If i->alpn is set, defer to + * whatever he has set in there (eg, "h2"). + * + * The problem is he has to commit to h2 before he can find out if the + * server has the SETTINGS for ws-over-h2 enabled; if not then ws is + * not possible on that connection. So we only try it if he + * assertively said to use h2 alpn. + */ + if (!i->method && !i->alpn) { + wsi->stash->alpn = lws_strdup("http/1.1"); + if (!wsi->stash->alpn) + goto bail1; + } else + if (i->alpn) { + wsi->stash->alpn = lws_strdup(i->alpn); + if (!wsi->stash->alpn) + goto bail1; + } if (i->pwsi) *i->pwsi = wsi; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) /* if we went on the waiting list, no probs just return the wsi * when we get the ah, now or later, he will call * lws_client_connect_via_info2() below. @@ -810,9 +1055,11 @@ lws_client_connect_via_info(struct lws_client_connect_info *i) * if we failed here, the connection is already closed * and freed. */ - goto bail1; + goto bail2; } +#endif + if (i->parent_wsi) { lwsl_info("%s: created child %p of parent %p\n", __func__, wsi, i->parent_wsi); @@ -822,17 +1069,21 @@ lws_client_connect_via_info(struct lws_client_connect_info *i) } #ifdef LWS_WITH_HTTP_PROXY if (i->uri_replace_to) - wsi->rw = lws_rewrite_create(wsi, html_parser_cb, + wsi->http.rw = lws_rewrite_create(wsi, html_parser_cb, i->uri_replace_from, i->uri_replace_to); #endif return wsi; +bail1: + lws_client_stash_destroy(wsi); + bail: lws_free(wsi); - -bail1: +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) +bail2: +#endif if (i->pwsi) *i->pwsi = NULL; @@ -842,28 +1093,27 @@ bail1: struct lws * lws_client_connect_via_info2(struct lws *wsi) { - struct client_info_stash *stash = wsi->u.hdr.stash; + struct client_info_stash *stash = wsi->stash; if (!stash) return wsi; /* * we're not necessarily in a position to action these right away, - * stash them... we only need during connect phase so u.hdr is fine + * stash them... we only need during connect phase so into a temp + * allocated stash */ if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, stash->address)) goto bail1; - /* these only need u.hdr lifetime as well */ - if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, stash->path)) goto bail1; if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, stash->host)) goto bail1; - if (stash->origin[0]) + if (stash->origin) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN, stash->origin)) goto bail1; @@ -871,45 +1121,28 @@ lws_client_connect_via_info2(struct lws *wsi) * this is a list of protocols we tell the server we're okay with * stash it for later when we compare server response with it */ - if (stash->protocol[0]) + if (stash->protocol) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, stash->protocol)) goto bail1; - if (stash->method[0]) + if (stash->method) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_METHOD, stash->method)) goto bail1; - if (stash->iface[0]) + if (stash->iface) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE, stash->iface)) goto bail1; + if (stash->alpn) + if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ALPN, + stash->alpn)) + goto bail1; #if defined(LWS_WITH_SOCKS5) if (!wsi->vhost->socks_proxy_port) - lws_free_set_NULL(wsi->u.hdr.stash); + lws_client_stash_destroy(wsi); #endif - /* - * Check with each extension if it is able to route and proxy this - * connection for us. For example, an extension like x-google-mux - * can handle this and then we don't need an actual socket for this - * connection. - */ - - if (lws_ext_cb_all_exts(wsi->context, wsi, - LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION, - (void *)stash->address, - wsi->c_port) > 0) { - lwsl_client("lws_client_connect: ext handling conn\n"); - - lws_set_timeout(wsi, - PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE, - AWAITING_TIMEOUT); - - wsi->mode = LWSCM_WSCL_WAITING_EXTENSION_CONNECT; - return wsi; - } - lwsl_client("lws_client_connect: direct conn\n"); wsi->context->count_wsi_allocated++; return lws_client_connect_2(wsi); @@ -917,7 +1150,7 @@ lws_client_connect_via_info2(struct lws *wsi) bail1: #if defined(LWS_WITH_SOCKS5) if (!wsi->vhost->socks_proxy_port) - lws_free_set_NULL(wsi->u.hdr.stash); + lws_free_set_NULL(wsi->stash); #endif return NULL; @@ -1003,14 +1236,14 @@ void socks_generate_msg(struct lws *wsi, enum socks_msg_type type, /* length of the user name */ pt->serv_buf[len++] = n; /* user name */ - strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_user, - context->pt_serv_buf_size - len); + lws_strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_user, + context->pt_serv_buf_size - len + 1); len += n; /* length of the password */ pt->serv_buf[len++] = passwd_len; /* password */ - strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_password, - context->pt_serv_buf_size - len); + lws_strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_password, + context->pt_serv_buf_size - len + 1); len += passwd_len; break; @@ -1029,9 +1262,9 @@ void socks_generate_msg(struct lws *wsi, enum socks_msg_type type, n = len++; /* the address we tell SOCKS proxy to connect to */ - strncpy((char *)&(pt->serv_buf[len]), wsi->u.hdr.stash->address, - context->pt_serv_buf_size - len); - len += strlen(wsi->u.hdr.stash->address); + lws_strncpy((char *)&(pt->serv_buf[len]), wsi->stash->address, + context->pt_serv_buf_size - len + 1); + len += strlen(wsi->stash->address); net_num = htons(wsi->c_port); /* the port we tell SOCKS proxy to connect to */ @@ -1039,7 +1272,7 @@ void socks_generate_msg(struct lws *wsi, enum socks_msg_type type, pt->serv_buf[len++] = p[1]; /* the length of the address, excluding port */ - pt->serv_buf[n] = strlen(wsi->u.hdr.stash->address); + pt->serv_buf[n] = strlen(wsi->stash->address); break; default: diff --git a/thirdparty/libwebsockets/roles/http/client/client.c b/thirdparty/libwebsockets/roles/http/client/client.c new file mode 100644 index 0000000000..ce42dc6cd3 --- /dev/null +++ b/thirdparty/libwebsockets/roles/http/client/client.c @@ -0,0 +1,1231 @@ +/* + * libwebsockets - lib/client/client.c + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +LWS_VISIBLE LWS_EXTERN void +lws_client_http_body_pending(struct lws *wsi, int something_left_to_send) +{ + wsi->client_http_body_pending = !!something_left_to_send; +} + +/* + * return self, or queued client wsi we are acting on behalf of + * + * That is the TAIL of the queue (new queue elements are added at the HEAD) + */ + +struct lws * +lws_client_wsi_effective(struct lws *wsi) +{ + struct lws_dll_lws *tail = NULL; + + if (!wsi->transaction_from_pipeline_queue || + !wsi->dll_client_transaction_queue_head.next) + return wsi; + + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + wsi->dll_client_transaction_queue_head.next) { + tail = d; + } lws_end_foreach_dll_safe(d, d1); + + return lws_container_of(tail, struct lws, + dll_client_transaction_queue); +} + +/* + * return self or the guy we are queued under + * + * REQUIRES VHOST LOCK HELD + */ + +static struct lws * +_lws_client_wsi_master(struct lws *wsi) +{ + struct lws *wsi_eff = wsi; + struct lws_dll_lws *d; + + d = wsi->dll_client_transaction_queue.prev; + while (d) { + wsi_eff = lws_container_of(d, struct lws, + dll_client_transaction_queue_head); + + d = d->prev; + } + + return wsi_eff; +} + +int +lws_client_socket_service(struct lws *wsi, struct lws_pollfd *pollfd, + struct lws *wsi_conn) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + char *p = (char *)&pt->serv_buf[0]; + struct lws *w; +#if defined(LWS_WITH_TLS) + char ebuf[128]; +#endif + const char *cce = NULL; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + ssize_t len = 0; + unsigned char c; +#endif + char *sb = p; + int n = 0; +#if defined(LWS_WITH_SOCKS5) + char conn_mode = 0, pending_timeout = 0; +#endif + + if ((pollfd->revents & LWS_POLLOUT) && + wsi->keepalive_active && + wsi->dll_client_transaction_queue_head.next) { + struct lws *wfound = NULL; + + lwsl_debug("%s: pollout HANDSHAKE2\n", __func__); + + /* + * We have a transaction queued that wants to pipeline. + * + * We have to allow it to send headers strictly in the order + * that it was queued, ie, tail-first. + */ + lws_vhost_lock(wsi->vhost); + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + wsi->dll_client_transaction_queue_head.next) { + struct lws *w = lws_container_of(d, struct lws, + dll_client_transaction_queue); + + lwsl_debug("%s: %p states 0x%x\n", __func__, w, w->wsistate); + if (lwsi_state(w) == LRS_H1C_ISSUE_HANDSHAKE2) + wfound = w; + } lws_end_foreach_dll_safe(d, d1); + + if (wfound) { + /* + * pollfd has the master sockfd in it... we + * need to use that in HANDSHAKE2 to understand + * which wsi to actually write on + */ + lws_client_socket_service(wfound, pollfd, wsi); + lws_callback_on_writable(wsi); + } else + lwsl_debug("%s: didn't find anything in txn q in HS2\n", + __func__); + + lws_vhost_unlock(wsi->vhost); + + return 0; + } + + switch (lwsi_state(wsi)) { + + case LRS_WAITING_CONNECT: + + /* + * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE + * timeout protection set in client-handshake.c + */ + + if (!lws_client_connect_2(wsi)) { + /* closed */ + lwsl_client("closed\n"); + return -1; + } + + /* either still pending connection, or changed mode */ + return 0; + +#if defined(LWS_WITH_SOCKS5) + /* SOCKS Greeting Reply */ + case LRS_WAITING_SOCKS_GREETING_REPLY: + case LRS_WAITING_SOCKS_AUTH_REPLY: + case LRS_WAITING_SOCKS_CONNECT_REPLY: + + /* handle proxy hung up on us */ + + if (pollfd->revents & LWS_POLLHUP) { + lwsl_warn("SOCKS connection %p (fd=%d) dead\n", + (void *)wsi, pollfd->fd); + goto bail3; + } + + n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0); + if (n < 0) { + if (LWS_ERRNO == LWS_EAGAIN) { + lwsl_debug("SOCKS read EAGAIN, retrying\n"); + return 0; + } + lwsl_err("ERROR reading from SOCKS socket\n"); + goto bail3; + } + + switch (lwsi_state(wsi)) { + + case LRS_WAITING_SOCKS_GREETING_REPLY: + if (pt->serv_buf[0] != SOCKS_VERSION_5) + goto socks_reply_fail; + + if (pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH) { + lwsl_client("SOCKS GR: No Auth Method\n"); + socks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len); + conn_mode = LRS_WAITING_SOCKS_CONNECT_REPLY; + pending_timeout = + PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY; + goto socks_send; + } + + if (pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD) { + lwsl_client("SOCKS GR: User/Pw Method\n"); + socks_generate_msg(wsi, + SOCKS_MSG_USERNAME_PASSWORD, + &len); + conn_mode = LRS_WAITING_SOCKS_AUTH_REPLY; + pending_timeout = + PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY; + goto socks_send; + } + goto socks_reply_fail; + + case LRS_WAITING_SOCKS_AUTH_REPLY: + if (pt->serv_buf[0] != SOCKS_SUBNEGOTIATION_VERSION_1 || + pt->serv_buf[1] != SOCKS_SUBNEGOTIATION_STATUS_SUCCESS) + goto socks_reply_fail; + + lwsl_client("SOCKS password OK, sending connect\n"); + socks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len); + conn_mode = LRS_WAITING_SOCKS_CONNECT_REPLY; + pending_timeout = + PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY; +socks_send: + n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len, + MSG_NOSIGNAL); + if (n < 0) { + lwsl_debug("ERROR writing to socks proxy\n"); + goto bail3; + } + + lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT); + lwsi_set_state(wsi, conn_mode); + break; + +socks_reply_fail: + lwsl_notice("socks reply: v%d, err %d\n", + pt->serv_buf[0], pt->serv_buf[1]); + goto bail3; + + case LRS_WAITING_SOCKS_CONNECT_REPLY: + if (pt->serv_buf[0] != SOCKS_VERSION_5 || + pt->serv_buf[1] != SOCKS_REQUEST_REPLY_SUCCESS) + goto socks_reply_fail; + + lwsl_client("socks connect OK\n"); + + /* free stash since we are done with it */ + lws_client_stash_destroy(wsi); + if (lws_hdr_simple_create(wsi, + _WSI_TOKEN_CLIENT_PEER_ADDRESS, + wsi->vhost->socks_proxy_address)) + goto bail3; + + wsi->c_port = wsi->vhost->socks_proxy_port; + + /* clear his proxy connection timeout */ + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + goto start_ws_handshake; + } + break; +#endif + + case LRS_WAITING_PROXY_REPLY: + + /* handle proxy hung up on us */ + + if (pollfd->revents & LWS_POLLHUP) { + + lwsl_warn("Proxy connection %p (fd=%d) dead\n", + (void *)wsi, pollfd->fd); + + goto bail3; + } + + n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0); + if (n < 0) { + if (LWS_ERRNO == LWS_EAGAIN) { + lwsl_debug("Proxy read EAGAIN... retrying\n"); + return 0; + } + lwsl_err("ERROR reading from proxy socket\n"); + goto bail3; + } + + pt->serv_buf[13] = '\0'; + if (strcmp(sb, "HTTP/1.0 200 ") && + strcmp(sb, "HTTP/1.1 200 ")) { + lwsl_err("ERROR proxy: %s\n", sb); + goto bail3; + } + + /* clear his proxy connection timeout */ + + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + + /* fallthru */ + + case LRS_H1C_ISSUE_HANDSHAKE: + + /* + * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE + * timeout protection set in client-handshake.c + * + * take care of our lws_callback_on_writable + * happening at a time when there's no real connection yet + */ +#if defined(LWS_WITH_SOCKS5) +start_ws_handshake: +#endif + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) + return -1; + +#if defined(LWS_WITH_TLS) + /* we can retry this... just cook the SSL BIO the first time */ + + if ((wsi->tls.use_ssl & LCCSCF_USE_SSL) && !wsi->tls.ssl && + lws_ssl_client_bio_create(wsi) < 0) { + cce = "bio_create failed"; + goto bail3; + } + + if (wsi->tls.use_ssl & LCCSCF_USE_SSL) { + n = lws_ssl_client_connect1(wsi); + if (!n) + return 0; + if (n < 0) { + cce = "lws_ssl_client_connect1 failed"; + goto bail3; + } + } else + wsi->tls.ssl = NULL; + + /* fallthru */ + + case LRS_WAITING_SSL: + + if (wsi->tls.use_ssl & LCCSCF_USE_SSL) { + n = lws_ssl_client_connect2(wsi, ebuf, sizeof(ebuf)); + if (!n) + return 0; + if (n < 0) { + cce = ebuf; + goto bail3; + } + } else + wsi->tls.ssl = NULL; +#endif +#if defined (LWS_WITH_HTTP2) + if (wsi->client_h2_alpn) { + /* + * We connected to the server and set up tls, and + * negotiated "h2". + * + * So this is it, we are an h2 master client connection + * now, not an h1 client connection. + */ + lws_tls_server_conn_alpn(wsi); + + /* send the H2 preface to legitimize the connection */ + if (lws_h2_issue_preface(wsi)) { + cce = "error sending h2 preface"; + goto bail3; + } + + break; + } +#endif + lwsi_set_state(wsi, LRS_H1C_ISSUE_HANDSHAKE2); + lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND, + context->timeout_secs); + + /* fallthru */ + + case LRS_H1C_ISSUE_HANDSHAKE2: + p = lws_generate_client_handshake(wsi, p); + if (p == NULL) { + if (wsi->role_ops == &role_ops_raw_skt || + wsi->role_ops == &role_ops_raw_file) + return 0; + + lwsl_err("Failed to generate handshake for client\n"); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "chs"); + return 0; + } + + /* send our request to the server */ + lws_latency_pre(context, wsi); + + w = _lws_client_wsi_master(wsi); + lwsl_info("%s: HANDSHAKE2: %p: sending headers on %p (wsistate 0x%x 0x%x)\n", + __func__, wsi, w, wsi->wsistate, w->wsistate); + + n = lws_ssl_capable_write(w, (unsigned char *)sb, (int)(p - sb)); + lws_latency(context, wsi, "send lws_issue_raw", n, + n == p - sb); + switch (n) { + case LWS_SSL_CAPABLE_ERROR: + lwsl_debug("ERROR writing to client socket\n"); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "cws"); + return 0; + case LWS_SSL_CAPABLE_MORE_SERVICE: + lws_callback_on_writable(wsi); + break; + } + + if (wsi->client_http_body_pending) { + lwsi_set_state(wsi, LRS_ISSUE_HTTP_BODY); + lws_set_timeout(wsi, + PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD, + context->timeout_secs); + /* user code must ask for writable callback */ + break; + } + + lwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY); + wsi->hdr_parsing_completed = 0; + + if (lwsi_state(w) == LRS_IDLING) { + lwsi_set_state(w, LRS_WAITING_SERVER_REPLY); + w->hdr_parsing_completed = 0; +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + w->http.ah->parser_state = WSI_TOKEN_NAME_PART; + w->http.ah->lextable_pos = 0; + /* If we're (re)starting on headers, need other implied init */ + wsi->http.ah->ues = URIES_IDLE; +#endif + } + + lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, + wsi->context->timeout_secs); + + lws_callback_on_writable(w); + + goto client_http_body_sent; + + case LRS_ISSUE_HTTP_BODY: + if (wsi->client_http_body_pending) { + //lws_set_timeout(wsi, + // PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD, + // context->timeout_secs); + /* user code must ask for writable callback */ + break; + } +client_http_body_sent: +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + /* prepare ourselves to do the parsing */ + wsi->http.ah->parser_state = WSI_TOKEN_NAME_PART; + wsi->http.ah->lextable_pos = 0; +#endif + lwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY); + lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, + context->timeout_secs); + break; + + case LRS_WAITING_SERVER_REPLY: + /* + * handle server hanging up on us... + * but if there is POLLIN waiting, handle that first + */ + if ((pollfd->revents & (LWS_POLLIN | LWS_POLLHUP)) == + LWS_POLLHUP) { + + lwsl_debug("Server connection %p (fd=%d) dead\n", + (void *)wsi, pollfd->fd); + cce = "Peer hung up"; + goto bail3; + } + + if (!(pollfd->revents & LWS_POLLIN)) + break; + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + /* interpret the server response + * + * HTTP/1.1 101 Switching Protocols + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= + * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== + * Sec-WebSocket-Protocol: chat + * + * we have to take some care here to only take from the + * socket bytewise. The browser may (and has been seen to + * in the case that onopen() performs websocket traffic) + * coalesce both handshake response and websocket traffic + * in one packet, since at that point the connection is + * definitively ready from browser pov. + */ + len = 1; + while (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE && + len > 0) { + int plen = 1; + + n = lws_ssl_capable_read(wsi, &c, 1); + lws_latency(context, wsi, "send lws_issue_raw", n, + n == 1); + switch (n) { + case 0: + case LWS_SSL_CAPABLE_ERROR: + cce = "read failed"; + goto bail3; + case LWS_SSL_CAPABLE_MORE_SERVICE: + return 0; + } + + if (lws_parse(wsi, &c, &plen)) { + lwsl_warn("problems parsing header\n"); + goto bail3; + } + } + + /* + * hs may also be coming in multiple packets, there is a 5-sec + * libwebsocket timeout still active here too, so if parsing did + * not complete just wait for next packet coming in this state + */ + if (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE) + break; + +#endif + + /* + * otherwise deal with the handshake. If there's any + * packet traffic already arrived we'll trigger poll() again + * right away and deal with it that way + */ + return lws_client_interpret_server_handshake(wsi); + +bail3: + lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n"); + if (cce) + lwsl_info("reason: %s\n", cce); + wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, + wsi->user_space, (void *)cce, cce ? strlen(cce) : 0); + wsi->already_did_cce = 1; + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "cbail3"); + return -1; + + default: + break; + } + + return 0; +} + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + +int LWS_WARN_UNUSED_RESULT +lws_http_transaction_completed_client(struct lws *wsi) +{ + struct lws *wsi_eff = lws_client_wsi_effective(wsi); + + lwsl_info("%s: wsi: %p, wsi_eff: %p\n", __func__, wsi, wsi_eff); + + if (user_callback_handle_rxflow(wsi_eff->protocol->callback, + wsi_eff, LWS_CALLBACK_COMPLETED_CLIENT_HTTP, + wsi_eff->user_space, NULL, 0)) { + lwsl_debug("%s: Completed call returned nonzero (role 0x%x)\n", + __func__, lwsi_role(wsi_eff)); + return -1; + } + + /* + * Are we constitutionally capable of having a queue, ie, we are on + * the "active client connections" list? + * + * If not, that's it for us. + */ + + if (lws_dll_is_null(&wsi->dll_active_client_conns)) + return -1; + + /* if this was a queued guy, close him and remove from queue */ + + if (wsi->transaction_from_pipeline_queue) { + lwsl_debug("closing queued wsi %p\n", wsi_eff); + /* so the close doesn't trigger a CCE */ + wsi_eff->already_did_cce = 1; + __lws_close_free_wsi(wsi_eff, + LWS_CLOSE_STATUS_CLIENT_TRANSACTION_DONE, + "queued client done"); + } + + /* after the first one, they can only be coming from the queue */ + wsi->transaction_from_pipeline_queue = 1; + + wsi->http.rx_content_length = 0; + wsi->hdr_parsing_completed = 0; + + /* is there a new tail after removing that one? */ + wsi_eff = lws_client_wsi_effective(wsi); + + /* + * Do we have something pipelined waiting? + * it's OK if he hasn't managed to send his headers yet... he's next + * in line to do that... + */ + if (wsi_eff == wsi) { + /* + * Nothing pipelined... we should hang around a bit + * in case something turns up... + */ + lwsl_info("%s: nothing pipelined waiting\n", __func__); + lwsi_set_state(wsi, LRS_IDLING); + + lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_CONN_IDLE, 5); + + return 0; + } + + /* + * H1: we can serialize the queued guys into the same ah + * H2: everybody needs their own ah until their own STREAM_END + */ + + /* otherwise set ourselves up ready to go again */ + lwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY); + + wsi->http.ah->parser_state = WSI_TOKEN_NAME_PART; + wsi->http.ah->lextable_pos = 0; + + lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, + wsi->context->timeout_secs); + + /* If we're (re)starting on headers, need other implied init */ + wsi->http.ah->ues = URIES_IDLE; + + lwsl_info("%s: %p: new queued transaction as %p\n", __func__, wsi, wsi_eff); + lws_callback_on_writable(wsi); + + return 0; +} + +LWS_VISIBLE LWS_EXTERN unsigned int +lws_http_client_http_response(struct lws *wsi) +{ + if (!wsi->http.ah) + return 0; + + return wsi->http.ah->http_response; +} +#endif +#if defined(LWS_PLAT_OPTEE) +char * +strrchr(const char *s, int c) +{ + char *hit = NULL; + + while (*s) + if (*(s++) == (char)c) + hit = (char *)s - 1; + + return hit; +} + +#define atoll atoi +#endif + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) +int +lws_client_interpret_server_handshake(struct lws *wsi) +{ + int n, port = 0, ssl = 0; + int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; + const char *prot, *ads = NULL, *path, *cce = NULL; + struct allocated_headers *ah = NULL; + struct lws *w = lws_client_wsi_effective(wsi); + char *p, *q; + char new_path[300]; + + lws_client_stash_destroy(wsi); + + ah = wsi->http.ah; + if (!wsi->do_ws) { + /* we are being an http client... + */ +#if defined(LWS_ROLE_H2) + if (wsi->client_h2_alpn || wsi->client_h2_substream) { + lwsl_debug("%s: %p: transitioning to h2 client\n", __func__, wsi); + lws_role_transition(wsi, LWSIFR_CLIENT, + LRS_ESTABLISHED, &role_ops_h2); + } else +#endif + { +#if defined(LWS_ROLE_H1) + { + lwsl_debug("%s: %p: transitioning to h1 client\n", __func__, wsi); + lws_role_transition(wsi, LWSIFR_CLIENT, + LRS_ESTABLISHED, &role_ops_h1); + } +#else + return -1; +#endif + } + + wsi->http.ah = ah; + ah->http_response = 0; + } + + /* + * well, what the server sent looked reasonable for syntax. + * Now let's confirm it sent all the necessary headers + * + * http (non-ws) client will expect something like this + * + * HTTP/1.0.200 + * server:.libwebsockets + * content-type:.text/html + * content-length:.17703 + * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000 + */ + + wsi->http.connection_type = HTTP_CONNECTION_KEEP_ALIVE; + if (!wsi->client_h2_substream) { + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); + if (wsi->do_ws && !p) { + lwsl_info("no URI\n"); + cce = "HS: URI missing"; + goto bail3; + } + if (!p) { + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0); + wsi->http.connection_type = HTTP_CONNECTION_CLOSE; + } + if (!p) { + cce = "HS: URI missing"; + lwsl_info("no URI\n"); + goto bail3; + } + } else { + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_STATUS); + if (!p) { + cce = "HS: :status missing"; + lwsl_info("no status\n"); + goto bail3; + } + } + n = atoi(p); + if (ah) + ah->http_response = n; + + if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) { + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION); + if (!p) { + cce = "HS: Redirect code but no Location"; + goto bail3; + } + + /* Relative reference absolute path */ + if (p[0] == '/') { +#if defined(LWS_WITH_TLS) + ssl = wsi->tls.use_ssl & LCCSCF_USE_SSL; +#endif + ads = lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_PEER_ADDRESS); + port = wsi->c_port; + /* +1 as lws_client_reset expects leading / omitted */ + path = p + 1; + } + /* Absolute (Full) URI */ + else if (strchr(p, ':')) { + if (lws_parse_uri(p, &prot, &ads, &port, &path)) { + cce = "HS: URI did not parse"; + goto bail3; + } + + if (!strcmp(prot, "wss") || !strcmp(prot, "https")) + ssl = 1; + } + /* Relative reference relative path */ + else { + /* This doesn't try to calculate an absolute path, + * that will be left to the server */ +#if defined(LWS_WITH_TLS) + ssl = wsi->tls.use_ssl & LCCSCF_USE_SSL; +#endif + ads = lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_PEER_ADDRESS); + port = wsi->c_port; + /* +1 as lws_client_reset expects leading / omitted */ + path = new_path + 1; + lws_strncpy(new_path, lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_URI), sizeof(new_path)); + q = strrchr(new_path, '/'); + if (q) + lws_strncpy(q + 1, p, sizeof(new_path) - + (q - new_path)); + else + path = p; + } + +#if defined(LWS_WITH_TLS) + if ((wsi->tls.use_ssl & LCCSCF_USE_SSL) && !ssl) { + cce = "HS: Redirect attempted SSL downgrade"; + goto bail3; + } +#endif + + if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) { + /* there are two ways to fail out with NULL return... + * simple, early problem where the wsi is intact, or + * we went through with the reconnect attempt and the + * wsi is already closed. In the latter case, the wsi + * has beet set to NULL additionally. + */ + lwsl_err("Redirect failed\n"); + cce = "HS: Redirect failed"; + if (wsi) + goto bail3; + + return 1; + } + return 0; + } + + if (!wsi->do_ws) { + + /* if h1 KA is allowed, enable the queued pipeline guys */ + + if (!wsi->client_h2_alpn && !wsi->client_h2_substream && w == wsi) { /* ie, coming to this for the first time */ + if (wsi->http.connection_type == HTTP_CONNECTION_KEEP_ALIVE) + wsi->keepalive_active = 1; + else { + /* + * Ugh... now the main http connection has seen + * both sides, we learn the server doesn't + * support keepalive. + * + * That means any guys queued on us are going + * to have to be restarted from connect2 with + * their own connections. + */ + + /* + * stick around telling any new guys they can't + * pipeline to this server + */ + wsi->keepalive_rejected = 1; + + lws_vhost_lock(wsi->vhost); + lws_start_foreach_dll_safe(struct lws_dll_lws *, d, d1, + wsi->dll_client_transaction_queue_head.next) { + struct lws *ww = lws_container_of(d, struct lws, + dll_client_transaction_queue); + + /* remove him from our queue */ + lws_dll_lws_remove(&ww->dll_client_transaction_queue); + /* give up on pipelining */ + ww->client_pipeline = 0; + + /* go back to "trying to connect" state */ + lws_role_transition(ww, LWSIFR_CLIENT, + LRS_UNCONNECTED, +#if defined(LWS_ROLE_H1) + &role_ops_h1); +#else +#if defined (LWS_ROLE_H2) + &role_ops_h2); +#else + &role_ops_raw); +#endif +#endif + ww->user_space = NULL; + } lws_end_foreach_dll_safe(d, d1); + lws_vhost_unlock(wsi->vhost); + } + } + +#ifdef LWS_WITH_HTTP_PROXY + wsi->http.perform_rewrite = 0; + if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) { + if (!strncmp(lws_hdr_simple_ptr(wsi, + WSI_TOKEN_HTTP_CONTENT_TYPE), + "text/html", 9)) + wsi->http.perform_rewrite = 1; + } +#endif + + /* allocate the per-connection user memory (if any) */ + if (lws_ensure_user_space(wsi)) { + lwsl_err("Problem allocating wsi user mem\n"); + cce = "HS: OOM"; + goto bail2; + } + + /* he may choose to send us stuff in chunked transfer-coding */ + wsi->chunked = 0; + wsi->chunk_remaining = 0; /* ie, next thing is chunk size */ + if (lws_hdr_total_length(wsi, + WSI_TOKEN_HTTP_TRANSFER_ENCODING)) { + wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi, + WSI_TOKEN_HTTP_TRANSFER_ENCODING), + "chunked"); + /* first thing is hex, after payload there is crlf */ + wsi->chunk_parser = ELCP_HEX; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) { + wsi->http.rx_content_length = + atoll(lws_hdr_simple_ptr(wsi, + WSI_TOKEN_HTTP_CONTENT_LENGTH)); + lwsl_info("%s: incoming content length %llu\n", + __func__, (unsigned long long) + wsi->http.rx_content_length); + wsi->http.rx_content_remain = + wsi->http.rx_content_length; + } else /* can't do 1.1 without a content length or chunked */ + if (!wsi->chunked) + wsi->http.connection_type = + HTTP_CONNECTION_CLOSE; + + /* + * we seem to be good to go, give client last chance to check + * headers and OK it + */ + if (wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, + wsi->user_space, NULL, 0)) { + + cce = "HS: disallowed by client filter"; + goto bail2; + } + + /* clear his proxy connection timeout */ + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + + wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; + + /* call him back to inform him he is up */ + if (wsi->protocol->callback(wsi, + LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP, + wsi->user_space, NULL, 0)) { + cce = "HS: disallowed at ESTABLISHED"; + goto bail3; + } + + /* + * for pipelining, master needs to keep his ah... guys who + * queued on him can drop it now though. + */ + + if (w != wsi) + /* free up parsing allocations for queued guy */ + lws_header_table_detach(w, 0); + + lwsl_info("%s: client connection up\n", __func__); + + return 0; + } + +#if defined(LWS_ROLE_WS) + switch (lws_client_ws_upgrade(wsi, &cce)) { + case 2: + goto bail2; + case 3: + goto bail3; + } + + return 0; +#endif + +bail3: + close_reason = LWS_CLOSE_STATUS_NOSTATUS; + +bail2: + if (wsi->protocol) { + n = 0; + if (cce) + n = (int)strlen(cce); + wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_CONNECTION_ERROR, + wsi->user_space, (void *)cce, + (unsigned int)n); + } + wsi->already_did_cce = 1; + + lwsl_info("closing connection due to bail2 connection error\n"); + + /* closing will free up his parsing allocations */ + lws_close_free_wsi(wsi, close_reason, "c hs interp"); + + return 1; +} +#endif + +char * +lws_generate_client_handshake(struct lws *wsi, char *pkt) +{ + char *p = pkt; + const char *meth; + const char *pp = lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); + + meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD); + if (!meth) { + meth = "GET"; + wsi->do_ws = 1; + } else { + wsi->do_ws = 0; + } + + if (!strcmp(meth, "RAW")) { + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + lwsl_notice("client transition to raw\n"); + + if (pp) { + const struct lws_protocols *pr; + + pr = lws_vhost_name_to_protocol(wsi->vhost, pp); + + if (!pr) { + lwsl_err("protocol %s not enabled on vhost\n", + pp); + return NULL; + } + + lws_bind_protocol(wsi, pr); + } + + if ((wsi->protocol->callback)(wsi, LWS_CALLBACK_RAW_ADOPT, + wsi->user_space, NULL, 0)) + return NULL; + + lws_role_transition(wsi, 0, LRS_ESTABLISHED, &role_ops_raw_skt); + lws_header_table_detach(wsi, 1); + + return NULL; + } + + /* + * 04 example client handshake + * + * GET /chat HTTP/1.1 + * Host: server.example.com + * Upgrade: websocket + * Connection: Upgrade + * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== + * Sec-WebSocket-Origin: http://example.com + * Sec-WebSocket-Protocol: chat, superchat + * Sec-WebSocket-Version: 4 + */ + + p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth, + lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI)); + + p += sprintf(p, "Pragma: no-cache\x0d\x0a" + "Cache-Control: no-cache\x0d\x0a"); + + p += sprintf(p, "Host: %s\x0d\x0a", + lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST)); + + if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) { + if (lws_check_opt(wsi->context->options, + LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN)) + p += sprintf(p, "Origin: %s\x0d\x0a", + lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_ORIGIN)); + else + p += sprintf(p, "Origin: http://%s\x0d\x0a", + lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_ORIGIN)); + } +#if defined(LWS_ROLE_WS) + if (wsi->do_ws) + p = lws_generate_client_ws_handshake(wsi, p); +#endif + + /* give userland a chance to append, eg, cookies */ + + if (wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER, + wsi->user_space, &p, + (pkt + wsi->context->pt_serv_buf_size) - p - 12)) + return NULL; + + p += sprintf(p, "\x0d\x0a"); + + return p; +} + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + +LWS_VISIBLE int +lws_http_client_read(struct lws *wsi, char **buf, int *len) +{ + int rlen, n; + + rlen = lws_ssl_capable_read(wsi, (unsigned char *)*buf, *len); + *len = 0; + + // lwsl_notice("%s: rlen %d\n", __func__, rlen); + + /* allow the source to signal he has data again next time */ + lws_change_pollfd(wsi, 0, LWS_POLLIN); + + if (rlen == LWS_SSL_CAPABLE_ERROR) { + lwsl_notice("%s: SSL capable error\n", __func__); + return -1; + } + + if (rlen == 0) + return -1; + + if (rlen < 0) + return 0; + + *len = rlen; + wsi->client_rx_avail = 0; + + /* + * server may insist on transfer-encoding: chunked, + * so http client must deal with it + */ +spin_chunks: + while (wsi->chunked && (wsi->chunk_parser != ELCP_CONTENT) && *len) { + switch (wsi->chunk_parser) { + case ELCP_HEX: + if ((*buf)[0] == '\x0d') { + wsi->chunk_parser = ELCP_CR; + break; + } + n = char_to_hex((*buf)[0]); + if (n < 0) { + lwsl_debug("chunking failure\n"); + return -1; + } + wsi->chunk_remaining <<= 4; + wsi->chunk_remaining |= n; + break; + case ELCP_CR: + if ((*buf)[0] != '\x0a') { + lwsl_debug("chunking failure\n"); + return -1; + } + wsi->chunk_parser = ELCP_CONTENT; + lwsl_info("chunk %d\n", wsi->chunk_remaining); + if (wsi->chunk_remaining) + break; + lwsl_info("final chunk\n"); + goto completed; + + case ELCP_CONTENT: + break; + + case ELCP_POST_CR: + if ((*buf)[0] != '\x0d') { + lwsl_debug("chunking failure\n"); + + return -1; + } + + wsi->chunk_parser = ELCP_POST_LF; + break; + + case ELCP_POST_LF: + if ((*buf)[0] != '\x0a') + return -1; + + wsi->chunk_parser = ELCP_HEX; + wsi->chunk_remaining = 0; + break; + } + (*buf)++; + (*len)--; + } + + if (wsi->chunked && !wsi->chunk_remaining) + return 0; + + if (wsi->http.rx_content_remain && + wsi->http.rx_content_remain < (unsigned int)*len) + n = (int)wsi->http.rx_content_remain; + else + n = *len; + + if (wsi->chunked && wsi->chunk_remaining && + wsi->chunk_remaining < n) + n = wsi->chunk_remaining; + +#ifdef LWS_WITH_HTTP_PROXY + /* hubbub */ + if (wsi->http.perform_rewrite) + lws_rewrite_parse(wsi->http.rw, (unsigned char *)*buf, n); + else +#endif + { + struct lws *wsi_eff = lws_client_wsi_effective(wsi); + + if (user_callback_handle_rxflow(wsi_eff->protocol->callback, + wsi_eff, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ, + wsi_eff->user_space, *buf, n)) { + lwsl_debug("%s: RECEIVE_CLIENT_HTTP_READ returned -1\n", + __func__); + + return -1; + } + } + + if (wsi->chunked && wsi->chunk_remaining) { + (*buf) += n; + wsi->chunk_remaining -= n; + *len -= n; + } + + if (wsi->chunked && !wsi->chunk_remaining) + wsi->chunk_parser = ELCP_POST_CR; + + if (wsi->chunked && *len) + goto spin_chunks; + + if (wsi->chunked) + return 0; + + /* if we know the content length, decrement the content remaining */ + if (wsi->http.rx_content_length > 0) + wsi->http.rx_content_remain -= n; + + // lwsl_notice("rx_content_remain %lld, rx_content_length %lld\n", + // wsi->http.rx_content_remain, wsi->http.rx_content_length); + + if (wsi->http.rx_content_remain || !wsi->http.rx_content_length) + return 0; + +completed: + + if (lws_http_transaction_completed_client(wsi)) { + lwsl_notice("%s: transaction completed says -1\n", __func__); + return -1; + } + + return 0; +} + +#endif
\ No newline at end of file diff --git a/thirdparty/lws/header.c b/thirdparty/libwebsockets/roles/http/header.c index e2562cd6ea..99e56f7564 100644 --- a/thirdparty/lws/header.c +++ b/thirdparty/libwebsockets/roles/http/header.c @@ -19,12 +19,12 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" - +#include "core/private.h" #include "lextable-strings.h" -const unsigned char *lws_token_to_string(enum lws_token_indexes token) +const unsigned char * +lws_token_to_string(enum lws_token_indexes token) { if ((unsigned int)token >= ARRAY_SIZE(set)) return NULL; @@ -38,7 +38,7 @@ lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name, unsigned char **p, unsigned char *end) { #ifdef LWS_WITH_HTTP2 - if (wsi->mode == LWSCM_HTTP2_SERVING) + if (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi)) return lws_add_http2_header_by_name(wsi, name, value, length, p, end); #else @@ -66,7 +66,7 @@ int lws_finalize_http_header(struct lws *wsi, unsigned char **p, unsigned char *end) { #ifdef LWS_WITH_HTTP2 - if (wsi->mode == LWSCM_HTTP2_SERVING) + if (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi)) return 0; #else (void)wsi; @@ -80,19 +80,39 @@ int lws_finalize_http_header(struct lws *wsi, unsigned char **p, } int +lws_finalize_write_http_header(struct lws *wsi, unsigned char *start, + unsigned char **pp, unsigned char *end) +{ + unsigned char *p; + int len; + + if (lws_finalize_http_header(wsi, pp, end)) + return 1; + + p = *pp; + len = lws_ptr_diff(p, start); + + if (lws_write(wsi, start, len, LWS_WRITE_HTTP_HEADERS) != len) + return 1; + + return 0; +} + +int lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token, const unsigned char *value, int length, unsigned char **p, unsigned char *end) { const unsigned char *name; #ifdef LWS_WITH_HTTP2 - if (wsi->mode == LWSCM_HTTP2_SERVING) + if (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi)) return lws_add_http2_header_by_token(wsi, token, value, length, p, end); #endif name = lws_token_to_string(token); if (!name) return 1; + return lws_add_http_header_by_name(wsi, name, value, length, p, end); } @@ -107,8 +127,31 @@ int lws_add_http_header_content_length(struct lws *wsi, if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, (unsigned char *)b, n, p, end)) return 1; - wsi->u.http.tx_content_length = content_length; - wsi->u.http.tx_content_remain = content_length; + wsi->http.tx_content_length = content_length; + wsi->http.tx_content_remain = content_length; + + lwsl_info("%s: wsi %p: tx_content_length/remain %llu\n", __func__, + wsi, (unsigned long long)content_length); + + return 0; +} + +int +lws_add_http_common_headers(struct lws *wsi, unsigned int code, + const char *content_type, lws_filepos_t content_len, + unsigned char **p, unsigned char *end) +{ + if (lws_add_http_header_status(wsi, code, p, end)) + return 1; + + if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, + (unsigned char *)content_type, + (int)strlen(content_type), p, end)) + return 1; + + if (content_len != LWS_ILLEGAL_HTTP_CONTENT_LEN && + lws_add_http_header_content_length(wsi, content_len, p, end)) + return 1; return 0; } @@ -157,11 +200,11 @@ lws_add_http_header_status(struct lws *wsi, unsigned int _code, int n; #ifdef LWS_WITH_ACCESS_LOG - wsi->access_log.response = code; + wsi->http.access_log.response = code; #endif #ifdef LWS_WITH_HTTP2 - if (wsi->mode == LWSCM_HTTP2_SERVING) + if (lwsi_role_h2(wsi) || lwsi_role_h2_ENCAPSULATION(wsi)) return lws_add_http2_header_status(wsi, code, p, end); #endif if (code >= 400 && code < (400 + ARRAY_SIZE(err400))) @@ -171,18 +214,16 @@ lws_add_http_header_status(struct lws *wsi, unsigned int _code, if (code == 100) description = "Continue"; - if (code == 200) description = "OK"; - if (code == 304) description = "Not Modified"; else if (code >= 300 && code < 400) description = "Redirect"; - if (wsi->u.http.request_version < ARRAY_SIZE(hver)) - p1 = hver[wsi->u.http.request_version]; + if (wsi->http.request_version < ARRAY_SIZE(hver)) + p1 = hver[wsi->http.request_version]; else p1 = hver[0]; @@ -196,7 +237,7 @@ lws_add_http_header_status(struct lws *wsi, unsigned int _code, if (lws_add_http_header_by_name(wsi, (const unsigned char *)headers->name, (unsigned char *)headers->value, - strlen(headers->value), p, end)) + (int)strlen(headers->value), p, end)) return 1; headers = headers->next; @@ -231,6 +272,26 @@ lws_return_http_status(struct lws *wsi, unsigned int code, int n = 0, m = 0, len; char slen[20]; + if (!wsi->vhost) { + lwsl_err("%s: wsi not bound to vhost\n", __func__); + + return 1; + } +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + if (!wsi->handling_404 && + wsi->vhost->http.error_document_404 && + code == HTTP_STATUS_NOT_FOUND) + /* we should do a redirect, and do the 404 there */ + if (lws_http_redirect(wsi, HTTP_STATUS_FOUND, + (uint8_t *)wsi->vhost->http.error_document_404, + (int)strlen(wsi->vhost->http.error_document_404), + &p, end) > 0) + return 0; +#endif + + /* if the redirect failed, just do a simple status */ + p = start; + if (!html_body) html_body = ""; @@ -242,12 +303,11 @@ lws_return_http_status(struct lws *wsi, unsigned int code, &p, end)) return 1; - len = 35 + strlen(html_body) + sprintf(slen, "%d", code); + len = 35 + (int)strlen(html_body) + sprintf(slen, "%d", code); n = sprintf(slen, "%d", len); if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, - (unsigned char *)slen, n, - &p, end)) + (unsigned char *)slen, n, &p, end)) return 1; if (lws_finalize_http_header(wsi, &p, end)) @@ -270,7 +330,7 @@ lws_return_http_status(struct lws *wsi, unsigned int code, * Solve it by writing the headers now... */ m = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS); - if (m != (int)(p - start)) + if (m != lws_ptr_diff(p, start)) return 1; /* @@ -281,15 +341,15 @@ lws_return_http_status(struct lws *wsi, unsigned int code, len = sprintf((char *)body, "<html><body><h1>%u</h1>%s</body></html>", code, html_body); - wsi->u.http.tx_content_length = len; - wsi->u.http.tx_content_remain = len; + wsi->http.tx_content_length = len; + wsi->http.tx_content_remain = len; - wsi->u.h2.pending_status_body = lws_malloc(len + LWS_PRE + 1, + wsi->h2.pending_status_body = lws_malloc(len + LWS_PRE + 1, "pending status body"); - if (!wsi->u.h2.pending_status_body) + if (!wsi->h2.pending_status_body) return -1; - strcpy(wsi->u.h2.pending_status_body + LWS_PRE, + strcpy(wsi->h2.pending_status_body + LWS_PRE, (const char *)body); lws_callback_on_writable(wsi); @@ -305,15 +365,12 @@ lws_return_http_status(struct lws *wsi, unsigned int code, "<html><body><h1>%u</h1>%s</body></html>", code, html_body); - n = (int)(p - start); - + n = lws_ptr_diff(p, start); m = lws_write(wsi, start, n, LWS_WRITE_HTTP); if (m != n) return 1; } - lwsl_notice("%s: return\n", __func__); - return m != n; } @@ -322,34 +379,29 @@ lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len, unsigned char **p, unsigned char *end) { unsigned char *start = *p; - int n; if (lws_add_http_header_status(wsi, code, p, end)) return -1; - if (lws_add_http_header_by_token(wsi, - WSI_TOKEN_HTTP_LOCATION, - loc, len, p, end)) + if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_LOCATION, loc, len, + p, end)) return -1; /* * if we're going with http/1.1 and keepalive, we have to give fake * content metadata so the client knows we completed the transaction and * it can do the redirect... */ - if (lws_add_http_header_by_token(wsi, - WSI_TOKEN_HTTP_CONTENT_TYPE, - (unsigned char *)"text/html", 9, - p, end)) + if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, + (unsigned char *)"text/html", 9, p, + end)) return -1; - if (lws_add_http_header_by_token(wsi, - WSI_TOKEN_HTTP_CONTENT_LENGTH, - (unsigned char *)"0", 1, p, end)) + if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH, + (unsigned char *)"0", 1, p, end)) return -1; if (lws_finalize_http_header(wsi, p, end)) return -1; - n = lws_write(wsi, start, *p - start, LWS_WRITE_HTTP_HEADERS | LWS_WRITE_H2_STREAM_END); - - return n; + return lws_write(wsi, start, *p - start, LWS_WRITE_HTTP_HEADERS | + LWS_WRITE_H2_STREAM_END); } diff --git a/thirdparty/lws/lextable-strings.h b/thirdparty/libwebsockets/roles/http/lextable-strings.h index ab42c3e476..631f5cb600 100644 --- a/thirdparty/lws/lextable-strings.h +++ b/thirdparty/libwebsockets/roles/http/lextable-strings.h @@ -98,6 +98,10 @@ STORE_IN_ROM static const char * const set[] = { "connect ", "head ", "te:", /* http/2 wants it to reject it */ + "replay-nonce:", /* ACME */ + ":protocol", /* defined in mcmanus-httpbis-h2-ws-02 */ + + "x-auth-token:", "", /* not matchable */ diff --git a/thirdparty/libwebsockets/roles/http/lextable.h b/thirdparty/libwebsockets/roles/http/lextable.h new file mode 100644 index 0000000000..9a8063b157 --- /dev/null +++ b/thirdparty/libwebsockets/roles/http/lextable.h @@ -0,0 +1,838 @@ +/* pos 0000: 0 */ 0x67 /* 'g' */, 0x40, 0x00 /* (to 0x0040 state 1) */, + 0x70 /* 'p' */, 0x42, 0x00 /* (to 0x0045 state 5) */, + 0x6F /* 'o' */, 0x51, 0x00 /* (to 0x0057 state 10) */, + 0x68 /* 'h' */, 0x5D, 0x00 /* (to 0x0066 state 18) */, + 0x63 /* 'c' */, 0x69, 0x00 /* (to 0x0075 state 23) */, + 0x75 /* 'u' */, 0x8A, 0x00 /* (to 0x0099 state 34) */, + 0x73 /* 's' */, 0xA0, 0x00 /* (to 0x00B2 state 48) */, + 0x0D /* '.' */, 0xD9, 0x00 /* (to 0x00EE state 68) */, + 0x61 /* 'a' */, 0x31, 0x01 /* (to 0x0149 state 129) */, + 0x69 /* 'i' */, 0x70, 0x01 /* (to 0x018B state 163) */, + 0x64 /* 'd' */, 0x19, 0x02 /* (to 0x0237 state 265) */, + 0x72 /* 'r' */, 0x22, 0x02 /* (to 0x0243 state 270) */, + 0x3A /* ':' */, 0x56, 0x02 /* (to 0x027A state 299) */, + 0x65 /* 'e' */, 0xE8, 0x02 /* (to 0x030F state 409) */, + 0x66 /* 'f' */, 0x04, 0x03 /* (to 0x032E state 425) */, + 0x6C /* 'l' */, 0x26, 0x03 /* (to 0x0353 state 458) */, + 0x6D /* 'm' */, 0x49, 0x03 /* (to 0x0379 state 484) */, + 0x74 /* 't' */, 0xB8, 0x03 /* (to 0x03EB state 578) */, + 0x76 /* 'v' */, 0xD9, 0x03 /* (to 0x040F state 606) */, + 0x77 /* 'w' */, 0xE6, 0x03 /* (to 0x041F state 614) */, + 0x78 /* 'x' */, 0x0D, 0x04 /* (to 0x0449 state 650) */, + 0x08, /* fail */ +/* pos 0040: 1 */ 0xE5 /* 'e' -> */, +/* pos 0041: 2 */ 0xF4 /* 't' -> */, +/* pos 0042: 3 */ 0xA0 /* ' ' -> */, +/* pos 0043: 4 */ 0x00, 0x00 /* - terminal marker 0 - */, +/* pos 0045: 5 */ 0x6F /* 'o' */, 0x0D, 0x00 /* (to 0x0052 state 6) */, + 0x72 /* 'r' */, 0x95, 0x01 /* (to 0x01DD state 211) */, + 0x61 /* 'a' */, 0xE6, 0x03 /* (to 0x0431 state 631) */, + 0x75 /* 'u' */, 0xE8, 0x03 /* (to 0x0436 state 635) */, + 0x08, /* fail */ +/* pos 0052: 6 */ 0xF3 /* 's' -> */, +/* pos 0053: 7 */ 0xF4 /* 't' -> */, +/* pos 0054: 8 */ 0xA0 /* ' ' -> */, +/* pos 0055: 9 */ 0x00, 0x01 /* - terminal marker 1 - */, +/* pos 0057: 10 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x005E state 11) */, + 0x72 /* 'r' */, 0x51, 0x00 /* (to 0x00AB state 42) */, + 0x08, /* fail */ +/* pos 005e: 11 */ 0xF4 /* 't' -> */, +/* pos 005f: 12 */ 0xE9 /* 'i' -> */, +/* pos 0060: 13 */ 0xEF /* 'o' -> */, +/* pos 0061: 14 */ 0xEE /* 'n' -> */, +/* pos 0062: 15 */ 0xF3 /* 's' -> */, +/* pos 0063: 16 */ 0xA0 /* ' ' -> */, +/* pos 0064: 17 */ 0x00, 0x02 /* - terminal marker 2 - */, +/* pos 0066: 18 */ 0x6F /* 'o' */, 0x0A, 0x00 /* (to 0x0070 state 19) */, + 0x74 /* 't' */, 0xBF, 0x00 /* (to 0x0128 state 110) */, + 0x65 /* 'e' */, 0x04, 0x04 /* (to 0x0470 state 676) */, + 0x08, /* fail */ +/* pos 0070: 19 */ 0xF3 /* 's' -> */, +/* pos 0071: 20 */ 0xF4 /* 't' -> */, +/* pos 0072: 21 */ 0xBA /* ':' -> */, +/* pos 0073: 22 */ 0x00, 0x03 /* - terminal marker 3 - */, +/* pos 0075: 23 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x007C state 24) */, + 0x61 /* 'a' */, 0x72, 0x01 /* (to 0x01EA state 217) */, + 0x08, /* fail */ +/* pos 007c: 24 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x0083 state 25) */, + 0x6F /* 'o' */, 0x87, 0x01 /* (to 0x0206 state 243) */, + 0x08, /* fail */ +/* pos 0083: 25 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x008A state 26) */, + 0x74 /* 't' */, 0x86, 0x01 /* (to 0x020C state 248) */, + 0x08, /* fail */ +/* pos 008a: 26 */ 0xE5 /* 'e' -> */, +/* pos 008b: 27 */ 0xE3 /* 'c' -> */, +/* pos 008c: 28 */ 0xF4 /* 't' -> */, +/* pos 008d: 29 */ 0x69 /* 'i' */, 0x07, 0x00 /* (to 0x0094 state 30) */, + 0x20 /* ' ' */, 0xDE, 0x03 /* (to 0x046E state 675) */, + 0x08, /* fail */ +/* pos 0094: 30 */ 0xEF /* 'o' -> */, +/* pos 0095: 31 */ 0xEE /* 'n' -> */, +/* pos 0096: 32 */ 0xBA /* ':' -> */, +/* pos 0097: 33 */ 0x00, 0x04 /* - terminal marker 4 - */, +/* pos 0099: 34 */ 0x70 /* 'p' */, 0x0A, 0x00 /* (to 0x00A3 state 35) */, + 0x73 /* 's' */, 0x68, 0x03 /* (to 0x0404 state 596) */, + 0x72 /* 'r' */, 0xA0, 0x03 /* (to 0x043F state 642) */, + 0x08, /* fail */ +/* pos 00a3: 35 */ 0xE7 /* 'g' -> */, +/* pos 00a4: 36 */ 0xF2 /* 'r' -> */, +/* pos 00a5: 37 */ 0xE1 /* 'a' -> */, +/* pos 00a6: 38 */ 0xE4 /* 'd' -> */, +/* pos 00a7: 39 */ 0xE5 /* 'e' -> */, +/* pos 00a8: 40 */ 0xBA /* ':' -> */, +/* pos 00a9: 41 */ 0x00, 0x05 /* - terminal marker 5 - */, +/* pos 00ab: 42 */ 0xE9 /* 'i' -> */, +/* pos 00ac: 43 */ 0xE7 /* 'g' -> */, +/* pos 00ad: 44 */ 0xE9 /* 'i' -> */, +/* pos 00ae: 45 */ 0xEE /* 'n' -> */, +/* pos 00af: 46 */ 0xBA /* ':' -> */, +/* pos 00b0: 47 */ 0x00, 0x06 /* - terminal marker 6 - */, +/* pos 00b2: 48 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x00B9 state 49) */, + 0x74 /* 't' */, 0x1C, 0x03 /* (to 0x03D1 state 553) */, + 0x08, /* fail */ +/* pos 00b9: 49 */ 0x63 /* 'c' */, 0x0A, 0x00 /* (to 0x00C3 state 50) */, + 0x72 /* 'r' */, 0x05, 0x03 /* (to 0x03C1 state 539) */, + 0x74 /* 't' */, 0x08, 0x03 /* (to 0x03C7 state 544) */, + 0x08, /* fail */ +/* pos 00c3: 50 */ 0xAD /* '-' -> */, +/* pos 00c4: 51 */ 0xF7 /* 'w' -> */, +/* pos 00c5: 52 */ 0xE5 /* 'e' -> */, +/* pos 00c6: 53 */ 0xE2 /* 'b' -> */, +/* pos 00c7: 54 */ 0xF3 /* 's' -> */, +/* pos 00c8: 55 */ 0xEF /* 'o' -> */, +/* pos 00c9: 56 */ 0xE3 /* 'c' -> */, +/* pos 00ca: 57 */ 0xEB /* 'k' -> */, +/* pos 00cb: 58 */ 0xE5 /* 'e' -> */, +/* pos 00cc: 59 */ 0xF4 /* 't' -> */, +/* pos 00cd: 60 */ 0xAD /* '-' -> */, +/* pos 00ce: 61 */ 0x64 /* 'd' */, 0x19, 0x00 /* (to 0x00E7 state 62) */, + 0x65 /* 'e' */, 0x20, 0x00 /* (to 0x00F1 state 70) */, + 0x6B /* 'k' */, 0x29, 0x00 /* (to 0x00FD state 81) */, + 0x70 /* 'p' */, 0x38, 0x00 /* (to 0x010F state 88) */, + 0x61 /* 'a' */, 0x3F, 0x00 /* (to 0x0119 state 97) */, + 0x6E /* 'n' */, 0x44, 0x00 /* (to 0x0121 state 104) */, + 0x76 /* 'v' */, 0x89, 0x01 /* (to 0x0269 state 284) */, + 0x6F /* 'o' */, 0x8F, 0x01 /* (to 0x0272 state 292) */, + 0x08, /* fail */ +/* pos 00e7: 62 */ 0xF2 /* 'r' -> */, +/* pos 00e8: 63 */ 0xE1 /* 'a' -> */, +/* pos 00e9: 64 */ 0xE6 /* 'f' -> */, +/* pos 00ea: 65 */ 0xF4 /* 't' -> */, +/* pos 00eb: 66 */ 0xBA /* ':' -> */, +/* pos 00ec: 67 */ 0x00, 0x07 /* - terminal marker 7 - */, +/* pos 00ee: 68 */ 0x8A /* '.' -> */, +/* pos 00ef: 69 */ 0x00, 0x08 /* - terminal marker 8 - */, +/* pos 00f1: 70 */ 0xF8 /* 'x' -> */, +/* pos 00f2: 71 */ 0xF4 /* 't' -> */, +/* pos 00f3: 72 */ 0xE5 /* 'e' -> */, +/* pos 00f4: 73 */ 0xEE /* 'n' -> */, +/* pos 00f5: 74 */ 0xF3 /* 's' -> */, +/* pos 00f6: 75 */ 0xE9 /* 'i' -> */, +/* pos 00f7: 76 */ 0xEF /* 'o' -> */, +/* pos 00f8: 77 */ 0xEE /* 'n' -> */, +/* pos 00f9: 78 */ 0xF3 /* 's' -> */, +/* pos 00fa: 79 */ 0xBA /* ':' -> */, +/* pos 00fb: 80 */ 0x00, 0x09 /* - terminal marker 9 - */, +/* pos 00fd: 81 */ 0xE5 /* 'e' -> */, +/* pos 00fe: 82 */ 0xF9 /* 'y' -> */, +/* pos 00ff: 83 */ 0x31 /* '1' */, 0x0A, 0x00 /* (to 0x0109 state 84) */, + 0x32 /* '2' */, 0x0A, 0x00 /* (to 0x010C state 86) */, + 0x3A /* ':' */, 0x62, 0x01 /* (to 0x0267 state 283) */, + 0x08, /* fail */ +/* pos 0109: 84 */ 0xBA /* ':' -> */, +/* pos 010a: 85 */ 0x00, 0x0A /* - terminal marker 10 - */, +/* pos 010c: 86 */ 0xBA /* ':' -> */, +/* pos 010d: 87 */ 0x00, 0x0B /* - terminal marker 11 - */, +/* pos 010f: 88 */ 0xF2 /* 'r' -> */, +/* pos 0110: 89 */ 0xEF /* 'o' -> */, +/* pos 0111: 90 */ 0xF4 /* 't' -> */, +/* pos 0112: 91 */ 0xEF /* 'o' -> */, +/* pos 0113: 92 */ 0xE3 /* 'c' -> */, +/* pos 0114: 93 */ 0xEF /* 'o' -> */, +/* pos 0115: 94 */ 0xEC /* 'l' -> */, +/* pos 0116: 95 */ 0xBA /* ':' -> */, +/* pos 0117: 96 */ 0x00, 0x0C /* - terminal marker 12 - */, +/* pos 0119: 97 */ 0xE3 /* 'c' -> */, +/* pos 011a: 98 */ 0xE3 /* 'c' -> */, +/* pos 011b: 99 */ 0xE5 /* 'e' -> */, +/* pos 011c: 100 */ 0xF0 /* 'p' -> */, +/* pos 011d: 101 */ 0xF4 /* 't' -> */, +/* pos 011e: 102 */ 0xBA /* ':' -> */, +/* pos 011f: 103 */ 0x00, 0x0D /* - terminal marker 13 - */, +/* pos 0121: 104 */ 0xEF /* 'o' -> */, +/* pos 0122: 105 */ 0xEE /* 'n' -> */, +/* pos 0123: 106 */ 0xE3 /* 'c' -> */, +/* pos 0124: 107 */ 0xE5 /* 'e' -> */, +/* pos 0125: 108 */ 0xBA /* ':' -> */, +/* pos 0126: 109 */ 0x00, 0x0E /* - terminal marker 14 - */, +/* pos 0128: 110 */ 0xF4 /* 't' -> */, +/* pos 0129: 111 */ 0xF0 /* 'p' -> */, +/* pos 012a: 112 */ 0x2F /* '/' */, 0x07, 0x00 /* (to 0x0131 state 113) */, + 0x32 /* '2' */, 0x10, 0x00 /* (to 0x013D state 118) */, + 0x08, /* fail */ +/* pos 0131: 113 */ 0xB1 /* '1' -> */, +/* pos 0132: 114 */ 0xAE /* '.' -> */, +/* pos 0133: 115 */ 0x31 /* '1' */, 0x07, 0x00 /* (to 0x013A state 116) */, + 0x30 /* '0' */, 0x27, 0x03 /* (to 0x045D state 660) */, + 0x08, /* fail */ +/* pos 013a: 116 */ 0xA0 /* ' ' -> */, +/* pos 013b: 117 */ 0x00, 0x0F /* - terminal marker 15 - */, +/* pos 013d: 118 */ 0xAD /* '-' -> */, +/* pos 013e: 119 */ 0xF3 /* 's' -> */, +/* pos 013f: 120 */ 0xE5 /* 'e' -> */, +/* pos 0140: 121 */ 0xF4 /* 't' -> */, +/* pos 0141: 122 */ 0xF4 /* 't' -> */, +/* pos 0142: 123 */ 0xE9 /* 'i' -> */, +/* pos 0143: 124 */ 0xEE /* 'n' -> */, +/* pos 0144: 125 */ 0xE7 /* 'g' -> */, +/* pos 0145: 126 */ 0xF3 /* 's' -> */, +/* pos 0146: 127 */ 0xBA /* ':' -> */, +/* pos 0147: 128 */ 0x00, 0x10 /* - terminal marker 16 - */, +/* pos 0149: 129 */ 0x63 /* 'c' */, 0x0D, 0x00 /* (to 0x0156 state 130) */, + 0x75 /* 'u' */, 0xAC, 0x00 /* (to 0x01F8 state 230) */, + 0x67 /* 'g' */, 0x86, 0x01 /* (to 0x02D5 state 358) */, + 0x6C /* 'l' */, 0x87, 0x01 /* (to 0x02D9 state 361) */, + 0x08, /* fail */ +/* pos 0156: 130 */ 0xE3 /* 'c' -> */, +/* pos 0157: 131 */ 0xE5 /* 'e' -> */, +/* pos 0158: 132 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x015F state 133) */, + 0x73 /* 's' */, 0x0E, 0x00 /* (to 0x0169 state 136) */, + 0x08, /* fail */ +/* pos 015f: 133 */ 0xF4 /* 't' -> */, +/* pos 0160: 134 */ 0x3A /* ':' */, 0x07, 0x00 /* (to 0x0167 state 135) */, + 0x2D /* '-' */, 0x59, 0x00 /* (to 0x01BC state 192) */, + 0x08, /* fail */ +/* pos 0167: 135 */ 0x00, 0x11 /* - terminal marker 17 - */, +/* pos 0169: 136 */ 0xF3 /* 's' -> */, +/* pos 016a: 137 */ 0xAD /* '-' -> */, +/* pos 016b: 138 */ 0xE3 /* 'c' -> */, +/* pos 016c: 139 */ 0xEF /* 'o' -> */, +/* pos 016d: 140 */ 0xEE /* 'n' -> */, +/* pos 016e: 141 */ 0xF4 /* 't' -> */, +/* pos 016f: 142 */ 0xF2 /* 'r' -> */, +/* pos 0170: 143 */ 0xEF /* 'o' -> */, +/* pos 0171: 144 */ 0xEC /* 'l' -> */, +/* pos 0172: 145 */ 0xAD /* '-' -> */, +/* pos 0173: 146 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x017A state 147) */, + 0x61 /* 'a' */, 0x51, 0x01 /* (to 0x02C7 state 345) */, + 0x08, /* fail */ +/* pos 017a: 147 */ 0xE5 /* 'e' -> */, +/* pos 017b: 148 */ 0xF1 /* 'q' -> */, +/* pos 017c: 149 */ 0xF5 /* 'u' -> */, +/* pos 017d: 150 */ 0xE5 /* 'e' -> */, +/* pos 017e: 151 */ 0xF3 /* 's' -> */, +/* pos 017f: 152 */ 0xF4 /* 't' -> */, +/* pos 0180: 153 */ 0xAD /* '-' -> */, +/* pos 0181: 154 */ 0xE8 /* 'h' -> */, +/* pos 0182: 155 */ 0xE5 /* 'e' -> */, +/* pos 0183: 156 */ 0xE1 /* 'a' -> */, +/* pos 0184: 157 */ 0xE4 /* 'd' -> */, +/* pos 0185: 158 */ 0xE5 /* 'e' -> */, +/* pos 0186: 159 */ 0xF2 /* 'r' -> */, +/* pos 0187: 160 */ 0xF3 /* 's' -> */, +/* pos 0188: 161 */ 0xBA /* ':' -> */, +/* pos 0189: 162 */ 0x00, 0x12 /* - terminal marker 18 - */, +/* pos 018b: 163 */ 0xE6 /* 'f' -> */, +/* pos 018c: 164 */ 0xAD /* '-' -> */, +/* pos 018d: 165 */ 0x6D /* 'm' */, 0x0D, 0x00 /* (to 0x019A state 166) */, + 0x6E /* 'n' */, 0x20, 0x00 /* (to 0x01B0 state 181) */, + 0x72 /* 'r' */, 0xA7, 0x01 /* (to 0x033A state 435) */, + 0x75 /* 'u' */, 0xAB, 0x01 /* (to 0x0341 state 441) */, + 0x08, /* fail */ +/* pos 019a: 166 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x01A1 state 167) */, + 0x61 /* 'a' */, 0x97, 0x01 /* (to 0x0334 state 430) */, + 0x08, /* fail */ +/* pos 01a1: 167 */ 0xE4 /* 'd' -> */, +/* pos 01a2: 168 */ 0xE9 /* 'i' -> */, +/* pos 01a3: 169 */ 0xE6 /* 'f' -> */, +/* pos 01a4: 170 */ 0xE9 /* 'i' -> */, +/* pos 01a5: 171 */ 0xE5 /* 'e' -> */, +/* pos 01a6: 172 */ 0xE4 /* 'd' -> */, +/* pos 01a7: 173 */ 0xAD /* '-' -> */, +/* pos 01a8: 174 */ 0xF3 /* 's' -> */, +/* pos 01a9: 175 */ 0xE9 /* 'i' -> */, +/* pos 01aa: 176 */ 0xEE /* 'n' -> */, +/* pos 01ab: 177 */ 0xE3 /* 'c' -> */, +/* pos 01ac: 178 */ 0xE5 /* 'e' -> */, +/* pos 01ad: 179 */ 0xBA /* ':' -> */, +/* pos 01ae: 180 */ 0x00, 0x13 /* - terminal marker 19 - */, +/* pos 01b0: 181 */ 0xEF /* 'o' -> */, +/* pos 01b1: 182 */ 0xEE /* 'n' -> */, +/* pos 01b2: 183 */ 0xE5 /* 'e' -> */, +/* pos 01b3: 184 */ 0xAD /* '-' -> */, +/* pos 01b4: 185 */ 0xED /* 'm' -> */, +/* pos 01b5: 186 */ 0xE1 /* 'a' -> */, +/* pos 01b6: 187 */ 0xF4 /* 't' -> */, +/* pos 01b7: 188 */ 0xE3 /* 'c' -> */, +/* pos 01b8: 189 */ 0xE8 /* 'h' -> */, +/* pos 01b9: 190 */ 0xBA /* ':' -> */, +/* pos 01ba: 191 */ 0x00, 0x14 /* - terminal marker 20 - */, +/* pos 01bc: 192 */ 0x65 /* 'e' */, 0x0D, 0x00 /* (to 0x01C9 state 193) */, + 0x6C /* 'l' */, 0x14, 0x00 /* (to 0x01D3 state 202) */, + 0x63 /* 'c' */, 0xF4, 0x00 /* (to 0x02B6 state 330) */, + 0x72 /* 'r' */, 0xFA, 0x00 /* (to 0x02BF state 338) */, + 0x08, /* fail */ +/* pos 01c9: 193 */ 0xEE /* 'n' -> */, +/* pos 01ca: 194 */ 0xE3 /* 'c' -> */, +/* pos 01cb: 195 */ 0xEF /* 'o' -> */, +/* pos 01cc: 196 */ 0xE4 /* 'd' -> */, +/* pos 01cd: 197 */ 0xE9 /* 'i' -> */, +/* pos 01ce: 198 */ 0xEE /* 'n' -> */, +/* pos 01cf: 199 */ 0xE7 /* 'g' -> */, +/* pos 01d0: 200 */ 0xBA /* ':' -> */, +/* pos 01d1: 201 */ 0x00, 0x15 /* - terminal marker 21 - */, +/* pos 01d3: 202 */ 0xE1 /* 'a' -> */, +/* pos 01d4: 203 */ 0xEE /* 'n' -> */, +/* pos 01d5: 204 */ 0xE7 /* 'g' -> */, +/* pos 01d6: 205 */ 0xF5 /* 'u' -> */, +/* pos 01d7: 206 */ 0xE1 /* 'a' -> */, +/* pos 01d8: 207 */ 0xE7 /* 'g' -> */, +/* pos 01d9: 208 */ 0xE5 /* 'e' -> */, +/* pos 01da: 209 */ 0xBA /* ':' -> */, +/* pos 01db: 210 */ 0x00, 0x16 /* - terminal marker 22 - */, +/* pos 01dd: 211 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x01E4 state 212) */, + 0x6F /* 'o' */, 0xA7, 0x01 /* (to 0x0387 state 497) */, + 0x08, /* fail */ +/* pos 01e4: 212 */ 0xE7 /* 'g' -> */, +/* pos 01e5: 213 */ 0xED /* 'm' -> */, +/* pos 01e6: 214 */ 0xE1 /* 'a' -> */, +/* pos 01e7: 215 */ 0xBA /* ':' -> */, +/* pos 01e8: 216 */ 0x00, 0x17 /* - terminal marker 23 - */, +/* pos 01ea: 217 */ 0xE3 /* 'c' -> */, +/* pos 01eb: 218 */ 0xE8 /* 'h' -> */, +/* pos 01ec: 219 */ 0xE5 /* 'e' -> */, +/* pos 01ed: 220 */ 0xAD /* '-' -> */, +/* pos 01ee: 221 */ 0xE3 /* 'c' -> */, +/* pos 01ef: 222 */ 0xEF /* 'o' -> */, +/* pos 01f0: 223 */ 0xEE /* 'n' -> */, +/* pos 01f1: 224 */ 0xF4 /* 't' -> */, +/* pos 01f2: 225 */ 0xF2 /* 'r' -> */, +/* pos 01f3: 226 */ 0xEF /* 'o' -> */, +/* pos 01f4: 227 */ 0xEC /* 'l' -> */, +/* pos 01f5: 228 */ 0xBA /* ':' -> */, +/* pos 01f6: 229 */ 0x00, 0x18 /* - terminal marker 24 - */, +/* pos 01f8: 230 */ 0xF4 /* 't' -> */, +/* pos 01f9: 231 */ 0xE8 /* 'h' -> */, +/* pos 01fa: 232 */ 0xEF /* 'o' -> */, +/* pos 01fb: 233 */ 0xF2 /* 'r' -> */, +/* pos 01fc: 234 */ 0xE9 /* 'i' -> */, +/* pos 01fd: 235 */ 0xFA /* 'z' -> */, +/* pos 01fe: 236 */ 0xE1 /* 'a' -> */, +/* pos 01ff: 237 */ 0xF4 /* 't' -> */, +/* pos 0200: 238 */ 0xE9 /* 'i' -> */, +/* pos 0201: 239 */ 0xEF /* 'o' -> */, +/* pos 0202: 240 */ 0xEE /* 'n' -> */, +/* pos 0203: 241 */ 0xBA /* ':' -> */, +/* pos 0204: 242 */ 0x00, 0x19 /* - terminal marker 25 - */, +/* pos 0206: 243 */ 0xEB /* 'k' -> */, +/* pos 0207: 244 */ 0xE9 /* 'i' -> */, +/* pos 0208: 245 */ 0xE5 /* 'e' -> */, +/* pos 0209: 246 */ 0xBA /* ':' -> */, +/* pos 020a: 247 */ 0x00, 0x1A /* - terminal marker 26 - */, +/* pos 020c: 248 */ 0xE5 /* 'e' -> */, +/* pos 020d: 249 */ 0xEE /* 'n' -> */, +/* pos 020e: 250 */ 0xF4 /* 't' -> */, +/* pos 020f: 251 */ 0xAD /* '-' -> */, +/* pos 0210: 252 */ 0x6C /* 'l' */, 0x10, 0x00 /* (to 0x0220 state 253) */, + 0x74 /* 't' */, 0x1E, 0x00 /* (to 0x0231 state 260) */, + 0x64 /* 'd' */, 0xC9, 0x00 /* (to 0x02DF state 366) */, + 0x65 /* 'e' */, 0xD3, 0x00 /* (to 0x02EC state 378) */, + 0x72 /* 'r' */, 0xEC, 0x00 /* (to 0x0308 state 403) */, + 0x08, /* fail */ +/* pos 0220: 253 */ 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x022A state 254) */, + 0x61 /* 'a' */, 0xD3, 0x00 /* (to 0x02F6 state 387) */, + 0x6F /* 'o' */, 0xD9, 0x00 /* (to 0x02FF state 395) */, + 0x08, /* fail */ +/* pos 022a: 254 */ 0xEE /* 'n' -> */, +/* pos 022b: 255 */ 0xE7 /* 'g' -> */, +/* pos 022c: 256 */ 0xF4 /* 't' -> */, +/* pos 022d: 257 */ 0xE8 /* 'h' -> */, +/* pos 022e: 258 */ 0xBA /* ':' -> */, +/* pos 022f: 259 */ 0x00, 0x1B /* - terminal marker 27 - */, +/* pos 0231: 260 */ 0xF9 /* 'y' -> */, +/* pos 0232: 261 */ 0xF0 /* 'p' -> */, +/* pos 0233: 262 */ 0xE5 /* 'e' -> */, +/* pos 0234: 263 */ 0xBA /* ':' -> */, +/* pos 0235: 264 */ 0x00, 0x1C /* - terminal marker 28 - */, +/* pos 0237: 265 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x023E state 266) */, + 0x65 /* 'e' */, 0xFF, 0x01 /* (to 0x0439 state 637) */, + 0x08, /* fail */ +/* pos 023e: 266 */ 0xF4 /* 't' -> */, +/* pos 023f: 267 */ 0xE5 /* 'e' -> */, +/* pos 0240: 268 */ 0xBA /* ':' -> */, +/* pos 0241: 269 */ 0x00, 0x1D /* - terminal marker 29 - */, +/* pos 0243: 270 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x024A state 271) */, + 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x0250 state 276) */, + 0x08, /* fail */ +/* pos 024a: 271 */ 0xEE /* 'n' -> */, +/* pos 024b: 272 */ 0xE7 /* 'g' -> */, +/* pos 024c: 273 */ 0xE5 /* 'e' -> */, +/* pos 024d: 274 */ 0xBA /* ':' -> */, +/* pos 024e: 275 */ 0x00, 0x1E /* - terminal marker 30 - */, +/* pos 0250: 276 */ 0x66 /* 'f' */, 0x0A, 0x00 /* (to 0x025A state 277) */, + 0x74 /* 't' */, 0x63, 0x01 /* (to 0x03B6 state 529) */, + 0x70 /* 'p' */, 0x22, 0x02 /* (to 0x0478 state 682) */, + 0x08, /* fail */ +/* pos 025a: 277 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x0261 state 278) */, + 0x72 /* 'r' */, 0x53, 0x01 /* (to 0x03B0 state 524) */, + 0x08, /* fail */ +/* pos 0261: 278 */ 0xF2 /* 'r' -> */, +/* pos 0262: 279 */ 0xE5 /* 'e' -> */, +/* pos 0263: 280 */ 0xF2 /* 'r' -> */, +/* pos 0264: 281 */ 0xBA /* ':' -> */, +/* pos 0265: 282 */ 0x00, 0x1F /* - terminal marker 31 - */, +/* pos 0267: 283 */ 0x00, 0x20 /* - terminal marker 32 - */, +/* pos 0269: 284 */ 0xE5 /* 'e' -> */, +/* pos 026a: 285 */ 0xF2 /* 'r' -> */, +/* pos 026b: 286 */ 0xF3 /* 's' -> */, +/* pos 026c: 287 */ 0xE9 /* 'i' -> */, +/* pos 026d: 288 */ 0xEF /* 'o' -> */, +/* pos 026e: 289 */ 0xEE /* 'n' -> */, +/* pos 026f: 290 */ 0xBA /* ':' -> */, +/* pos 0270: 291 */ 0x00, 0x21 /* - terminal marker 33 - */, +/* pos 0272: 292 */ 0xF2 /* 'r' -> */, +/* pos 0273: 293 */ 0xE9 /* 'i' -> */, +/* pos 0274: 294 */ 0xE7 /* 'g' -> */, +/* pos 0275: 295 */ 0xE9 /* 'i' -> */, +/* pos 0276: 296 */ 0xEE /* 'n' -> */, +/* pos 0277: 297 */ 0xBA /* ':' -> */, +/* pos 0278: 298 */ 0x00, 0x22 /* - terminal marker 34 - */, +/* pos 027a: 299 */ 0x61 /* 'a' */, 0x0D, 0x00 /* (to 0x0287 state 300) */, + 0x6D /* 'm' */, 0x14, 0x00 /* (to 0x0291 state 309) */, + 0x70 /* 'p' */, 0x18, 0x00 /* (to 0x0298 state 315) */, + 0x73 /* 's' */, 0x20, 0x00 /* (to 0x02A3 state 319) */, + 0x08, /* fail */ +/* pos 0287: 300 */ 0xF5 /* 'u' -> */, +/* pos 0288: 301 */ 0xF4 /* 't' -> */, +/* pos 0289: 302 */ 0xE8 /* 'h' -> */, +/* pos 028a: 303 */ 0xEF /* 'o' -> */, +/* pos 028b: 304 */ 0xF2 /* 'r' -> */, +/* pos 028c: 305 */ 0xE9 /* 'i' -> */, +/* pos 028d: 306 */ 0xF4 /* 't' -> */, +/* pos 028e: 307 */ 0xF9 /* 'y' -> */, +/* pos 028f: 308 */ 0x00, 0x23 /* - terminal marker 35 - */, +/* pos 0291: 309 */ 0xE5 /* 'e' -> */, +/* pos 0292: 310 */ 0xF4 /* 't' -> */, +/* pos 0293: 311 */ 0xE8 /* 'h' -> */, +/* pos 0294: 312 */ 0xEF /* 'o' -> */, +/* pos 0295: 313 */ 0xE4 /* 'd' -> */, +/* pos 0296: 314 */ 0x00, 0x24 /* - terminal marker 36 - */, +/* pos 0298: 315 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x029F state 316) */, + 0x72 /* 'r' */, 0xE9, 0x01 /* (to 0x0484 state 693) */, + 0x08, /* fail */ +/* pos 029f: 316 */ 0xF4 /* 't' -> */, +/* pos 02a0: 317 */ 0xE8 /* 'h' -> */, +/* pos 02a1: 318 */ 0x00, 0x25 /* - terminal marker 37 - */, +/* pos 02a3: 319 */ 0x63 /* 'c' */, 0x07, 0x00 /* (to 0x02AA state 320) */, + 0x74 /* 't' */, 0x0A, 0x00 /* (to 0x02B0 state 325) */, + 0x08, /* fail */ +/* pos 02aa: 320 */ 0xE8 /* 'h' -> */, +/* pos 02ab: 321 */ 0xE5 /* 'e' -> */, +/* pos 02ac: 322 */ 0xED /* 'm' -> */, +/* pos 02ad: 323 */ 0xE5 /* 'e' -> */, +/* pos 02ae: 324 */ 0x00, 0x26 /* - terminal marker 38 - */, +/* pos 02b0: 325 */ 0xE1 /* 'a' -> */, +/* pos 02b1: 326 */ 0xF4 /* 't' -> */, +/* pos 02b2: 327 */ 0xF5 /* 'u' -> */, +/* pos 02b3: 328 */ 0xF3 /* 's' -> */, +/* pos 02b4: 329 */ 0x00, 0x27 /* - terminal marker 39 - */, +/* pos 02b6: 330 */ 0xE8 /* 'h' -> */, +/* pos 02b7: 331 */ 0xE1 /* 'a' -> */, +/* pos 02b8: 332 */ 0xF2 /* 'r' -> */, +/* pos 02b9: 333 */ 0xF3 /* 's' -> */, +/* pos 02ba: 334 */ 0xE5 /* 'e' -> */, +/* pos 02bb: 335 */ 0xF4 /* 't' -> */, +/* pos 02bc: 336 */ 0xBA /* ':' -> */, +/* pos 02bd: 337 */ 0x00, 0x28 /* - terminal marker 40 - */, +/* pos 02bf: 338 */ 0xE1 /* 'a' -> */, +/* pos 02c0: 339 */ 0xEE /* 'n' -> */, +/* pos 02c1: 340 */ 0xE7 /* 'g' -> */, +/* pos 02c2: 341 */ 0xE5 /* 'e' -> */, +/* pos 02c3: 342 */ 0xF3 /* 's' -> */, +/* pos 02c4: 343 */ 0xBA /* ':' -> */, +/* pos 02c5: 344 */ 0x00, 0x29 /* - terminal marker 41 - */, +/* pos 02c7: 345 */ 0xEC /* 'l' -> */, +/* pos 02c8: 346 */ 0xEC /* 'l' -> */, +/* pos 02c9: 347 */ 0xEF /* 'o' -> */, +/* pos 02ca: 348 */ 0xF7 /* 'w' -> */, +/* pos 02cb: 349 */ 0xAD /* '-' -> */, +/* pos 02cc: 350 */ 0xEF /* 'o' -> */, +/* pos 02cd: 351 */ 0xF2 /* 'r' -> */, +/* pos 02ce: 352 */ 0xE9 /* 'i' -> */, +/* pos 02cf: 353 */ 0xE7 /* 'g' -> */, +/* pos 02d0: 354 */ 0xE9 /* 'i' -> */, +/* pos 02d1: 355 */ 0xEE /* 'n' -> */, +/* pos 02d2: 356 */ 0xBA /* ':' -> */, +/* pos 02d3: 357 */ 0x00, 0x2A /* - terminal marker 42 - */, +/* pos 02d5: 358 */ 0xE5 /* 'e' -> */, +/* pos 02d6: 359 */ 0xBA /* ':' -> */, +/* pos 02d7: 360 */ 0x00, 0x2B /* - terminal marker 43 - */, +/* pos 02d9: 361 */ 0xEC /* 'l' -> */, +/* pos 02da: 362 */ 0xEF /* 'o' -> */, +/* pos 02db: 363 */ 0xF7 /* 'w' -> */, +/* pos 02dc: 364 */ 0xBA /* ':' -> */, +/* pos 02dd: 365 */ 0x00, 0x2C /* - terminal marker 44 - */, +/* pos 02df: 366 */ 0xE9 /* 'i' -> */, +/* pos 02e0: 367 */ 0xF3 /* 's' -> */, +/* pos 02e1: 368 */ 0xF0 /* 'p' -> */, +/* pos 02e2: 369 */ 0xEF /* 'o' -> */, +/* pos 02e3: 370 */ 0xF3 /* 's' -> */, +/* pos 02e4: 371 */ 0xE9 /* 'i' -> */, +/* pos 02e5: 372 */ 0xF4 /* 't' -> */, +/* pos 02e6: 373 */ 0xE9 /* 'i' -> */, +/* pos 02e7: 374 */ 0xEF /* 'o' -> */, +/* pos 02e8: 375 */ 0xEE /* 'n' -> */, +/* pos 02e9: 376 */ 0xBA /* ':' -> */, +/* pos 02ea: 377 */ 0x00, 0x2D /* - terminal marker 45 - */, +/* pos 02ec: 378 */ 0xEE /* 'n' -> */, +/* pos 02ed: 379 */ 0xE3 /* 'c' -> */, +/* pos 02ee: 380 */ 0xEF /* 'o' -> */, +/* pos 02ef: 381 */ 0xE4 /* 'd' -> */, +/* pos 02f0: 382 */ 0xE9 /* 'i' -> */, +/* pos 02f1: 383 */ 0xEE /* 'n' -> */, +/* pos 02f2: 384 */ 0xE7 /* 'g' -> */, +/* pos 02f3: 385 */ 0xBA /* ':' -> */, +/* pos 02f4: 386 */ 0x00, 0x2E /* - terminal marker 46 - */, +/* pos 02f6: 387 */ 0xEE /* 'n' -> */, +/* pos 02f7: 388 */ 0xE7 /* 'g' -> */, +/* pos 02f8: 389 */ 0xF5 /* 'u' -> */, +/* pos 02f9: 390 */ 0xE1 /* 'a' -> */, +/* pos 02fa: 391 */ 0xE7 /* 'g' -> */, +/* pos 02fb: 392 */ 0xE5 /* 'e' -> */, +/* pos 02fc: 393 */ 0xBA /* ':' -> */, +/* pos 02fd: 394 */ 0x00, 0x2F /* - terminal marker 47 - */, +/* pos 02ff: 395 */ 0xE3 /* 'c' -> */, +/* pos 0300: 396 */ 0xE1 /* 'a' -> */, +/* pos 0301: 397 */ 0xF4 /* 't' -> */, +/* pos 0302: 398 */ 0xE9 /* 'i' -> */, +/* pos 0303: 399 */ 0xEF /* 'o' -> */, +/* pos 0304: 400 */ 0xEE /* 'n' -> */, +/* pos 0305: 401 */ 0xBA /* ':' -> */, +/* pos 0306: 402 */ 0x00, 0x30 /* - terminal marker 48 - */, +/* pos 0308: 403 */ 0xE1 /* 'a' -> */, +/* pos 0309: 404 */ 0xEE /* 'n' -> */, +/* pos 030a: 405 */ 0xE7 /* 'g' -> */, +/* pos 030b: 406 */ 0xE5 /* 'e' -> */, +/* pos 030c: 407 */ 0xBA /* ':' -> */, +/* pos 030d: 408 */ 0x00, 0x31 /* - terminal marker 49 - */, +/* pos 030f: 409 */ 0x74 /* 't' */, 0x07, 0x00 /* (to 0x0316 state 410) */, + 0x78 /* 'x' */, 0x09, 0x00 /* (to 0x031B state 414) */, + 0x08, /* fail */ +/* pos 0316: 410 */ 0xE1 /* 'a' -> */, +/* pos 0317: 411 */ 0xE7 /* 'g' -> */, +/* pos 0318: 412 */ 0xBA /* ':' -> */, +/* pos 0319: 413 */ 0x00, 0x32 /* - terminal marker 50 - */, +/* pos 031b: 414 */ 0xF0 /* 'p' -> */, +/* pos 031c: 415 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x0323 state 416) */, + 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x0328 state 420) */, + 0x08, /* fail */ +/* pos 0323: 416 */ 0xE3 /* 'c' -> */, +/* pos 0324: 417 */ 0xF4 /* 't' -> */, +/* pos 0325: 418 */ 0xBA /* ':' -> */, +/* pos 0326: 419 */ 0x00, 0x33 /* - terminal marker 51 - */, +/* pos 0328: 420 */ 0xF2 /* 'r' -> */, +/* pos 0329: 421 */ 0xE5 /* 'e' -> */, +/* pos 032a: 422 */ 0xF3 /* 's' -> */, +/* pos 032b: 423 */ 0xBA /* ':' -> */, +/* pos 032c: 424 */ 0x00, 0x34 /* - terminal marker 52 - */, +/* pos 032e: 425 */ 0xF2 /* 'r' -> */, +/* pos 032f: 426 */ 0xEF /* 'o' -> */, +/* pos 0330: 427 */ 0xED /* 'm' -> */, +/* pos 0331: 428 */ 0xBA /* ':' -> */, +/* pos 0332: 429 */ 0x00, 0x35 /* - terminal marker 53 - */, +/* pos 0334: 430 */ 0xF4 /* 't' -> */, +/* pos 0335: 431 */ 0xE3 /* 'c' -> */, +/* pos 0336: 432 */ 0xE8 /* 'h' -> */, +/* pos 0337: 433 */ 0xBA /* ':' -> */, +/* pos 0338: 434 */ 0x00, 0x36 /* - terminal marker 54 - */, +/* pos 033a: 435 */ 0xE1 /* 'a' -> */, +/* pos 033b: 436 */ 0xEE /* 'n' -> */, +/* pos 033c: 437 */ 0xE7 /* 'g' -> */, +/* pos 033d: 438 */ 0xE5 /* 'e' -> */, +/* pos 033e: 439 */ 0xBA /* ':' -> */, +/* pos 033f: 440 */ 0x00, 0x37 /* - terminal marker 55 - */, +/* pos 0341: 441 */ 0xEE /* 'n' -> */, +/* pos 0342: 442 */ 0xED /* 'm' -> */, +/* pos 0343: 443 */ 0xEF /* 'o' -> */, +/* pos 0344: 444 */ 0xE4 /* 'd' -> */, +/* pos 0345: 445 */ 0xE9 /* 'i' -> */, +/* pos 0346: 446 */ 0xE6 /* 'f' -> */, +/* pos 0347: 447 */ 0xE9 /* 'i' -> */, +/* pos 0348: 448 */ 0xE5 /* 'e' -> */, +/* pos 0349: 449 */ 0xE4 /* 'd' -> */, +/* pos 034a: 450 */ 0xAD /* '-' -> */, +/* pos 034b: 451 */ 0xF3 /* 's' -> */, +/* pos 034c: 452 */ 0xE9 /* 'i' -> */, +/* pos 034d: 453 */ 0xEE /* 'n' -> */, +/* pos 034e: 454 */ 0xE3 /* 'c' -> */, +/* pos 034f: 455 */ 0xE5 /* 'e' -> */, +/* pos 0350: 456 */ 0xBA /* ':' -> */, +/* pos 0351: 457 */ 0x00, 0x38 /* - terminal marker 56 - */, +/* pos 0353: 458 */ 0x61 /* 'a' */, 0x0A, 0x00 /* (to 0x035D state 459) */, + 0x69 /* 'i' */, 0x15, 0x00 /* (to 0x036B state 472) */, + 0x6F /* 'o' */, 0x17, 0x00 /* (to 0x0370 state 476) */, + 0x08, /* fail */ +/* pos 035d: 459 */ 0xF3 /* 's' -> */, +/* pos 035e: 460 */ 0xF4 /* 't' -> */, +/* pos 035f: 461 */ 0xAD /* '-' -> */, +/* pos 0360: 462 */ 0xED /* 'm' -> */, +/* pos 0361: 463 */ 0xEF /* 'o' -> */, +/* pos 0362: 464 */ 0xE4 /* 'd' -> */, +/* pos 0363: 465 */ 0xE9 /* 'i' -> */, +/* pos 0364: 466 */ 0xE6 /* 'f' -> */, +/* pos 0365: 467 */ 0xE9 /* 'i' -> */, +/* pos 0366: 468 */ 0xE5 /* 'e' -> */, +/* pos 0367: 469 */ 0xE4 /* 'd' -> */, +/* pos 0368: 470 */ 0xBA /* ':' -> */, +/* pos 0369: 471 */ 0x00, 0x39 /* - terminal marker 57 - */, +/* pos 036b: 472 */ 0xEE /* 'n' -> */, +/* pos 036c: 473 */ 0xEB /* 'k' -> */, +/* pos 036d: 474 */ 0xBA /* ':' -> */, +/* pos 036e: 475 */ 0x00, 0x3A /* - terminal marker 58 - */, +/* pos 0370: 476 */ 0xE3 /* 'c' -> */, +/* pos 0371: 477 */ 0xE1 /* 'a' -> */, +/* pos 0372: 478 */ 0xF4 /* 't' -> */, +/* pos 0373: 479 */ 0xE9 /* 'i' -> */, +/* pos 0374: 480 */ 0xEF /* 'o' -> */, +/* pos 0375: 481 */ 0xEE /* 'n' -> */, +/* pos 0376: 482 */ 0xBA /* ':' -> */, +/* pos 0377: 483 */ 0x00, 0x3B /* - terminal marker 59 - */, +/* pos 0379: 484 */ 0xE1 /* 'a' -> */, +/* pos 037a: 485 */ 0xF8 /* 'x' -> */, +/* pos 037b: 486 */ 0xAD /* '-' -> */, +/* pos 037c: 487 */ 0xE6 /* 'f' -> */, +/* pos 037d: 488 */ 0xEF /* 'o' -> */, +/* pos 037e: 489 */ 0xF2 /* 'r' -> */, +/* pos 037f: 490 */ 0xF7 /* 'w' -> */, +/* pos 0380: 491 */ 0xE1 /* 'a' -> */, +/* pos 0381: 492 */ 0xF2 /* 'r' -> */, +/* pos 0382: 493 */ 0xE4 /* 'd' -> */, +/* pos 0383: 494 */ 0xF3 /* 's' -> */, +/* pos 0384: 495 */ 0xBA /* ':' -> */, +/* pos 0385: 496 */ 0x00, 0x3C /* - terminal marker 60 - */, +/* pos 0387: 497 */ 0xF8 /* 'x' -> */, +/* pos 0388: 498 */ 0xF9 /* 'y' -> */, +/* pos 0389: 499 */ 0x2D /* '-' */, 0x07, 0x00 /* (to 0x0390 state 500) */, + 0x20 /* ' ' */, 0xBB, 0x00 /* (to 0x0447 state 649) */, + 0x08, /* fail */ +/* pos 0390: 500 */ 0xE1 /* 'a' -> */, +/* pos 0391: 501 */ 0xF5 /* 'u' -> */, +/* pos 0392: 502 */ 0xF4 /* 't' -> */, +/* pos 0393: 503 */ 0xE8 /* 'h' -> */, +/* pos 0394: 504 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x039B state 505) */, + 0x6F /* 'o' */, 0x0E, 0x00 /* (to 0x03A5 state 514) */, + 0x08, /* fail */ +/* pos 039b: 505 */ 0xEE /* 'n' -> */, +/* pos 039c: 506 */ 0xF4 /* 't' -> */, +/* pos 039d: 507 */ 0xE9 /* 'i' -> */, +/* pos 039e: 508 */ 0xE3 /* 'c' -> */, +/* pos 039f: 509 */ 0xE1 /* 'a' -> */, +/* pos 03a0: 510 */ 0xF4 /* 't' -> */, +/* pos 03a1: 511 */ 0xE5 /* 'e' -> */, +/* pos 03a2: 512 */ 0xBA /* ':' -> */, +/* pos 03a3: 513 */ 0x00, 0x3D /* - terminal marker 61 - */, +/* pos 03a5: 514 */ 0xF2 /* 'r' -> */, +/* pos 03a6: 515 */ 0xE9 /* 'i' -> */, +/* pos 03a7: 516 */ 0xFA /* 'z' -> */, +/* pos 03a8: 517 */ 0xE1 /* 'a' -> */, +/* pos 03a9: 518 */ 0xF4 /* 't' -> */, +/* pos 03aa: 519 */ 0xE9 /* 'i' -> */, +/* pos 03ab: 520 */ 0xEF /* 'o' -> */, +/* pos 03ac: 521 */ 0xEE /* 'n' -> */, +/* pos 03ad: 522 */ 0xBA /* ':' -> */, +/* pos 03ae: 523 */ 0x00, 0x3E /* - terminal marker 62 - */, +/* pos 03b0: 524 */ 0xE5 /* 'e' -> */, +/* pos 03b1: 525 */ 0xF3 /* 's' -> */, +/* pos 03b2: 526 */ 0xE8 /* 'h' -> */, +/* pos 03b3: 527 */ 0xBA /* ':' -> */, +/* pos 03b4: 528 */ 0x00, 0x3F /* - terminal marker 63 - */, +/* pos 03b6: 529 */ 0xF2 /* 'r' -> */, +/* pos 03b7: 530 */ 0xF9 /* 'y' -> */, +/* pos 03b8: 531 */ 0xAD /* '-' -> */, +/* pos 03b9: 532 */ 0xE1 /* 'a' -> */, +/* pos 03ba: 533 */ 0xE6 /* 'f' -> */, +/* pos 03bb: 534 */ 0xF4 /* 't' -> */, +/* pos 03bc: 535 */ 0xE5 /* 'e' -> */, +/* pos 03bd: 536 */ 0xF2 /* 'r' -> */, +/* pos 03be: 537 */ 0xBA /* ':' -> */, +/* pos 03bf: 538 */ 0x00, 0x40 /* - terminal marker 64 - */, +/* pos 03c1: 539 */ 0xF6 /* 'v' -> */, +/* pos 03c2: 540 */ 0xE5 /* 'e' -> */, +/* pos 03c3: 541 */ 0xF2 /* 'r' -> */, +/* pos 03c4: 542 */ 0xBA /* ':' -> */, +/* pos 03c5: 543 */ 0x00, 0x41 /* - terminal marker 65 - */, +/* pos 03c7: 544 */ 0xAD /* '-' -> */, +/* pos 03c8: 545 */ 0xE3 /* 'c' -> */, +/* pos 03c9: 546 */ 0xEF /* 'o' -> */, +/* pos 03ca: 547 */ 0xEF /* 'o' -> */, +/* pos 03cb: 548 */ 0xEB /* 'k' -> */, +/* pos 03cc: 549 */ 0xE9 /* 'i' -> */, +/* pos 03cd: 550 */ 0xE5 /* 'e' -> */, +/* pos 03ce: 551 */ 0xBA /* ':' -> */, +/* pos 03cf: 552 */ 0x00, 0x42 /* - terminal marker 66 - */, +/* pos 03d1: 553 */ 0xF2 /* 'r' -> */, +/* pos 03d2: 554 */ 0xE9 /* 'i' -> */, +/* pos 03d3: 555 */ 0xE3 /* 'c' -> */, +/* pos 03d4: 556 */ 0xF4 /* 't' -> */, +/* pos 03d5: 557 */ 0xAD /* '-' -> */, +/* pos 03d6: 558 */ 0xF4 /* 't' -> */, +/* pos 03d7: 559 */ 0xF2 /* 'r' -> */, +/* pos 03d8: 560 */ 0xE1 /* 'a' -> */, +/* pos 03d9: 561 */ 0xEE /* 'n' -> */, +/* pos 03da: 562 */ 0xF3 /* 's' -> */, +/* pos 03db: 563 */ 0xF0 /* 'p' -> */, +/* pos 03dc: 564 */ 0xEF /* 'o' -> */, +/* pos 03dd: 565 */ 0xF2 /* 'r' -> */, +/* pos 03de: 566 */ 0xF4 /* 't' -> */, +/* pos 03df: 567 */ 0xAD /* '-' -> */, +/* pos 03e0: 568 */ 0xF3 /* 's' -> */, +/* pos 03e1: 569 */ 0xE5 /* 'e' -> */, +/* pos 03e2: 570 */ 0xE3 /* 'c' -> */, +/* pos 03e3: 571 */ 0xF5 /* 'u' -> */, +/* pos 03e4: 572 */ 0xF2 /* 'r' -> */, +/* pos 03e5: 573 */ 0xE9 /* 'i' -> */, +/* pos 03e6: 574 */ 0xF4 /* 't' -> */, +/* pos 03e7: 575 */ 0xF9 /* 'y' -> */, +/* pos 03e8: 576 */ 0xBA /* ':' -> */, +/* pos 03e9: 577 */ 0x00, 0x43 /* - terminal marker 67 - */, +/* pos 03eb: 578 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x03F2 state 579) */, + 0x65 /* 'e' */, 0x87, 0x00 /* (to 0x0475 state 680) */, + 0x08, /* fail */ +/* pos 03f2: 579 */ 0xE1 /* 'a' -> */, +/* pos 03f3: 580 */ 0xEE /* 'n' -> */, +/* pos 03f4: 581 */ 0xF3 /* 's' -> */, +/* pos 03f5: 582 */ 0xE6 /* 'f' -> */, +/* pos 03f6: 583 */ 0xE5 /* 'e' -> */, +/* pos 03f7: 584 */ 0xF2 /* 'r' -> */, +/* pos 03f8: 585 */ 0xAD /* '-' -> */, +/* pos 03f9: 586 */ 0xE5 /* 'e' -> */, +/* pos 03fa: 587 */ 0xEE /* 'n' -> */, +/* pos 03fb: 588 */ 0xE3 /* 'c' -> */, +/* pos 03fc: 589 */ 0xEF /* 'o' -> */, +/* pos 03fd: 590 */ 0xE4 /* 'd' -> */, +/* pos 03fe: 591 */ 0xE9 /* 'i' -> */, +/* pos 03ff: 592 */ 0xEE /* 'n' -> */, +/* pos 0400: 593 */ 0xE7 /* 'g' -> */, +/* pos 0401: 594 */ 0xBA /* ':' -> */, +/* pos 0402: 595 */ 0x00, 0x44 /* - terminal marker 68 - */, +/* pos 0404: 596 */ 0xE5 /* 'e' -> */, +/* pos 0405: 597 */ 0xF2 /* 'r' -> */, +/* pos 0406: 598 */ 0xAD /* '-' -> */, +/* pos 0407: 599 */ 0xE1 /* 'a' -> */, +/* pos 0408: 600 */ 0xE7 /* 'g' -> */, +/* pos 0409: 601 */ 0xE5 /* 'e' -> */, +/* pos 040a: 602 */ 0xEE /* 'n' -> */, +/* pos 040b: 603 */ 0xF4 /* 't' -> */, +/* pos 040c: 604 */ 0xBA /* ':' -> */, +/* pos 040d: 605 */ 0x00, 0x45 /* - terminal marker 69 - */, +/* pos 040f: 606 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x0416 state 607) */, + 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x041B state 611) */, + 0x08, /* fail */ +/* pos 0416: 607 */ 0xF2 /* 'r' -> */, +/* pos 0417: 608 */ 0xF9 /* 'y' -> */, +/* pos 0418: 609 */ 0xBA /* ':' -> */, +/* pos 0419: 610 */ 0x00, 0x46 /* - terminal marker 70 - */, +/* pos 041b: 611 */ 0xE1 /* 'a' -> */, +/* pos 041c: 612 */ 0xBA /* ':' -> */, +/* pos 041d: 613 */ 0x00, 0x47 /* - terminal marker 71 - */, +/* pos 041f: 614 */ 0xF7 /* 'w' -> */, +/* pos 0420: 615 */ 0xF7 /* 'w' -> */, +/* pos 0421: 616 */ 0xAD /* '-' -> */, +/* pos 0422: 617 */ 0xE1 /* 'a' -> */, +/* pos 0423: 618 */ 0xF5 /* 'u' -> */, +/* pos 0424: 619 */ 0xF4 /* 't' -> */, +/* pos 0425: 620 */ 0xE8 /* 'h' -> */, +/* pos 0426: 621 */ 0xE5 /* 'e' -> */, +/* pos 0427: 622 */ 0xEE /* 'n' -> */, +/* pos 0428: 623 */ 0xF4 /* 't' -> */, +/* pos 0429: 624 */ 0xE9 /* 'i' -> */, +/* pos 042a: 625 */ 0xE3 /* 'c' -> */, +/* pos 042b: 626 */ 0xE1 /* 'a' -> */, +/* pos 042c: 627 */ 0xF4 /* 't' -> */, +/* pos 042d: 628 */ 0xE5 /* 'e' -> */, +/* pos 042e: 629 */ 0xBA /* ':' -> */, +/* pos 042f: 630 */ 0x00, 0x48 /* - terminal marker 72 - */, +/* pos 0431: 631 */ 0xF4 /* 't' -> */, +/* pos 0432: 632 */ 0xE3 /* 'c' -> */, +/* pos 0433: 633 */ 0xE8 /* 'h' -> */, +/* pos 0434: 634 */ 0x00, 0x49 /* - terminal marker 73 - */, +/* pos 0436: 635 */ 0xF4 /* 't' -> */, +/* pos 0437: 636 */ 0x00, 0x4A /* - terminal marker 74 - */, +/* pos 0439: 637 */ 0xEC /* 'l' -> */, +/* pos 043a: 638 */ 0xE5 /* 'e' -> */, +/* pos 043b: 639 */ 0xF4 /* 't' -> */, +/* pos 043c: 640 */ 0xE5 /* 'e' -> */, +/* pos 043d: 641 */ 0x00, 0x4B /* - terminal marker 75 - */, +/* pos 043f: 642 */ 0xE9 /* 'i' -> */, +/* pos 0440: 643 */ 0xAD /* '-' -> */, +/* pos 0441: 644 */ 0xE1 /* 'a' -> */, +/* pos 0442: 645 */ 0xF2 /* 'r' -> */, +/* pos 0443: 646 */ 0xE7 /* 'g' -> */, +/* pos 0444: 647 */ 0xF3 /* 's' -> */, +/* pos 0445: 648 */ 0x00, 0x4C /* - terminal marker 76 - */, +/* pos 0447: 649 */ 0x00, 0x4D /* - terminal marker 77 - */, +/* pos 0449: 650 */ 0xAD /* '-' -> */, +/* pos 044a: 651 */ 0x72 /* 'r' */, 0x0A, 0x00 /* (to 0x0454 state 652) */, + 0x66 /* 'f' */, 0x13, 0x00 /* (to 0x0460 state 662) */, + 0x61 /* 'a' */, 0x3C, 0x00 /* (to 0x048C state 700) */, + 0x08, /* fail */ +/* pos 0454: 652 */ 0xE5 /* 'e' -> */, +/* pos 0455: 653 */ 0xE1 /* 'a' -> */, +/* pos 0456: 654 */ 0xEC /* 'l' -> */, +/* pos 0457: 655 */ 0xAD /* '-' -> */, +/* pos 0458: 656 */ 0xE9 /* 'i' -> */, +/* pos 0459: 657 */ 0xF0 /* 'p' -> */, +/* pos 045a: 658 */ 0xBA /* ':' -> */, +/* pos 045b: 659 */ 0x00, 0x4E /* - terminal marker 78 - */, +/* pos 045d: 660 */ 0xA0 /* ' ' -> */, +/* pos 045e: 661 */ 0x00, 0x4F /* - terminal marker 79 - */, +/* pos 0460: 662 */ 0xEF /* 'o' -> */, +/* pos 0461: 663 */ 0xF2 /* 'r' -> */, +/* pos 0462: 664 */ 0xF7 /* 'w' -> */, +/* pos 0463: 665 */ 0xE1 /* 'a' -> */, +/* pos 0464: 666 */ 0xF2 /* 'r' -> */, +/* pos 0465: 667 */ 0xE4 /* 'd' -> */, +/* pos 0466: 668 */ 0xE5 /* 'e' -> */, +/* pos 0467: 669 */ 0xE4 /* 'd' -> */, +/* pos 0468: 670 */ 0xAD /* '-' -> */, +/* pos 0469: 671 */ 0xE6 /* 'f' -> */, +/* pos 046a: 672 */ 0xEF /* 'o' -> */, +/* pos 046b: 673 */ 0xF2 /* 'r' -> */, +/* pos 046c: 674 */ 0x00, 0x50 /* - terminal marker 80 - */, +/* pos 046e: 675 */ 0x00, 0x51 /* - terminal marker 81 - */, +/* pos 0470: 676 */ 0xE1 /* 'a' -> */, +/* pos 0471: 677 */ 0xE4 /* 'd' -> */, +/* pos 0472: 678 */ 0xA0 /* ' ' -> */, +/* pos 0473: 679 */ 0x00, 0x52 /* - terminal marker 82 - */, +/* pos 0475: 680 */ 0xBA /* ':' -> */, +/* pos 0476: 681 */ 0x00, 0x53 /* - terminal marker 83 - */, +/* pos 0478: 682 */ 0xEC /* 'l' -> */, +/* pos 0479: 683 */ 0xE1 /* 'a' -> */, +/* pos 047a: 684 */ 0xF9 /* 'y' -> */, +/* pos 047b: 685 */ 0xAD /* '-' -> */, +/* pos 047c: 686 */ 0xEE /* 'n' -> */, +/* pos 047d: 687 */ 0xEF /* 'o' -> */, +/* pos 047e: 688 */ 0xEE /* 'n' -> */, +/* pos 047f: 689 */ 0xE3 /* 'c' -> */, +/* pos 0480: 690 */ 0xE5 /* 'e' -> */, +/* pos 0481: 691 */ 0xBA /* ':' -> */, +/* pos 0482: 692 */ 0x00, 0x54 /* - terminal marker 84 - */, +/* pos 0484: 693 */ 0xEF /* 'o' -> */, +/* pos 0485: 694 */ 0xF4 /* 't' -> */, +/* pos 0486: 695 */ 0xEF /* 'o' -> */, +/* pos 0487: 696 */ 0xE3 /* 'c' -> */, +/* pos 0488: 697 */ 0xEF /* 'o' -> */, +/* pos 0489: 698 */ 0xEC /* 'l' -> */, +/* pos 048a: 699 */ 0x00, 0x55 /* - terminal marker 85 - */, +/* pos 048c: 700 */ 0xF5 /* 'u' -> */, +/* pos 048d: 701 */ 0xF4 /* 't' -> */, +/* pos 048e: 702 */ 0xE8 /* 'h' -> */, +/* pos 048f: 703 */ 0xAD /* '-' -> */, +/* pos 0490: 704 */ 0xF4 /* 't' -> */, +/* pos 0491: 705 */ 0xEF /* 'o' -> */, +/* pos 0492: 706 */ 0xEB /* 'k' -> */, +/* pos 0493: 707 */ 0xE5 /* 'e' -> */, +/* pos 0494: 708 */ 0xEE /* 'n' -> */, +/* pos 0495: 709 */ 0xBA /* ':' -> */, +/* pos 0496: 710 */ 0x00, 0x56 /* - terminal marker 86 - */, +/* total size 1176 bytes */ diff --git a/thirdparty/libwebsockets/roles/http/private.h b/thirdparty/libwebsockets/roles/http/private.h new file mode 100644 index 0000000000..2aa7a92f75 --- /dev/null +++ b/thirdparty/libwebsockets/roles/http/private.h @@ -0,0 +1,257 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h if either H1 or H2 roles are + * enabled + */ + +#if defined(LWS_WITH_HTTP_PROXY) + #include <hubbub/hubbub.h> + #include <hubbub/parser.h> + #endif + +#define lwsi_role_http(wsi) (lwsi_role_h1(wsi) || lwsi_role_h2(wsi)) + +enum http_version { + HTTP_VERSION_1_0, + HTTP_VERSION_1_1, + HTTP_VERSION_2 +}; + +enum http_connection_type { + HTTP_CONNECTION_CLOSE, + HTTP_CONNECTION_KEEP_ALIVE +}; + +/* + * This is totally opaque to code using the library. It's exported as a + * forward-reference pointer-only declaration; the user can use the pointer with + * other APIs to get information out of it. + */ + +#if defined(LWS_WITH_ESP32) +typedef uint16_t ah_data_idx_t; +#else +typedef uint32_t ah_data_idx_t; +#endif + +struct lws_fragments { + ah_data_idx_t offset; + uint16_t len; + uint8_t nfrag; /* which ah->frag[] continues this content, or 0 */ + uint8_t flags; /* only http2 cares */ +}; + +#if defined(LWS_WITH_RANGES) +enum range_states { + LWSRS_NO_ACTIVE_RANGE, + LWSRS_BYTES_EQ, + LWSRS_FIRST, + LWSRS_STARTING, + LWSRS_ENDING, + LWSRS_COMPLETED, + LWSRS_SYNTAX, +}; + +struct lws_range_parsing { + unsigned long long start, end, extent, agg, budget; + const char buf[128]; + int pos; + enum range_states state; + char start_valid, end_valid, ctr, count_ranges, did_try, inside, send_ctr; +}; + +int +lws_ranges_init(struct lws *wsi, struct lws_range_parsing *rp, + unsigned long long extent); +int +lws_ranges_next(struct lws_range_parsing *rp); +void +lws_ranges_reset(struct lws_range_parsing *rp); +#endif + +/* + * these are assigned from a pool held in the context. + * Both client and server mode uses them for http header analysis + */ + +struct allocated_headers { + struct allocated_headers *next; /* linked list */ + struct lws *wsi; /* owner */ + char *data; /* prepared by context init to point to dedicated storage */ + ah_data_idx_t data_length; + /* + * the randomly ordered fragments, indexed by frag_index and + * lws_fragments->nfrag for continuation. + */ + struct lws_fragments frags[WSI_TOKEN_COUNT]; + time_t assigned; + /* + * for each recognized token, frag_index says which frag[] his data + * starts in (0 means the token did not appear) + * the actual header data gets dumped as it comes in, into data[] + */ + uint8_t frag_index[WSI_TOKEN_COUNT]; + +#ifndef LWS_NO_CLIENT + char initial_handshake_hash_base64[30]; +#endif + + uint32_t pos; + uint32_t http_response; + uint32_t current_token_limit; + int hdr_token_idx; + + int16_t lextable_pos; + + uint8_t in_use; + uint8_t nfrag; + char /*enum uri_path_states */ ups; + char /*enum uri_esc_states */ ues; + + char esc_stash; + char post_literal_equal; + uint8_t /* enum lws_token_indexes */ parser_state; +}; + + + +#if defined(LWS_WITH_HTTP_PROXY) +struct lws_rewrite { + hubbub_parser *parser; + hubbub_parser_optparams params; + const char *from, *to; + int from_len, to_len; + unsigned char *p, *end; + struct lws *wsi; +}; +static LWS_INLINE int hstrcmp(hubbub_string *s, const char *p, int len) +{ + if ((int)s->len != len) + return 1; + + return strncmp((const char *)s->ptr, p, len); +} +typedef hubbub_error (*hubbub_callback_t)(const hubbub_token *token, void *pw); +LWS_EXTERN struct lws_rewrite * +lws_rewrite_create(struct lws *wsi, hubbub_callback_t cb, const char *from, const char *to); +LWS_EXTERN void +lws_rewrite_destroy(struct lws_rewrite *r); +LWS_EXTERN int +lws_rewrite_parse(struct lws_rewrite *r, const unsigned char *in, int in_len); +#endif + +struct lws_pt_role_http { + struct allocated_headers *ah_list; + struct lws *ah_wait_list; +#ifdef LWS_WITH_CGI + struct lws_cgi *cgi_list; +#endif + int ah_wait_list_length; + uint32_t ah_pool_length; + + int ah_count_in_use; +}; + +struct lws_peer_role_http { + uint32_t count_ah; + uint32_t total_ah; +}; + +struct lws_vhost_role_http { + char http_proxy_address[128]; + const struct lws_http_mount *mount_list; + const char *error_document_404; + unsigned int http_proxy_port; +}; + +#ifdef LWS_WITH_ACCESS_LOG +struct lws_access_log { + char *header_log; + char *user_agent; + char *referrer; + unsigned long sent; + int response; +}; +#endif + +struct _lws_http_mode_related { + struct lws *new_wsi_list; + +#if defined(LWS_WITH_HTTP_PROXY) + struct lws_rewrite *rw; +#endif + struct allocated_headers *ah; + struct lws *ah_wait_list; + + lws_filepos_t filepos; + lws_filepos_t filelen; + lws_fop_fd_t fop_fd; + +#if defined(LWS_WITH_RANGES) + struct lws_range_parsing range; + char multipart_content_type[64]; +#endif + +#ifdef LWS_WITH_ACCESS_LOG + struct lws_access_log access_log; +#endif +#ifdef LWS_WITH_CGI + struct lws_cgi *cgi; /* wsi being cgi master have one of these */ +#endif + + enum http_version request_version; + enum http_connection_type connection_type; + lws_filepos_t tx_content_length; + lws_filepos_t tx_content_remain; + lws_filepos_t rx_content_length; + lws_filepos_t rx_content_remain; + +#if defined(LWS_WITH_HTTP_PROXY) + unsigned int perform_rewrite:1; +#endif +}; + + +#ifndef LWS_NO_CLIENT +enum lws_chunk_parser { + ELCP_HEX, + ELCP_CR, + ELCP_CONTENT, + ELCP_POST_CR, + ELCP_POST_LF, +}; +#endif + +enum lws_parse_urldecode_results { + LPUR_CONTINUE, + LPUR_SWALLOW, + LPUR_FORBID, + LPUR_EXCESSIVE, +}; + +int +lws_read_h1(struct lws *wsi, unsigned char *buf, lws_filepos_t len); + +void +_lws_header_table_reset(struct allocated_headers *ah); + +LWS_EXTERN int +_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah); diff --git a/thirdparty/libwebsockets/roles/http/server/access-log.c b/thirdparty/libwebsockets/roles/http/server/access-log.c new file mode 100644 index 0000000000..0e75309d7a --- /dev/null +++ b/thirdparty/libwebsockets/roles/http/server/access-log.c @@ -0,0 +1,182 @@ +/* + * libwebsockets - server access log handling + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +/* + * Produce Apache-compatible log string for wsi, like this: + * + * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800] + * "GET /aep-screen.png HTTP/1.1" + * 200 152987 "https://libwebsockets.org/index.html" + * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36" + * + */ + +extern const char * const method_names[]; + +static const char * const hver[] = { + "HTTP/1.0", "HTTP/1.1", "HTTP/2" +}; + +void +lws_prepare_access_log_info(struct lws *wsi, char *uri_ptr, int meth) +{ +#ifdef LWS_WITH_IPV6 + char ads[INET6_ADDRSTRLEN]; +#else + char ads[INET_ADDRSTRLEN]; +#endif + char da[64]; + const char *pa, *me; + struct tm *tmp; + time_t t = time(NULL); + int l = 256, m; + + if (!wsi->vhost) + return; + + /* only worry about preparing it if we store it */ + if (wsi->vhost->log_fd == (int)LWS_INVALID_FILE) + return; + + if (wsi->access_log_pending) + lws_access_log(wsi); + + wsi->http.access_log.header_log = lws_malloc(l, "access log"); + if (wsi->http.access_log.header_log) { + + tmp = localtime(&t); + if (tmp) + strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp); + else + strcpy(da, "01/Jan/1970:00:00:00 +0000"); + + pa = lws_get_peer_simple(wsi, ads, sizeof(ads)); + if (!pa) + pa = "(unknown)"; + + if (wsi->http2_substream) + me = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_METHOD); + else + me = method_names[meth]; + if (!me) + me = "(null)"; + + lws_snprintf(wsi->http.access_log.header_log, l, + "%s - - [%s] \"%s %s %s\"", + pa, da, me, uri_ptr, + hver[wsi->http.request_version]); + + l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT); + if (l) { + wsi->http.access_log.user_agent = lws_malloc(l + 2, "access log"); + if (!wsi->http.access_log.user_agent) { + lwsl_err("OOM getting user agent\n"); + lws_free_set_NULL(wsi->http.access_log.header_log); + return; + } + + lws_hdr_copy(wsi, wsi->http.access_log.user_agent, + l + 1, WSI_TOKEN_HTTP_USER_AGENT); + + for (m = 0; m < l; m++) + if (wsi->http.access_log.user_agent[m] == '\"') + wsi->http.access_log.user_agent[m] = '\''; + } + l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_REFERER); + if (l) { + wsi->http.access_log.referrer = lws_malloc(l + 2, "referrer"); + if (!wsi->http.access_log.referrer) { + lwsl_err("OOM getting user agent\n"); + lws_free_set_NULL(wsi->http.access_log.user_agent); + lws_free_set_NULL(wsi->http.access_log.header_log); + return; + } + lws_hdr_copy(wsi, wsi->http.access_log.referrer, + l + 1, WSI_TOKEN_HTTP_REFERER); + + for (m = 0; m < l; m++) + if (wsi->http.access_log.referrer[m] == '\"') + wsi->http.access_log.referrer[m] = '\''; + } + wsi->access_log_pending = 1; + } +} + + +int +lws_access_log(struct lws *wsi) +{ + char *p = wsi->http.access_log.user_agent, ass[512], + *p1 = wsi->http.access_log.referrer; + int l; + + if (!wsi->vhost) + return 0; + + if (wsi->vhost->log_fd == (int)LWS_INVALID_FILE) + return 0; + + if (!wsi->access_log_pending) + return 0; + + if (!wsi->http.access_log.header_log) + return 0; + + if (!p) + p = ""; + + if (!p1) + p1 = ""; + + /* + * We do this in two parts to restrict an oversize referrer such that + * we will always have space left to append an empty useragent, while + * maintaining the structure of the log text + */ + l = lws_snprintf(ass, sizeof(ass) - 7, "%s %d %lu \"%s", + wsi->http.access_log.header_log, + wsi->http.access_log.response, wsi->http.access_log.sent, p1); + if (strlen(p) > sizeof(ass) - 6 - l) + p[sizeof(ass) - 6 - l] = '\0'; + l += lws_snprintf(ass + l, sizeof(ass) - 1 - l, "\" \"%s\"\n", p); + + if (write(wsi->vhost->log_fd, ass, l) != l) + lwsl_err("Failed to write log\n"); + + if (wsi->http.access_log.header_log) { + lws_free(wsi->http.access_log.header_log); + wsi->http.access_log.header_log = NULL; + } + if (wsi->http.access_log.user_agent) { + lws_free(wsi->http.access_log.user_agent); + wsi->http.access_log.user_agent = NULL; + } + if (wsi->http.access_log.referrer) { + lws_free(wsi->http.access_log.referrer); + wsi->http.access_log.referrer = NULL; + } + wsi->access_log_pending = 0; + + return 0; +} + diff --git a/thirdparty/lws/server/fops-zip.c b/thirdparty/libwebsockets/roles/http/server/fops-zip.c index 2b254f67af..4db83ce621 100644 --- a/thirdparty/lws/server/fops-zip.c +++ b/thirdparty/libwebsockets/roles/http/server/fops-zip.c @@ -51,7 +51,7 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" #include <zlib.h> @@ -241,13 +241,13 @@ lws_fops_zip_scan(lws_fops_zip_t priv, const char *name, int len) if (priv->hdr.filename_len != len) goto next; - if (len >= sizeof(buf) - 1) + if (len >= (int)sizeof(buf) - 1) return LWS_FZ_ERR_NAME_TOO_LONG; if (priv->zip_fop_fd->fops->LWS_FOP_READ(priv->zip_fop_fd, &amount, buf, len)) return LWS_FZ_ERR_NAME_READ; - if (amount != len) + if ((int)amount != len) return LWS_FZ_ERR_NAME_READ; buf[len] = '\0'; @@ -348,9 +348,8 @@ lws_fops_zip_open(const struct lws_plat_file_ops *fops, const char *vfs_path, m = sizeof(rp) - 1; if ((vpath - vfs_path - 1) < m) - m = vpath - vfs_path - 1; - strncpy(rp, vfs_path, m); - rp[m] = '\0'; + m = lws_ptr_diff(vpath, vfs_path) - 1; + lws_strncpy(rp, vfs_path, m + 1); /* open the zip file itself using the incoming fops, not fops_zip */ @@ -363,7 +362,7 @@ lws_fops_zip_open(const struct lws_plat_file_ops *fops, const char *vfs_path, if (*vpath == '/') vpath++; - m = lws_fops_zip_scan(priv, vpath, strlen(vpath)); + m = lws_fops_zip_scan(priv, vpath, (int)strlen(vpath)); if (m) { lwsl_err("unable to find record matching '%s' %d\n", vpath, m); goto bail2; @@ -565,7 +564,7 @@ spin: switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; - /* and fall through */ + /* fallthru */ case Z_DATA_ERROR: case Z_MEM_ERROR: diff --git a/thirdparty/lws/server/lejp-conf.c b/thirdparty/libwebsockets/roles/http/server/lejp-conf.c index c2b684c278..e9ce854cfc 100644 --- a/thirdparty/lws/server/lejp-conf.c +++ b/thirdparty/libwebsockets/roles/http/server/lejp-conf.c @@ -19,8 +19,7 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" -#include "../misc/lejp.h" +#include "core/private.h" #ifndef _WIN32 /* this is needed for Travis CI */ @@ -40,6 +39,7 @@ static const char * const paths_global[] = { "global.timeout-secs", "global.reject-service-keywords[].*", "global.reject-service-keywords[]", + "global.default-alpn", }; enum lejp_global_paths { @@ -52,7 +52,8 @@ enum lejp_global_paths { LWJPGP_PINGPONG_SECS, LWJPGP_TIMEOUT_SECS, LWJPGP_REJECT_SERVICE_KEYWORDS_NAME, - LWJPGP_REJECT_SERVICE_KEYWORDS + LWJPGP_REJECT_SERVICE_KEYWORDS, + LWJPGP_DEFAULT_ALPN, }; static const char * const paths_vhosts[] = { @@ -100,6 +101,10 @@ static const char * const paths_vhosts[] = { "vhosts[].client-ssl-ca", "vhosts[].client-ssl-ciphers", "vhosts[].onlyraw", + "vhosts[].client-cert-required", + "vhosts[].ignore-missing-cert", + "vhosts[].error-document-404", + "vhosts[].alpn", }; enum lejp_vhost_paths { @@ -147,6 +152,10 @@ enum lejp_vhost_paths { LEJPVP_CLIENT_SSL_CA, LEJPVP_CLIENT_CIPHERS, LEJPVP_FLAG_ONLYRAW, + LEJPVP_FLAG_CLIENT_CERT_REQUIRED, + LEJPVP_IGNORE_MISSING_CERT, + LEJPVP_ERROR_DOCUMENT_404, + LEJPVP_ALPN, }; static const char * const parser_errs[] = { @@ -216,7 +225,7 @@ arg_to_bool(const char *s) if (n) return 1; - for (n = 0; n < ARRAY_SIZE(on); n++) + for (n = 0; n < (int)ARRAY_SIZE(on); n++) if (!strcasecmp(s, on[n])) return 1; @@ -285,6 +294,10 @@ lejp_globals_cb(struct lejp_ctx *ctx, char reason) a->info->timeout_secs = atoi(ctx->buf); return 0; + case LWJPGP_DEFAULT_ALPN: + a->info->alpn = a->p; + break; + default: return 0; } @@ -312,20 +325,39 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) #endif if (reason == LEJPCB_OBJECT_START && ctx->path_match == LEJPVP + 1) { + uint32_t i[4]; + const char *ss; + /* set the defaults for this vhost */ a->valid = 1; a->head = NULL; a->last = NULL; - a->info->port = 0; - a->info->iface = NULL; + + i[0] = a->info->count_threads; + i[1] = a->info->options & ( + LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME | + LWS_SERVER_OPTION_LIBUV | + LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | + LWS_SERVER_OPTION_EXPLICIT_VHOSTS | + LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN | + LWS_SERVER_OPTION_LIBEVENT | + LWS_SERVER_OPTION_LIBEV + ); + ss = a->info->server_string; + i[2] = a->info->ws_ping_pong_interval; + i[3] = a->info->timeout_secs; + + memset(a->info, 0, sizeof(*a->info)); + + a->info->count_threads = i[0]; + a->info->options = i[1]; + a->info->server_string = ss; + a->info->ws_ping_pong_interval = i[2]; + a->info->timeout_secs = i[3]; + a->info->protocols = a->protocols; a->info->extensions = a->extensions; - a->info->ssl_cert_filepath = NULL; - a->info->ssl_private_key_filepath = NULL; - a->info->ssl_ca_filepath = NULL; - a->info->client_ssl_cert_filepath = NULL; - a->info->client_ssl_private_key_filepath = NULL; - a->info->client_ssl_ca_filepath = NULL; +#if defined(LWS_WITH_TLS) a->info->client_ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:" "ECDHE-RSA-AES256-GCM-SHA384:" "DHE-RSA-AES256-GCM-SHA384:" @@ -339,7 +371,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) "!DHE-RSA-AES256-SHA256:" "!AES256-GCM-SHA384:" "!AES256-SHA256"; - a->info->timeout_secs = 5; +#endif a->info->ssl_cipher_list = "ECDHE-ECDSA-AES256-GCM-SHA384:" "ECDHE-RSA-AES256-GCM-SHA384:" "DHE-RSA-AES256-GCM-SHA384:" @@ -353,13 +385,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) "!DHE-RSA-AES256-SHA256:" "!AES256-GCM-SHA384:" "!AES256-SHA256"; - a->info->pvo = NULL; - a->info->headers = NULL; a->info->keepalive_timeout = 5; - a->info->log_filepath = NULL; - a->info->options &= ~(LWS_SERVER_OPTION_UNIX_SOCK | - LWS_SERVER_OPTION_STS | LWS_SERVER_OPTION_ONLY_RAW); - a->enable_client_ssl = 0; } if (reason == LEJPCB_OBJECT_START && @@ -379,7 +405,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) a->pvo->next = a->info->pvo; a->info->pvo = a->pvo; a->pvo->name = a->p; - lwsl_notice(" adding protocol %s\n", a->p); + lwsl_info(" adding protocol %s\n", a->p); a->p += n; a->pvo->value = a->p; a->pvo->options = NULL; @@ -431,6 +457,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) } a->any_vhosts = 1; +#if defined(LWS_WITH_TLS) if (a->enable_client_ssl) { const char *cert_filepath = a->info->client_ssl_cert_filepath; const char *private_key_filepath = a->info->client_ssl_private_key_filepath; @@ -444,6 +471,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) a->info->options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; lws_init_vhost_client_ssl(a->info, vhost); } +#endif return 0; } @@ -474,7 +502,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) if (a->last) a->last->mount_next = m; - for (n = 0; n < ARRAY_SIZE(mount_protocols); n++) + for (n = 0; n < (int)ARRAY_SIZE(mount_protocols); n++) if (!strncmp(a->m.origin, mount_protocols[n], strlen(mount_protocols[n]))) { lwsl_info("----%s\n", a->m.origin); @@ -484,7 +512,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) break; } - if (n == ARRAY_SIZE(mount_protocols)) { + if (n == (int)ARRAY_SIZE(mount_protocols)) { lwsl_err("unsupported protocol:// %s\n", a->m.origin); return 1; } @@ -573,9 +601,11 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) case LEJPVP_KEEPALIVE_TIMEOUT: a->info->keepalive_timeout = atoi(ctx->buf); return 0; +#if defined(LWS_WITH_TLS) case LEJPVP_CLIENT_CIPHERS: a->info->client_ssl_cipher_list = a->p; break; +#endif case LEJPVP_CIPHERS: a->info->ssl_cipher_list = a->p; break; @@ -651,6 +681,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) case LEJPVP_ENABLE_CLIENT_SSL: a->enable_client_ssl = arg_to_bool(ctx->buf); return 0; +#if defined(LWS_WITH_TLS) case LEJPVP_CLIENT_SSL_KEY: a->info->client_ssl_private_key_filepath = a->p; break; @@ -660,6 +691,7 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) case LEJPVP_CLIENT_SSL_CA: a->info->client_ssl_ca_filepath = a->p; break; +#endif case LEJPVP_NOIPV6: if (arg_to_bool(ctx->buf)) @@ -683,6 +715,24 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) a->info->options &= ~(LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE); return 0; + case LEJPVP_FLAG_CLIENT_CERT_REQUIRED: + if (arg_to_bool(ctx->buf)) + a->info->options |= + LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT; + return 0; + + case LEJPVP_IGNORE_MISSING_CERT: + if (arg_to_bool(ctx->buf)) + a->info->options |= LWS_SERVER_OPTION_IGNORE_MISSING_CERT; + else + a->info->options &= ~(LWS_SERVER_OPTION_IGNORE_MISSING_CERT); + + return 0; + + case LEJPVP_ERROR_DOCUMENT_404: + a->info->error_document_404 = a->p; + break; + case LEJPVP_SSL_OPTION_SET: a->info->ssl_options_set |= atol(ctx->buf); return 0; @@ -690,6 +740,10 @@ lejp_vhosts_cb(struct lejp_ctx *ctx, char reason) a->info->ssl_options_clear |= atol(ctx->buf); return 0; + case LEJPVP_ALPN: + a->info->alpn = a->p; + break; + default: return 0; } @@ -701,7 +755,7 @@ dostring: n = p1 - p; if (n > a->end - a->p) n = a->end - a->p; - strncpy(a->p, p, n); + lws_strncpy(a->p, p, n + 1); a->p += n; a->p += lws_snprintf(a->p, a->end - a->p, "%s", LWS_INSTALL_DATADIR); p += n + strlen(ESC_INSTALL_DATADIR); diff --git a/thirdparty/libwebsockets/roles/http/server/parsers.c b/thirdparty/libwebsockets/roles/http/server/parsers.c new file mode 100644 index 0000000000..cb022e362b --- /dev/null +++ b/thirdparty/libwebsockets/roles/http/server/parsers.c @@ -0,0 +1,1139 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +static const unsigned char lextable[] = { + #include "../lextable.h" +}; + +#define FAIL_CHAR 0x08 + +static struct allocated_headers * +_lws_create_ah(struct lws_context_per_thread *pt, ah_data_idx_t data_size) +{ + struct allocated_headers *ah = lws_zalloc(sizeof(*ah), "ah struct"); + + if (!ah) + return NULL; + + ah->data = lws_malloc(data_size, "ah data"); + if (!ah->data) { + lws_free(ah); + + return NULL; + } + ah->next = pt->http.ah_list; + pt->http.ah_list = ah; + ah->data_length = data_size; + pt->http.ah_pool_length++; + + lwsl_info("%s: created ah %p (size %d): pool length %d\n", __func__, + ah, (int)data_size, pt->http.ah_pool_length); + + return ah; +} + +int +_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah) +{ + lws_start_foreach_llp(struct allocated_headers **, a, pt->http.ah_list) { + if ((*a) == ah) { + *a = ah->next; + pt->http.ah_pool_length--; + lwsl_info("%s: freed ah %p : pool length %d\n", + __func__, ah, pt->http.ah_pool_length); + if (ah->data) + lws_free(ah->data); + lws_free(ah); + + return 0; + } + } lws_end_foreach_llp(a, next); + + return 1; +} + +void +_lws_header_table_reset(struct allocated_headers *ah) +{ + /* init the ah to reflect no headers or data have appeared yet */ + memset(ah->frag_index, 0, sizeof(ah->frag_index)); + memset(ah->frags, 0, sizeof(ah->frags)); + ah->nfrag = 0; + ah->pos = 0; + ah->http_response = 0; + ah->parser_state = WSI_TOKEN_NAME_PART; + ah->lextable_pos = 0; +} + +// doesn't scrub the ah rxbuffer by default, parent must do if needed + +void +__lws_header_table_reset(struct lws *wsi, int autoservice) +{ + struct allocated_headers *ah = wsi->http.ah; + struct lws_context_per_thread *pt; + struct lws_pollfd *pfd; + + /* if we have the idea we're resetting 'our' ah, must be bound to one */ + assert(ah); + /* ah also concurs with ownership */ + assert(ah->wsi == wsi); + + _lws_header_table_reset(ah); + + /* since we will restart the ah, our new headers are not completed */ + wsi->hdr_parsing_completed = 0; + + /* while we hold the ah, keep a timeout on the wsi */ + __lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH, + wsi->vhost->timeout_secs_ah_idle); + + time(&ah->assigned); + + if (wsi->position_in_fds_table != LWS_NO_FDS_POS && + lws_buflist_next_segment_len(&wsi->buflist, NULL) && + autoservice) { + lwsl_debug("%s: service on readbuf ah\n", __func__); + + pt = &wsi->context->pt[(int)wsi->tsi]; + /* + * Unlike a normal connect, we have the headers already + * (or the first part of them anyway) + */ + pfd = &pt->fds[wsi->position_in_fds_table]; + pfd->revents |= LWS_POLLIN; + lwsl_err("%s: calling service\n", __func__); + lws_service_fd_tsi(wsi->context, pfd, wsi->tsi); + } +} + +void +lws_header_table_reset(struct lws *wsi, int autoservice) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + lws_pt_lock(pt, __func__); + + __lws_header_table_reset(wsi, autoservice); + + lws_pt_unlock(pt); +} + +static void +_lws_header_ensure_we_are_on_waiting_list(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct lws_pollargs pa; + struct lws **pwsi = &pt->http.ah_wait_list; + + while (*pwsi) { + if (*pwsi == wsi) + return; + pwsi = &(*pwsi)->http.ah_wait_list; + } + + lwsl_info("%s: wsi: %p\n", __func__, wsi); + wsi->http.ah_wait_list = pt->http.ah_wait_list; + pt->http.ah_wait_list = wsi; + pt->http.ah_wait_list_length++; + + /* we cannot accept input then */ + + _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa); +} + +static int +__lws_remove_from_ah_waiting_list(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct lws **pwsi =&pt->http.ah_wait_list; + + while (*pwsi) { + if (*pwsi == wsi) { + lwsl_info("%s: wsi %p\n", __func__, wsi); + /* point prev guy to our next */ + *pwsi = wsi->http.ah_wait_list; + /* we shouldn't point anywhere now */ + wsi->http.ah_wait_list = NULL; + pt->http.ah_wait_list_length--; + + return 1; + } + pwsi = &(*pwsi)->http.ah_wait_list; + } + + return 0; +} + +int LWS_WARN_UNUSED_RESULT +lws_header_table_attach(struct lws *wsi, int autoservice) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + struct lws_pollargs pa; + int n; + + lwsl_info("%s: wsi %p: ah %p (tsi %d, count = %d) in\n", __func__, + (void *)wsi, (void *)wsi->http.ah, wsi->tsi, + pt->http.ah_count_in_use); + + lws_pt_lock(pt, __func__); + + /* if we are already bound to one, just clear it down */ + if (wsi->http.ah) { + lwsl_info("%s: cleardown\n", __func__); + goto reset; + } + + n = pt->http.ah_count_in_use == context->max_http_header_pool; +#if defined(LWS_WITH_PEER_LIMITS) + if (!n) { + n = lws_peer_confirm_ah_attach_ok(context, wsi->peer); + if (n) + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); + } +#endif + if (n) { + /* + * Pool is either all busy, or we don't want to give this + * particular guy an ah right now... + * + * Make sure we are on the waiting list, and return that we + * weren't able to provide the ah + */ + _lws_header_ensure_we_are_on_waiting_list(wsi); + + goto bail; + } + + __lws_remove_from_ah_waiting_list(wsi); + + wsi->http.ah = _lws_create_ah(pt, context->max_http_header_data); + if (!wsi->http.ah) { /* we could not create an ah */ + _lws_header_ensure_we_are_on_waiting_list(wsi); + + goto bail; + } + + wsi->http.ah->in_use = 1; + wsi->http.ah->wsi = wsi; /* mark our owner */ + pt->http.ah_count_in_use++; + +#if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)) + lws_context_lock(context); /* <====================================== */ + if (wsi->peer) + wsi->peer->http.count_ah++; + lws_context_unlock(context); /* ====================================> */ +#endif + + _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); + + lwsl_info("%s: did attach wsi %p: ah %p: count %d (on exit)\n", __func__, + (void *)wsi, (void *)wsi->http.ah, pt->http.ah_count_in_use); + +reset: + __lws_header_table_reset(wsi, autoservice); + + lws_pt_unlock(pt); + +#ifndef LWS_NO_CLIENT + if (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED) + if (!lws_client_connect_via_info2(wsi)) + /* our client connect has failed, the wsi + * has been closed + */ + return -1; +#endif + + return 0; + +bail: + lws_pt_unlock(pt); + + return 1; +} + +int __lws_header_table_detach(struct lws *wsi, int autoservice) +{ + struct lws_context *context = wsi->context; + struct allocated_headers *ah = wsi->http.ah; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + struct lws_pollargs pa; + struct lws **pwsi, **pwsi_eligible; + time_t now; + + __lws_remove_from_ah_waiting_list(wsi); + + if (!ah) + return 0; + + lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, + (void *)wsi, (void *)ah, wsi->tsi, + pt->http.ah_count_in_use); + + /* we did have an ah attached */ + time(&now); + if (ah->assigned && now - ah->assigned > 3) { + /* + * we're detaching the ah, but it was held an + * unreasonably long time + */ + lwsl_debug("%s: wsi %p: ah held %ds, role/state 0x%x 0x%x," + "\n", __func__, wsi, (int)(now - ah->assigned), + lwsi_role(wsi), lwsi_state(wsi)); + } + + ah->assigned = 0; + + /* if we think we're detaching one, there should be one in use */ + assert(pt->http.ah_count_in_use > 0); + /* and this specific one should have been in use */ + assert(ah->in_use); + memset(&wsi->http.ah, 0, sizeof(wsi->http.ah)); + +#if defined(LWS_WITH_PEER_LIMITS) + if (ah->wsi) + lws_peer_track_ah_detach(context, wsi->peer); +#endif + ah->wsi = NULL; /* no owner */ + + pwsi = &pt->http.ah_wait_list; + + /* oh there is nobody on the waiting list... leave the ah unattached */ + if (!*pwsi) + goto nobody_usable_waiting; + + /* + * at least one wsi on the same tsi is waiting, give it to oldest guy + * who is allowed to take it (if any) + */ + lwsl_info("pt wait list %p\n", *pwsi); + wsi = NULL; + pwsi_eligible = NULL; + + while (*pwsi) { +#if defined(LWS_WITH_PEER_LIMITS) + /* are we willing to give this guy an ah? */ + if (!lws_peer_confirm_ah_attach_ok(context, (*pwsi)->peer)) +#endif + { + wsi = *pwsi; + pwsi_eligible = pwsi; + } +#if defined(LWS_WITH_PEER_LIMITS) + else + if (!(*pwsi)->http.ah_wait_list) + lws_stats_atomic_bump(context, pt, + LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); +#endif + pwsi = &(*pwsi)->http.ah_wait_list; + } + + if (!wsi) /* everybody waiting already has too many ah... */ + goto nobody_usable_waiting; + + lwsl_info("%s: transferring ah to last eligible wsi in wait list %p (wsistate 0x%x)\n", __func__, wsi, wsi->wsistate); + + wsi->http.ah = ah; + ah->wsi = wsi; /* new owner */ + + __lws_header_table_reset(wsi, autoservice); +#if defined(LWS_WITH_PEER_LIMITS) && (defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)) + lws_context_lock(context); /* <====================================== */ + if (wsi->peer) + wsi->peer->http.count_ah++; + lws_context_unlock(context); /* ====================================> */ +#endif + + /* clients acquire the ah and then insert themselves in fds table... */ + if (wsi->position_in_fds_table != LWS_NO_FDS_POS) { + lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi); + + /* he has been stuck waiting for an ah, but now his wait is + * over, let him progress */ + + _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); + } + + /* point prev guy to next guy in list instead */ + *pwsi_eligible = wsi->http.ah_wait_list; + /* the guy who got one is out of the list */ + wsi->http.ah_wait_list = NULL; + pt->http.ah_wait_list_length--; + +#ifndef LWS_NO_CLIENT + if (lwsi_role_client(wsi) && lwsi_state(wsi) == LRS_UNCONNECTED) { + lws_pt_unlock(pt); + + if (!lws_client_connect_via_info2(wsi)) { + /* our client connect has failed, the wsi + * has been closed + */ + + return -1; + } + return 0; + } +#endif + + assert(!!pt->http.ah_wait_list_length == !!(lws_intptr_t)pt->http.ah_wait_list); +bail: + lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, + (void *)wsi, (void *)ah, pt->tid, pt->http.ah_count_in_use); + + return 0; + +nobody_usable_waiting: + lwsl_info("%s: nobody usable waiting\n", __func__); + _lws_destroy_ah(pt, ah); + pt->http.ah_count_in_use--; + + goto bail; +} + +int lws_header_table_detach(struct lws *wsi, int autoservice) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + int n; + + lws_pt_lock(pt, __func__); + n = __lws_header_table_detach(wsi, autoservice); + lws_pt_unlock(pt); + + return n; +} + +LWS_VISIBLE int +lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx) +{ + int n; + + if (!wsi->http.ah) + return 0; + + n = wsi->http.ah->frag_index[h]; + if (!n) + return 0; + do { + if (!frag_idx) + return wsi->http.ah->frags[n].len; + n = wsi->http.ah->frags[n].nfrag; + } while (frag_idx-- && n); + + return 0; +} + +LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h) +{ + int n; + int len = 0; + + if (!wsi->http.ah) + return 0; + + n = wsi->http.ah->frag_index[h]; + if (!n) + return 0; + do { + len += wsi->http.ah->frags[n].len; + n = wsi->http.ah->frags[n].nfrag; + } while (n); + + return len; +} + +LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len, + enum lws_token_indexes h, int frag_idx) +{ + int n = 0; + int f; + + if (!wsi->http.ah) + return -1; + + f = wsi->http.ah->frag_index[h]; + + if (!f) + return -1; + + while (n < frag_idx) { + f = wsi->http.ah->frags[f].nfrag; + if (!f) + return -1; + n++; + } + + if (wsi->http.ah->frags[f].len >= len) + return -1; + + memcpy(dst, wsi->http.ah->data + wsi->http.ah->frags[f].offset, + wsi->http.ah->frags[f].len); + dst[wsi->http.ah->frags[f].len] = '\0'; + + return wsi->http.ah->frags[f].len; +} + +LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len, + enum lws_token_indexes h) +{ + int toklen = lws_hdr_total_length(wsi, h); + int n; + + if (toklen >= len) + return -1; + + if (!wsi->http.ah) + return -1; + + n = wsi->http.ah->frag_index[h]; + if (!n) + return 0; + + do { + if (wsi->http.ah->frags[n].len >= len) + return -1; + strncpy(dst, &wsi->http.ah->data[wsi->http.ah->frags[n].offset], + wsi->http.ah->frags[n].len); + dst += wsi->http.ah->frags[n].len; + len -= wsi->http.ah->frags[n].len; + n = wsi->http.ah->frags[n].nfrag; + } while (n); + *dst = '\0'; + + return toklen; +} + +char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h) +{ + int n; + + n = wsi->http.ah->frag_index[h]; + if (!n) + return NULL; + + return wsi->http.ah->data + wsi->http.ah->frags[n].offset; +} + +static int LWS_WARN_UNUSED_RESULT +lws_pos_in_bounds(struct lws *wsi) +{ + if (wsi->http.ah->pos < + (unsigned int)wsi->context->max_http_header_data) + return 0; + + if ((int)wsi->http.ah->pos == wsi->context->max_http_header_data) { + lwsl_err("Ran out of header data space\n"); + return 1; + } + + /* + * with these tests everywhere, it should never be able to exceed + * the limit, only meet it + */ + lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->http.ah->pos, + wsi->context->max_http_header_data); + assert(0); + + return 1; +} + +int LWS_WARN_UNUSED_RESULT +lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s) +{ + wsi->http.ah->nfrag++; + if (wsi->http.ah->nfrag == ARRAY_SIZE(wsi->http.ah->frags)) { + lwsl_warn("More hdr frags than we can deal with, dropping\n"); + return -1; + } + + wsi->http.ah->frag_index[h] = wsi->http.ah->nfrag; + + wsi->http.ah->frags[wsi->http.ah->nfrag].offset = wsi->http.ah->pos; + wsi->http.ah->frags[wsi->http.ah->nfrag].len = 0; + wsi->http.ah->frags[wsi->http.ah->nfrag].nfrag = 0; + + do { + if (lws_pos_in_bounds(wsi)) + return -1; + + wsi->http.ah->data[wsi->http.ah->pos++] = *s; + if (*s) + wsi->http.ah->frags[wsi->http.ah->nfrag].len++; + } while (*s++); + + return 0; +} + +static int LWS_WARN_UNUSED_RESULT +issue_char(struct lws *wsi, unsigned char c) +{ + unsigned short frag_len; + + if (lws_pos_in_bounds(wsi)) + return -1; + + frag_len = wsi->http.ah->frags[wsi->http.ah->nfrag].len; + /* + * If we haven't hit the token limit, just copy the character into + * the header + */ + if (frag_len < wsi->http.ah->current_token_limit) { + wsi->http.ah->data[wsi->http.ah->pos++] = c; + if (c) + wsi->http.ah->frags[wsi->http.ah->nfrag].len++; + return 0; + } + + /* Insert a null character when we *hit* the limit: */ + if (frag_len == wsi->http.ah->current_token_limit) { + if (lws_pos_in_bounds(wsi)) + return -1; + + wsi->http.ah->data[wsi->http.ah->pos++] = '\0'; + lwsl_warn("header %i exceeds limit %d\n", + wsi->http.ah->parser_state, + wsi->http.ah->current_token_limit); + } + + return 1; +} + +int +lws_parse_urldecode(struct lws *wsi, uint8_t *_c) +{ + struct allocated_headers *ah = wsi->http.ah; + unsigned int enc = 0; + uint8_t c = *_c; + + // lwsl_notice("ah->ups %d\n", ah->ups); + + /* + * PRIORITY 1 + * special URI processing... convert %xx + */ + switch (ah->ues) { + case URIES_IDLE: + if (c == '%') { + ah->ues = URIES_SEEN_PERCENT; + goto swallow; + } + break; + case URIES_SEEN_PERCENT: + if (char_to_hex(c) < 0) + /* illegal post-% char */ + goto forbid; + + ah->esc_stash = c; + ah->ues = URIES_SEEN_PERCENT_H1; + goto swallow; + + case URIES_SEEN_PERCENT_H1: + if (char_to_hex(c) < 0) + /* illegal post-% char */ + goto forbid; + + *_c = (char_to_hex(ah->esc_stash) << 4) | + char_to_hex(c); + c = *_c; + enc = 1; + ah->ues = URIES_IDLE; + break; + } + + /* + * PRIORITY 2 + * special URI processing... + * convert /.. or /... or /../ etc to / + * convert /./ to / + * convert // or /// etc to / + * leave /.dir or whatever alone + */ + + switch (ah->ups) { + case URIPS_IDLE: + if (!c) + return -1; + /* genuine delimiter */ + if ((c == '&' || c == ';') && !enc) { + if (issue_char(wsi, c) < 0) + return -1; + /* swallow the terminator */ + ah->frags[ah->nfrag].len--; + /* link to next fragment */ + ah->frags[ah->nfrag].nfrag = ah->nfrag + 1; + ah->nfrag++; + if (ah->nfrag >= ARRAY_SIZE(ah->frags)) + goto excessive; + /* start next fragment after the & */ + ah->post_literal_equal = 0; + ah->frags[ah->nfrag].offset = ah->pos; + ah->frags[ah->nfrag].len = 0; + ah->frags[ah->nfrag].nfrag = 0; + goto swallow; + } + /* uriencoded = in the name part, disallow */ + if (c == '=' && enc && + ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] && + !ah->post_literal_equal) { + c = '_'; + *_c =c; + } + + /* after the real =, we don't care how many = */ + if (c == '=' && !enc) + ah->post_literal_equal = 1; + + /* + to space */ + if (c == '+' && !enc) { + c = ' '; + *_c = c; + } + /* issue the first / always */ + if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) + ah->ups = URIPS_SEEN_SLASH; + break; + case URIPS_SEEN_SLASH: + /* swallow subsequent slashes */ + if (c == '/') + goto swallow; + /* track and swallow the first . after / */ + if (c == '.') { + ah->ups = URIPS_SEEN_SLASH_DOT; + goto swallow; + } + ah->ups = URIPS_IDLE; + break; + case URIPS_SEEN_SLASH_DOT: + /* swallow second . */ + if (c == '.') { + ah->ups = URIPS_SEEN_SLASH_DOT_DOT; + goto swallow; + } + /* change /./ to / */ + if (c == '/') { + ah->ups = URIPS_SEEN_SLASH; + goto swallow; + } + /* it was like /.dir ... regurgitate the . */ + ah->ups = URIPS_IDLE; + if (issue_char(wsi, '.') < 0) + return -1; + break; + + case URIPS_SEEN_SLASH_DOT_DOT: + + /* /../ or /..[End of URI] --> backup to last / */ + if (c == '/' || c == '?') { + /* + * back up one dir level if possible + * safe against header fragmentation because + * the method URI can only be in 1 fragment + */ + if (ah->frags[ah->nfrag].len > 2) { + ah->pos--; + ah->frags[ah->nfrag].len--; + do { + ah->pos--; + ah->frags[ah->nfrag].len--; + } while (ah->frags[ah->nfrag].len > 1 && + ah->data[ah->pos] != '/'); + } + ah->ups = URIPS_SEEN_SLASH; + if (ah->frags[ah->nfrag].len > 1) + break; + goto swallow; + } + + /* /..[^/] ... regurgitate and allow */ + + if (issue_char(wsi, '.') < 0) + return -1; + if (issue_char(wsi, '.') < 0) + return -1; + ah->ups = URIPS_IDLE; + break; + } + + if (c == '?' && !enc && + !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI args */ + if (ah->ues != URIES_IDLE) + goto forbid; + + /* seal off uri header */ + if (issue_char(wsi, '\0') < 0) + return -1; + + /* move to using WSI_TOKEN_HTTP_URI_ARGS */ + ah->nfrag++; + if (ah->nfrag >= ARRAY_SIZE(ah->frags)) + goto excessive; + ah->frags[ah->nfrag].offset = ah->pos; + ah->frags[ah->nfrag].len = 0; + ah->frags[ah->nfrag].nfrag = 0; + + ah->post_literal_equal = 0; + ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag; + ah->ups = URIPS_IDLE; + goto swallow; + } + + return LPUR_CONTINUE; + +swallow: + return LPUR_SWALLOW; + +forbid: + return LPUR_FORBID; + +excessive: + return LPUR_EXCESSIVE; +} + +static const unsigned char methods[] = { + WSI_TOKEN_GET_URI, + WSI_TOKEN_POST_URI, + WSI_TOKEN_OPTIONS_URI, + WSI_TOKEN_PUT_URI, + WSI_TOKEN_PATCH_URI, + WSI_TOKEN_DELETE_URI, + WSI_TOKEN_CONNECT, + WSI_TOKEN_HEAD_URI, +}; + +/* + * possible returns:, -1 fail, 0 ok or 2, transition to raw + */ + +int LWS_WARN_UNUSED_RESULT +lws_parse(struct lws *wsi, unsigned char *buf, int *len) +{ + struct allocated_headers *ah = wsi->http.ah; + struct lws_context *context = wsi->context; + unsigned int n, m; + unsigned char c; + int r, pos; + + assert(wsi->http.ah); + + do { + (*len)--; + c = *buf++; + + switch (ah->parser_state) { + default: + + lwsl_parser("WSI_TOK_(%d) '%c'\n", ah->parser_state, c); + + /* collect into malloc'd buffers */ + /* optional initial space swallow */ + if (!ah->frags[ah->frag_index[ah->parser_state]].len && + c == ' ') + break; + + for (m = 0; m < ARRAY_SIZE(methods); m++) + if (ah->parser_state == methods[m]) + break; + if (m == ARRAY_SIZE(methods)) + /* it was not any of the methods */ + goto check_eol; + + /* special URI processing... end at space */ + + if (c == ' ') { + /* enforce starting with / */ + if (!ah->frags[ah->nfrag].len) + if (issue_char(wsi, '/') < 0) + return -1; + + if (ah->ups == URIPS_SEEN_SLASH_DOT_DOT) { + /* + * back up one dir level if possible + * safe against header fragmentation because + * the method URI can only be in 1 fragment + */ + if (ah->frags[ah->nfrag].len > 2) { + ah->pos--; + ah->frags[ah->nfrag].len--; + do { + ah->pos--; + ah->frags[ah->nfrag].len--; + } while (ah->frags[ah->nfrag].len > 1 && + ah->data[ah->pos] != '/'); + } + } + + /* begin parsing HTTP version: */ + if (issue_char(wsi, '\0') < 0) + return -1; + ah->parser_state = WSI_TOKEN_HTTP; + goto start_fragment; + } + + r = lws_parse_urldecode(wsi, &c); + switch (r) { + case LPUR_CONTINUE: + break; + case LPUR_SWALLOW: + goto swallow; + case LPUR_FORBID: + goto forbid; + case LPUR_EXCESSIVE: + goto excessive; + default: + return -1; + } +check_eol: + /* bail at EOL */ + if (ah->parser_state != WSI_TOKEN_CHALLENGE && + c == '\x0d') { + if (ah->ues != URIES_IDLE) + goto forbid; + + c = '\0'; + ah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR; + lwsl_parser("*\n"); + } + + n = issue_char(wsi, c); + if ((int)n < 0) + return -1; + if (n > 0) + ah->parser_state = WSI_TOKEN_SKIPPING; + +swallow: + /* per-protocol end of headers management */ + + if (ah->parser_state == WSI_TOKEN_CHALLENGE) + goto set_parsing_complete; + break; + + /* collecting and checking a name part */ + case WSI_TOKEN_NAME_PART: + lwsl_parser("WSI_TOKEN_NAME_PART '%c' 0x%02X (role=0x%x) " + "wsi->lextable_pos=%d\n", c, c, lwsi_role(wsi), + ah->lextable_pos); + + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + + pos = ah->lextable_pos; + + while (1) { + if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */ + if ((lextable[pos] & 0x7f) != c) { +nope: + ah->lextable_pos = -1; + break; + } + /* fall thru */ + pos++; + if (lextable[pos] == FAIL_CHAR) + goto nope; + + ah->lextable_pos = pos; + break; + } + + if (lextable[pos] == FAIL_CHAR) + goto nope; + + /* b7 = 0, end or 3-byte */ + if (lextable[pos] < FAIL_CHAR) { /* terminal marker */ + ah->lextable_pos = pos; + break; + } + + if (lextable[pos] == c) { /* goto */ + ah->lextable_pos = pos + (lextable[pos + 1]) + + (lextable[pos + 2] << 8); + break; + } + + /* fall thru goto */ + pos += 3; + /* continue */ + } + + /* + * If it's h1, server needs to look out for unknown + * methods... + */ + if (ah->lextable_pos < 0 && lwsi_role_h1(wsi) && + lwsi_role_server(wsi)) { + /* this is not a header we know about */ + for (m = 0; m < ARRAY_SIZE(methods); m++) + if (ah->frag_index[methods[m]]) { + /* + * already had the method, no idea what + * this crap from the client is, ignore + */ + ah->parser_state = WSI_TOKEN_SKIPPING; + break; + } + /* + * hm it's an unknown http method from a client in fact, + * it cannot be valid http + */ + if (m == ARRAY_SIZE(methods)) { + /* + * are we set up to accept raw in these cases? + */ + if (lws_check_opt(wsi->vhost->options, + LWS_SERVER_OPTION_FALLBACK_TO_RAW)) + return 2; /* transition to raw */ + + lwsl_info("Unknown method - dropping\n"); + goto forbid; + } + break; + } + /* + * ...otherwise for a client, let him ignore unknown headers + * coming from the server + */ + if (ah->lextable_pos < 0) { + ah->parser_state = WSI_TOKEN_SKIPPING; + break; + } + + if (lextable[ah->lextable_pos] < FAIL_CHAR) { + /* terminal state */ + + n = ((unsigned int)lextable[ah->lextable_pos] << 8) | + lextable[ah->lextable_pos + 1]; + + lwsl_parser("known hdr %d\n", n); + for (m = 0; m < ARRAY_SIZE(methods); m++) + if (n == methods[m] && + ah->frag_index[methods[m]]) { + lwsl_warn("Duplicated method\n"); + return -1; + } + + /* + * WSORIGIN is protocol equiv to ORIGIN, + * JWebSocket likes to send it, map to ORIGIN + */ + if (n == WSI_TOKEN_SWORIGIN) + n = WSI_TOKEN_ORIGIN; + + ah->parser_state = (enum lws_token_indexes) + (WSI_TOKEN_GET_URI + n); + ah->ups = URIPS_IDLE; + + if (context->token_limits) + ah->current_token_limit = context-> + token_limits->token_limit[ + ah->parser_state]; + else + ah->current_token_limit = + wsi->context->max_http_header_data; + + if (ah->parser_state == WSI_TOKEN_CHALLENGE) + goto set_parsing_complete; + + goto start_fragment; + } + break; + +start_fragment: + ah->nfrag++; +excessive: + if (ah->nfrag == ARRAY_SIZE(ah->frags)) { + lwsl_warn("More hdr frags than we can deal with\n"); + return -1; + } + + ah->frags[ah->nfrag].offset = ah->pos; + ah->frags[ah->nfrag].len = 0; + ah->frags[ah->nfrag].nfrag = 0; + ah->frags[ah->nfrag].flags = 2; + + n = ah->frag_index[ah->parser_state]; + if (!n) { /* first fragment */ + ah->frag_index[ah->parser_state] = ah->nfrag; + ah->hdr_token_idx = ah->parser_state; + break; + } + /* continuation */ + while (ah->frags[n].nfrag) + n = ah->frags[n].nfrag; + ah->frags[n].nfrag = ah->nfrag; + + if (issue_char(wsi, ' ') < 0) + return -1; + break; + + /* skipping arg part of a name we didn't recognize */ + case WSI_TOKEN_SKIPPING: + lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c); + + if (c == '\x0d') + ah->parser_state = WSI_TOKEN_SKIPPING_SAW_CR; + break; + + case WSI_TOKEN_SKIPPING_SAW_CR: + lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c); + if (ah->ues != URIES_IDLE) + goto forbid; + if (c == '\x0a') { + ah->parser_state = WSI_TOKEN_NAME_PART; + ah->lextable_pos = 0; + } else + ah->parser_state = WSI_TOKEN_SKIPPING; + break; + /* we're done, ignore anything else */ + + case WSI_PARSING_COMPLETE: + lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c); + break; + } + + } while (*len); + + return 0; + +set_parsing_complete: + if (ah->ues != URIES_IDLE) + goto forbid; + if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) { + if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION)) + wsi->rx_frame_type = /* temp for ws version index */ + atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION)); + + lwsl_parser("v%02d hdrs done\n", wsi->rx_frame_type); + } + ah->parser_state = WSI_PARSING_COMPLETE; + wsi->hdr_parsing_completed = 1; + + return 0; + +forbid: + lwsl_notice(" forbidding on uri sanitation\n"); + lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL); + + return -1; +} + diff --git a/thirdparty/lws/server/server.c b/thirdparty/libwebsockets/roles/http/server/server.c index db05954257..350af3cd7e 100644 --- a/thirdparty/lws/server/server.c +++ b/thirdparty/libwebsockets/roles/http/server/server.c @@ -1,7 +1,7 @@ /* * libwebsockets - small server side websockets and web server implementation * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -19,7 +19,7 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" const char * const method_names[] = { "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT", "HEAD", @@ -28,42 +28,46 @@ const char * const method_names[] = { #endif }; -#if defined (LWS_WITH_ESP8266) -#undef memcpy -void *memcpy(void *dest, const void *src, size_t n) -{ - return ets_memcpy(dest, src, n); -} -#endif +/* + * return 0: all done + * 1: nonfatal error + * <0: fatal error + * + * REQUIRES CONTEXT LOCK HELD + */ int -lws_context_init_server(struct lws_context_creation_info *info, - struct lws_vhost *vhost) +_lws_vhost_init_server(const struct lws_context_creation_info *info, + struct lws_vhost *vhost) { -#if LWS_POSIX int n, opt = 1, limit = 1; -#endif lws_sockfd_type sockfd; struct lws_vhost *vh; struct lws *wsi; - int m = 0; + int m = 0, is; (void)method_names; (void)opt; + + if (info) { + vhost->iface = info->iface; + vhost->listen_port = info->port; + } + /* set up our external listening socket we serve on */ - if (info->port == CONTEXT_PORT_NO_LISTEN || - info->port == CONTEXT_PORT_NO_LISTEN_SERVER) + if (vhost->listen_port == CONTEXT_PORT_NO_LISTEN || + vhost->listen_port == CONTEXT_PORT_NO_LISTEN_SERVER) return 0; vh = vhost->context->vhost_list; while (vh) { - if (vh->listen_port == info->port) { - if ((!info->iface && !vh->iface) || - (info->iface && vh->iface && - !strcmp(info->iface, vh->iface))) { - vhost->listen_port = info->port; - vhost->iface = info->iface; + if (vh->listen_port == vhost->listen_port) { + if (((!vhost->iface && !vh->iface) || + (vhost->iface && vh->iface && + !strcmp(vhost->iface, vh->iface))) && + vh->lserv_wsi + ) { lwsl_notice(" using listen skt from vhost %s\n", vh->name); return 0; @@ -72,7 +76,59 @@ lws_context_init_server(struct lws_context_creation_info *info, vh = vh->vhost_next; } -#if LWS_POSIX + if (vhost->iface) { + /* + * let's check before we do anything else about the disposition + * of the interface he wants to bind to... + */ + is = lws_socket_bind(vhost, LWS_SOCK_INVALID, vhost->listen_port, vhost->iface); + lwsl_debug("initial if check says %d\n", is); +deal: + + lws_start_foreach_llp(struct lws_vhost **, pv, + vhost->context->no_listener_vhost_list) { + if (is >= LWS_ITOSA_USABLE && *pv == vhost) { + /* on the list and shouldn't be: remove it */ + lwsl_debug("deferred iface: removing vh %s\n", (*pv)->name); + *pv = vhost->no_listener_vhost_list; + vhost->no_listener_vhost_list = NULL; + goto done_list; + } + if (is < LWS_ITOSA_USABLE && *pv == vhost) + goto done_list; + } lws_end_foreach_llp(pv, no_listener_vhost_list); + + /* not on the list... */ + + if (is < LWS_ITOSA_USABLE) { + + /* ... but needs to be: so add it */ + + lwsl_debug("deferred iface: adding vh %s\n", vhost->name); + vhost->no_listener_vhost_list = vhost->context->no_listener_vhost_list; + vhost->context->no_listener_vhost_list = vhost; + } + +done_list: + + switch (is) { + default: + break; + case LWS_ITOSA_NOT_EXIST: + /* can't add it */ + if (info) /* first time */ + lwsl_err("VH %s: iface %s port %d DOESN'T EXIST\n", + vhost->name, vhost->iface, vhost->listen_port); + return 1; + case LWS_ITOSA_NOT_USABLE: + /* can't add it */ + if (info) /* first time */ + lwsl_err("VH %s: iface %s port %d NOT USABLE\n", + vhost->name, vhost->iface, vhost->listen_port); + return 1; + } + } + (void)n; #if defined(__linux__) limit = vhost->context->count_threads; @@ -80,159 +136,150 @@ lws_context_init_server(struct lws_context_creation_info *info, for (m = 0; m < limit; m++) { #ifdef LWS_WITH_UNIX_SOCK - if (LWS_UNIX_SOCK_ENABLED(vhost)) - sockfd = socket(AF_UNIX, SOCK_STREAM, 0); - else + if (LWS_UNIX_SOCK_ENABLED(vhost)) + sockfd = socket(AF_UNIX, SOCK_STREAM, 0); + else #endif #ifdef LWS_WITH_IPV6 - if (LWS_IPV6_ENABLED(vhost)) - sockfd = socket(AF_INET6, SOCK_STREAM, 0); - else + if (LWS_IPV6_ENABLED(vhost)) + sockfd = socket(AF_INET6, SOCK_STREAM, 0); + else #endif - sockfd = socket(AF_INET, SOCK_STREAM, 0); + sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { -#else -#if defined(LWS_WITH_ESP8266) - sockfd = esp8266_create_tcp_listen_socket(vhost); - if (!lws_sockfd_valid(sockfd)) { -#endif + if (sockfd == LWS_SOCK_INVALID) { + lwsl_err("ERROR opening socket\n"); + return 1; + } +#if !defined(LWS_WITH_ESP32) +#if (defined(WIN32) || defined(_WIN32)) && defined(SO_EXCLUSIVEADDRUSE) + /* + * only accept that we are the only listener on the port + * https://msdn.microsoft.com/zh-tw/library/ + * windows/desktop/ms740621(v=vs.85).aspx + * + * for lws, to match Linux, we default to exclusive listen + */ + if (!lws_check_opt(vhost->options, + LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE)) { + if (setsockopt(sockfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + (const void *)&opt, sizeof(opt)) < 0) { + lwsl_err("reuseaddr failed\n"); + compatible_close(sockfd); + return -1; + } + } else #endif - lwsl_err("ERROR opening socket\n"); - return 1; - } -#if LWS_POSIX && !defined(LWS_WITH_ESP32) -#if (defined(WIN32) || defined(_WIN32)) && defined(SO_EXCLUSIVEADDRUSE) - /* - * only accept that we are the only listener on the port - * https://msdn.microsoft.com/zh-tw/library/ - * windows/desktop/ms740621(v=vs.85).aspx - * - * for lws, to match Linux, we default to exclusive listen - */ - if (!lws_check_opt(vhost->options, - LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE)) { - if (setsockopt(sockfd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, + /* + * allow us to restart even if old sockets in TIME_WAIT + */ + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt)) < 0) { lwsl_err("reuseaddr failed\n"); compatible_close(sockfd); - return 1; + return -1; } - } else -#endif - - /* - * allow us to restart even if old sockets in TIME_WAIT - */ - if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, - (const void *)&opt, sizeof(opt)) < 0) { - lwsl_err("reuseaddr failed\n"); - compatible_close(sockfd); - return 1; - } #if defined(LWS_WITH_IPV6) && defined(IPV6_V6ONLY) - if (LWS_IPV6_ENABLED(vhost)) { - if (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) { + if (LWS_IPV6_ENABLED(vhost) && + vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) { int value = (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0; if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const void*)&value, sizeof(value)) < 0) { compatible_close(sockfd); - return 1; + return -1; } } - } #endif #if defined(__linux__) && defined(SO_REUSEPORT) - n = lws_check_opt(vhost->options, LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE); + /* keep coverity happy */ #if LWS_MAX_SMP > 1 - n = 1; + n = 1; +#else + n = lws_check_opt(vhost->options, + LWS_SERVER_OPTION_ALLOW_LISTEN_SHARE); #endif - - if (n) - if (vhost->context->count_threads > 1) + if (n && vhost->context->count_threads > 1) if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const void *)&opt, sizeof(opt)) < 0) { compatible_close(sockfd); - return 1; + return -1; } #endif #endif - lws_plat_set_socket_options(vhost, sockfd); + lws_plat_set_socket_options(vhost, sockfd); -#if LWS_POSIX - n = lws_socket_bind(vhost, sockfd, info->port, info->iface); - if (n < 0) - goto bail; - info->port = n; -#endif - vhost->listen_port = info->port; - vhost->iface = info->iface; + is = lws_socket_bind(vhost, sockfd, vhost->listen_port, vhost->iface); + /* + * There is a race where the network device may come up and then + * go away and fail here. So correctly handle unexpected failure + * here despite we earlier confirmed it. + */ + if (is < 0) { + lwsl_info("%s: lws_socket_bind says %d\n", __func__, is); + compatible_close(sockfd); + goto deal; + } + vhost->listen_port = is; - wsi = lws_zalloc(sizeof(struct lws), "listen wsi"); - if (wsi == NULL) { - lwsl_err("Out of mem\n"); - goto bail; - } - wsi->context = vhost->context; - wsi->desc.sockfd = sockfd; - wsi->mode = LWSCM_SERVER_LISTENER; - wsi->protocol = vhost->protocols; - wsi->tsi = m; - wsi->vhost = vhost; - wsi->listener = 1; - -#ifdef LWS_WITH_LIBUV - if (LWS_LIBUV_ENABLED(vhost->context)) - lws_uv_initvhost(vhost, wsi); -#endif + lwsl_debug("%s: lws_socket_bind says %d\n", __func__, is); - if (insert_wsi_socket_into_fds(vhost->context, wsi)) - goto bail; + wsi = lws_zalloc(sizeof(struct lws), "listen wsi"); + if (wsi == NULL) { + lwsl_err("Out of mem\n"); + goto bail; + } + wsi->context = vhost->context; + wsi->desc.sockfd = sockfd; + lws_role_transition(wsi, 0, LRS_UNCONNECTED, &role_ops_listen); + wsi->protocol = vhost->protocols; + wsi->tsi = m; + wsi->vhost = vhost; + wsi->listener = 1; - vhost->context->count_wsi_allocated++; - vhost->lserv_wsi = wsi; + if (wsi->context->event_loop_ops->init_vhost_listen_wsi) + wsi->context->event_loop_ops->init_vhost_listen_wsi(wsi); -#if LWS_POSIX - n = listen(wsi->desc.sockfd, LWS_SOMAXCONN); - if (n < 0) { - lwsl_err("listen failed with error %d\n", LWS_ERRNO); - vhost->lserv_wsi = NULL; - vhost->context->count_wsi_allocated--; - remove_wsi_socket_from_fds(wsi); - goto bail; - } + if (__insert_wsi_socket_into_fds(vhost->context, wsi)) { + lwsl_notice("inserting wsi socket into fds failed\n"); + goto bail; + } + + vhost->context->count_wsi_allocated++; + vhost->lserv_wsi = wsi; + + n = listen(wsi->desc.sockfd, LWS_SOMAXCONN); + if (n < 0) { + lwsl_err("listen failed with error %d\n", LWS_ERRNO); + vhost->lserv_wsi = NULL; + vhost->context->count_wsi_allocated--; + __remove_wsi_socket_from_fds(wsi); + goto bail; + } } /* for each thread able to independently listen */ -#else -#if defined(LWS_WITH_ESP8266) - esp8266_tcp_stream_bind(wsi->desc.sockfd, info->port, wsi); -#endif -#endif - if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) { + + if (!lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) { #ifdef LWS_WITH_UNIX_SOCK if (LWS_UNIX_SOCK_ENABLED(vhost)) - lwsl_info(" Listening on \"%s\"\n", info->iface); + lwsl_info(" Listening on \"%s\"\n", vhost->iface); else #endif - lwsl_info(" Listening on port %d\n", info->port); + lwsl_info(" Listening on port %d\n", vhost->listen_port); } + // info->port = vhost->listen_port; + return 0; bail: compatible_close(sockfd); - return 1; + return -1; } -#if defined(LWS_WITH_ESP8266) -#undef strchr -#define strchr ets_strchr -#endif - struct lws_vhost * lws_select_vhost(struct lws_context *context, int port, const char *servername) { @@ -240,11 +287,11 @@ lws_select_vhost(struct lws_context *context, int port, const char *servername) const char *p; int n, m, colon; - n = strlen(servername); + n = (int)strlen(servername); colon = n; p = strchr(servername, ':'); if (p) - colon = p - servername; + colon = lws_ptr_diff(p, servername); /* Priotity 1: first try exact matches */ @@ -266,7 +313,7 @@ lws_select_vhost(struct lws_context *context, int port, const char *servername) */ vhost = context->vhost_list; while (vhost) { - m = strlen(vhost->name); + m = (int)strlen(vhost->name); if (port == vhost->listen_port && m <= (colon - 2) && servername[colon - m - 1] == '.' && @@ -283,8 +330,8 @@ lws_select_vhost(struct lws_context *context, int port, const char *servername) vhost = context->vhost_list; while (vhost) { if (port == vhost->listen_port) { - lwsl_info("vhost match to %s based on port %d\n", - vhost->name, port); + lwsl_info("%s: vhost match to %s based on port %d\n", + __func__, vhost->name, port); return vhost; } vhost = vhost->vhost_next; @@ -298,7 +345,7 @@ lws_select_vhost(struct lws_context *context, int port, const char *servername) LWS_VISIBLE LWS_EXTERN const char * lws_get_mimetype(const char *file, const struct lws_http_mount *m) { - int n = strlen(file); + int n = (int)strlen(file); const struct lws_protocol_vhost_options *pvo = NULL; if (m) @@ -388,7 +435,7 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, const struct lws_protocol_vhost_options *pvo = m->interpret; struct lws_process_html_args args; const char *mimetype; -#if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) +#if !defined(_WIN32_WCE) const struct lws_plat_file_ops *fops; const char *vpath; lws_fop_flags_t fflags = LWS_O_RDONLY; @@ -402,14 +449,24 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, char path[256], sym[512]; unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p; unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE; -#if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32) +#if !defined(WIN32) && !defined(LWS_WITH_ESP32) size_t len; #endif int n; + wsi->handling_404 = 0; + if (!wsi->vhost) + return -1; + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + if (wsi->vhost->http.error_document_404 && + !strcmp(uri, wsi->vhost->http.error_document_404)) + wsi->handling_404 = 1; +#endif + lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri); -#if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) +#if !defined(_WIN32_WCE) fflags |= lws_vfs_prepare_flags(wsi); @@ -417,13 +474,14 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, spin++; fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath); - if (wsi->u.http.fop_fd) - lws_vfs_file_close(&wsi->u.http.fop_fd); + if (wsi->http.fop_fd) + lws_vfs_file_close(&wsi->http.fop_fd); - wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops, + wsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops, path, vpath, &fflags); - if (!wsi->u.http.fop_fd) { - lwsl_err("Unable to open '%s'\n", path); + if (!wsi->http.fop_fd) { + lwsl_info("%s: Unable to open '%s': errno %d\n", + __func__, path, errno); return -1; } @@ -435,7 +493,7 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, break; #endif #if !defined(WIN32) - if (fstat(wsi->u.http.fop_fd->fd, &st)) { + if (fstat(wsi->http.fop_fd->fd, &st)) { lwsl_info("unable to stat %s\n", path); goto bail; } @@ -453,10 +511,10 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, #endif #endif - wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime; + wsi->http.fop_fd->mod_time = (uint32_t)st.st_mtime; fflags |= LWS_FOP_FLAG_MOD_TIME_VALID; -#if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32) +#if !defined(WIN32) && !defined(LWS_WITH_ESP32) if ((S_IFMT & st.st_mode) == S_IFLNK) { len = readlink(path, sym, sizeof(sym) - 1); if (len) { @@ -480,15 +538,15 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, lwsl_err("symlink loop %s \n", path); n = sprintf(sym, "%08llX%08lX", - (unsigned long long)lws_vfs_get_length(wsi->u.http.fop_fd), - (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd)); + (unsigned long long)lws_vfs_get_length(wsi->http.fop_fd), + (unsigned long)lws_vfs_get_mod_time(wsi->http.fop_fd)); /* disable ranges if IF_RANGE token invalid */ if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE)) if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE))) /* differs - defeat Range: */ - wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0; + wsi->http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0; if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) { /* @@ -523,7 +581,7 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, return -1; } - lws_vfs_file_close(&wsi->u.http.fop_fd); + lws_vfs_file_close(&wsi->http.fop_fd); return lws_http_transaction_completed(wsi); } @@ -549,10 +607,12 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, * a protocol */ while (pvo) { - n = strlen(path); + n = (int)strlen(path); if (n > (int)strlen(pvo->name) && !strcmp(&path[n - strlen(pvo->name)], pvo->name)) { - wsi->sending_chunked = 1; + wsi->interpreting = 1; + if (!wsi->http2_substream) + wsi->sending_chunked = 1; wsi->protocol_interpret_idx = (char)(lws_intptr_t)pvo->value; lwsl_info("want %s interpreted by %s\n", path, @@ -574,14 +634,15 @@ lws_http_serve(struct lws *wsi, char *uri, const char *origin, if (lws_bind_protocol(wsi, pp)) return 1; args.p = (char *)p; - args.max_len = end - p; + args.max_len = lws_ptr_diff(end, p); if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS, wsi->user_space, &args, 0)) return -1; p = (unsigned char *)args.p; } - n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start); + n = lws_serve_http_file(wsi, path, mimetype, (char *)start, + lws_ptr_diff(p, start)); if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi))) return -1; /* error or can't reuse connection: close the socket */ @@ -592,13 +653,14 @@ bail: return -1; } +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) const struct lws_http_mount * lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len) { const struct lws_http_mount *hm, *hit = NULL; int best = 0; - hm = wsi->vhost->mount_list; + hm = wsi->vhost->http.mount_list; while (hm) { if (uri_len >= hm->mountpoint_len && !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) && @@ -623,9 +685,9 @@ lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len) return hit; } +#endif -#if LWS_POSIX - +#if !defined(LWS_WITH_ESP32) static int lws_find_string_in_file(const char *filename, const char *string, int stringlen) { @@ -635,7 +697,7 @@ lws_find_string_in_file(const char *filename, const char *string, int stringlen) fd = open(filename, O_RDONLY); if (fd < 0) { lwsl_err("can't open auth file: %s\n", filename); - return 1; + return 0; } while (1) { @@ -669,6 +731,7 @@ lws_find_string_in_file(const char *filename, const char *string, int stringlen) return hit; } +#endif static int lws_unauthorised_basic_auth(struct lws *wsi) @@ -702,8 +765,6 @@ lws_unauthorised_basic_auth(struct lws *wsi) } -#endif - int lws_clean_url(char *p) { if (p[0] == 'h' && p[1] == 't' && p[2] == 't' && p[3] == 'p') { @@ -732,7 +793,6 @@ int lws_clean_url(char *p) return 0; } - static const unsigned char methods[] = { WSI_TOKEN_GET_URI, WSI_TOKEN_POST_URI, @@ -752,7 +812,7 @@ lws_http_get_uri_and_method(struct lws *wsi, char **puri_ptr, int *puri_len) { int n, count = 0; - for (n = 0; n < ARRAY_SIZE(methods); n++) + for (n = 0; n < (int)ARRAY_SIZE(methods); n++) if (lws_hdr_total_length(wsi, methods[n])) count++; if (!count) { @@ -767,7 +827,7 @@ lws_http_get_uri_and_method(struct lws *wsi, char **puri_ptr, int *puri_len) return -1; } - for (n = 0; n < ARRAY_SIZE(methods); n++) + for (n = 0; n < (int)ARRAY_SIZE(methods); n++) if (lws_hdr_total_length(wsi, methods[n])) { *puri_ptr = lws_hdr_simple_ptr(wsi, methods[n]); *puri_len = lws_hdr_total_length(wsi, methods[n]); @@ -797,7 +857,7 @@ lws_http_action(struct lws *wsi) }; meth = lws_http_get_uri_and_method(wsi, &uri_ptr, &uri_len); - if (meth < 0 || meth >= ARRAY_SIZE(method_names)) + if (meth < 0 || meth >= (int)ARRAY_SIZE(method_names)) goto bail_nuke_ah; /* we insist on absolute paths */ @@ -811,26 +871,36 @@ lws_http_action(struct lws *wsi) lwsl_info("Method: '%s' (%d), request for '%s'\n", method_names[meth], meth, uri_ptr); + if (wsi->role_ops && wsi->role_ops->check_upgrades) + switch (wsi->role_ops->check_upgrades(wsi)) { + case LWS_UPG_RET_DONE: + return 0; + case LWS_UPG_RET_CONTINUE: + break; + case LWS_UPG_RET_BAIL: + goto bail_nuke_ah; + } + if (lws_ensure_user_space(wsi)) goto bail_nuke_ah; /* HTTP header had a content length? */ - wsi->u.http.rx_content_length = 0; + wsi->http.rx_content_length = 0; if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) || lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) || lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI)) - wsi->u.http.rx_content_length = 100 * 1024 * 1024; + wsi->http.rx_content_length = 100 * 1024 * 1024; if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) { lws_hdr_copy(wsi, content_length_str, sizeof(content_length_str) - 1, WSI_TOKEN_HTTP_CONTENT_LENGTH); - wsi->u.http.rx_content_length = atoll(content_length_str); + wsi->http.rx_content_length = atoll(content_length_str); } if (wsi->http2_substream) { - wsi->u.http.request_version = HTTP_VERSION_2; + wsi->http.request_version = HTTP_VERSION_2; } else { /* http_version? Default to 1.0, override with token: */ request_version = HTTP_VERSION_1_0; @@ -845,7 +915,7 @@ lws_http_action(struct lws *wsi) http_version_str[7] == '1') request_version = HTTP_VERSION_1_1; } - wsi->u.http.request_version = request_version; + wsi->http.request_version = request_version; /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */ if (request_version == HTTP_VERSION_1_1) @@ -865,7 +935,7 @@ lws_http_action(struct lws *wsi) if (!strcasecmp(http_conn_str, "close")) connection_type = HTTP_CONNECTION_CLOSE; } - wsi->u.http.connection_type = connection_type; + wsi->http.connection_type = connection_type; } n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION, @@ -881,8 +951,8 @@ lws_http_action(struct lws *wsi) */ lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, wsi->context->timeout_secs); -#ifdef LWS_OPENSSL_SUPPORT - if (wsi->redirect_to_https) { +#ifdef LWS_WITH_TLS + if (wsi->tls.redirect_to_https) { /* * we accepted http:// only so we could redirect to * https://, so issue the redirect. Create the redirection @@ -921,6 +991,8 @@ lws_http_action(struct lws *wsi) if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0])) return 1; + lwsi_set_state(wsi, LRS_DOING_TRANSACTION); + n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP, wsi->user_space, uri_ptr, uri_len); @@ -989,7 +1061,6 @@ lws_http_action(struct lws *wsi) return lws_http_transaction_completed(wsi); } -#if LWS_POSIX /* basic auth? */ if (hit->basic_auth_login_file) { @@ -1029,11 +1100,10 @@ lws_http_action(struct lws *wsi) return lws_unauthorised_basic_auth(wsi); } - lwsl_notice("basic auth accepted\n"); + lwsl_info("basic auth accepted\n"); /* accept the auth */ } -#endif #if defined(LWS_WITH_HTTP_PROXY) /* @@ -1064,7 +1134,7 @@ lws_http_action(struct lws *wsi) else n = pslash - hit->origin; - if (n >= sizeof(ads) - 2) + if (n >= (int)sizeof(ads) - 2) n = sizeof(ads) - 2; memcpy(ads, hit->origin, n); @@ -1104,9 +1174,10 @@ lws_http_action(struct lws *wsi) i.uri_replace_from = hit->origin; i.uri_replace_to = hit->mountpoint; - lwsl_notice("proxying to %s port %d url %s, ssl %d, from %s, to %s\n", - i.address, i.port, i.path, i.ssl_connection, - i.uri_replace_from, i.uri_replace_to); + lwsl_notice("proxying to %s port %d url %s, ssl %d, " + "from %s, to %s\n", + i.address, i.port, i.path, i.ssl_connection, + i.uri_replace_from, i.uri_replace_to); if (!lws_client_connect_via_info(&i)) { lwsl_err("proxy connect fail\n"); @@ -1144,8 +1215,10 @@ lws_http_action(struct lws *wsi) args.len = uri_len; args.max_len = hit->auth_mask; args.final = 0; /* used to signal callback dealt with it */ + args.chunked = 0; - n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS, + n = wsi->protocol->callback(wsi, + LWS_CALLBACK_CHECK_ACCESS_RIGHTS, wsi->user_space, &args, 0); if (n) { lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED, @@ -1195,7 +1268,7 @@ lws_http_action(struct lws *wsi) } #endif - n = strlen(s); + n = (int)strlen(s); if (s[0] == '\0' || (n == 1 && s[n - 1] == '/')) s = (char *)hit->def; if (!s) @@ -1206,14 +1279,17 @@ lws_http_action(struct lws *wsi) wsi->cache_revalidate = hit->cache_revalidate; wsi->cache_intermediaries = hit->cache_intermediaries; - n = lws_http_serve(wsi, s, hit->origin, hit); + n = 1; + if (hit->origin_protocol == LWSMPRO_FILE) + n = lws_http_serve(wsi, s, hit->origin, hit); if (n) { /* - * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); + * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); */ if (hit->protocol) { - const struct lws_protocols *pp = lws_vhost_name_to_protocol( - wsi->vhost, hit->protocol); + const struct lws_protocols *pp = + lws_vhost_name_to_protocol( + wsi->vhost, hit->protocol); if (lws_bind_protocol(wsi, pp)) return 1; @@ -1245,125 +1321,90 @@ deal_body: * In any case, return 0 and let lws_read decide how to * proceed based on state */ - if (wsi->state != LWSS_HTTP_ISSUING_FILE) { + if (lwsi_state(wsi) != LRS_ISSUING_FILE) { /* Prepare to read body if we have a content length: */ - lwsl_debug("wsi->u.http.rx_content_length %lld %d %d\n", - (long long)wsi->u.http.rx_content_length, + lwsl_debug("wsi->http.rx_content_length %lld %d %d\n", + (long long)wsi->http.rx_content_length, wsi->upgraded_to_http2, wsi->http2_substream); - if (wsi->u.http.rx_content_length > 0) { - lwsl_notice("%s: %p: LWSS_HTTP_BODY state set\n", - __func__, wsi); - wsi->state = LWSS_HTTP_BODY; - wsi->u.http.rx_content_remain = - wsi->u.http.rx_content_length; + if (wsi->http.rx_content_length > 0) { + struct lws_tokens ebuf; + int m; + + lwsi_set_state(wsi, LRS_BODY); + lwsl_info("%s: %p: LRS_BODY state set (0x%x)\n", + __func__, wsi, wsi->wsistate); + wsi->http.rx_content_remain = + wsi->http.rx_content_length; + + /* + * At this point we have transitioned from deferred + * action to expecting BODY on the stream wsi, if it's + * in a bundle like h2. So if the stream wsi has its + * own buflist, we need to deal with that first. + */ + + while (1) { + ebuf.len = (int)lws_buflist_next_segment_len( + &wsi->buflist, (uint8_t **)&ebuf.token); + if (!ebuf.len) + break; + lwsl_notice("%s: consuming %d\n", __func__, (int)ebuf.len); + m = lws_read_h1(wsi, (uint8_t *)ebuf.token, ebuf.len); + if (m < 0) + return -1; + + if (lws_buflist_aware_consume(wsi, &ebuf, m, 1)) + return -1; + } } } return 0; bail_nuke_ah: - /* we're closing, losing some rx is OK */ - lws_header_table_force_to_detachable_state(wsi); lws_header_table_detach(wsi, 1); return 1; -#if LWS_POSIX transaction_result_n: lws_return_http_status(wsi, n, NULL); return lws_http_transaction_completed(wsi); -#endif -} - -static int -lws_server_init_wsi_for_ws(struct lws *wsi) -{ - int n; - - wsi->state = LWSS_ESTABLISHED; - lws_restart_ws_ping_pong_timer(wsi); - - /* - * create the frame buffer for this connection according to the - * size mentioned in the protocol definition. If 0 there, use - * a big default for compatibility - */ - - n = wsi->protocol->rx_buffer_size; - if (!n) - n = wsi->context->pt_serv_buf_size; - n += LWS_PRE; - wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, "rx_ubuf"); - if (!wsi->u.ws.rx_ubuf) { - lwsl_err("Out of Mem allocating rx buffer %d\n", n); - return 1; - } - wsi->u.ws.rx_ubuf_alloc = n; - lwsl_debug("Allocating RX buffer %d\n", n); - -#if LWS_POSIX && !defined(LWS_WITH_ESP32) - if (!wsi->parent_carries_io) - if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, - (const char *)&n, sizeof n)) { - lwsl_warn("Failed to set SNDBUF to %d", n); - return 1; - } -#endif - - /* notify user code that we're ready to roll */ - - if (wsi->protocol->callback) - if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED, - wsi->user_space, -#ifdef LWS_OPENSSL_SUPPORT - wsi->ssl, -#else - NULL, -#endif - 0)) - return 1; - - return 0; } int lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len) { - int protocol_len, n = 0, hit, non_space_char_found = 0, m; struct lws_context *context = lws_get_context(wsi); - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - struct _lws_header_related hdr; - struct allocated_headers *ah; unsigned char *obuf = *buf; - char protocol_list[128]; - char protocol_name[64]; +#if defined(LWS_WITH_HTTP2) + char tbuf[128], *p; +#endif size_t olen = len; - char *p; + int n = 0, m, i; if (len >= 10000000) { lwsl_err("%s: assert: len %ld\n", __func__, (long)len); assert(0); } - if (!wsi->u.hdr.ah) { + if (!wsi->http.ah) { lwsl_err("%s: assert: NULL ah\n", __func__); assert(0); } - lwsl_hexdump(*buf, len); - - while (len--) { - wsi->more_rx_waiting = !!len; - - if (wsi->mode != LWSCM_HTTP_SERVING && - wsi->mode != LWSCM_HTTP2_SERVING && - wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) { - lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode); + while (len) { + if (!lwsi_role_server(wsi) || !lwsi_role_http(wsi)) { + lwsl_err("%s: bad wsi role 0x%x\n", __func__, + lwsi_role(wsi)); goto bail_nuke_ah; } - m = lws_parse(wsi, *(*buf)++); + i = (int)len; + m = lws_parse(wsi, *buf, &i); + lwsl_info("%s: parsed count %d\n", __func__, (int)len - i); + (*buf) += (int)len - i; + len = i; if (m) { if (m == 2) { /* @@ -1384,8 +1425,8 @@ raw_transition: wsi->user_space, NULL, 0)) goto bail_nuke_ah; - lws_header_table_force_to_detachable_state(wsi); - lws_union_transition(wsi, LWSCM_RAW); + lws_role_transition(wsi, 0, LRS_ESTABLISHED, + &role_ops_raw_skt); lws_header_table_detach(wsi, 1); if (m == 2 && (wsi->protocol->callback)(wsi, @@ -1399,12 +1440,10 @@ raw_transition: goto bail_nuke_ah; } - if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE) + if (wsi->http.ah->parser_state != WSI_PARSING_COMPLETE) continue; lwsl_parser("%s: lws_parse sees parsing complete\n", __func__); - lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__, - wsi->more_rx_waiting); /* select vhost */ @@ -1418,7 +1457,7 @@ raw_transition: } else lwsl_info("no host\n"); - if (wsi->mode != LWSCM_HTTP2_SERVING) { + if (!lwsi_role_h2(wsi) || !lwsi_role_server(wsi)) { wsi->vhost->conn_stats.h1_trans++; if (!wsi->conn_stat_done) { wsi->vhost->conn_stats.h1_conn++; @@ -1435,38 +1474,39 @@ raw_transition: if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1, WSI_TOKEN_HTTP_USER_AGENT) > 0) { - ua[sizeof(ua) - 1] = '\0'; - while (rej) { - if (strstr(ua, rej->name)) { #ifdef LWS_WITH_ACCESS_LOG - char *uri_ptr = NULL; - int meth, uri_len; + char *uri_ptr = NULL; + int meth, uri_len; #endif + ua[sizeof(ua) - 1] = '\0'; + while (rej) { + if (!strstr(ua, rej->name)) { + rej = rej->next; + continue; + } - msg = strchr(rej->value, ' '); - if (msg) - msg++; - lws_return_http_status(wsi, - atoi(rej->value), msg); + msg = strchr(rej->value, ' '); + if (msg) + msg++; + lws_return_http_status(wsi, + atoi(rej->value), msg); #ifdef LWS_WITH_ACCESS_LOG - meth = lws_http_get_uri_and_method(wsi, - &uri_ptr, &uri_len); - if (meth >= 0) - lws_prepare_access_log_info(wsi, + meth = lws_http_get_uri_and_method(wsi, + &uri_ptr, &uri_len); + if (meth >= 0) + lws_prepare_access_log_info(wsi, uri_ptr, meth); - /* wsi close will do the log */ + /* wsi close will do the log */ #endif - wsi->vhost->conn_stats.rejected++; - /* - * We don't want anything from - * this rejected guy. Follow - * the close flow, not the - * transaction complete flow. - */ - goto bail_nuke_ah; - } - rej = rej->next; + wsi->vhost->conn_stats.rejected++; + /* + * We don't want anything from + * this rejected guy. Follow + * the close flow, not the + * transaction complete flow. + */ + goto bail_nuke_ah; } } } @@ -1478,20 +1518,24 @@ raw_transition: goto raw_transition; } - wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT; + lwsi_set_state(wsi, LRS_PRE_WS_SERVING_ACCEPT); lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* is this websocket protocol or normal http 1.0? */ if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) { - if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), + if (!strcasecmp(lws_hdr_simple_ptr(wsi, + WSI_TOKEN_UPGRADE), "websocket")) { +#if defined(LWS_ROLE_WS) wsi->vhost->conn_stats.ws_upg++; lwsl_info("Upgrade to ws\n"); goto upgrade_ws; +#endif } -#ifdef LWS_WITH_HTTP2 - if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE), +#if defined(LWS_WITH_HTTP2) + if (!strcasecmp(lws_hdr_simple_ptr(wsi, + WSI_TOKEN_UPGRADE), "h2c")) { wsi->vhost->conn_stats.h2_upg++; lwsl_info("Upgrade to h2c\n"); @@ -1505,23 +1549,19 @@ raw_transition: /* no upgrade ack... he remained as HTTP */ - lwsl_info("No upgrade\n"); - ah = wsi->u.hdr.ah; + lwsl_info("%s: %p: No upgrade\n", __func__, wsi); - lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED); - wsi->state = LWSS_HTTP; - wsi->u.http.fop_fd = NULL; + lwsi_set_state(wsi, LRS_ESTABLISHED); + wsi->http.fop_fd = NULL; - /* expose it at the same offset as u.hdr */ - wsi->u.http.ah = ah; lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi, - (void *)wsi->u.hdr.ah); + (void *)wsi->http.ah); n = lws_http_action(wsi); return n; -#ifdef LWS_WITH_HTTP2 +#if defined(LWS_WITH_HTTP2) upgrade_h2c: if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) { lwsl_info("missing http2_settings\n"); @@ -1532,8 +1572,7 @@ upgrade_h2c: p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS); /* convert the peer's HTTP-Settings */ - n = lws_b64_decode_string(p, protocol_list, - sizeof(protocol_list)); + n = lws_b64_decode_string(p, tbuf, sizeof(tbuf)); if (n < 0) { lwsl_parser("HTTP2_SETTINGS too long\n"); return 1; @@ -1541,16 +1580,10 @@ upgrade_h2c: /* adopt the header info */ - ah = wsi->u.hdr.ah; - - lws_union_transition(wsi, LWSCM_HTTP2_SERVING); - - /* http2 union member has http union struct at start */ - wsi->u.http.ah = ah; - - if (!wsi->u.h2.h2n) { - wsi->u.h2.h2n = lws_zalloc(sizeof(*wsi->u.h2.h2n), "h2n"); - if (!wsi->u.h2.h2n) + if (!wsi->h2.h2n) { + wsi->h2.h2n = lws_zalloc(sizeof(*wsi->h2.h2n), + "h2n"); + if (!wsi->h2.h2n) return 1; } @@ -1558,195 +1591,39 @@ upgrade_h2c: /* HTTP2 union */ - lws_h2_settings(wsi, &wsi->u.h2.h2n->set, - (unsigned char *)protocol_list, n); + lws_h2_settings(wsi, &wsi->h2.h2n->set, (unsigned char *)tbuf, n); - lws_hpack_dynamic_size(wsi, wsi->u.h2.h2n->set.s[ + lws_hpack_dynamic_size(wsi, wsi->h2.h2n->set.s[ H2SET_HEADER_TABLE_SIZE]); - strcpy(protocol_list, "HTTP/1.1 101 Switching Protocols\x0d\x0a" - "Connection: Upgrade\x0d\x0a" - "Upgrade: h2c\x0d\x0a\x0d\x0a"); - n = lws_issue_raw(wsi, (unsigned char *)protocol_list, - strlen(protocol_list)); - if (n != strlen(protocol_list)) { + strcpy(tbuf, "HTTP/1.1 101 Switching Protocols\x0d\x0a" + "Connection: Upgrade\x0d\x0a" + "Upgrade: h2c\x0d\x0a\x0d\x0a"); + m = (int)strlen(tbuf); + n = lws_issue_raw(wsi, (unsigned char *)tbuf, m); + if (n != m) { lwsl_debug("http2 switch: ERROR writing to socket\n"); return 1; } - wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE; + lwsi_set_state(wsi, LRS_H2_AWAIT_PREFACE); + wsi->upgraded_to_http2 = 1; return 0; #endif - +#if defined(LWS_ROLE_WS) upgrade_ws: - if (!wsi->protocol) - lwsl_err("NULL protocol at lws_read\n"); - - /* - * It's websocket - * - * Select the first protocol we support from the list - * the client sent us. - * - * Copy it to remove header fragmentation - */ - - if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1, - WSI_TOKEN_PROTOCOL) < 0) { - lwsl_err("protocol list too long"); - goto bail_nuke_ah; - } - - protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); - protocol_list[protocol_len] = '\0'; - p = protocol_list; - hit = 0; - - while (*p && !hit) { - n = 0; - non_space_char_found = 0; - while (n < sizeof(protocol_name) - 1 && - *p && *p != ',') { - /* ignore leading spaces */ - if (!non_space_char_found && *p == ' ') { - n++; - continue; - } - non_space_char_found = 1; - protocol_name[n++] = *p++; - } - protocol_name[n] = '\0'; - if (*p) - p++; - - lwsl_info("checking %s\n", protocol_name); - - n = 0; - while (wsi->vhost->protocols[n].callback) { - lwsl_info("try %s\n", - wsi->vhost->protocols[n].name); - - if (wsi->vhost->protocols[n].name && - !strcmp(wsi->vhost->protocols[n].name, - protocol_name)) { - wsi->protocol = &wsi->vhost->protocols[n]; - hit = 1; - break; - } - - n++; - } - } - - /* we didn't find a protocol he wanted? */ - - if (!hit) { - if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) { - lwsl_info("No protocol from \"%s\" supported\n", - protocol_list); - goto bail_nuke_ah; - } - /* - * some clients only have one protocol and - * do not send the protocol list header... - * allow it and match to the vhost's default - * protocol (which itself defaults to zero) - */ - lwsl_info("defaulting to prot handler %d\n", - wsi->vhost->default_protocol_index); - n = wsi->vhost->default_protocol_index; - wsi->protocol = &wsi->vhost->protocols[ - (int)wsi->vhost->default_protocol_index]; - } - - /* allocate wsi->user storage */ - if (lws_ensure_user_space(wsi)) - goto bail_nuke_ah; - - /* - * Give the user code a chance to study the request and - * have the opportunity to deny it - */ - if ((wsi->protocol->callback)(wsi, - LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, - wsi->user_space, - lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) { - lwsl_warn("User code denied connection\n"); - goto bail_nuke_ah; - } - - /* - * Perform the handshake according to the protocol version the - * client announced - */ - - switch (wsi->ietf_spec_revision) { - case 13: - lwsl_parser("lws_parse calling handshake_04\n"); - if (handshake_0405(context, wsi)) { - lwsl_info("hs0405 has failed the connection\n"); - goto bail_nuke_ah; - } - break; - - default: - lwsl_info("Unknown client spec version %d\n", - wsi->ietf_spec_revision); + if (lws_process_ws_upgrade(wsi)) goto bail_nuke_ah; - } - - lws_same_vh_protocol_insert(wsi, n); - - /* we are upgrading to ws, so http/1.1 and keepalive + - * pipelined header considerations about keeping the ah around - * no longer apply. However it's common for the first ws - * protocol data to have been coalesced with the browser - * upgrade request and to already be in the ah rx buffer. - */ - - lwsl_info("%s: %p: inheriting ws ah (rxpos:%d, rxlen:%d)\n", - __func__, wsi, wsi->u.hdr.ah->rxpos, - wsi->u.hdr.ah->rxlen); - lws_pt_lock(pt); - hdr = wsi->u.hdr; - - lws_union_transition(wsi, LWSCM_WS_SERVING); - /* - * first service is WS mode will notice this, use the RX and - * then detach the ah (caution: we are not in u.hdr union - * mode any more then... ah_temp member is at start the same - * though) - * - * Because rxpos/rxlen shows something in the ah, we will get - * service guaranteed next time around the event loop - * - * All union members begin with hdr, so we can use it even - * though we transitioned to ws union mode (the ah detach - * code uses it anyway). - */ - wsi->u.hdr = hdr; - lws_pt_unlock(pt); - - lws_server_init_wsi_for_ws(wsi); - lwsl_parser("accepted v%02d connection\n", - wsi->ietf_spec_revision); - - /* !!! drop ah unreservedly after ESTABLISHED */ - if (!wsi->more_rx_waiting) { - lws_header_table_force_to_detachable_state(wsi); - lws_header_table_detach(wsi, 1); - } return 0; +#endif } /* while all chars are handled */ return 0; bail_nuke_ah: /* drop the header info */ - /* we're closing, losing some rx is OK */ - lws_header_table_force_to_detachable_state(wsi); lws_header_table_detach(wsi, 1); return 1; @@ -1772,10 +1649,13 @@ lws_get_idlest_tsi(struct lws_context *context) } struct lws * -lws_create_new_server_wsi(struct lws_vhost *vhost) +lws_create_new_server_wsi(struct lws_vhost *vhost, int fixed_tsi) { struct lws *new_wsi; - int n = lws_get_idlest_tsi(vhost->context); + int n = fixed_tsi; + + if (n < 0) + n = lws_get_idlest_tsi(vhost->context); if (n < 0) { lwsl_err("no space for new conn\n"); @@ -1799,12 +1679,11 @@ lws_create_new_server_wsi(struct lws_vhost *vhost) /* initialize the instance struct */ - new_wsi->state = LWSS_HTTP; - new_wsi->mode = LWSCM_HTTP_SERVING; + lwsi_set_state(new_wsi, LRS_UNCONNECTED); new_wsi->hdr_parsing_completed = 0; -#ifdef LWS_OPENSSL_SUPPORT - new_wsi->use_ssl = LWS_SSL_ENABLED(vhost); +#ifdef LWS_WITH_TLS + new_wsi->tls.use_ssl = LWS_SSL_ENABLED(vhost); #endif /* @@ -1815,9 +1694,8 @@ lws_create_new_server_wsi(struct lws_vhost *vhost) */ new_wsi->protocol = vhost->protocols; new_wsi->user_space = NULL; - new_wsi->ietf_spec_revision = 0; new_wsi->desc.sockfd = LWS_SOCK_INVALID; - new_wsi->position_in_fds_table = -1; + new_wsi->position_in_fds_table = LWS_NO_FDS_POS; vhost->context->count_wsi_allocated++; @@ -1845,7 +1723,6 @@ lws_http_transaction_completed(struct lws *wsi) return 0; } - lwsl_debug("%s: wsi %p\n", __func__, wsi); /* if we can't go back to accept new headers, drop the connection */ if (wsi->http2_substream) return 0; @@ -1853,22 +1730,28 @@ lws_http_transaction_completed(struct lws *wsi) if (wsi->seen_zero_length_recv) return 1; - if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) { - lwsl_info("%s: %p: close connection\n", __func__, wsi); + if (wsi->http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) { + lwsl_notice("%s: %p: close connection\n", __func__, wsi); return 1; } if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0])) return 1; - /* otherwise set ourselves up ready to go again */ - wsi->state = LWSS_HTTP; - wsi->mode = LWSCM_HTTP_SERVING; - wsi->u.http.tx_content_length = 0; - wsi->u.http.tx_content_remain = 0; + /* + * otherwise set ourselves up ready to go again, but because we have no + * idea about the wsi writability, we make put it in a holding state + * until we can verify POLLOUT. The part of this that confirms POLLOUT + * with no partials is in lws_server_socket_service() below. + */ + lwsl_debug("%s: %p: setting DEF_ACT from 0x%x\n", __func__, + wsi, wsi->wsistate); + lwsi_set_state(wsi, LRS_DEFERRING_ACTION); + wsi->http.tx_content_length = 0; + wsi->http.tx_content_remain = 0; wsi->hdr_parsing_completed = 0; #ifdef LWS_WITH_ACCESS_LOG - wsi->access_log.sent = 0; + wsi->http.access_log.sent = 0; #endif if (wsi->vhost->keepalive_timeout) @@ -1887,21 +1770,20 @@ lws_http_transaction_completed(struct lws *wsi) * that is already at least the start of another header set, simply * reset the existing header table and keep it. */ - if (wsi->u.hdr.ah) { - lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__, - wsi->more_rx_waiting); - - if (!wsi->more_rx_waiting) { - lws_header_table_force_to_detachable_state(wsi); + if (wsi->http.ah) { + // lws_buflist_describe(&wsi->buflist, wsi); + if (!lws_buflist_next_segment_len(&wsi->buflist, NULL)) { + lwsl_info("%s: %p: nothing in buflist so detaching ah\n", + __func__, wsi); lws_header_table_detach(wsi, 1); -#ifdef LWS_OPENSSL_SUPPORT +#ifdef LWS_WITH_TLS /* * additionally... if we are hogging an SSL instance * with no pending pipelined headers (or ah now), and * SSL is scarce, drop this connection without waiting */ - if (wsi->vhost->use_ssl && + if (wsi->vhost->tls.use_ssl && wsi->context->simultaneous_ssl_restriction && wsi->context->simultaneous_ssl == wsi->context->simultaneous_ssl_restriction) { @@ -1911,7 +1793,9 @@ lws_http_transaction_completed(struct lws *wsi) } #endif } else { - lws_header_table_reset(wsi, 1); + lwsl_info("%s: %p: resetting and keeping ah as pipeline\n", + __func__, wsi); + lws_header_table_reset(wsi, 0); /* * If we kept the ah, we should restrict the amount * of time we are willing to keep it. Otherwise it @@ -1921,12 +1805,18 @@ lws_http_transaction_completed(struct lws *wsi) lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH, wsi->vhost->keepalive_timeout); } - } + /* If we're (re)starting on headers, need other implied init */ + if (wsi->http.ah) + wsi->http.ah->ues = URIES_IDLE; - /* If we're (re)starting on headers, need other implied init */ - wsi->u.hdr.ues = URIES_IDLE; + //lwsi_set_state(wsi, LRS_ESTABLISHED); + } else + if (lws_buflist_next_segment_len(&wsi->buflist, NULL)) + if (lws_header_table_attach(wsi, 0)) + lwsl_debug("acquired ah\n"); lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi); + lws_callback_on_writable(wsi); return 0; } @@ -1949,11 +1839,7 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, if (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO)) { peer = lws_get_or_create_peer(vh, fd.sockfd); - if (!peer) { - lwsl_err("OOM creating peer\n"); - return NULL; - } - if (context->ip_limit_wsi && + if (peer && context->ip_limit_wsi && peer->count_wsi >= context->ip_limit_wsi) { lwsl_notice("Peer reached wsi limit %d\n", context->ip_limit_wsi); @@ -1964,7 +1850,10 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, } #endif - new_wsi = lws_create_new_server_wsi(vh); + n = -1; + if (parent) + n = parent->tsi; + new_wsi = lws_create_new_server_wsi(vh, n); if (!new_wsi) { if (type & LWS_ADOPT_SOCKET && !(type & LWS_ADOPT_WS_PARENTIO)) compatible_close(fd.sockfd); @@ -2000,28 +1889,51 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, lwsl_notice("OOM trying to get user_space\n"); goto bail; } +#if defined(LWS_ROLE_WS) if (type & LWS_ADOPT_WS_PARENTIO) { new_wsi->desc.sockfd = LWS_SOCK_INVALID; lwsl_debug("binding to %s\n", new_wsi->protocol->name); lws_bind_protocol(new_wsi, new_wsi->protocol); - lws_union_transition(new_wsi, LWSCM_WS_SERVING); + lws_role_transition(new_wsi, LWSIFR_SERVER, + LRS_ESTABLISHED, &role_ops_ws); + /* allocate the ws struct for the wsi */ + new_wsi->ws = lws_zalloc(sizeof(*new_wsi->ws), "ws struct"); + if (!new_wsi->ws) { + lwsl_notice("OOM\n"); + goto bail; + } lws_server_init_wsi_for_ws(new_wsi); return new_wsi; } +#endif } else - if (type & LWS_ADOPT_HTTP) /* he will transition later */ +#if defined(LWS_ROLE_H1) + if (type & LWS_ADOPT_HTTP) {/* he will transition later */ new_wsi->protocol = &vh->protocols[vh->default_protocol_index]; - else { /* this is the only time he will transition */ + new_wsi->role_ops = &role_ops_h1; + } + else +#endif + { /* this is the only time he will transition */ lws_bind_protocol(new_wsi, &vh->protocols[vh->raw_protocol_index]); - lws_union_transition(new_wsi, LWSCM_RAW); + lws_role_transition(new_wsi, 0, LRS_ESTABLISHED, + &role_ops_raw_skt); } if (type & LWS_ADOPT_SOCKET) { /* socket desc */ lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, (int)(lws_intptr_t)fd.sockfd); +#if !defined(LWS_WITH_ESP32) + if (type & LWS_ADOPT_FLAG_UDP) + /* + * these can be >128 bytes, so just alloc for UDP + */ + new_wsi->udp = lws_malloc(sizeof(*new_wsi->udp), + "udp struct"); +#endif if (type & LWS_ADOPT_HTTP) /* the transport is accepted... @@ -2030,11 +1942,6 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, context->timeout_secs); -#if LWS_POSIX == 0 -#if defined(LWS_WITH_ESP8266) - esp8266_tcp_stream_accept(accept_fd, new_wsi); -#endif -#endif } else /* file desc */ lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi, (int)(lws_intptr_t)fd.filefd); @@ -2058,29 +1965,43 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, /* non-SSL */ if (!(type & LWS_ADOPT_HTTP)) { if (!(type & LWS_ADOPT_SOCKET)) - new_wsi->mode = LWSCM_RAW_FILEDESC; + lws_role_transition(new_wsi, 0, LRS_ESTABLISHED, + &role_ops_raw_file); else - new_wsi->mode = LWSCM_RAW; + lws_role_transition(new_wsi, 0, LRS_ESTABLISHED, + &role_ops_raw_skt); } +#if defined(LWS_ROLE_H1) + else + lws_role_transition(new_wsi, LWSIFR_SERVER, + LRS_HEADERS, &role_ops_h1); +#endif } else { /* SSL */ if (!(type & LWS_ADOPT_HTTP)) - new_wsi->mode = LWSCM_SSL_INIT_RAW; + lws_role_transition(new_wsi, 0, LRS_SSL_INIT, + &role_ops_raw_skt); +#if defined(LWS_ROLE_H1) else - new_wsi->mode = LWSCM_SSL_INIT; - + lws_role_transition(new_wsi, LWSIFR_SERVER, + LRS_SSL_INIT, &role_ops_h1); +#endif ssl = 1; } - lws_libev_accept(new_wsi, new_wsi->desc); - lws_libuv_accept(new_wsi, new_wsi->desc); - lws_libevent_accept(new_wsi, new_wsi->desc); + lwsl_debug("new wsi wsistate 0x%x\n", new_wsi->wsistate); + + if (context->event_loop_ops->accept) + context->event_loop_ops->accept(new_wsi); if (!ssl) { - if (insert_wsi_socket_into_fds(context, new_wsi)) { + lws_pt_lock(pt, __func__); + if (__insert_wsi_socket_into_fds(context, new_wsi)) { + lws_pt_unlock(pt); lwsl_err("%s: fail inserting socket\n", __func__); goto fail; } + lws_pt_unlock(pt); } else if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) { lwsl_info("%s: fail ssl negotiation\n", __func__); @@ -2102,11 +2023,13 @@ lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type, lwsl_info("%s: waiting for ah\n", __func__); } + lws_cancel_service_pt(new_wsi); + return new_wsi; fail: if (type & LWS_ADOPT_SOCKET) - lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS); + lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS, "adopt skt fail"); return NULL; @@ -2143,8 +2066,8 @@ static struct lws* adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len) { struct lws_context_per_thread *pt; - struct allocated_headers *ah; struct lws_pollfd *pfd; + int n; if (!wsi) return NULL; @@ -2152,10 +2075,16 @@ adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len) if (!readbuf || len == 0) return wsi; - if (len > sizeof(ah->rx)) { - lwsl_err("%s: rx in too big\n", __func__); + if (wsi->position_in_fds_table == LWS_NO_FDS_POS) + return wsi; + + pt = &wsi->context->pt[(int)wsi->tsi]; + + n = lws_buflist_append_segment(&wsi->buflist, (const uint8_t *)readbuf, len); + if (n < 0) goto bail; - } + if (n) + lws_dll_lws_add_front(&wsi->dll_buflist, &pt->dll_head_buflist); /* * we can't process the initial read data until we can attach an ah. @@ -2167,14 +2096,9 @@ adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len) * readbuf data to wsi or ah yet, and we will do it next if we get * the ah. */ - if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) { - ah = wsi->u.hdr.ah; - memcpy(ah->rx, readbuf, len); - ah->rxpos = 0; - ah->rxlen = (int16_t)len; + if (wsi->http.ah || !lws_header_table_attach(wsi, 0)) { lwsl_notice("%s: calling service on readbuf ah\n", __func__); - pt = &wsi->context->pt[(int)wsi->tsi]; /* unlike a normal connect, we have the headers already * (or the first part of them anyway). @@ -2191,25 +2115,11 @@ adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len) return wsi; } lwsl_err("%s: deferring handling ah\n", __func__); - /* - * hum if no ah came, we are on the wait list and must defer - * dealing with this until the ah arrives. - * - * later successful lws_header_table_attach() will apply the - * below to the rx buffer (via lws_header_table_reset()). - */ - wsi->u.hdr.preamble_rx = lws_malloc(len, "preamble_rx"); - if (!wsi->u.hdr.preamble_rx) { - lwsl_err("OOM\n"); - goto bail; - } - memcpy(wsi->u.hdr.preamble_rx, readbuf, len); - wsi->u.hdr.preamble_rx_len = len; return wsi; bail: - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "adopt skt readbuf fail"); return NULL; } @@ -2232,397 +2142,6 @@ lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, } LWS_VISIBLE int -lws_server_socket_service(struct lws_context *context, struct lws *wsi, - struct lws_pollfd *pollfd) -{ - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - lws_sockfd_type accept_fd = LWS_SOCK_INVALID; - struct allocated_headers *ah; - lws_sock_file_fd_type fd; - int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL; -#if LWS_POSIX - struct sockaddr_storage cli_addr; - socklen_t clilen; -#endif - int n, len; - - switch (wsi->mode) { - - case LWSCM_HTTP_SERVING: - case LWSCM_HTTP_SERVING_ACCEPTED: - case LWSCM_HTTP2_SERVING: - case LWSCM_RAW: - - /* handle http headers coming in */ - - /* pending truncated sends have uber priority */ - - if (wsi->trunc_len) { - if (!(pollfd->revents & LWS_POLLOUT)) - break; - - if (lws_issue_raw(wsi, wsi->trunc_alloc + - wsi->trunc_offset, - wsi->trunc_len) < 0) - goto fail; - /* - * we can't afford to allow input processing to send - * something new, so spin around he event loop until - * he doesn't have any partials - */ - break; - } - - /* any incoming data ready? */ - - if (!(pollfd->revents & pollfd->events & LWS_POLLIN)) - goto try_pollout; - - /* - * If we previously just did POLLIN when IN and OUT were - * signalled (because POLLIN processing may have used up - * the POLLOUT), don't let that happen twice in a row... - * next time we see the situation favour POLLOUT - */ -#if !defined(LWS_WITH_ESP8266) - if (wsi->favoured_pollin && - (pollfd->revents & pollfd->events & LWS_POLLOUT)) { - lwsl_notice("favouring pollout\n"); - wsi->favoured_pollin = 0; - goto try_pollout; - } -#endif - - /* these states imply we MUST have an ah attached */ - - if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP || - wsi->state == LWSS_HTTP_ISSUING_FILE || - wsi->state == LWSS_HTTP_HEADERS)) { - if (!wsi->u.hdr.ah) { - /* no autoservice beacuse we will do it next */ - if (lws_header_table_attach(wsi, 0)) { - lwsl_info("wsi %p: ah get fail\n", wsi); - goto try_pollout; - } - } - ah = wsi->u.hdr.ah; - - /* if nothing in ah rx buffer, get some fresh rx */ - if (ah->rxpos == ah->rxlen) { - ah->rxlen = lws_ssl_capable_read(wsi, ah->rx, - sizeof(ah->rx)); - ah->rxpos = 0; - switch (ah->rxlen) { - case 0: - lwsl_info("%s: read 0 len a\n", __func__); - wsi->seen_zero_length_recv = 1; - lws_change_pollfd(wsi, LWS_POLLIN, 0); - goto try_pollout; - /* fallthru */ - case LWS_SSL_CAPABLE_ERROR: - goto fail; - case LWS_SSL_CAPABLE_MORE_SERVICE: - ah->rxlen = ah->rxpos = 0; - goto try_pollout; - } - - /* - * make sure ah does not get detached if we - * have live data in the rx - */ - if (ah->rxlen) - wsi->more_rx_waiting = 1; - } - - if (!(ah->rxpos != ah->rxlen && ah->rxlen)) { - lwsl_err("%s: assert: rxpos %d, rxlen %d\n", - __func__, ah->rxpos, ah->rxlen); - - assert(0); - } - - /* just ignore incoming if waiting for close */ - if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE && - wsi->state != LWSS_HTTP_ISSUING_FILE) { - /* - * otherwise give it to whoever wants it - * according to the connection state - */ - - n = lws_read(wsi, ah->rx + ah->rxpos, - ah->rxlen - ah->rxpos); - if (n < 0) /* we closed wsi */ - return 1; - - if (!wsi->u.hdr.ah) - break; - if ( wsi->u.hdr.ah->rxlen) - wsi->u.hdr.ah->rxpos += n; - - lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", - __func__, wsi, wsi->u.hdr.ah->rxpos, - wsi->u.hdr.ah->rxlen); - - if (lws_header_table_is_in_detachable_state(wsi) && - (wsi->mode != LWSCM_HTTP_SERVING && - wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED && - wsi->mode != LWSCM_HTTP2_SERVING)) - lws_header_table_detach(wsi, 1); - - break; - } - - goto try_pollout; - } - - len = lws_ssl_capable_read(wsi, pt->serv_buf, - context->pt_serv_buf_size); - lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len); - switch (len) { - case 0: - lwsl_info("%s: read 0 len b\n", __func__); - - /* fallthru */ - case LWS_SSL_CAPABLE_ERROR: - goto fail; - case LWS_SSL_CAPABLE_MORE_SERVICE: - goto try_pollout; - } - - if (len < 0) /* coverity */ - goto fail; - - if (wsi->mode == LWSCM_RAW) { - n = user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_RAW_RX, - wsi->user_space, pt->serv_buf, len); - if (n < 0) { - lwsl_info("LWS_CALLBACK_RAW_RX_fail\n"); - goto fail; - } - goto try_pollout; - } - - /* just ignore incoming if waiting for close */ - if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE && - wsi->state != LWSS_HTTP_ISSUING_FILE) { - /* - * this may want to send - * (via HTTP callback for example) - */ - n = lws_read(wsi, pt->serv_buf, len); - if (n < 0) /* we closed wsi */ - return 1; - /* - * he may have used up the - * writability above, if we will defer POLLOUT - * processing in favour of POLLIN, note it - */ - if (pollfd->revents & LWS_POLLOUT) - wsi->favoured_pollin = 1; - break; - } - /* - * he may have used up the - * writability above, if we will defer POLLOUT - * processing in favour of POLLIN, note it - */ - if (pollfd->revents & LWS_POLLOUT) - wsi->favoured_pollin = 1; - -try_pollout: - - /* this handles POLLOUT for http serving fragments */ - - if (!(pollfd->revents & LWS_POLLOUT)) - break; - - /* one shot */ - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_notice("%s a\n", __func__); - goto fail; - } - - if (wsi->mode == LWSCM_RAW) { - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_WRITEABLE_CB, 1); -#if defined(LWS_WITH_STATS) - if (wsi->active_writable_req_us) { - uint64_t ul = time_in_microseconds() - - wsi->active_writable_req_us; - - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_MS_WRITABLE_DELAY, ul); - lws_stats_atomic_max(wsi->context, pt, - LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); - wsi->active_writable_req_us = 0; - } -#endif - n = user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_RAW_WRITEABLE, - wsi->user_space, NULL, 0); - if (n < 0) { - lwsl_info("writeable_fail\n"); - goto fail; - } - break; - } - - if (!wsi->hdr_parsing_completed) - break; - - if (wsi->state != LWSS_HTTP_ISSUING_FILE) { - - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_WRITEABLE_CB, 1); -#if defined(LWS_WITH_STATS) - if (wsi->active_writable_req_us) { - uint64_t ul = time_in_microseconds() - - wsi->active_writable_req_us; - - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_MS_WRITABLE_DELAY, ul); - lws_stats_atomic_max(wsi->context, pt, - LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); - wsi->active_writable_req_us = 0; - } -#endif - - n = user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_HTTP_WRITEABLE, - wsi->user_space, NULL, 0); - if (n < 0) { - lwsl_info("writeable_fail\n"); - goto fail; - } - break; - } - - /* >0 == completion, <0 == error - * - * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when - * it's done. That's the case even if we just completed the - * send, so wait for that. - */ - n = lws_serve_http_file_fragment(wsi); - if (n < 0) - goto fail; - - break; - - case LWSCM_SERVER_LISTENER: - -#if LWS_POSIX - /* pollin means a client has connected to us then */ - - do { - if (!(pollfd->revents & LWS_POLLIN) || - !(pollfd->events & LWS_POLLIN)) - break; - -#ifdef LWS_OPENSSL_SUPPORT - /* - * can we really accept it, with regards to SSL limit? - * another vhost may also have had POLLIN on his listener this - * round and used it up already - */ - - if (wsi->vhost->use_ssl && - context->simultaneous_ssl_restriction && - context->simultaneous_ssl == - context->simultaneous_ssl_restriction) - /* no... ignore it, he won't come again until we are - * below the simultaneous_ssl_restriction limit and - * POLLIN is enabled on him again - */ - break; -#endif - /* listen socket got an unencrypted connection... */ - - clilen = sizeof(cli_addr); - lws_latency_pre(context, wsi); - - /* - * We cannot identify the peer who is in the listen - * socket connect queue before we accept it; even if - * we could, not accepting it due to PEER_LIMITS would - * block the connect queue for other legit peers. - */ - accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr, - &clilen); - lws_latency(context, wsi, "listener accept", accept_fd, - accept_fd >= 0); - if (accept_fd < 0) { - if (LWS_ERRNO == LWS_EAGAIN || - LWS_ERRNO == LWS_EWOULDBLOCK) { - break; - } - lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO)); - break; - } - - lws_plat_set_socket_options(wsi->vhost, accept_fd); - -#if defined(LWS_WITH_IPV6) - lwsl_debug("accepted new conn port %u on fd=%d\n", - ((cli_addr.ss_family == AF_INET6) ? - ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) : - ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)), - accept_fd); -#else - lwsl_debug("accepted new conn port %u on fd=%d\n", - ntohs(((struct sockaddr_in *) &cli_addr)->sin_port), - accept_fd); -#endif - -#else - /* not very beautiful... */ - accept_fd = (lws_sockfd_type)pollfd; -#endif - /* - * look at who we connected to and give user code a chance - * to reject based on client IP. There's no protocol selected - * yet so we issue this to protocols[0] - */ - if ((wsi->vhost->protocols[0].callback)(wsi, - LWS_CALLBACK_FILTER_NETWORK_CONNECTION, - NULL, (void *)(lws_intptr_t)accept_fd, 0)) { - lwsl_debug("Callback denied network connection\n"); - compatible_close(accept_fd); - break; - } - - if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW)) - opts |= LWS_ADOPT_HTTP; - else - opts = LWS_ADOPT_SOCKET; - - fd.sockfd = accept_fd; - if (!lws_adopt_descriptor_vhost(wsi->vhost, opts, fd, - NULL, NULL)) - /* already closed cleanly as necessary */ - return 1; - -#if LWS_POSIX - } while (pt->fds_count < context->fd_limit_per_thread - 1 && - lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0); -#endif - return 0; - - default: - break; - } - - if (!lws_server_socket_service_ssl(wsi, accept_fd)) - return 0; - -fail: - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - - return 1; -} - -LWS_VISIBLE int lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, const char *other_headers, int other_headers_len) { @@ -2630,13 +2149,13 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; #if defined(LWS_WITH_RANGES) - struct lws_range_parsing *rp = &wsi->u.http.range; + struct lws_range_parsing *rp = &wsi->http.range; #endif char cache_control[50], *cc = "no-store"; unsigned char *response = pt->serv_buf + LWS_PRE; unsigned char *p = response; unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE; - lws_filepos_t computed_total_content_length; + lws_filepos_t total_content_length; int ret = 0, cclen = 8, n = HTTP_STATUS_OK; lws_fop_flags_t fflags = LWS_O_RDONLY; #if defined(LWS_WITH_RANGES) @@ -2645,29 +2164,34 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, const struct lws_plat_file_ops *fops; const char *vpath; + if (wsi->handling_404) + n = HTTP_STATUS_NOT_FOUND; + /* * We either call the platform fops .open with first arg platform fops, * or we call fops_zip .open with first arg platform fops, and fops_zip * open will decide whether to switch to fops_zip or stay with fops_def. * - * If wsi->u.http.fop_fd is already set, the caller already opened it + * If wsi->http.fop_fd is already set, the caller already opened it */ - if (!wsi->u.http.fop_fd) { + if (!wsi->http.fop_fd) { fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath); fflags |= lws_vfs_prepare_flags(wsi); - wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops, + wsi->http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops, file, vpath, &fflags); - if (!wsi->u.http.fop_fd) { - lwsl_err("Unable to open '%s'\n", file); - - return -1; + if (!wsi->http.fop_fd) { + lwsl_info("%s: Unable to open: '%s': errno %d\n", + __func__, file, errno); + if (lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL)) + return -1; + return !wsi->http2_substream; } } - wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd); - computed_total_content_length = wsi->u.http.filelen; + wsi->http.filelen = lws_vfs_get_length(wsi->http.fop_fd); + total_content_length = wsi->http.filelen; #if defined(LWS_WITH_RANGES) - ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen); + ranges = lws_ranges_init(wsi, rp, wsi->http.filelen); lwsl_debug("Range count %d\n", ranges); /* @@ -2684,7 +2208,7 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, if (lws_http_transaction_completed(wsi)) return -1; /* <0 means just hang up */ - lws_vfs_file_close(&wsi->u.http.fop_fd); + lws_vfs_file_close(&wsi->http.fop_fd); return 0; /* == 0 means we dealt with the transaction complete */ } @@ -2695,7 +2219,7 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, if (lws_add_http_header_status(wsi, n, &p, end)) return -1; - if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | + if ((wsi->http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) == (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) { if (lws_add_http_header_by_token(wsi, @@ -2710,20 +2234,24 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, ranges < 2 && #endif content_type && content_type[0]) - if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, + if (lws_add_http_header_by_token(wsi, + WSI_TOKEN_HTTP_CONTENT_TYPE, (unsigned char *)content_type, - strlen(content_type), &p, end)) + (int)strlen(content_type), + &p, end)) return -1; #if defined(LWS_WITH_RANGES) if (ranges >= 2) { /* multipart byteranges */ - strncpy(wsi->u.http.multipart_content_type, content_type, - sizeof(wsi->u.http.multipart_content_type) - 1); - wsi->u.http.multipart_content_type[ - sizeof(wsi->u.http.multipart_content_type) - 1] = '\0'; - if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE, - (unsigned char *)"multipart/byteranges; boundary=_lws", - 20, &p, end)) + lws_strncpy(wsi->http.multipart_content_type, content_type, + sizeof(wsi->http.multipart_content_type)); + + if (lws_add_http_header_by_token(wsi, + WSI_TOKEN_HTTP_CONTENT_TYPE, + (unsigned char *) + "multipart/byteranges; " + "boundary=_lws", + 20, &p, end)) return -1; /* @@ -2738,8 +2266,8 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, * Precompute it for the main response header */ - computed_total_content_length = (lws_filepos_t)rp->agg + - 6 /* final _lws\r\n */; + total_content_length = (lws_filepos_t)rp->agg + + 6 /* final _lws\r\n */; lws_ranges_reset(rp); while (lws_ranges_next(rp)) { @@ -2747,7 +2275,7 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, "bytes %llu-%llu/%llu", rp->start, rp->end, rp->extent); - computed_total_content_length += + total_content_length += 6 /* header _lws\r\n */ + /* Content-Type: xxx/xxx\r\n */ 14 + strlen(content_type) + 2 + @@ -2761,35 +2289,38 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, } if (ranges == 1) { - computed_total_content_length = (lws_filepos_t)rp->agg; + total_content_length = (lws_filepos_t)rp->agg; n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu", rp->start, rp->end, rp->extent); - if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE, + if (lws_add_http_header_by_token(wsi, + WSI_TOKEN_HTTP_CONTENT_RANGE, (unsigned char *)cache_control, n, &p, end)) return -1; } - wsi->u.http.range.inside = 0; + wsi->http.range.inside = 0; if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES, (unsigned char *)"bytes", 5, &p, end)) return -1; #endif - if (!wsi->sending_chunked) { - if (lws_add_http_header_content_length(wsi, - computed_total_content_length, - &p, end)) - return -1; - } else { - if (lws_add_http_header_by_token(wsi, + if (!wsi->http2_substream) { + if (!wsi->sending_chunked) { + if (lws_add_http_header_content_length(wsi, + total_content_length, + &p, end)) + return -1; + } else { + if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING, (unsigned char *)"chunked", 7, &p, end)) - return -1; + return -1; + } } if (wsi->cache_secs && wsi->cache_reuse) { @@ -2808,7 +2339,7 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, (unsigned char *)cc, cclen, &p, end)) return -1; - if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE) + if (wsi->http.connection_type == HTTP_CONNECTION_KEEP_ALIVE) if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION, (unsigned char *)"keep-alive", 10, &p, end)) return -1; @@ -2830,91 +2361,268 @@ lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type, return -1; } - wsi->u.http.filepos = 0; - wsi->state = LWSS_HTTP_ISSUING_FILE; + wsi->http.filepos = 0; + lwsi_set_state(wsi, LRS_ISSUING_FILE); lws_callback_on_writable(wsi); return 0; } -int -lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len) +LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi) { - int m; + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + struct lws_process_html_args args; + lws_filepos_t amount, poss; + unsigned char *p, *pstart; +#if defined(LWS_WITH_RANGES) + unsigned char finished = 0; +#endif + int n, m; + + lwsl_debug("wsi->http2_substream %d\n", wsi->http2_substream); + + do { + + if (wsi->trunc_len) { + if (lws_issue_raw(wsi, wsi->trunc_alloc + + wsi->trunc_offset, + wsi->trunc_len) < 0) { + lwsl_info("%s: closing\n", __func__); + goto file_had_it; + } + break; + } + + if (wsi->http.filepos == wsi->http.filelen) + goto all_sent; + + n = 0; + + pstart = pt->serv_buf + LWS_H2_FRAME_HEADER_LENGTH; + + p = pstart; + +#if defined(LWS_WITH_RANGES) + if (wsi->http.range.count_ranges && !wsi->http.range.inside) { + + lwsl_notice("%s: doing range start %llu\n", __func__, + wsi->http.range.start); + + if ((long long)lws_vfs_file_seek_cur(wsi->http.fop_fd, + wsi->http.range.start - + wsi->http.filepos) < 0) + goto file_had_it; + + wsi->http.filepos = wsi->http.range.start; + + if (wsi->http.range.count_ranges > 1) { + n = lws_snprintf((char *)p, + context->pt_serv_buf_size - + LWS_H2_FRAME_HEADER_LENGTH, + "_lws\x0d\x0a" + "Content-Type: %s\x0d\x0a" + "Content-Range: bytes %llu-%llu/%llu\x0d\x0a" + "\x0d\x0a", + wsi->http.multipart_content_type, + wsi->http.range.start, + wsi->http.range.end, + wsi->http.range.extent); + p += n; + } - lwsl_parser("%s: received %d byte packet\n", __func__, (int)len); -#if 0 - lwsl_hexdump(*buf, len); + wsi->http.range.budget = wsi->http.range.end - + wsi->http.range.start + 1; + wsi->http.range.inside = 1; + } #endif - /* let the rx protocol state machine have as much as it needs */ + poss = context->pt_serv_buf_size - n - LWS_H2_FRAME_HEADER_LENGTH; + + if (wsi->http.tx_content_length) + if (poss > wsi->http.tx_content_remain) + poss = wsi->http.tx_content_remain; - while (len) { /* - * we were accepting input but now we stopped doing so + * if there is a hint about how much we will do well to send at + * one time, restrict ourselves to only trying to send that. */ - if (wsi->rxflow_bitmap) { - lws_rxflow_cache(wsi, *buf, 0, len); - lwsl_parser("%s: cached %ld\n", __func__, (long)len); - return 1; - } + if (wsi->protocol->tx_packet_size && + poss > wsi->protocol->tx_packet_size) + poss = wsi->protocol->tx_packet_size; - if (wsi->u.ws.rx_draining_ext) { - m = lws_rx_sm(wsi, 0); - if (m < 0) - return -1; - continue; - } + if (wsi->role_ops->tx_credit) { + lws_filepos_t txc = wsi->role_ops->tx_credit(wsi); - /* account for what we're using in rxflow buffer */ - if (wsi->rxflow_buffer) { - wsi->rxflow_pos++; - if (wsi->rxflow_pos > wsi->rxflow_len) { - lwsl_err("bumped rxflow buffer too far (%d / %d)", wsi->rxflow_pos, wsi->rxflow_len); - assert(0); + if (!txc) { + lwsl_info("%s: came here with no tx credit\n", + __func__); + return 0; } + if (txc < poss) + poss = txc; + + /* + * consumption of the actual payload amount sent will be + * handled when the role data frame is sent + */ } - /* consume payload bytes efficiently */ - if (wsi->lws_rx_parse_state == - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) { - m = lws_payload_until_length_exhausted(wsi, buf, &len); - if (wsi->rxflow_buffer) - wsi->rxflow_pos += m; +#if defined(LWS_WITH_RANGES) + if (wsi->http.range.count_ranges) { + if (wsi->http.range.count_ranges > 1) + poss -= 7; /* allow for final boundary */ + if (poss > wsi->http.range.budget) + poss = wsi->http.range.budget; + } +#endif + if (wsi->sending_chunked) { + /* we need to drop the chunk size in here */ + p += 10; + /* allow for the chunk to grow by 128 in translation */ + poss -= 10 + 128; } - if (wsi->rxflow_buffer && wsi->rxflow_pos == wsi->rxflow_len) { - lwsl_debug("%s: %p flow buf: drained\n", __func__, wsi); - lws_free_set_NULL(wsi->rxflow_buffer); - /* having drained the rxflow buffer, can rearm POLLIN */ -#ifdef LWS_NO_SERVER - m = + if (lws_vfs_file_read(wsi->http.fop_fd, &amount, p, poss) < 0) + goto file_had_it; /* caller will close */ + + if (wsi->sending_chunked) + n = (int)amount; + else + n = lws_ptr_diff(p, pstart) + (int)amount; + + lwsl_debug("%s: sending %d\n", __func__, n); + + if (n) { + lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, + context->timeout_secs); + + if (wsi->interpreting) { + args.p = (char *)p; + args.len = n; + args.max_len = (unsigned int)poss + 128; + args.final = wsi->http.filepos + n == + wsi->http.filelen; + args.chunked = wsi->sending_chunked; + if (user_callback_handle_rxflow( + wsi->vhost->protocols[ + (int)wsi->protocol_interpret_idx].callback, + wsi, LWS_CALLBACK_PROCESS_HTML, + wsi->user_space, &args, 0) < 0) + goto file_had_it; + n = args.len; + p = (unsigned char *)args.p; + } else + p = pstart; + +#if defined(LWS_WITH_RANGES) + if (wsi->http.range.send_ctr + 1 == + wsi->http.range.count_ranges && // last range + wsi->http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart) + wsi->http.range.budget - amount == 0) {// final part + n += lws_snprintf((char *)pstart + n, 6, + "_lws\x0d\x0a"); // append trailing boundary + lwsl_debug("added trailing boundary\n"); + } +#endif + m = lws_write(wsi, p, n, + wsi->http.filepos + amount == wsi->http.filelen ? + LWS_WRITE_HTTP_FINAL : + LWS_WRITE_HTTP + ); + if (m < 0) + goto file_had_it; + + wsi->http.filepos += amount; + +#if defined(LWS_WITH_RANGES) + if (wsi->http.range.count_ranges >= 1) { + wsi->http.range.budget -= amount; + if (wsi->http.range.budget == 0) { + lwsl_notice("range budget exhausted\n"); + wsi->http.range.inside = 0; + wsi->http.range.send_ctr++; + + if (lws_ranges_next(&wsi->http.range) < 1) { + finished = 1; + goto all_sent; + } + } + } #endif - _lws_rx_flow_control(wsi); - /* m ignored, needed for NO_SERVER case */ + + if (m != n) { + /* adjust for what was not sent */ + if (lws_vfs_file_seek_cur(wsi->http.fop_fd, + m - n) == + (lws_fileofs_t)-1) + goto file_had_it; + } } - /* process the byte */ - m = lws_rx_sm(wsi, *(*buf)++); - if (m < 0) - return -1; - len--; - } +all_sent: + if ((!wsi->trunc_len && wsi->http.filepos >= wsi->http.filelen) +#if defined(LWS_WITH_RANGES) + || finished) +#else + ) +#endif + { + lwsi_set_state(wsi, LRS_ESTABLISHED); + /* we might be in keepalive, so close it off here */ + lws_vfs_file_close(&wsi->http.fop_fd); + + lwsl_debug("file completed\n"); + + if (wsi->protocol->callback && + user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION, + wsi->user_space, NULL, + 0) < 0) { + /* + * For http/1.x, the choices from + * transaction_completed are either + * 0 to use the connection for pipelined + * or nonzero to hang it up. + * + * However for http/2. while we are + * still interested in hanging up the + * nwsi if there was a network-level + * fatal error, simply completing the + * transaction is a matter of the stream + * state, not the root connection at the + * network level + */ + if (wsi->http2_substream) + return 1; + else + return -1; + } + + return 1; /* >0 indicates completed */ + } + } while (0); // while (!lws_send_pipe_choked(wsi)) + + lws_callback_on_writable(wsi); - lwsl_parser("%s: exit with %d unused\n", __func__, (int)len); + return 0; /* indicates further processing must be done */ - return 0; +file_had_it: + lws_vfs_file_close(&wsi->http.fop_fd); + + return -1; } + LWS_VISIBLE void lws_server_get_canonical_hostname(struct lws_context *context, - struct lws_context_creation_info *info) + const struct lws_context_creation_info *info) { if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME)) return; -#if LWS_POSIX && !defined(LWS_WITH_ESP32) +#if !defined(LWS_WITH_ESP32) /* find canonical hostname */ gethostname((char *)context->canonical_hostname, sizeof(context->canonical_hostname) - 1); @@ -2968,11 +2676,11 @@ skip: sp = s->start + 1; continue; } - if (hits == 1 && s->pos == strlen(s->vars[hit])) { + if (hits == 1 && s->pos == (int)strlen(s->vars[hit])) { pc = s->replace(s->data, hit); if (!pc) pc = "NULL"; - n = strlen(pc); + n = (int)strlen(pc); s->swallow[s->pos] = '\0'; if (n != s->pos) { memmove(s->start + n, @@ -2994,31 +2702,33 @@ skip: sp++; } - /* no space left for final chunk trailer */ - if (args->final && args->len + 7 >= args->max_len) - return -1; + if (args->chunked) { + /* no space left for final chunk trailer */ + if (args->final && args->len + 7 >= args->max_len) + return -1; - n = sprintf(buffer, "%X\x0d\x0a", args->len); - - args->p -= n; - memcpy(args->p, buffer, n); - args->len += n; - - if (args->final) { - sp = args->p + args->len; - *sp++ = '\x0d'; - *sp++ = '\x0a'; - *sp++ = '0'; - *sp++ = '\x0d'; - *sp++ = '\x0a'; - *sp++ = '\x0d'; - *sp++ = '\x0a'; - args->len += 7; - } else { - sp = args->p + args->len; - *sp++ = '\x0d'; - *sp++ = '\x0a'; - args->len += 2; + n = sprintf(buffer, "%X\x0d\x0a", args->len); + + args->p -= n; + memcpy(args->p, buffer, n); + args->len += n; + + if (args->final) { + sp = args->p + args->len; + *sp++ = '\x0d'; + *sp++ = '\x0a'; + *sp++ = '0'; + *sp++ = '\x0d'; + *sp++ = '\x0a'; + *sp++ = '\x0d'; + *sp++ = '\x0a'; + args->len += 7; + } else { + sp = args->p + args->len; + *sp++ = '\x0d'; + *sp++ = '\x0a'; + args->len += 2; + } } return 0; diff --git a/thirdparty/libwebsockets/roles/listen/ops-listen.c b/thirdparty/libwebsockets/roles/listen/ops-listen.c new file mode 100644 index 0000000000..dbeb9753a2 --- /dev/null +++ b/thirdparty/libwebsockets/roles/listen/ops-listen.c @@ -0,0 +1,177 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +static int +rops_handle_POLLIN_listen(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ + struct lws_context *context = wsi->context; + lws_sockfd_type accept_fd = LWS_SOCK_INVALID; + lws_sock_file_fd_type fd; + int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL; + struct sockaddr_storage cli_addr; + socklen_t clilen; + + /* pollin means a client has connected to us then + * + * pollout is a hack on esp32 for background accepts signalling + * they completed + */ + + do { + struct lws *cwsi; + + if (!(pollfd->revents & (LWS_POLLIN | LWS_POLLOUT)) || + !(pollfd->events & LWS_POLLIN)) + break; + +#if defined(LWS_WITH_TLS) + /* + * can we really accept it, with regards to SSL limit? + * another vhost may also have had POLLIN on his + * listener this round and used it up already + */ + if (wsi->vhost->tls.use_ssl && + context->simultaneous_ssl_restriction && + context->simultaneous_ssl == + context->simultaneous_ssl_restriction) + /* + * no... ignore it, he won't come again until + * we are below the simultaneous_ssl_restriction + * limit and POLLIN is enabled on him again + */ + break; +#endif + /* listen socket got an unencrypted connection... */ + + clilen = sizeof(cli_addr); + lws_latency_pre(context, wsi); + + /* + * We cannot identify the peer who is in the listen + * socket connect queue before we accept it; even if + * we could, not accepting it due to PEER_LIMITS would + * block the connect queue for other legit peers. + */ + + accept_fd = accept((int)pollfd->fd, + (struct sockaddr *)&cli_addr, &clilen); + lws_latency(context, wsi, "listener accept", + (int)accept_fd, accept_fd != LWS_SOCK_INVALID); + if (accept_fd == LWS_SOCK_INVALID) { + if (LWS_ERRNO == LWS_EAGAIN || + LWS_ERRNO == LWS_EWOULDBLOCK) { + break; + } + lwsl_err("ERROR on accept: %s\n", + strerror(LWS_ERRNO)); + break; + } + + lws_plat_set_socket_options(wsi->vhost, accept_fd); + +#if defined(LWS_WITH_IPV6) + lwsl_debug("accepted new conn port %u on fd=%d\n", + ((cli_addr.ss_family == AF_INET6) ? + ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) : + ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)), + accept_fd); +#else + lwsl_debug("accepted new conn port %u on fd=%d\n", + ntohs(((struct sockaddr_in *) &cli_addr)->sin_port), + accept_fd); +#endif + + /* + * look at who we connected to and give user code a + * chance to reject based on client IP. There's no + * protocol selected yet so we issue this to + * protocols[0] + */ + if ((wsi->vhost->protocols[0].callback)(wsi, + LWS_CALLBACK_FILTER_NETWORK_CONNECTION, + NULL, + (void *)(lws_intptr_t)accept_fd, 0)) { + lwsl_debug("Callback denied net connection\n"); + compatible_close(accept_fd); + break; + } + + if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW)) + opts |= LWS_ADOPT_HTTP; + else + opts = LWS_ADOPT_SOCKET; + + fd.sockfd = accept_fd; + cwsi = lws_adopt_descriptor_vhost(wsi->vhost, opts, fd, + NULL, NULL); + if (!cwsi) + /* already closed cleanly as necessary */ + return LWS_HPI_RET_WSI_ALREADY_DIED; + + if (lws_server_socket_service_ssl(cwsi, accept_fd)) { + lws_close_free_wsi(cwsi, LWS_CLOSE_STATUS_NOSTATUS, + "listen svc fail"); + return LWS_HPI_RET_WSI_ALREADY_DIED; + } + + lwsl_info("%s: new wsi %p: wsistate 0x%x, role_ops %s\n", + __func__, cwsi, cwsi->wsistate, cwsi->role_ops->name); + + } while (pt->fds_count < context->fd_limit_per_thread - 1 && + wsi->position_in_fds_table != LWS_NO_FDS_POS && + lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0); + + return LWS_HPI_RET_HANDLED; +} + +int rops_handle_POLLOUT_listen(struct lws *wsi) +{ + return LWS_HP_RET_USER_SERVICE; +} + +struct lws_role_ops role_ops_listen = { + /* role name */ "listen", + /* alpn id */ NULL, + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ NULL, + /* destroy_vhost */ NULL, + /* periodic_checks */ NULL, + /* service_flag_pending */ NULL, + /* handle_POLLIN */ rops_handle_POLLIN_listen, + /* handle_POLLOUT */ rops_handle_POLLOUT_listen, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ NULL, + /* tx_credit */ NULL, + /* write_role_protocol */ NULL, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ NULL, + /* close_via_role_protocol */ NULL, + /* close_role */ NULL, + /* close_kill_connection */ NULL, + /* destroy_role */ NULL, + /* writeable cb clnt, srv */ { 0, 0 }, + /* close cb clnt, srv */ { 0, 0 }, + /* file_handle */ 0, +}; diff --git a/thirdparty/libwebsockets/roles/pipe/ops-pipe.c b/thirdparty/libwebsockets/roles/pipe/ops-pipe.c new file mode 100644 index 0000000000..b9348d58d7 --- /dev/null +++ b/thirdparty/libwebsockets/roles/pipe/ops-pipe.c @@ -0,0 +1,81 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +static int +rops_handle_POLLIN_pipe(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ +#if !defined(WIN32) && !defined(_WIN32) + char s[100]; + int n; + + /* + * discard the byte(s) that signaled us + * We really don't care about the number of bytes, but coverity + * thinks we should. + */ + n = read(wsi->desc.sockfd, s, sizeof(s)); + (void)n; + if (n < 0) + return LWS_HPI_RET_PLEASE_CLOSE_ME; +#endif + /* + * the poll() wait, or the event loop for libuv etc is a + * process-wide resource that we interrupted. So let every + * protocol that may be interested in the pipe event know that + * it happened. + */ + if (lws_broadcast(wsi->context, LWS_CALLBACK_EVENT_WAIT_CANCELLED, + NULL, 0)) { + lwsl_info("closed in event cancel\n"); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + return LWS_HPI_RET_HANDLED; +} + +struct lws_role_ops role_ops_pipe = { + /* role name */ "pipe", + /* alpn id */ NULL, + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ NULL, + /* destroy_vhost */ NULL, + /* periodic_checks */ NULL, + /* service_flag_pending */ NULL, + /* handle_POLLIN */ rops_handle_POLLIN_pipe, + /* handle_POLLOUT */ NULL, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ NULL, + /* tx_credit */ NULL, + /* write_role_protocol */ NULL, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ NULL, + /* close_via_role_protocol */ NULL, + /* close_role */ NULL, + /* close_kill_connection */ NULL, + /* destroy_role */ NULL, + /* writeable cb clnt, srv */ { 0, 0 }, + /* close cb clnt, srv */ { 0, 0 }, + /* file_handle */ 1, +}; diff --git a/thirdparty/libwebsockets/roles/private.h b/thirdparty/libwebsockets/roles/private.h new file mode 100644 index 0000000000..ae4278b5d3 --- /dev/null +++ b/thirdparty/libwebsockets/roles/private.h @@ -0,0 +1,282 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h + */ + +typedef uint32_t lws_wsi_state_t; + +/* + * The wsi->role_ops pointer decides almost everything about what role the wsi + * will play, h2, raw, ws, etc. + * + * However there are a few additional flags needed that vary, such as if the + * role is a client or server side, if it has that concept. And the connection + * fulfilling the role, has a separate dynamic state. + * + * 31 16 15 0 + * [ role flags ] [ state ] + * + * The role flags part is generally invariant for the lifetime of the wsi, + * although it can change if the connection role itself does, eg, if the + * connection upgrades from H1 -> WS1 the role flags may be changed at that + * point. + * + * The state part reflects the dynamic connection state, and the states are + * reused between roles. + * + * None of the internal role or state representations are made available outside + * of lws internals. Even for lws internals, if you add stuff here, please keep + * the constants inside this header only by adding necessary helpers here and + * use the helpers in the actual code. This is to ease any future refactors. + * + * Notice LWSIFR_ENCAP means we have a parent wsi that actually carries our + * data as a stream inside a different protocol. + */ + +#define _RS 16 + +#define LWSIFR_CLIENT (0x1000 << _RS) /* client side */ +#define LWSIFR_SERVER (0x2000 << _RS) /* server side */ + +#define LWSIFR_P_ENCAP_H2 (0x0100 << _RS) /* we are encapsulated by h2 */ + +enum lwsi_role { + LWSI_ROLE_MASK = (0xffff << _RS), + LWSI_ROLE_ENCAP_MASK = (0x0f00 << _RS), +}; + +#define lwsi_role(wsi) (wsi->wsistate & LWSI_ROLE_MASK) +#if !defined (_DEBUG) +#define lwsi_set_role(wsi, role) wsi->wsistate = \ + (wsi->wsistate & (~LWSI_ROLE_MASK)) | role +#else +void lwsi_set_role(struct lws *wsi, lws_wsi_state_t role); +#endif + +#define lwsi_role_client(wsi) (!!(wsi->wsistate & LWSIFR_CLIENT)) +#define lwsi_role_server(wsi) (!!(wsi->wsistate & LWSIFR_SERVER)) +#define lwsi_role_h2_ENCAPSULATION(wsi) \ + ((wsi->wsistate & LWSI_ROLE_ENCAP_MASK) == LWSIFR_P_ENCAP_H2) + +/* Pollout wants a callback in this state */ +#define LWSIFS_POCB (0x100) +/* Before any protocol connection was established */ +#define LWSIFS_NOT_EST (0x200) + +enum lwsi_state { + + /* Phase 1: pre-transport */ + + LRS_UNCONNECTED = LWSIFS_NOT_EST | 0, + LRS_WAITING_CONNECT = LWSIFS_NOT_EST | 1, + + /* Phase 2: establishing intermediaries on top of transport */ + + LRS_WAITING_PROXY_REPLY = LWSIFS_NOT_EST | 2, + LRS_WAITING_SSL = LWSIFS_NOT_EST | 3, + LRS_WAITING_SOCKS_GREETING_REPLY = LWSIFS_NOT_EST | 4, + LRS_WAITING_SOCKS_CONNECT_REPLY = LWSIFS_NOT_EST | 5, + LRS_WAITING_SOCKS_AUTH_REPLY = LWSIFS_NOT_EST | 6, + + /* Phase 3: establishing tls tunnel */ + + LRS_SSL_INIT = LWSIFS_NOT_EST | 7, + LRS_SSL_ACK_PENDING = LWSIFS_NOT_EST | 8, + LRS_PRE_WS_SERVING_ACCEPT = LWSIFS_NOT_EST | 9, + + /* Phase 4: connected */ + + LRS_WAITING_SERVER_REPLY = LWSIFS_NOT_EST | 10, + LRS_H2_AWAIT_PREFACE = LWSIFS_NOT_EST | 11, + LRS_H2_AWAIT_SETTINGS = LWSIFS_NOT_EST | + LWSIFS_POCB | 12, + + /* Phase 5: protocol logically established */ + + LRS_H2_CLIENT_SEND_SETTINGS = LWSIFS_POCB | 13, + LRS_H2_WAITING_TO_SEND_HEADERS = LWSIFS_POCB | 14, + LRS_DEFERRING_ACTION = LWSIFS_POCB | 15, + LRS_IDLING = 16, + LRS_H1C_ISSUE_HANDSHAKE = 17, + LRS_H1C_ISSUE_HANDSHAKE2 = 18, + LRS_ISSUE_HTTP_BODY = 19, + LRS_ISSUING_FILE = 20, + LRS_HEADERS = 21, + LRS_BODY = 22, + LRS_ESTABLISHED = LWSIFS_POCB | 23, + /* we are established, but we have embarked on serving a single + * transaction. Other transaction input may be pending, but we will + * not service it while we are busy dealing with the current + * transaction. + * + * When we complete the current transaction, we would reset our state + * back to ESTABLISHED and start to process the next transaction. + */ + LRS_DOING_TRANSACTION = LWSIFS_POCB | 24, + + /* Phase 6: finishing */ + + LRS_WAITING_TO_SEND_CLOSE = LWSIFS_POCB | 25, + LRS_RETURNED_CLOSE = LWSIFS_POCB | 26, + LRS_AWAITING_CLOSE_ACK = LWSIFS_POCB | 27, + LRS_FLUSHING_BEFORE_CLOSE = LWSIFS_POCB | 28, + LRS_SHUTDOWN = 29, + + /* Phase 7: dead */ + + LRS_DEAD_SOCKET = 30, + + LRS_MASK = 0xffff +}; + +#define lwsi_state(wsi) ((enum lwsi_state)(wsi->wsistate & LRS_MASK)) +#define lwsi_state_PRE_CLOSE(wsi) ((enum lwsi_state)(wsi->wsistate_pre_close & LRS_MASK)) +#define lwsi_state_est(wsi) (!(wsi->wsistate & LWSIFS_NOT_EST)) +#define lwsi_state_est_PRE_CLOSE(wsi) (!(wsi->wsistate_pre_close & LWSIFS_NOT_EST)) +#define lwsi_state_can_handle_POLLOUT(wsi) (wsi->wsistate & LWSIFS_POCB) +#if !defined (_DEBUG) +#define lwsi_set_state(wsi, lrs) wsi->wsistate = \ + (wsi->wsistate & (~LRS_MASK)) | lrs +#else +void lwsi_set_state(struct lws *wsi, lws_wsi_state_t lrs); +#endif + +/* + * internal role-specific ops + */ +struct lws_context_per_thread; +struct lws_role_ops { + const char *name; + const char *alpn; + /* + * After http headers have parsed, this is the last chance for a role + * to upgrade the connection to something else using the headers. + * ws-over-h2 is upgraded from h2 like this. + */ + int (*check_upgrades)(struct lws *wsi); + /* role-specific context init during context creation */ + int (*init_context)(struct lws_context *context, + const struct lws_context_creation_info *info); + /* role-specific per-vhost init during vhost creation */ + int (*init_vhost)(struct lws_vhost *vh, + const struct lws_context_creation_info *info); + /* role-specific per-vhost destructor during vhost destroy */ + int (*destroy_vhost)(struct lws_vhost *vh); + /* generic 1Hz callback for the role itself */ + int (*periodic_checks)(struct lws_context *context, int tsi, + time_t now); + /* chance for the role to force POLLIN without network activity */ + int (*service_flag_pending)(struct lws_context *context, int tsi); + /* an fd using this role has POLLIN signalled */ + int (*handle_POLLIN)(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd); + /* an fd using the role wanted a POLLOUT callback and now has it */ + int (*handle_POLLOUT)(struct lws *wsi); + /* perform user pollout */ + int (*perform_user_POLLOUT)(struct lws *wsi); + /* do effective callback on writeable */ + int (*callback_on_writable)(struct lws *wsi); + /* connection-specific tx credit in bytes */ + lws_fileofs_t (*tx_credit)(struct lws *wsi); + /* role-specific write formatting */ + int (*write_role_protocol)(struct lws *wsi, unsigned char *buf, + size_t len, enum lws_write_protocol *wp); + + /* get encapsulation parent */ + struct lws * (*encapsulation_parent)(struct lws *wsi); + + /* role-specific destructor */ + int (*alpn_negotiated)(struct lws *wsi, const char *alpn); + + /* chance for the role to handle close in the protocol */ + int (*close_via_role_protocol)(struct lws *wsi, + enum lws_close_status reason); + /* role-specific close processing */ + int (*close_role)(struct lws_context_per_thread *pt, struct lws *wsi); + /* role-specific connection close processing */ + int (*close_kill_connection)(struct lws *wsi, + enum lws_close_status reason); + /* role-specific destructor */ + int (*destroy_role)(struct lws *wsi); + + /* + * the callback reasons for WRITEABLE for client, server + * (just client applies if no concept of client or server) + */ + uint16_t writeable_cb[2]; + /* + * the callback reasons for CLOSE for client, server + * (just client applies if no concept of client or server) + */ + uint16_t close_cb[2]; + + unsigned int file_handle:1; /* role operates on files not sockets */ +}; + +/* core roles */ +extern struct lws_role_ops role_ops_raw_skt, role_ops_raw_file, role_ops_listen, + role_ops_pipe; + +/* bring in role private declarations */ + +#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2) + #include "roles/http/private.h" +#else + #define lwsi_role_http(wsi) (0) +#endif + +#if defined(LWS_ROLE_H1) + #include "roles/h1/private.h" +#else + #define lwsi_role_h1(wsi) (0) +#endif + +#if defined(LWS_ROLE_H2) + #include "roles/h2/private.h" +#else + #define lwsi_role_h2(wsi) (0) +#endif + +#if defined(LWS_ROLE_WS) + #include "roles/ws/private.h" +#else + #define lwsi_role_ws(wsi) (0) +#endif + +#if defined(LWS_ROLE_CGI) + #include "roles/cgi/private.h" +#else + #define lwsi_role_cgi(wsi) (0) +#endif + +enum { + LWS_HP_RET_BAIL_OK, + LWS_HP_RET_BAIL_DIE, + LWS_HP_RET_USER_SERVICE, + + LWS_HPI_RET_WSI_ALREADY_DIED, /* we closed it */ + LWS_HPI_RET_HANDLED, /* no probs */ + LWS_HPI_RET_PLEASE_CLOSE_ME, /* close it for us */ + + LWS_UPG_RET_DONE, + LWS_UPG_RET_CONTINUE, + LWS_UPG_RET_BAIL +}; diff --git a/thirdparty/libwebsockets/roles/raw/ops-raw.c b/thirdparty/libwebsockets/roles/raw/ops-raw.c new file mode 100644 index 0000000000..68b52bded6 --- /dev/null +++ b/thirdparty/libwebsockets/roles/raw/ops-raw.c @@ -0,0 +1,223 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +static int +rops_handle_POLLIN_raw_skt(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ + struct lws_tokens ebuf; + int n, buffered; + + /* pending truncated sends have uber priority */ + + if (wsi->trunc_len) { + if (!(pollfd->revents & LWS_POLLOUT)) + return LWS_HPI_RET_HANDLED; + + if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset, + wsi->trunc_len) < 0) + goto fail; + /* + * we can't afford to allow input processing to send + * something new, so spin around he event loop until + * he doesn't have any partials + */ + return LWS_HPI_RET_HANDLED; + } + + if ((pollfd->revents & pollfd->events & LWS_POLLIN) && + /* any tunnel has to have been established... */ + lwsi_state(wsi) != LRS_SSL_ACK_PENDING && + !(wsi->favoured_pollin && + (pollfd->revents & pollfd->events & LWS_POLLOUT))) { + + buffered = lws_buflist_aware_read(pt, wsi, &ebuf); + switch (ebuf.len) { + case 0: + lwsl_info("%s: read 0 len\n", __func__); + wsi->seen_zero_length_recv = 1; + lws_change_pollfd(wsi, LWS_POLLIN, 0); + + /* + * we need to go to fail here, since it's the only + * chance we get to understand that the socket has + * closed + */ + // goto try_pollout; + goto fail; + + case LWS_SSL_CAPABLE_ERROR: + goto fail; + case LWS_SSL_CAPABLE_MORE_SERVICE: + goto try_pollout; + } + + n = user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_RAW_RX, + wsi->user_space, ebuf.token, + ebuf.len); + if (n < 0) { + lwsl_info("LWS_CALLBACK_RAW_RX_fail\n"); + goto fail; + } + + if (lws_buflist_aware_consume(wsi, &ebuf, ebuf.len, buffered)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } else + if (wsi->favoured_pollin && + (pollfd->revents & pollfd->events & LWS_POLLOUT)) + /* we balanced the last favouring of pollin */ + wsi->favoured_pollin = 0; + +try_pollout: + + /* this handles POLLOUT for http serving fragments */ + + if (!(pollfd->revents & LWS_POLLOUT)) + return LWS_HPI_RET_HANDLED; + + /* one shot */ + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_notice("%s a\n", __func__); + goto fail; + } + + /* clear back-to-back write detection */ + wsi->could_have_pending = 0; + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_WRITEABLE_CB, 1); +#if defined(LWS_WITH_STATS) + if (wsi->active_writable_req_us) { + uint64_t ul = time_in_microseconds() - + wsi->active_writable_req_us; + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_MS_WRITABLE_DELAY, ul); + lws_stats_atomic_max(wsi->context, pt, + LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); + wsi->active_writable_req_us = 0; + } +#endif + n = user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_RAW_WRITEABLE, + wsi->user_space, NULL, 0); + if (n < 0) { + lwsl_info("writeable_fail\n"); + goto fail; + } + + return LWS_HPI_RET_HANDLED; + +fail: + lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS, "raw svc fail"); + + return LWS_HPI_RET_WSI_ALREADY_DIED; +} + + +static int +rops_handle_POLLIN_raw_file(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ + int n; + + if (pollfd->revents & LWS_POLLOUT) { + n = lws_callback_as_writeable(wsi); + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_info("failed at set pollfd\n"); + return LWS_HPI_RET_WSI_ALREADY_DIED; + } + if (n) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + if (pollfd->revents & LWS_POLLIN) { + if (user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_RAW_RX_FILE, + wsi->user_space, NULL, 0)) { + lwsl_debug("raw rx callback closed it\n"); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + } + + if (pollfd->revents & LWS_POLLHUP) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + + return LWS_HPI_RET_HANDLED; +} + + +struct lws_role_ops role_ops_raw_skt = { + /* role name */ "raw-skt", + /* alpn id */ NULL, + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ NULL, + /* destroy_vhost */ NULL, + /* periodic_checks */ NULL, + /* service_flag_pending */ NULL, + /* handle_POLLIN */ rops_handle_POLLIN_raw_skt, + /* handle_POLLOUT */ NULL, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ NULL, + /* tx_credit */ NULL, + /* write_role_protocol */ NULL, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ NULL, + /* close_via_role_protocol */ NULL, + /* close_role */ NULL, + /* close_kill_connection */ NULL, + /* destroy_role */ NULL, + /* writeable cb clnt, srv */ { LWS_CALLBACK_RAW_WRITEABLE, 0 }, + /* close cb clnt, srv */ { LWS_CALLBACK_RAW_CLOSE, 0 }, + /* file_handle */ 0, +}; + + + +struct lws_role_ops role_ops_raw_file = { + /* role name */ "raw-file", + /* alpn id */ NULL, + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ NULL, + /* destroy_vhost */ NULL, + /* periodic_checks */ NULL, + /* service_flag_pending */ NULL, + /* handle_POLLIN */ rops_handle_POLLIN_raw_file, + /* handle_POLLOUT */ NULL, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ NULL, + /* tx_credit */ NULL, + /* write_role_protocol */ NULL, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ NULL, + /* close_via_role_protocol */ NULL, + /* close_role */ NULL, + /* close_kill_connection */ NULL, + /* destroy_role */ NULL, + /* writeable cb clnt, srv */ { LWS_CALLBACK_RAW_WRITEABLE_FILE, 0 }, + /* close cb clnt, srv */ { LWS_CALLBACK_RAW_CLOSE_FILE, 0 }, + /* file_handle */ 1, +}; diff --git a/thirdparty/lws/client/client-parser.c b/thirdparty/libwebsockets/roles/ws/client-parser-ws.c index 0e42dac362..aa561ce034 100644 --- a/thirdparty/lws/client/client-parser.c +++ b/thirdparty/libwebsockets/roles/ws/client-parser-ws.c @@ -19,31 +19,38 @@ * MA 02110-1301 USA */ -#include "private-libwebsockets.h" +#include "core/private.h" /* - * parsers.c: lws_rx_sm() needs to be roughly kept in + * parsers.c: lws_ws_rx_sm() needs to be roughly kept in * sync with changes here, esp related to ext draining */ -int lws_client_rx_sm(struct lws *wsi, unsigned char c) +int lws_ws_client_rx_sm(struct lws *wsi, unsigned char c) { int callback_action = LWS_CALLBACK_CLIENT_RECEIVE; - int handled, n, m, rx_draining_ext = 0; + int handled, m; unsigned short close_code; - struct lws_tokens eff_buf; + struct lws_tokens ebuf; unsigned char *pp; +#if !defined(LWS_WITHOUT_EXTENSIONS) + int rx_draining_ext = 0, n; +#endif + + ebuf.token = NULL; + ebuf.len = 0; - if (wsi->u.ws.rx_draining_ext) { +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { assert(!c); - eff_buf.token = NULL; - eff_buf.token_len = 0; + lws_remove_wsi_from_draining_ext_list(wsi); rx_draining_ext = 1; lwsl_debug("%s: doing draining flow\n", __func__); goto drain_extension; } +#endif if (wsi->socket_is_permanently_unusable) return -1; @@ -51,35 +58,38 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) switch (wsi->lws_rx_parse_state) { case LWS_RXPS_NEW: /* control frames (PING) may interrupt checkable sequences */ - wsi->u.ws.defeat_check_utf8 = 0; + wsi->ws->defeat_check_utf8 = 0; - switch (wsi->ietf_spec_revision) { + switch (wsi->ws->ietf_spec_revision) { case 13: - wsi->u.ws.opcode = c & 0xf; + wsi->ws->opcode = c & 0xf; /* revisit if an extension wants them... */ - switch (wsi->u.ws.opcode) { + switch (wsi->ws->opcode) { case LWSWSOPC_TEXT_FRAME: - wsi->u.ws.rsv_first_msg = (c & 0x70); - wsi->u.ws.continuation_possible = 1; - wsi->u.ws.check_utf8 = lws_check_opt( + wsi->ws->rsv_first_msg = (c & 0x70); + wsi->ws->continuation_possible = 1; + wsi->ws->check_utf8 = lws_check_opt( wsi->context->options, LWS_SERVER_OPTION_VALIDATE_UTF8); - wsi->u.ws.utf8 = 0; + wsi->ws->utf8 = 0; + wsi->ws->first_fragment = 1; break; case LWSWSOPC_BINARY_FRAME: - wsi->u.ws.rsv_first_msg = (c & 0x70); - wsi->u.ws.check_utf8 = 0; - wsi->u.ws.continuation_possible = 1; + wsi->ws->rsv_first_msg = (c & 0x70); + wsi->ws->check_utf8 = 0; + wsi->ws->continuation_possible = 1; + wsi->ws->first_fragment = 1; break; case LWSWSOPC_CONTINUATION: - if (!wsi->u.ws.continuation_possible) { + if (!wsi->ws->continuation_possible) { lwsl_info("disordered continuation\n"); return -1; } + wsi->ws->first_fragment = 0; break; case LWSWSOPC_CLOSE: - wsi->u.ws.check_utf8 = 0; - wsi->u.ws.utf8 = 0; + wsi->ws->check_utf8 = 0; + wsi->ws->utf8 = 0; break; case 3: case 4: @@ -94,45 +104,45 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) lwsl_info("illegal opcode\n"); return -1; default: - wsi->u.ws.defeat_check_utf8 = 1; + wsi->ws->defeat_check_utf8 = 1; break; } - wsi->u.ws.rsv = (c & 0x70); + wsi->ws->rsv = (c & 0x70); /* revisit if an extension wants them... */ if ( -#ifndef LWS_NO_EXTENSIONS - !wsi->count_act_ext && +#if !defined(LWS_WITHOUT_EXTENSIONS) + !wsi->ws->count_act_ext && #endif - wsi->u.ws.rsv) { + wsi->ws->rsv) { lwsl_info("illegal rsv bits set\n"); return -1; } - wsi->u.ws.final = !!((c >> 7) & 1); + wsi->ws->final = !!((c >> 7) & 1); lwsl_ext("%s: This RX frame Final %d\n", __func__, - wsi->u.ws.final); + wsi->ws->final); - if (wsi->u.ws.owed_a_fin && - (wsi->u.ws.opcode == LWSWSOPC_TEXT_FRAME || - wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME)) { + if (wsi->ws->owed_a_fin && + (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME || + wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) { lwsl_info("hey you owed us a FIN\n"); return -1; } - if ((!(wsi->u.ws.opcode & 8)) && wsi->u.ws.final) { - wsi->u.ws.continuation_possible = 0; - wsi->u.ws.owed_a_fin = 0; + if ((!(wsi->ws->opcode & 8)) && wsi->ws->final) { + wsi->ws->continuation_possible = 0; + wsi->ws->owed_a_fin = 0; } - if ((wsi->u.ws.opcode & 8) && !wsi->u.ws.final) { + if ((wsi->ws->opcode & 8) && !wsi->ws->final) { lwsl_info("control msg can't be fragmented\n"); return -1; } - if (!wsi->u.ws.final) - wsi->u.ws.owed_a_fin = 1; + if (!wsi->ws->final) + wsi->ws->owed_a_fin = 1; - switch (wsi->u.ws.opcode) { + switch (wsi->ws->opcode) { case LWSWSOPC_TEXT_FRAME: case LWSWSOPC_BINARY_FRAME: - wsi->u.ws.frame_is_binary = wsi->u.ws.opcode == + wsi->ws->frame_is_binary = wsi->ws->opcode == LWSWSOPC_BINARY_FRAME; break; } @@ -141,38 +151,38 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) default: lwsl_err("unknown spec version %02d\n", - wsi->ietf_spec_revision); + wsi->ws->ietf_spec_revision); break; } break; case LWS_RXPS_04_FRAME_HDR_LEN: - wsi->u.ws.this_frame_masked = !!(c & 0x80); + wsi->ws->this_frame_masked = !!(c & 0x80); switch (c & 0x7f) { case 126: /* control frames are not allowed to have big lengths */ - if (wsi->u.ws.opcode & 8) + if (wsi->ws->opcode & 8) goto illegal_ctl_length; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2; break; case 127: /* control frames are not allowed to have big lengths */ - if (wsi->u.ws.opcode & 8) + if (wsi->ws->opcode & 8) goto illegal_ctl_length; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8; break; default: - wsi->u.ws.rx_packet_length = c; - if (wsi->u.ws.this_frame_masked) + wsi->ws->rx_packet_length = c & 0x7f; + if (wsi->ws->this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { - if (c) + if (wsi->ws->rx_packet_length) { wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; - else { + LWS_RXPS_WS_FRAME_PAYLOAD; + } else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } @@ -182,18 +192,18 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) break; case LWS_RXPS_04_FRAME_HDR_LEN16_2: - wsi->u.ws.rx_packet_length = c << 8; + wsi->ws->rx_packet_length = c << 8; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1; break; case LWS_RXPS_04_FRAME_HDR_LEN16_1: - wsi->u.ws.rx_packet_length |= c; - if (wsi->u.ws.this_frame_masked) + wsi->ws->rx_packet_length |= c; + if (wsi->ws->this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { - if (wsi->u.ws.rx_packet_length) + if (wsi->ws->rx_packet_length) wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + LWS_RXPS_WS_FRAME_PAYLOAD; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; @@ -208,58 +218,58 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) return -1; } #if defined __LP64__ - wsi->u.ws.rx_packet_length = ((size_t)c) << 56; + wsi->ws->rx_packet_length = ((size_t)c) << 56; #else - wsi->u.ws.rx_packet_length = 0; + wsi->ws->rx_packet_length = 0; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7; break; case LWS_RXPS_04_FRAME_HDR_LEN64_7: #if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 48; + wsi->ws->rx_packet_length |= ((size_t)c) << 48; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6; break; case LWS_RXPS_04_FRAME_HDR_LEN64_6: #if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 40; + wsi->ws->rx_packet_length |= ((size_t)c) << 40; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5; break; case LWS_RXPS_04_FRAME_HDR_LEN64_5: #if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 32; + wsi->ws->rx_packet_length |= ((size_t)c) << 32; #endif wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4; break; case LWS_RXPS_04_FRAME_HDR_LEN64_4: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 24; + wsi->ws->rx_packet_length |= ((size_t)c) << 24; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3; break; case LWS_RXPS_04_FRAME_HDR_LEN64_3: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 16; + wsi->ws->rx_packet_length |= ((size_t)c) << 16; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2; break; case LWS_RXPS_04_FRAME_HDR_LEN64_2: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 8; + wsi->ws->rx_packet_length |= ((size_t)c) << 8; wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1; break; case LWS_RXPS_04_FRAME_HDR_LEN64_1: - wsi->u.ws.rx_packet_length |= (size_t)c; - if (wsi->u.ws.this_frame_masked) + wsi->ws->rx_packet_length |= (size_t)c; + if (wsi->ws->this_frame_masked) wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_1; else { - if (wsi->u.ws.rx_packet_length) + if (wsi->ws->rx_packet_length) wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + LWS_RXPS_WS_FRAME_PAYLOAD; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; @@ -268,53 +278,53 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) break; case LWS_RXPS_07_COLLECT_FRAME_KEY_1: - wsi->u.ws.mask[0] = c; + wsi->ws->mask[0] = c; if (c) - wsi->u.ws.all_zero_nonce = 0; + wsi->ws->all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_2: - wsi->u.ws.mask[1] = c; + wsi->ws->mask[1] = c; if (c) - wsi->u.ws.all_zero_nonce = 0; + wsi->ws->all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_3: - wsi->u.ws.mask[2] = c; + wsi->ws->mask[2] = c; if (c) - wsi->u.ws.all_zero_nonce = 0; + wsi->ws->all_zero_nonce = 0; wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4; break; case LWS_RXPS_07_COLLECT_FRAME_KEY_4: - wsi->u.ws.mask[3] = c; + wsi->ws->mask[3] = c; if (c) - wsi->u.ws.all_zero_nonce = 0; + wsi->ws->all_zero_nonce = 0; - if (wsi->u.ws.rx_packet_length) + if (wsi->ws->rx_packet_length) wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; + LWS_RXPS_WS_FRAME_PAYLOAD; else { wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; } break; - case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED: - - assert(wsi->u.ws.rx_ubuf); + case LWS_RXPS_WS_FRAME_PAYLOAD: - if (wsi->u.ws.rx_draining_ext) + assert(wsi->ws->rx_ubuf); +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) goto drain_extension; +#endif + if (wsi->ws->this_frame_masked && !wsi->ws->all_zero_nonce) + c ^= wsi->ws->mask[(wsi->ws->mask_idx++) & 3]; - if (wsi->u.ws.this_frame_masked && !wsi->u.ws.all_zero_nonce) - c ^= wsi->u.ws.mask[(wsi->u.ws.mask_idx++) & 3]; - - wsi->u.ws.rx_ubuf[LWS_PRE + (wsi->u.ws.rx_ubuf_head++)] = c; + wsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] = c; - if (--wsi->u.ws.rx_packet_length == 0) { + if (--wsi->ws->rx_packet_length == 0) { /* spill because we have the whole frame */ wsi->lws_rx_parse_state = LWS_RXPS_NEW; goto spill; @@ -325,11 +335,11 @@ int lws_client_rx_sm(struct lws *wsi, unsigned char c) * supposed to default to context->pt_serv_buf_size */ if (!wsi->protocol->rx_buffer_size && - wsi->u.ws.rx_ubuf_head != wsi->context->pt_serv_buf_size) + wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size) break; if (wsi->protocol->rx_buffer_size && - wsi->u.ws.rx_ubuf_head != wsi->protocol->rx_buffer_size) + wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size) break; /* spill because we filled our rx buffer */ @@ -342,18 +352,18 @@ spill: * layer? If so service it and hide it from the user callback */ - switch (wsi->u.ws.opcode) { + switch (wsi->ws->opcode) { case LWSWSOPC_CLOSE: - pp = (unsigned char *)&wsi->u.ws.rx_ubuf[LWS_PRE]; + pp = (unsigned char *)&wsi->ws->rx_ubuf[LWS_PRE]; if (lws_check_opt(wsi->context->options, LWS_SERVER_OPTION_VALIDATE_UTF8) && - wsi->u.ws.rx_ubuf_head > 2 && - lws_check_utf8(&wsi->u.ws.utf8, pp + 2, - wsi->u.ws.rx_ubuf_head - 2)) + wsi->ws->rx_ubuf_head > 2 && + lws_check_utf8(&wsi->ws->utf8, pp + 2, + wsi->ws->rx_ubuf_head - 2)) goto utf8_fail; - /* is this an acknowledgement of our close? */ - if (wsi->state == LWSS_AWAITING_CLOSE_ACK) { + /* is this an acknowledgment of our close? */ + if (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) { /* * fine he has told us he is closing too, let's * finish our close @@ -363,8 +373,8 @@ spill: } lwsl_parser("client sees server close len = %d\n", - wsi->u.ws.rx_ubuf_head); - if (wsi->u.ws.rx_ubuf_head >= 2) { + wsi->ws->rx_ubuf_head); + if (wsi->ws->rx_ubuf_head >= 2) { close_code = (pp[0] << 8) | pp[1]; if (close_code < 1000 || close_code == 1004 || @@ -384,39 +394,32 @@ spill: wsi->protocol->callback, wsi, LWS_CALLBACK_WS_PEER_INITIATED_CLOSE, wsi->user_space, pp, - wsi->u.ws.rx_ubuf_head)) + wsi->ws->rx_ubuf_head)) return -1; - if (lws_partial_buffered(wsi)) - /* - * if we're in the middle of something, - * we can't do a normal close response and - * have to just close our end. - */ - wsi->socket_is_permanently_unusable = 1; - else - /* - * parrot the close packet payload back - * we do not care about how it went, we are closing - * immediately afterwards - */ - lws_write(wsi, (unsigned char *) - &wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head, - LWS_WRITE_CLOSE); - wsi->state = LWSS_RETURNED_CLOSE_ALREADY; - /* close the connection */ - return -1; + memcpy(wsi->ws->ping_payload_buf + LWS_PRE, pp, + wsi->ws->rx_ubuf_head); + wsi->ws->close_in_ping_buffer_len = wsi->ws->rx_ubuf_head; + + lwsl_info("%s: scheduling return close as ack\n", __func__); + __lws_change_pollfd(wsi, LWS_POLLIN, 0); + lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 3); + wsi->waiting_to_send_close_frame = 1; + wsi->close_needs_ack = 0; + lwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE); + lws_callback_on_writable(wsi); + handled = 1; + break; case LWSWSOPC_PING: lwsl_info("received %d byte ping, sending pong\n", - wsi->u.ws.rx_ubuf_head); + wsi->ws->rx_ubuf_head); /* he set a close reason on this guy, ignore PING */ - if (wsi->u.ws.close_in_ping_buffer_len) + if (wsi->ws->close_in_ping_buffer_len) goto ping_drop; - if (wsi->u.ws.ping_pending_flag) { + if (wsi->ws->ping_pending_flag) { /* * there is already a pending ping payload * we should just log and drop @@ -426,30 +429,30 @@ spill: } /* control packets can only be < 128 bytes long */ - if (wsi->u.ws.rx_ubuf_head > 128 - 3) { + if (wsi->ws->rx_ubuf_head > 128 - 3) { lwsl_parser("DROP PING payload too large\n"); goto ping_drop; } /* stash the pong payload */ - memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE, - &wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head); + memcpy(wsi->ws->ping_payload_buf + LWS_PRE, + &wsi->ws->rx_ubuf[LWS_PRE], + wsi->ws->rx_ubuf_head); - wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head; - wsi->u.ws.ping_pending_flag = 1; + wsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head; + wsi->ws->ping_pending_flag = 1; /* get it sent as soon as possible */ lws_callback_on_writable(wsi); ping_drop: - wsi->u.ws.rx_ubuf_head = 0; + wsi->ws->rx_ubuf_head = 0; handled = 1; break; case LWSWSOPC_PONG: lwsl_info("client receied pong\n"); - lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head); + lwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE], + wsi->ws->rx_ubuf_head); if (wsi->pending_timeout == PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) { @@ -467,30 +470,11 @@ ping_drop: break; default: + /* not handled or failed */ + lwsl_ext("Unhandled ext opc 0x%x\n", wsi->ws->opcode); + wsi->ws->rx_ubuf_head = 0; - lwsl_parser("Reserved opc 0x%2X\n", wsi->u.ws.opcode); - - /* - * It's something special we can't understand here. - * Pass the payload up to the extension's parsing - * state machine. - */ - - eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE]; - eff_buf.token_len = wsi->u.ws.rx_ubuf_head; - - if (lws_ext_cb_active(wsi, - LWS_EXT_CB_EXTENDED_PAYLOAD_RX, - &eff_buf, 0) <= 0) { - /* not handled or failed */ - lwsl_ext("Unhandled ext opc 0x%x\n", - wsi->u.ws.opcode); - wsi->u.ws.rx_ubuf_head = 0; - - return 0; - } - handled = 1; - break; + return -1; } /* @@ -501,53 +485,71 @@ ping_drop: if (handled) goto already_done; - eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE]; - eff_buf.token_len = wsi->u.ws.rx_ubuf_head; + ebuf.token = &wsi->ws->rx_ubuf[LWS_PRE]; + ebuf.len = wsi->ws->rx_ubuf_head; - if (wsi->u.ws.opcode == LWSWSOPC_PONG && !eff_buf.token_len) + if (wsi->ws->opcode == LWSWSOPC_PONG && !ebuf.len) goto already_done; +#if !defined(LWS_WITHOUT_EXTENSIONS) drain_extension: - lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len); + lwsl_ext("%s: passing %d to ext\n", __func__, ebuf.len); - n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0); + n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0); lwsl_ext("Ext RX returned %d\n", n); if (n < 0) { wsi->socket_is_permanently_unusable = 1; return -1; } +#endif + lwsl_debug("post inflate ebuf len %d\n", ebuf.len); - lwsl_ext("post inflate eff_buf len %d\n", eff_buf.token_len); - - if (rx_draining_ext && !eff_buf.token_len) { + if ( +#if !defined(LWS_WITHOUT_EXTENSIONS) + rx_draining_ext && +#endif + !ebuf.len) { lwsl_debug(" --- ending drain on 0 read result\n"); goto already_done; } - if (wsi->u.ws.check_utf8 && !wsi->u.ws.defeat_check_utf8) { - if (lws_check_utf8(&wsi->u.ws.utf8, - (unsigned char *)eff_buf.token, - eff_buf.token_len)) + if (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) { + if (lws_check_utf8(&wsi->ws->utf8, + (unsigned char *)ebuf.token, + ebuf.len)) { + lws_close_reason(wsi, + LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"bad utf8", 8); goto utf8_fail; + } /* we are ending partway through utf-8 character? */ - if (!wsi->u.ws.rx_packet_length && wsi->u.ws.final && - wsi->u.ws.utf8 && !n) { + if (!wsi->ws->rx_packet_length && wsi->ws->final && + wsi->ws->utf8 +#if !defined(LWS_WITHOUT_EXTENSIONS) + && !n +#endif + ) { lwsl_info("FINAL utf8 error\n"); + lws_close_reason(wsi, + LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"partial utf8", 12); utf8_fail: lwsl_info("utf8 error\n"); + lwsl_hexdump_info(ebuf.token, ebuf.len); + return -1; } } - if (eff_buf.token_len < 0 && + if (ebuf.len < 0 && callback_action != LWS_CALLBACK_CLIENT_RECEIVE_PONG) goto already_done; - if (!eff_buf.token) + if (!ebuf.token) goto already_done; - eff_buf.token[eff_buf.token_len] = '\0'; + ebuf.token[ebuf.len] = '\0'; if (!wsi->protocol->callback) goto already_done; @@ -555,7 +557,12 @@ utf8_fail: if (callback_action == LWS_CALLBACK_CLIENT_RECEIVE_PONG) lwsl_info("Client doing pong callback\n"); - if (n && eff_buf.token_len) + if ( + /* coverity says dead code otherwise */ +#if !defined(LWS_WITHOUT_EXTENSIONS) + n && +#endif + ebuf.len) /* extension had more... main loop will come back * we want callback to be done with this set, if so, * because lws_is_final() hides it was final until the @@ -565,21 +572,26 @@ utf8_fail: else lws_remove_wsi_from_draining_ext_list(wsi); - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY || - wsi->state == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION || - wsi->state == LWSS_AWAITING_CLOSE_ACK) + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE || + lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE || + lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) goto already_done; m = wsi->protocol->callback(wsi, (enum lws_callback_reasons)callback_action, - wsi->user_space, eff_buf.token, eff_buf.token_len); + wsi->user_space, ebuf.token, ebuf.len); + + wsi->ws->first_fragment = 0; + + // lwsl_notice("%s: bulk ws rx: input used %d, output %d\n", + // __func__, wsi->ws->rx_ubuf_head, ebuf.len); /* if user code wants to close, let caller know */ if (m) return 1; already_done: - wsi->u.ws.rx_ubuf_head = 0; + wsi->ws->rx_ubuf_head = 0; break; default: lwsl_err("client rx illegal state\n"); diff --git a/thirdparty/libwebsockets/roles/ws/client-ws.c b/thirdparty/libwebsockets/roles/ws/client-ws.c new file mode 100644 index 0000000000..fd6cf42551 --- /dev/null +++ b/thirdparty/libwebsockets/roles/ws/client-ws.c @@ -0,0 +1,629 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +/* + * In-place str to lower case + */ + +static void +strtolower(char *s) +{ + while (*s) { +#ifdef LWS_PLAT_OPTEE + int tolower_optee(int c); + *s = tolower_optee((int)*s); +#else + *s = tolower((int)*s); +#endif + s++; + } +} + +int +lws_create_client_ws_object(struct lws_client_connect_info *i, struct lws *wsi) +{ + int v = SPEC_LATEST_SUPPORTED; + + /* allocate the ws struct for the wsi */ + wsi->ws = lws_zalloc(sizeof(*wsi->ws), "client ws struct"); + if (!wsi->ws) { + lwsl_notice("OOM\n"); + return 1; + } + + /* -1 means just use latest supported */ + if (i->ietf_version_or_minus_one != -1 && + i->ietf_version_or_minus_one) + v = i->ietf_version_or_minus_one; + + wsi->ws->ietf_spec_revision = v; + + return 0; +} + +#if !defined(LWS_NO_CLIENT) +int +lws_ws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len) +{ + if ((lwsi_state(wsi) != LRS_WAITING_PROXY_REPLY) && + (lwsi_state(wsi) != LRS_H1C_ISSUE_HANDSHAKE) && + (lwsi_state(wsi) != LRS_WAITING_SERVER_REPLY) && + !lwsi_role_client(wsi)) + return 0; + + // lwsl_notice("%s: hs client gets %d in\n", __func__, (int)len); + + while (len) { + /* + * we were accepting input but now we stopped doing so + */ + if (lws_is_flowcontrolled(wsi)) { + //lwsl_notice("%s: caching %ld\n", __func__, (long)len); + lws_rxflow_cache(wsi, *buf, 0, (int)len); + *buf += len; + return 0; + } +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { + int m; + + //lwsl_notice("%s: draining ext\n", __func__); + if (lwsi_role_client(wsi)) + m = lws_ws_client_rx_sm(wsi, 0); + else + m = lws_ws_rx_sm(wsi, 0, 0); + if (m < 0) + return -1; + continue; + } +#endif + /* caller will account for buflist usage */ + + if (lws_ws_client_rx_sm(wsi, *(*buf)++)) { + lwsl_notice("%s: client_rx_sm exited, DROPPING %d\n", + __func__, (int)len); + return -1; + } + len--; + } + // lwsl_notice("%s: finished with %ld\n", __func__, (long)len); + + return 0; +} +#endif + +char * +lws_generate_client_ws_handshake(struct lws *wsi, char *p) +{ + char buf[128], hash[20], key_b64[40]; + int n; +#if !defined(LWS_WITHOUT_EXTENSIONS) + const struct lws_extension *ext; + int ext_count = 0; +#endif + + /* + * create the random key + */ + n = lws_get_random(wsi->context, hash, 16); + if (n != 16) { + lwsl_err("Unable to read from random dev %s\n", + SYSTEM_RANDOM_FILEPATH); + return NULL; + } + + lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64)); + + p += sprintf(p, "Upgrade: websocket\x0d\x0a" + "Connection: Upgrade\x0d\x0a" + "Sec-WebSocket-Key: "); + strcpy(p, key_b64); + p += strlen(key_b64); + p += sprintf(p, "\x0d\x0a"); + if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS)) + p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a", + lws_hdr_simple_ptr(wsi, + _WSI_TOKEN_CLIENT_SENT_PROTOCOLS)); + + /* tell the server what extensions we could support */ + +#if !defined(LWS_WITHOUT_EXTENSIONS) + ext = wsi->vhost->ws.extensions; + while (ext && ext->callback) { + + n = wsi->vhost->protocols[0].callback(wsi, + LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED, + wsi->user_space, (char *)ext->name, 0); + + /* + * zero return from callback means go ahead and allow + * the extension, it's what we get if the callback is + * unhandled + */ + + if (n) { + ext++; + continue; + } + + /* apply it */ + + if (ext_count) + *p++ = ','; + else + p += sprintf(p, "Sec-WebSocket-Extensions: "); + p += sprintf(p, "%s", ext->client_offer); + ext_count++; + + ext++; + } + if (ext_count) + p += sprintf(p, "\x0d\x0a"); +#endif + + if (wsi->ws->ietf_spec_revision) + p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a", + wsi->ws->ietf_spec_revision); + + /* prepare the expected server accept response */ + + key_b64[39] = '\0'; /* enforce composed length below buf sizeof */ + n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + key_b64); + + lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash); + + lws_b64_encode_string(hash, 20, + wsi->http.ah->initial_handshake_hash_base64, + sizeof(wsi->http.ah->initial_handshake_hash_base64)); + + return p; +} + +int +lws_client_ws_upgrade(struct lws *wsi, const char **cce) +{ + int n, len, okay = 0; + struct lws_context *context = wsi->context; + const char *pc; + char *p; +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + char *sb = (char *)&pt->serv_buf[0]; + const struct lws_ext_options *opts; + const struct lws_extension *ext; + char ext_name[128]; + const char *c, *a; + char ignore; + int more = 1; +#endif + + if (wsi->client_h2_substream) {/* !!! client ws-over-h2 not there yet */ + lwsl_warn("%s: client ws-over-h2 upgrade not supported yet\n", + __func__); + *cce = "HS: h2 / ws upgrade unsupported"; + goto bail3; + } + + if (wsi->http.ah->http_response == 401) { + lwsl_warn( + "lws_client_handshake: got bad HTTP response '%d'\n", + wsi->http.ah->http_response); + *cce = "HS: ws upgrade unauthorized"; + goto bail3; + } + + if (wsi->http.ah->http_response != 101) { + lwsl_warn( + "lws_client_handshake: got bad HTTP response '%d'\n", + wsi->http.ah->http_response); + *cce = "HS: ws upgrade response not 101"; + goto bail3; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { + lwsl_info("no ACCEPT\n"); + *cce = "HS: ACCEPT missing"; + goto bail3; + } + + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); + if (!p) { + lwsl_info("no UPGRADE\n"); + *cce = "HS: UPGRADE missing"; + goto bail3; + } + strtolower(p); + if (strcmp(p, "websocket")) { + lwsl_warn( + "lws_client_handshake: got bad Upgrade header '%s'\n", p); + *cce = "HS: Upgrade to something other than websocket"; + goto bail3; + } + + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); + if (!p) { + lwsl_info("no Connection hdr\n"); + *cce = "HS: CONNECTION missing"; + goto bail3; + } + strtolower(p); + if (strcmp(p, "upgrade")) { + lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); + *cce = "HS: UPGRADE malformed"; + goto bail3; + } + + pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); + if (!pc) { + lwsl_parser("lws_client_int_s_hs: no protocol list\n"); + } else + lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); + + /* + * confirm the protocol the server wants to talk was in the list + * of protocols we offered + */ + + len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); + if (!len) { + lwsl_info("%s: WSI_TOKEN_PROTOCOL is null\n", __func__); + /* + * no protocol name to work from, + * default to first protocol + */ + n = 0; + wsi->protocol = &wsi->vhost->protocols[0]; + goto check_extensions; + } + + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); + len = (int)strlen(p); + + while (pc && *pc && !okay) { + if (!strncmp(pc, p, len) && + (pc[len] == ',' || pc[len] == '\0')) { + okay = 1; + continue; + } + while (*pc && *pc++ != ',') + ; + while (*pc && *pc == ' ') + pc++; + } + + if (!okay) { + lwsl_info("%s: got bad protocol %s\n", __func__, p); + *cce = "HS: PROTOCOL malformed"; + goto bail2; + } + + /* + * identify the selected protocol struct and set it + */ + n = 0; + /* keep client connection pre-bound protocol */ + if (!lwsi_role_client(wsi)) + wsi->protocol = NULL; + + while (wsi->vhost->protocols[n].callback) { + if (!wsi->protocol && + strcmp(p, wsi->vhost->protocols[n].name) == 0) { + wsi->protocol = &wsi->vhost->protocols[n]; + break; + } + n++; + } + + if (!wsi->vhost->protocols[n].callback) { /* no match */ + /* if server, that's already fatal */ + if (!lwsi_role_client(wsi)) { + lwsl_info("%s: fail protocol %s\n", __func__, p); + *cce = "HS: Cannot match protocol"; + goto bail2; + } + + /* for client, find the index of our pre-bound protocol */ + + n = 0; + while (wsi->vhost->protocols[n].callback) { + if (wsi->protocol && strcmp(wsi->protocol->name, + wsi->vhost->protocols[n].name) == 0) { + wsi->protocol = &wsi->vhost->protocols[n]; + break; + } + n++; + } + + if (!wsi->vhost->protocols[n].callback) { + if (wsi->protocol) + lwsl_err("Failed to match protocol %s\n", + wsi->protocol->name); + else + lwsl_err("No protocol on client\n"); + goto bail2; + } + } + + lwsl_debug("Selected protocol %s\n", wsi->protocol->name); + +check_extensions: + /* + * stitch protocol choice into the vh protocol linked list + * We always insert ourselves at the start of the list + * + * X <-> B + * X <-> pAn <-> pB + */ + + lws_vhost_lock(wsi->vhost); + + wsi->same_vh_protocol_prev = /* guy who points to us */ + &wsi->vhost->same_vh_protocol_list[n]; + wsi->same_vh_protocol_next = /* old first guy is our next */ + wsi->vhost->same_vh_protocol_list[n]; + /* we become the new first guy */ + wsi->vhost->same_vh_protocol_list[n] = wsi; + + if (wsi->same_vh_protocol_next) + /* old first guy points back to us now */ + wsi->same_vh_protocol_next->same_vh_protocol_prev = + &wsi->same_vh_protocol_next; + wsi->on_same_vh_list = 1; + + lws_vhost_unlock(wsi->vhost); + +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* instantiate the accepted extensions */ + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { + lwsl_ext("no client extensions allowed by server\n"); + goto check_accept; + } + + /* + * break down the list of server accepted extensions + * and go through matching them or identifying bogons + */ + + if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, + WSI_TOKEN_EXTENSIONS) < 0) { + lwsl_warn("ext list from server failed to copy\n"); + *cce = "HS: EXT: list too big"; + goto bail2; + } + + c = sb; + n = 0; + ignore = 0; + a = NULL; + while (more) { + + if (*c && (*c != ',' && *c != '\t')) { + if (*c == ';') { + ignore = 1; + if (!a) + a = c + 1; + } + if (ignore || *c == ' ') { + c++; + continue; + } + + ext_name[n] = *c++; + if (n < (int)sizeof(ext_name) - 1) + n++; + continue; + } + ext_name[n] = '\0'; + ignore = 0; + if (!*c) + more = 0; + else { + c++; + if (!n) + continue; + } + + /* check we actually support it */ + + lwsl_notice("checking client ext %s\n", ext_name); + + n = 0; + ext = wsi->vhost->ws.extensions; + while (ext && ext->callback) { + if (strcmp(ext_name, ext->name)) { + ext++; + continue; + } + + n = 1; + lwsl_notice("instantiating client ext %s\n", ext_name); + + /* instantiate the extension on this conn */ + + wsi->ws->active_extensions[wsi->ws->count_act_ext] = ext; + + /* allow him to construct his ext instance */ + + if (ext->callback(lws_get_context(wsi), ext, wsi, + LWS_EXT_CB_CLIENT_CONSTRUCT, + (void *)&wsi->ws->act_ext_user[wsi->ws->count_act_ext], + (void *)&opts, 0)) { + lwsl_info(" ext %s failed construction\n", + ext_name); + ext++; + continue; + } + + /* + * allow the user code to override ext defaults if it + * wants to + */ + ext_name[0] = '\0'; + if (user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_WS_EXT_DEFAULTS, + (char *)ext->name, ext_name, + sizeof(ext_name))) { + *cce = "HS: EXT: failed setting defaults"; + goto bail2; + } + + if (ext_name[0] && + lws_ext_parse_options(ext, wsi, wsi->ws->act_ext_user[ + wsi->ws->count_act_ext], opts, ext_name, + (int)strlen(ext_name))) { + lwsl_err("%s: unable to parse user defaults '%s'", + __func__, ext_name); + *cce = "HS: EXT: failed parsing defaults"; + goto bail2; + } + + /* + * give the extension the server options + */ + if (a && lws_ext_parse_options(ext, wsi, + wsi->ws->act_ext_user[wsi->ws->count_act_ext], + opts, a, lws_ptr_diff(c, a))) { + lwsl_err("%s: unable to parse remote def '%s'", + __func__, a); + *cce = "HS: EXT: failed parsing options"; + goto bail2; + } + + if (ext->callback(lws_get_context(wsi), ext, wsi, + LWS_EXT_CB_OPTION_CONFIRM, + wsi->ws->act_ext_user[wsi->ws->count_act_ext], + NULL, 0)) { + lwsl_err("%s: ext %s rejects server options %s", + __func__, ext->name, a); + *cce = "HS: EXT: Rejects server options"; + goto bail2; + } + + wsi->ws->count_act_ext++; + + ext++; + } + + if (n == 0) { + lwsl_warn("Unknown ext '%s'!\n", ext_name); + *cce = "HS: EXT: unknown ext"; + goto bail2; + } + + a = NULL; + n = 0; + } + +check_accept: +#endif + + /* + * Confirm his accept token is the one we precomputed + */ + + p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); + if (strcmp(p, wsi->http.ah->initial_handshake_hash_base64)) { + lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p, + wsi->http.ah->initial_handshake_hash_base64); + *cce = "HS: Accept hash wrong"; + goto bail2; + } + + /* allocate the per-connection user memory (if any) */ + if (lws_ensure_user_space(wsi)) { + lwsl_err("Problem allocating wsi user mem\n"); + *cce = "HS: OOM"; + goto bail2; + } + + /* + * we seem to be good to go, give client last chance to check + * headers and OK it + */ + if (wsi->protocol->callback(wsi, + LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, + wsi->user_space, NULL, 0)) { + *cce = "HS: Rejected by filter cb"; + goto bail2; + } + + /* clear his proxy connection timeout */ + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + + /* free up his parsing allocations */ + lws_header_table_detach(wsi, 0); + + lws_role_transition(wsi, LWSIFR_CLIENT, LRS_ESTABLISHED, + &role_ops_ws); + lws_restart_ws_ping_pong_timer(wsi); + + wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; + + /* + * create the frame buffer for this connection according to the + * size mentioned in the protocol definition. If 0 there, then + * use a big default for compatibility + */ + n = (int)wsi->protocol->rx_buffer_size; + if (!n) + n = context->pt_serv_buf_size; + n += LWS_PRE; + wsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, + "client frame buffer"); + if (!wsi->ws->rx_ubuf) { + lwsl_err("Out of Mem allocating rx buffer %d\n", n); + *cce = "HS: OOM"; + goto bail2; + } + wsi->ws->rx_ubuf_alloc = n; + lwsl_info("Allocating client RX buffer %d\n", n); + +#if !defined(LWS_WITH_ESP32) + if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, + (const char *)&n, sizeof n)) { + lwsl_warn("Failed to set SNDBUF to %d", n); + *cce = "HS: SO_SNDBUF failed"; + goto bail3; + } +#endif + + lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); + + /* call him back to inform him he is up */ + + if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, + wsi->user_space, NULL, 0)) { + *cce = "HS: Rejected at CLIENT_ESTABLISHED"; + goto bail3; + } + + return 0; + +bail3: + return 3; + +bail2: + return 2; +} diff --git a/thirdparty/libwebsockets/roles/ws/ops-ws.c b/thirdparty/libwebsockets/roles/ws/ops-ws.c new file mode 100644 index 0000000000..5ddaba9e18 --- /dev/null +++ b/thirdparty/libwebsockets/roles/ws/ops-ws.c @@ -0,0 +1,1992 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); } + +/* + * client-parser.c: lws_ws_client_rx_sm() needs to be roughly kept in + * sync with changes here, esp related to ext draining + */ + +int +lws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c) +{ + int callback_action = LWS_CALLBACK_RECEIVE; + int ret = 0; + unsigned short close_code; + struct lws_tokens ebuf; + unsigned char *pp; + int n = 0; +#if !defined(LWS_WITHOUT_EXTENSIONS) + int rx_draining_ext = 0; + int lin; +#endif + + ebuf.token = NULL; + ebuf.len = 0; + if (wsi->socket_is_permanently_unusable) + return -1; + + switch (wsi->lws_rx_parse_state) { + case LWS_RXPS_NEW: +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { + ebuf.token = NULL; + ebuf.len = 0; + lws_remove_wsi_from_draining_ext_list(wsi); + rx_draining_ext = 1; + lwsl_debug("%s: doing draining flow\n", __func__); + + goto drain_extension; + } +#endif + switch (wsi->ws->ietf_spec_revision) { + case 13: + /* + * no prepended frame key any more + */ + wsi->ws->all_zero_nonce = 1; + goto handle_first; + + default: + lwsl_warn("lws_ws_rx_sm: unknown spec version %d\n", + wsi->ws->ietf_spec_revision); + break; + } + break; + case LWS_RXPS_04_mask_1: + wsi->ws->mask[1] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2; + break; + case LWS_RXPS_04_mask_2: + wsi->ws->mask[2] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3; + break; + case LWS_RXPS_04_mask_3: + wsi->ws->mask[3] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + + /* + * start from the zero'th byte in the XOR key buffer since + * this is the start of a frame with a new key + */ + + wsi->ws->mask_idx = 0; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1; + break; + + /* + * 04 logical framing from the spec (all this is masked when incoming + * and has to be unmasked) + * + * We ignore the possibility of extension data because we don't + * negotiate any extensions at the moment. + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-------+-+-------------+-------------------------------+ + * |F|R|R|R| opcode|R| Payload len | Extended payload length | + * |I|S|S|S| (4) |S| (7) | (16/63) | + * |N|V|V|V| |V| | (if payload len==126/127) | + * | |1|2|3| |4| | | + * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + * | Extended payload length continued, if payload len == 127 | + * + - - - - - - - - - - - - - - - +-------------------------------+ + * | | Extension data | + * +-------------------------------+ - - - - - - - - - - - - - - - + + * : : + * +---------------------------------------------------------------+ + * : Application data : + * +---------------------------------------------------------------+ + * + * We pass payload through to userland as soon as we get it, ignoring + * FIN. It's up to userland to buffer it up if it wants to see a + * whole unfragmented block of the original size (which may be up to + * 2^63 long!) + */ + + case LWS_RXPS_04_FRAME_HDR_1: +handle_first: + + wsi->ws->opcode = c & 0xf; + wsi->ws->rsv = c & 0x70; + wsi->ws->final = !!((c >> 7) & 1); + wsi->ws->defeat_check_utf8 = 0; + + if (((wsi->ws->opcode) & 8) && !wsi->ws->final) { + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, + (uint8_t *)"frag ctl", 8); + return -1; + } + + switch (wsi->ws->opcode) { + case LWSWSOPC_TEXT_FRAME: + wsi->ws->check_utf8 = lws_check_opt( + wsi->context->options, + LWS_SERVER_OPTION_VALIDATE_UTF8); + /* fallthru */ + case LWSWSOPC_BINARY_FRAME: + if (wsi->ws->opcode == LWSWSOPC_BINARY_FRAME) + wsi->ws->check_utf8 = 0; + if (wsi->ws->continuation_possible) { + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad cont", 8); + return -1; + } + wsi->ws->rsv_first_msg = (c & 0x70); + wsi->ws->frame_is_binary = + wsi->ws->opcode == LWSWSOPC_BINARY_FRAME; + wsi->ws->first_fragment = 1; + wsi->ws->continuation_possible = !wsi->ws->final; + break; + case LWSWSOPC_CONTINUATION: + if (!wsi->ws->continuation_possible) { + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad cont", 8); + return -1; + } + break; + case LWSWSOPC_CLOSE: + wsi->ws->check_utf8 = 0; + wsi->ws->utf8 = 0; + break; + case 3: + case 4: + case 5: + case 6: + case 7: + case 0xb: + case 0xc: + case 0xd: + case 0xe: + case 0xf: + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad opc", 7); + lwsl_info("illegal opcode\n"); + return -1; + } + + if (wsi->ws->owed_a_fin && + (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME || + wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) { + lwsl_info("hey you owed us a FIN\n"); + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, (uint8_t *)"bad fin", 7); + return -1; + } + if ((!(wsi->ws->opcode & 8)) && wsi->ws->final) { + wsi->ws->continuation_possible = 0; + wsi->ws->owed_a_fin = 0; + } + + if (!wsi->ws->final) + wsi->ws->owed_a_fin = 1; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN; + if (wsi->ws->rsv && + ( +#if !defined(LWS_WITHOUT_EXTENSIONS) + !wsi->ws->count_act_ext || +#endif + (wsi->ws->rsv & ~0x40))) { + lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR, + (uint8_t *)"rsv bits", 8); + return -1; + } + break; + + case LWS_RXPS_04_FRAME_HDR_LEN: + + wsi->ws->this_frame_masked = !!(c & 0x80); + + switch (c & 0x7f) { + case 126: + /* control frames are not allowed to have big lengths */ + if (wsi->ws->opcode & 8) + goto illegal_ctl_length; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2; + break; + case 127: + /* control frames are not allowed to have big lengths */ + if (wsi->ws->opcode & 8) + goto illegal_ctl_length; + + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8; + break; + default: + wsi->ws->rx_packet_length = c & 0x7f; + + + if (wsi->ws->this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else + if (wsi->ws->rx_packet_length) { + wsi->lws_rx_parse_state = + LWS_RXPS_WS_FRAME_PAYLOAD; + } else { + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } + break; + } + break; + + case LWS_RXPS_04_FRAME_HDR_LEN16_2: + wsi->ws->rx_packet_length = c << 8; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN16_1: + wsi->ws->rx_packet_length |= c; + if (wsi->ws->this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else { + wsi->lws_rx_parse_state = + LWS_RXPS_WS_FRAME_PAYLOAD; + } + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_8: + if (c & 0x80) { + lwsl_warn("b63 of length must be zero\n"); + /* kill the connection */ + return -1; + } +#if defined __LP64__ + wsi->ws->rx_packet_length = ((size_t)c) << 56; +#else + wsi->ws->rx_packet_length = 0; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_7: +#if defined __LP64__ + wsi->ws->rx_packet_length |= ((size_t)c) << 48; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_6: +#if defined __LP64__ + wsi->ws->rx_packet_length |= ((size_t)c) << 40; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_5: +#if defined __LP64__ + wsi->ws->rx_packet_length |= ((size_t)c) << 32; +#endif + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_4: + wsi->ws->rx_packet_length |= ((size_t)c) << 24; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_3: + wsi->ws->rx_packet_length |= ((size_t)c) << 16; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_2: + wsi->ws->rx_packet_length |= ((size_t)c) << 8; + wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1; + break; + + case LWS_RXPS_04_FRAME_HDR_LEN64_1: + wsi->ws->rx_packet_length |= ((size_t)c); + if (wsi->ws->this_frame_masked) + wsi->lws_rx_parse_state = + LWS_RXPS_07_COLLECT_FRAME_KEY_1; + else + wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_1: + wsi->ws->mask[0] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_2: + wsi->ws->mask[1] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_3: + wsi->ws->mask[2] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4; + break; + + case LWS_RXPS_07_COLLECT_FRAME_KEY_4: + wsi->ws->mask[3] = c; + if (c) + wsi->ws->all_zero_nonce = 0; + wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD; + wsi->ws->mask_idx = 0; + if (wsi->ws->rx_packet_length == 0) { + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } + break; + + + case LWS_RXPS_WS_FRAME_PAYLOAD: + assert(wsi->ws->rx_ubuf); + + if (wsi->ws->rx_ubuf_head + LWS_PRE >= wsi->ws->rx_ubuf_alloc) { + lwsl_err("Attempted overflow \n"); + return -1; + } + if (!(already_processed & ALREADY_PROCESSED_IGNORE_CHAR)) { + if (wsi->ws->all_zero_nonce) + wsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] = + c; + else + wsi->ws->rx_ubuf[LWS_PRE + (wsi->ws->rx_ubuf_head++)] = + c ^ wsi->ws->mask[(wsi->ws->mask_idx++) & 3]; + + --wsi->ws->rx_packet_length; + } + + if (!wsi->ws->rx_packet_length) { + lwsl_debug("%s: ws fragment length exhausted\n", __func__); + /* spill because we have the whole frame */ + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + goto spill; + } +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { + lwsl_debug("%s: UNTIL_EXHAUSTED draining\n", __func__); + goto drain_extension; + } +#endif + /* + * if there's no protocol max frame size given, we are + * supposed to default to context->pt_serv_buf_size + */ + if (!wsi->protocol->rx_buffer_size && + wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size) + break; + + if (wsi->protocol->rx_buffer_size && + wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size) + break; + + /* spill because we filled our rx buffer */ +spill: + /* + * is this frame a control packet we should take care of at this + * layer? If so service it and hide it from the user callback + */ + + lwsl_parser("spill on %s\n", wsi->protocol->name); + + switch (wsi->ws->opcode) { + case LWSWSOPC_CLOSE: + + if (wsi->ws->peer_has_sent_close) + break; + + wsi->ws->peer_has_sent_close = 1; + + pp = (unsigned char *)&wsi->ws->rx_ubuf[LWS_PRE]; + if (lws_check_opt(wsi->context->options, + LWS_SERVER_OPTION_VALIDATE_UTF8) && + wsi->ws->rx_ubuf_head > 2 && + lws_check_utf8(&wsi->ws->utf8, pp + 2, + wsi->ws->rx_ubuf_head - 2)) + goto utf8_fail; + + /* is this an acknowledgment of our close? */ + if (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) { + /* + * fine he has told us he is closing too, let's + * finish our close + */ + lwsl_parser("seen client close ack\n"); + return -1; + } + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE) + /* if he sends us 2 CLOSE, kill him */ + return -1; + + if (lws_partial_buffered(wsi)) { + /* + * if we're in the middle of something, + * we can't do a normal close response and + * have to just close our end. + */ + wsi->socket_is_permanently_unusable = 1; + lwsl_parser("Closing on peer close due to Pending tx\n"); + return -1; + } + + if (wsi->ws->rx_ubuf_head >= 2) { + close_code = (pp[0] << 8) | pp[1]; + if (close_code < 1000 || + close_code == 1004 || + close_code == 1005 || + close_code == 1006 || + close_code == 1012 || + close_code == 1013 || + close_code == 1014 || + close_code == 1015 || + (close_code >= 1016 && close_code < 3000) + ) { + pp[0] = (LWS_CLOSE_STATUS_PROTOCOL_ERR >> 8) & 0xff; + pp[1] = LWS_CLOSE_STATUS_PROTOCOL_ERR & 0xff; + } + } + + if (user_callback_handle_rxflow( + wsi->protocol->callback, wsi, + LWS_CALLBACK_WS_PEER_INITIATED_CLOSE, + wsi->user_space, + &wsi->ws->rx_ubuf[LWS_PRE], + wsi->ws->rx_ubuf_head)) + return -1; + + lwsl_parser("server sees client close packet\n"); + lwsi_set_state(wsi, LRS_RETURNED_CLOSE); + /* deal with the close packet contents as a PONG */ + wsi->ws->payload_is_close = 1; + goto process_as_ping; + + case LWSWSOPC_PING: + lwsl_info("received %d byte ping, sending pong\n", + wsi->ws->rx_ubuf_head); + + if (wsi->ws->ping_pending_flag) { + /* + * there is already a pending ping payload + * we should just log and drop + */ + lwsl_parser("DROP PING since one pending\n"); + goto ping_drop; + } +process_as_ping: + /* control packets can only be < 128 bytes long */ + if (wsi->ws->rx_ubuf_head > 128 - 3) { + lwsl_parser("DROP PING payload too large\n"); + goto ping_drop; + } + + /* stash the pong payload */ + memcpy(wsi->ws->ping_payload_buf + LWS_PRE, + &wsi->ws->rx_ubuf[LWS_PRE], + wsi->ws->rx_ubuf_head); + + wsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head; + wsi->ws->ping_pending_flag = 1; + + /* get it sent as soon as possible */ + lws_callback_on_writable(wsi); +ping_drop: + wsi->ws->rx_ubuf_head = 0; + return 0; + + case LWSWSOPC_PONG: + lwsl_info("received pong\n"); + lwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE], + wsi->ws->rx_ubuf_head); + + if (wsi->pending_timeout == + PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) { + lwsl_info("received expected PONG on wsi %p\n", + wsi); + lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); + } + + /* issue it */ + callback_action = LWS_CALLBACK_RECEIVE_PONG; + break; + + case LWSWSOPC_TEXT_FRAME: + case LWSWSOPC_BINARY_FRAME: + case LWSWSOPC_CONTINUATION: + break; + + default: + lwsl_parser("unknown opc %x\n", wsi->ws->opcode); + + return -1; + } + + /* + * No it's real payload, pass it up to the user callback. + * It's nicely buffered with the pre-padding taken care of + * so it can be sent straight out again using lws_write + */ + + ebuf.token = &wsi->ws->rx_ubuf[LWS_PRE]; + ebuf.len = wsi->ws->rx_ubuf_head; + + if (wsi->ws->opcode == LWSWSOPC_PONG && !ebuf.len) + goto already_done; +#if !defined(LWS_WITHOUT_EXTENSIONS) +drain_extension: +#endif + // lwsl_notice("%s: passing %d to ext\n", __func__, ebuf.len); + + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE || + lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) + goto already_done; +#if !defined(LWS_WITHOUT_EXTENSIONS) + lin = ebuf.len; + //if (lin) + // lwsl_hexdump_notice(ebuf.token, ebuf.len); + n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0); + lwsl_debug("%s: ext says %d / ebuf.len %d\n", __func__, n, ebuf.len); + if (wsi->ws->rx_draining_ext) + already_processed &= ~ALREADY_PROCESSED_NO_CB; +#endif + /* + * ebuf may be pointing somewhere completely different now, + * it's the output + */ +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (n < 0) { + /* + * we may rely on this to get RX, just drop connection + */ + wsi->socket_is_permanently_unusable = 1; + return -1; + } +#endif + if ( +#if !defined(LWS_WITHOUT_EXTENSIONS) + rx_draining_ext && +#endif + ebuf.len == 0) + goto already_done; + + if ( +#if !defined(LWS_WITHOUT_EXTENSIONS) + n && +#endif + ebuf.len) + /* extension had more... main loop will come back */ + lws_add_wsi_to_draining_ext_list(wsi); + else + lws_remove_wsi_from_draining_ext_list(wsi); + + if (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) { + if (lws_check_utf8(&wsi->ws->utf8, + (unsigned char *)ebuf.token, + ebuf.len)) { + lws_close_reason(wsi, + LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"bad utf8", 8); + goto utf8_fail; + } + + /* we are ending partway through utf-8 character? */ + if (!wsi->ws->rx_packet_length && wsi->ws->final && + wsi->ws->utf8 && !n) { + lwsl_info("FINAL utf8 error\n"); + lws_close_reason(wsi, + LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"partial utf8", 12); +utf8_fail: + lwsl_notice("utf8 error\n"); + lwsl_hexdump_notice(ebuf.token, ebuf.len); + + return -1; + } + } + + if (!wsi->wsistate_pre_close && (ebuf.len >= 0 || + callback_action == LWS_CALLBACK_RECEIVE_PONG)) { + if (ebuf.len) + ebuf.token[ebuf.len] = '\0'; + + if (wsi->protocol->callback && + !(already_processed & ALREADY_PROCESSED_NO_CB)) { + if (callback_action == LWS_CALLBACK_RECEIVE_PONG) + lwsl_info("Doing pong callback\n"); + + ret = user_callback_handle_rxflow( + wsi->protocol->callback, + wsi, (enum lws_callback_reasons) + callback_action, + wsi->user_space, + ebuf.token, + ebuf.len); + } + wsi->ws->first_fragment = 0; + } + +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (!lin) + break; +#endif + +already_done: + wsi->ws->rx_ubuf_head = 0; + break; + } + + return ret; + +illegal_ctl_length: + + lwsl_warn("Control frame with xtended length is illegal\n"); + /* kill the connection */ + return -1; +} + + +LWS_VISIBLE size_t +lws_remaining_packet_payload(struct lws *wsi) +{ + return wsi->ws->rx_packet_length; +} + +LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi) +{ + return wsi->ws->frame_is_binary; +} + +void +lws_add_wsi_to_draining_ext_list(struct lws *wsi) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + if (wsi->ws->rx_draining_ext) + return; + + lwsl_debug("%s: RX EXT DRAINING: Adding to list\n", __func__); + + wsi->ws->rx_draining_ext = 1; + wsi->ws->rx_draining_ext_list = pt->ws.rx_draining_ext_list; + pt->ws.rx_draining_ext_list = wsi; +#endif +} + +void +lws_remove_wsi_from_draining_ext_list(struct lws *wsi) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + struct lws **w = &pt->ws.rx_draining_ext_list; + + if (!wsi->ws->rx_draining_ext) + return; + + lwsl_debug("%s: RX EXT DRAINING: Removing from list\n", __func__); + + wsi->ws->rx_draining_ext = 0; + + /* remove us from context draining ext list */ + while (*w) { + if (*w == wsi) { + /* if us, point it instead to who we were pointing to */ + *w = wsi->ws->rx_draining_ext_list; + break; + } + w = &((*w)->ws->rx_draining_ext_list); + } + wsi->ws->rx_draining_ext_list = NULL; +#endif +} + +LWS_EXTERN void +lws_restart_ws_ping_pong_timer(struct lws *wsi) +{ + if (!wsi->context->ws_ping_pong_interval || + !lwsi_role_ws(wsi)) + return; + + wsi->ws->time_next_ping_check = (time_t)lws_now_secs(); +} + +static int +lws_0405_frame_mask_generate(struct lws *wsi) +{ + int n; + /* fetch the per-frame nonce */ + + n = lws_get_random(lws_get_context(wsi), wsi->ws->mask, 4); + if (n != 4) { + lwsl_parser("Unable to read from random device %s %d\n", + SYSTEM_RANDOM_FILEPATH, n); + return 1; + } + + /* start masking from first byte of masking key buffer */ + wsi->ws->mask_idx = 0; + + return 0; +} + +int +lws_server_init_wsi_for_ws(struct lws *wsi) +{ + int n; + + lwsi_set_state(wsi, LRS_ESTABLISHED); + lws_restart_ws_ping_pong_timer(wsi); + + /* + * create the frame buffer for this connection according to the + * size mentioned in the protocol definition. If 0 there, use + * a big default for compatibility + */ + + n = (int)wsi->protocol->rx_buffer_size; + if (!n) + n = wsi->context->pt_serv_buf_size; + n += LWS_PRE; + wsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, "rx_ubuf"); + if (!wsi->ws->rx_ubuf) { + lwsl_err("Out of Mem allocating rx buffer %d\n", n); + return 1; + } + wsi->ws->rx_ubuf_alloc = n; + lwsl_debug("Allocating RX buffer %d\n", n); + +#if !defined(LWS_WITH_ESP32) + if (!wsi->parent_carries_io && + !wsi->h2_stream_carries_ws) + if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, + (const char *)&n, sizeof n)) { + lwsl_warn("Failed to set SNDBUF to %d", n); + return 1; + } +#endif + + /* notify user code that we're ready to roll */ + + if (wsi->protocol->callback) + if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED, + wsi->user_space, +#ifdef LWS_WITH_TLS + wsi->tls.ssl, +#else + NULL, +#endif + wsi->h2_stream_carries_ws)) + return 1; + + lwsl_debug("ws established\n"); + + return 0; +} + + + +LWS_VISIBLE int +lws_is_final_fragment(struct lws *wsi) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + lwsl_debug("%s: final %d, rx pk length %ld, draining %ld\n", __func__, + wsi->ws->final, (long)wsi->ws->rx_packet_length, + (long)wsi->ws->rx_draining_ext); + return wsi->ws->final && !wsi->ws->rx_packet_length && + !wsi->ws->rx_draining_ext; +#else + return wsi->ws->final && !wsi->ws->rx_packet_length; +#endif +} + +LWS_VISIBLE int +lws_is_first_fragment(struct lws *wsi) +{ + return wsi->ws->first_fragment; +} + +LWS_VISIBLE unsigned char +lws_get_reserved_bits(struct lws *wsi) +{ + return wsi->ws->rsv; +} + +LWS_VISIBLE LWS_EXTERN int +lws_get_close_length(struct lws *wsi) +{ + return wsi->ws->close_in_ping_buffer_len; +} + +LWS_VISIBLE LWS_EXTERN unsigned char * +lws_get_close_payload(struct lws *wsi) +{ + return &wsi->ws->ping_payload_buf[LWS_PRE]; +} + +LWS_VISIBLE LWS_EXTERN void +lws_close_reason(struct lws *wsi, enum lws_close_status status, + unsigned char *buf, size_t len) +{ + unsigned char *p, *start; + int budget = sizeof(wsi->ws->ping_payload_buf) - LWS_PRE; + + assert(lwsi_role_ws(wsi)); + + start = p = &wsi->ws->ping_payload_buf[LWS_PRE]; + + *p++ = (((int)status) >> 8) & 0xff; + *p++ = ((int)status) & 0xff; + + if (buf) + while (len-- && p < start + budget) + *p++ = *buf++; + + wsi->ws->close_in_ping_buffer_len = lws_ptr_diff(p, start); +} + +static int +lws_is_ws_with_ext(struct lws *wsi) +{ +#if defined(LWS_WITHOUT_EXTENSIONS) + return 0; +#else + return lwsi_role_ws(wsi) && !!wsi->ws->count_act_ext; +#endif +} + +static int +rops_handle_POLLIN_ws(struct lws_context_per_thread *pt, struct lws *wsi, + struct lws_pollfd *pollfd) +{ + struct lws_tokens ebuf; + unsigned int pending = 0; + char buffered = 0; + int n = 0, m; +#if defined(LWS_WITH_HTTP2) + struct lws *wsi1; +#endif + + if (!wsi->ws) { + lwsl_err("ws role wsi with no ws\n"); + return 1; + } + + // lwsl_notice("%s: %s\n", __func__, wsi->protocol->name); + + //lwsl_info("%s: wsistate 0x%x, pollout %d\n", __func__, + // wsi->wsistate, pollfd->revents & LWS_POLLOUT); + + /* + * something went wrong with parsing the handshake, and + * we ended up back in the event loop without completing it + */ + if (lwsi_state(wsi) == LRS_PRE_WS_SERVING_ACCEPT) { + wsi->socket_is_permanently_unusable = 1; + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + ebuf.token = NULL; + ebuf.len = 0; + + if (lwsi_state(wsi) == LRS_WAITING_CONNECT) { +#if !defined(LWS_NO_CLIENT) + if ((pollfd->revents & LWS_POLLOUT) && + lws_handle_POLLOUT_event(wsi, pollfd)) { + lwsl_debug("POLLOUT event closed it\n"); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + n = lws_client_socket_service(wsi, pollfd, NULL); + if (n) + return LWS_HPI_RET_WSI_ALREADY_DIED; +#endif + return LWS_HPI_RET_HANDLED; + } + + //lwsl_notice("%s: wsi->ws->tx_draining_ext %d revents 0x%x 0x%x %d\n", __func__, wsi->ws->tx_draining_ext, pollfd->revents, wsi->wsistate, lwsi_state_can_handle_POLLOUT(wsi)); + + /* 1: something requested a callback when it was OK to write */ + + if ((pollfd->revents & LWS_POLLOUT) && + lwsi_state_can_handle_POLLOUT(wsi) && + lws_handle_POLLOUT_event(wsi, pollfd)) { + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE) + lwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE); + + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE || + lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) { + /* + * we stopped caring about anything except control + * packets. Force flow control off, defeat tx + * draining. + */ + lws_rx_flow_control(wsi, 1); +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws) + wsi->ws->tx_draining_ext = 0; +#endif + } +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->tx_draining_ext) + /* + * We cannot deal with new RX until the TX ext path has + * been drained. It's because new rx will, eg, crap on + * the wsi rx buf that may be needed to retain state. + * + * TX ext drain path MUST go through event loop to avoid + * blocking. + */ + return LWS_HPI_RET_HANDLED; +#endif + if (lws_is_flowcontrolled(wsi)) { + /* We cannot deal with any kind of new RX because we are + * RX-flowcontrolled. + */ + lwsl_info("flowcontrolled\n"); + return LWS_HPI_RET_HANDLED; + } + +#if defined(LWS_WITH_HTTP2) + if (wsi->http2_substream || wsi->upgraded_to_http2) { + wsi1 = lws_get_network_wsi(wsi); + if (wsi1 && wsi1->trunc_len) + /* We cannot deal with any kind of new RX + * because we are dealing with a partial send + * (new RX may trigger new http_action() that + * expect to be able to send) + */ + return LWS_HPI_RET_HANDLED; + } +#endif + +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* 2: RX Extension needs to be drained + */ + + if (wsi->ws->rx_draining_ext) { + + lwsl_debug("%s: RX EXT DRAINING: Service\n", __func__); +#ifndef LWS_NO_CLIENT + if (lwsi_role_client(wsi)) { + n = lws_ws_client_rx_sm(wsi, 0); + if (n < 0) + /* we closed wsi */ + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } else +#endif + n = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0); + + return LWS_HPI_RET_HANDLED; + } + + if (wsi->ws->rx_draining_ext) + /* + * We have RX EXT content to drain, but can't do it + * right now. That means we cannot do anything lower + * priority either. + */ + return LWS_HPI_RET_HANDLED; +#endif + + /* 3: buflist needs to be drained + */ +read: + //lws_buflist_describe(&wsi->buflist, wsi); + ebuf.len = (int)lws_buflist_next_segment_len(&wsi->buflist, + (uint8_t **)&ebuf.token); + if (ebuf.len) { + lwsl_info("draining buflist (len %d)\n", ebuf.len); + buffered = 1; + goto drain; + } + + if (!(pollfd->revents & pollfd->events & LWS_POLLIN) && !wsi->http.ah) + return LWS_HPI_RET_HANDLED; + + if (lws_is_flowcontrolled(wsi)) { + lwsl_info("%s: %p should be rxflow (bm 0x%x)..\n", + __func__, wsi, wsi->rxflow_bitmap); + return LWS_HPI_RET_HANDLED; + } + + if (!(lwsi_role_client(wsi) && + (lwsi_state(wsi) != LRS_ESTABLISHED && + lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK && + lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS))) { + /* + * In case we are going to react to this rx by scheduling + * writes, we need to restrict the amount of rx to the size + * the protocol reported for rx buffer. + * + * Otherwise we get a situation we have to absorb possibly a + * lot of reads before we get a chance to drain them by writing + * them, eg, with echo type tests in autobahn. + */ + + buffered = 0; + ebuf.token = (char *)pt->serv_buf; + if (lwsi_role_ws(wsi)) + ebuf.len = wsi->ws->rx_ubuf_alloc; + else + ebuf.len = wsi->context->pt_serv_buf_size; + + if ((unsigned int)ebuf.len > wsi->context->pt_serv_buf_size) + ebuf.len = wsi->context->pt_serv_buf_size; + + if ((int)pending > ebuf.len) + pending = ebuf.len; + + ebuf.len = lws_ssl_capable_read(wsi, (uint8_t *)ebuf.token, + pending ? (int)pending : + ebuf.len); + switch (ebuf.len) { + case 0: + lwsl_info("%s: zero length read\n", + __func__); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + case LWS_SSL_CAPABLE_MORE_SERVICE: + lwsl_info("SSL Capable more service\n"); + return LWS_HPI_RET_HANDLED; + case LWS_SSL_CAPABLE_ERROR: + lwsl_info("%s: LWS_SSL_CAPABLE_ERROR\n", + __func__); + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + // lwsl_notice("Actual RX %d\n", ebuf.len); + + lws_restart_ws_ping_pong_timer(wsi); + + /* + * coverity thinks ssl_capable_read() may read over + * 2GB. Dissuade it... + */ + ebuf.len &= 0x7fffffff; + } + +drain: + + /* + * give any active extensions a chance to munge the buffer + * before parse. We pass in a pointer to an lws_tokens struct + * prepared with the default buffer and content length that's in + * there. Rather than rewrite the default buffer, extensions + * that expect to grow the buffer can adapt .token to + * point to their own per-connection buffer in the extension + * user allocation. By default with no extensions or no + * extension callback handling, just the normal input buffer is + * used then so it is efficient. + */ + m = 0; + do { + + /* service incoming data */ + //lws_buflist_describe(&wsi->buflist, wsi); + if (ebuf.len) { +#if defined(LWS_ROLE_H2) + if (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY) + n = lws_read_h2(wsi, (unsigned char *)ebuf.token, + ebuf.len); + else +#endif + n = lws_read_h1(wsi, (unsigned char *)ebuf.token, + ebuf.len); + + if (n < 0) { + /* we closed wsi */ + n = 0; + return LWS_HPI_RET_WSI_ALREADY_DIED; + } + //lws_buflist_describe(&wsi->buflist, wsi); + //lwsl_notice("%s: consuming %d / %d\n", __func__, n, ebuf.len); + if (lws_buflist_aware_consume(wsi, &ebuf, n, buffered)) + return LWS_HPI_RET_PLEASE_CLOSE_ME; + } + + ebuf.token = NULL; + ebuf.len = 0; + } while (m); + + if (wsi->http.ah +#if !defined(LWS_NO_CLIENT) + && !wsi->client_h2_alpn +#endif + ) { + lwsl_info("%s: %p: detaching ah\n", __func__, wsi); + lws_header_table_detach(wsi, 0); + } + + pending = lws_ssl_pending(wsi); + if (pending) { + if (lws_is_ws_with_ext(wsi)) + pending = pending > wsi->ws->rx_ubuf_alloc ? + wsi->ws->rx_ubuf_alloc : pending; + else + pending = pending > wsi->context->pt_serv_buf_size ? + wsi->context->pt_serv_buf_size : pending; + goto read; + } + + if (buffered && /* were draining, now nothing left */ + !lws_buflist_next_segment_len(&wsi->buflist, NULL)) { + lwsl_info("%s: %p flow buf: drained\n", __func__, wsi); + /* having drained the rxflow buffer, can rearm POLLIN */ +#ifdef LWS_NO_SERVER + n = +#endif + __lws_rx_flow_control(wsi); + /* n ignored, needed for NO_SERVER case */ + } + + /* n = 0 */ + return LWS_HPI_RET_HANDLED; +} + + +int rops_handle_POLLOUT_ws(struct lws *wsi) +{ + int write_type = LWS_WRITE_PONG; +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_tokens ebuf; + int ret, m; +#endif + int n; + +#if !defined(LWS_WITHOUT_EXTENSIONS) + lwsl_debug("%s: %s: wsi->ws->tx_draining_ext %d\n", __func__, + wsi->protocol->name, wsi->ws->tx_draining_ext); +#endif + + /* Priority 3: pending control packets (pong or close) + * + * 3a: close notification packet requested from close api + */ + + if (lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) { + lwsl_debug("sending close packet\n"); + lwsl_hexdump_debug(&wsi->ws->ping_payload_buf[LWS_PRE], + wsi->ws->close_in_ping_buffer_len); + wsi->waiting_to_send_close_frame = 0; + n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE], + wsi->ws->close_in_ping_buffer_len, + LWS_WRITE_CLOSE); + if (n >= 0) { + if (wsi->close_needs_ack) { + lwsi_set_state(wsi, LRS_AWAITING_CLOSE_ACK); + lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 5); + lwsl_debug("sent close indication, awaiting ack\n"); + + return LWS_HP_RET_BAIL_OK; + } + wsi->close_needs_ack = 0; + lwsi_set_state(wsi, LRS_RETURNED_CLOSE); + } + + return LWS_HP_RET_BAIL_DIE; + } + + /* else, the send failed and we should just hang up */ + + if ((lwsi_role_ws(wsi) && wsi->ws->ping_pending_flag) || + (lwsi_state(wsi) == LRS_RETURNED_CLOSE && + wsi->ws->payload_is_close)) { + + if (wsi->ws->payload_is_close) + write_type = LWS_WRITE_CLOSE; + else { + if (wsi->wsistate_pre_close) { + /* we started close flow, forget pong */ + wsi->ws->ping_pending_flag = 0; + return LWS_HP_RET_BAIL_OK; + } + lwsl_info("issuing pong %d on wsi %p\n", wsi->ws->ping_payload_len, wsi); + } + + n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE], + wsi->ws->ping_payload_len, write_type); + if (n < 0) + return LWS_HP_RET_BAIL_DIE; + + /* well he is sent, mark him done */ + wsi->ws->ping_pending_flag = 0; + if (wsi->ws->payload_is_close) { + // assert(0); + /* oh... a close frame was it... then we are done */ + return LWS_HP_RET_BAIL_DIE; + } + + /* otherwise for PING, leave POLLOUT active either way */ + return LWS_HP_RET_BAIL_OK; + } + + if (lwsi_role_client(wsi) && !wsi->socket_is_permanently_unusable && + wsi->ws->send_check_ping) { + + lwsl_info("issuing ping on wsi %p\n", wsi); + wsi->ws->send_check_ping = 0; + n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE], + 0, LWS_WRITE_PING); + if (n < 0) + return LWS_HP_RET_BAIL_DIE; + + /* + * we apparently were able to send the PING in a reasonable time + * now reset the clock on our peer to be able to send the + * PONG in a reasonable time. + */ + + lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG, + wsi->context->timeout_secs); + + return LWS_HP_RET_BAIL_OK; + } + + /* Priority 4: if we are closing, not allowed to send more data frags + * which means user callback or tx ext flush banned now + */ + if (lwsi_state(wsi) == LRS_RETURNED_CLOSE) + return LWS_HP_RET_USER_SERVICE; + +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* Priority 5: Tx path extension with more to send + * + * These are handled as new fragments each time around + * So while we must block new writeable callback to enforce + * payload ordering, but since they are always complete + * fragments control packets can interleave OK. + */ + if (lwsi_role_client(wsi) && wsi->ws->tx_draining_ext) { + lwsl_ext("SERVICING TX EXT DRAINING\n"); + if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0) + return LWS_HP_RET_BAIL_DIE; + /* leave POLLOUT active */ + return LWS_HP_RET_BAIL_OK; + } + + /* Priority 6: extensions + */ + if (!wsi->ws->extension_data_pending) + return LWS_HP_RET_USER_SERVICE; + + /* + * check in on the active extensions, see if they + * had pending stuff to spill... they need to get the + * first look-in otherwise sequence will be disordered + * + * NULL, zero-length ebuf means just spill pending + */ + + ret = 1; + if (wsi->role_ops == &role_ops_raw_skt || + wsi->role_ops == &role_ops_raw_file) + ret = 0; + + while (ret == 1) { + + /* default to nobody has more to spill */ + + ret = 0; + ebuf.token = NULL; + ebuf.len = 0; + + /* give every extension a chance to spill */ + + m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND, + &ebuf, 0); + if (m < 0) { + lwsl_err("ext reports fatal error\n"); + return LWS_HP_RET_BAIL_DIE; + } + if (m) + /* + * at least one extension told us he has more + * to spill, so we will go around again after + */ + ret = 1; + + /* assuming they gave us something to send, send it */ + + if (ebuf.len) { + n = lws_issue_raw(wsi, (unsigned char *)ebuf.token, + ebuf.len); + if (n < 0) { + lwsl_info("closing from POLLOUT spill\n"); + return LWS_HP_RET_BAIL_DIE; + } + /* + * Keep amount spilled small to minimize chance of this + */ + if (n != ebuf.len) { + lwsl_err("Unable to spill ext %d vs %d\n", + ebuf.len, n); + return LWS_HP_RET_BAIL_DIE; + } + } else + continue; + + /* no extension has more to spill */ + + if (!ret) + continue; + + /* + * There's more to spill from an extension, but we just sent + * something... did that leave the pipe choked? + */ + + if (!lws_send_pipe_choked(wsi)) + /* no we could add more */ + continue; + + lwsl_info("choked in POLLOUT service\n"); + + /* + * Yes, he's choked. Leave the POLLOUT masked on so we will + * come back here when he is unchoked. Don't call the user + * callback to enforce ordering of spilling, he'll get called + * when we come back here and there's nothing more to spill. + */ + + return LWS_HP_RET_BAIL_OK; + } + + wsi->ws->extension_data_pending = 0; +#endif + + return LWS_HP_RET_USER_SERVICE; +} + +static int +rops_periodic_checks_ws(struct lws_context *context, int tsi, time_t now) +{ + struct lws_vhost *vh; + + if (!context->ws_ping_pong_interval || + context->last_ws_ping_pong_check_s >= now + 10) + return 0; + + vh = context->vhost_list; + context->last_ws_ping_pong_check_s = now; + + while (vh) { + int n; + + lws_vhost_lock(vh); + + for (n = 0; n < vh->count_protocols; n++) { + struct lws *wsi = vh->same_vh_protocol_list[n]; + + while (wsi) { + if (lwsi_role_ws(wsi) && + !wsi->socket_is_permanently_unusable && + !wsi->ws->send_check_ping && + wsi->ws->time_next_ping_check && + lws_compare_time_t(context, now, + wsi->ws->time_next_ping_check) > + context->ws_ping_pong_interval) { + + lwsl_info("req pp on wsi %p\n", + wsi); + wsi->ws->send_check_ping = 1; + lws_set_timeout(wsi, + PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING, + context->timeout_secs); + lws_callback_on_writable(wsi); + wsi->ws->time_next_ping_check = + now; + } + wsi = wsi->same_vh_protocol_next; + } + } + + lws_vhost_unlock(vh); + vh = vh->vhost_next; + } + + return 0; +} + +static int +rops_service_flag_pending_ws(struct lws_context *context, int tsi) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_context_per_thread *pt = &context->pt[tsi]; + struct lws *wsi; + int forced = 0; + + /* POLLIN faking (the pt lock is taken by the parent) */ + + /* + * 1) For all guys with already-available ext data to drain, if they are + * not flowcontrolled, fake their POLLIN status + */ + wsi = pt->ws.rx_draining_ext_list; + while (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) { + pt->fds[wsi->position_in_fds_table].revents |= + pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; + if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) + forced = 1; + + wsi = wsi->ws->rx_draining_ext_list; + } + + return forced; +#else + return 0; +#endif +} + +static int +rops_close_via_role_protocol_ws(struct lws *wsi, enum lws_close_status reason) +{ + if (!wsi->ws->close_in_ping_buffer_len && /* already a reason */ + (reason == LWS_CLOSE_STATUS_NOSTATUS || + reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY)) + return 0; + + lwsl_debug("%s: sending close indication...\n", __func__); + + /* if no prepared close reason, use 1000 and no aux data */ + + if (!wsi->ws->close_in_ping_buffer_len) { + wsi->ws->close_in_ping_buffer_len = 2; + wsi->ws->ping_payload_buf[LWS_PRE] = (reason >> 8) & 0xff; + wsi->ws->ping_payload_buf[LWS_PRE + 1] = reason & 0xff; + } + + wsi->waiting_to_send_close_frame = 1; + wsi->close_needs_ack = 1; + lwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE); + __lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 5); + + lws_callback_on_writable(wsi); + + return 1; +} + +static int +rops_close_role_ws(struct lws_context_per_thread *pt, struct lws *wsi) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { + struct lws **w = &pt->ws.rx_draining_ext_list; + + wsi->ws->rx_draining_ext = 0; + /* remove us from context draining ext list */ + while (*w) { + if (*w == wsi) { + *w = wsi->ws->rx_draining_ext_list; + break; + } + w = &((*w)->ws->rx_draining_ext_list); + } + wsi->ws->rx_draining_ext_list = NULL; + } + + if (wsi->ws->tx_draining_ext) { + struct lws **w = &pt->ws.tx_draining_ext_list; + lwsl_notice("%s: CLEARING tx_draining_ext\n", __func__); + wsi->ws->tx_draining_ext = 0; + /* remove us from context draining ext list */ + while (*w) { + if (*w == wsi) { + *w = wsi->ws->tx_draining_ext_list; + break; + } + w = &((*w)->ws->tx_draining_ext_list); + } + wsi->ws->tx_draining_ext_list = NULL; + } +#endif + lws_free_set_NULL(wsi->ws->rx_ubuf); + + if (wsi->trunc_alloc) + /* not going to be completed... nuke it */ + lws_free_set_NULL(wsi->trunc_alloc); + + wsi->ws->ping_payload_len = 0; + wsi->ws->ping_pending_flag = 0; + + /* deallocate any active extension contexts */ + + if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0) + lwsl_warn("extension destruction failed\n"); + + return 0; +} + +static int +rops_write_role_protocol_ws(struct lws *wsi, unsigned char *buf, size_t len, + enum lws_write_protocol *wp) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + enum lws_write_protocol wpt; +#endif + int masked7 = lwsi_role_client(wsi); + unsigned char is_masked_bit = 0; + unsigned char *dropmask = NULL; + struct lws_tokens ebuf; + size_t orig_len = len; + int pre = 0, n = 0; + + // lwsl_err("%s: wp 0x%x len %d\n", __func__, *wp, (int)len); +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->tx_draining_ext) { + /* remove us from the list */ + struct lws **w = &pt->ws.tx_draining_ext_list; + + lwsl_notice("%s: CLEARING tx_draining_ext\n", __func__); + wsi->ws->tx_draining_ext = 0; + /* remove us from context draining ext list */ + while (*w) { + if (*w == wsi) { + *w = wsi->ws->tx_draining_ext_list; + break; + } + w = &((*w)->ws->tx_draining_ext_list); + } + wsi->ws->tx_draining_ext_list = NULL; + + wpt = *wp; + *wp = (wsi->ws->tx_draining_stashed_wp & 0xc0)| + LWS_WRITE_CONTINUATION; + + /* + * When we are just flushing (len == 0), we can trust the + * stashed wp info completely. Otherwise adjust it to the + * FIN status of the incoming packet. + */ + + if (!(wpt & LWS_WRITE_NO_FIN) && len) + *wp &= ~LWS_WRITE_NO_FIN; + + lwsl_notice("FORCED draining wp to 0x%02X (stashed 0x%02X, incoming 0x%02X)\n", *wp, + wsi->ws->tx_draining_stashed_wp, wpt); + // assert(0); + } +#endif + lws_restart_ws_ping_pong_timer(wsi); + + if (((*wp) & 0x1f) == LWS_WRITE_HTTP || + ((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL || + ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION || + ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS) + goto send_raw; + + + + /* if we are continuing a frame that already had its header done */ + + if (wsi->ws->inside_frame) { + lwsl_debug("INSIDE FRAME\n"); + goto do_more_inside_frame; + } + + wsi->ws->clean_buffer = 1; + + /* + * give a chance to the extensions to modify payload + * the extension may decide to produce unlimited payload erratically + * (eg, compression extension), so we require only that if he produces + * something, it will be a complete fragment of the length known at + * the time (just the fragment length known), and if he has + * more we will come back next time he is writeable and allow him to + * produce more fragments until he's drained. + * + * This allows what is sent each time it is writeable to be limited to + * a size that can be sent without partial sends or blocking, allows + * interleaving of control frames and other connection service. + */ + ebuf.token = (char *)buf; + ebuf.len = (int)len; + + switch ((int)*wp) { + case LWS_WRITE_PING: + case LWS_WRITE_PONG: + case LWS_WRITE_CLOSE: + break; + default: +#if !defined(LWS_WITHOUT_EXTENSIONS) + // lwsl_notice("LWS_EXT_CB_PAYLOAD_TX\n"); + // m = (int)ebuf.len; + /* returns 0 if no more tx pending, 1 if more pending */ + n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &ebuf, *wp); + if (n < 0) + return -1; + // lwsl_notice("ext processed %d plaintext into %d compressed (wp 0x%x)\n", m, (int)ebuf.len, *wp); + + if (n && ebuf.len) { + lwsl_notice("write drain len %d (wp 0x%x) SETTING tx_draining_ext\n", (int)ebuf.len, *wp); + /* extension requires further draining */ + wsi->ws->tx_draining_ext = 1; + wsi->ws->tx_draining_ext_list = pt->ws.tx_draining_ext_list; + pt->ws.tx_draining_ext_list = wsi; + /* we must come back to do more */ + lws_callback_on_writable(wsi); + /* + * keep a copy of the write type for the overall + * action that has provoked generation of these + * fragments, so the last guy can use its FIN state. + */ + wsi->ws->tx_draining_stashed_wp = *wp; + /* this is definitely not actually the last fragment + * because the extension asserted he has more coming + * So make sure this intermediate one doesn't go out + * with a FIN. + */ + *wp |= LWS_WRITE_NO_FIN; + } +#endif + if (ebuf.len && wsi->ws->stashed_write_pending) { + wsi->ws->stashed_write_pending = 0; + *wp = ((*wp) & 0xc0) | (int)wsi->ws->stashed_write_type; + } + } + + /* + * an extension did something we need to keep... for example, if + * compression extension, it has already updated its state according + * to this being issued + */ + if ((char *)buf != ebuf.token) { + /* + * ext might eat it, but not have anything to issue yet. + * In that case we have to follow his lead, but stash and + * replace the write type that was lost here the first time. + */ + if (len && !ebuf.len) { + if (!wsi->ws->stashed_write_pending) + wsi->ws->stashed_write_type = (char)(*wp) & 0x3f; + wsi->ws->stashed_write_pending = 1; + return (int)len; + } + /* + * extension recreated it: + * need to buffer this if not all sent + */ + wsi->ws->clean_buffer = 0; + } + + buf = (unsigned char *)ebuf.token; + len = ebuf.len; + + if (!buf) { + lwsl_err("null buf (%d)\n", (int)len); + return -1; + } + + switch (wsi->ws->ietf_spec_revision) { + case 13: + if (masked7) { + pre += 4; + dropmask = &buf[0 - pre]; + is_masked_bit = 0x80; + } + + switch ((*wp) & 0xf) { + case LWS_WRITE_TEXT: + n = LWSWSOPC_TEXT_FRAME; + break; + case LWS_WRITE_BINARY: + n = LWSWSOPC_BINARY_FRAME; + break; + case LWS_WRITE_CONTINUATION: + n = LWSWSOPC_CONTINUATION; + break; + + case LWS_WRITE_CLOSE: + n = LWSWSOPC_CLOSE; + break; + case LWS_WRITE_PING: + n = LWSWSOPC_PING; + break; + case LWS_WRITE_PONG: + n = LWSWSOPC_PONG; + break; + default: + lwsl_warn("lws_write: unknown write opc / wp\n"); + return -1; + } + + if (!((*wp) & LWS_WRITE_NO_FIN)) + n |= 1 << 7; + + if (len < 126) { + pre += 2; + buf[-pre] = n; + buf[-pre + 1] = (unsigned char)(len | is_masked_bit); + } else { + if (len < 65536) { + pre += 4; + buf[-pre] = n; + buf[-pre + 1] = 126 | is_masked_bit; + buf[-pre + 2] = (unsigned char)(len >> 8); + buf[-pre + 3] = (unsigned char)len; + } else { + pre += 10; + buf[-pre] = n; + buf[-pre + 1] = 127 | is_masked_bit; +#if defined __LP64__ + buf[-pre + 2] = (len >> 56) & 0x7f; + buf[-pre + 3] = len >> 48; + buf[-pre + 4] = len >> 40; + buf[-pre + 5] = len >> 32; +#else + buf[-pre + 2] = 0; + buf[-pre + 3] = 0; + buf[-pre + 4] = 0; + buf[-pre + 5] = 0; +#endif + buf[-pre + 6] = (unsigned char)(len >> 24); + buf[-pre + 7] = (unsigned char)(len >> 16); + buf[-pre + 8] = (unsigned char)(len >> 8); + buf[-pre + 9] = (unsigned char)len; + } + } + break; + } + +do_more_inside_frame: + + /* + * Deal with masking if we are in client -> server direction and + * the wp demands it + */ + + if (masked7) { + if (!wsi->ws->inside_frame) + if (lws_0405_frame_mask_generate(wsi)) { + lwsl_err("frame mask generation failed\n"); + return -1; + } + + /* + * in v7, just mask the payload + */ + if (dropmask) { /* never set if already inside frame */ + for (n = 4; n < (int)len + 4; n++) + dropmask[n] = dropmask[n] ^ wsi->ws->mask[ + (wsi->ws->mask_idx++) & 3]; + + /* copy the frame nonce into place */ + memcpy(dropmask, wsi->ws->mask, 4); + } + } + + if (lwsi_role_h2_ENCAPSULATION(wsi)) { + struct lws *encap = lws_get_network_wsi(wsi); + + assert(encap != wsi); + return encap->role_ops->write_role_protocol(wsi, buf - pre, + len + pre, wp); + } + + switch ((*wp) & 0x1f) { + case LWS_WRITE_TEXT: + case LWS_WRITE_BINARY: + case LWS_WRITE_CONTINUATION: + if (!wsi->h2_stream_carries_ws) { + + /* + * give any active extensions a chance to munge the + * buffer before send. We pass in a pointer to an + * lws_tokens struct prepared with the default buffer + * and content length that's in there. Rather than + * rewrite the default buffer, extensions that expect + * to grow the buffer can adapt .token to point to their + * own per-connection buffer in the extension user + * allocation. By default with no extensions or no + * extension callback handling, just the normal input + * buffer is used then so it is efficient. + * + * callback returns 1 in case it wants to spill more + * buffers + * + * This takes care of holding the buffer if send is + * incomplete, ie, if wsi->ws->clean_buffer is 0 + * (meaning an extension meddled with the buffer). If + * wsi->ws->clean_buffer is 1, it will instead return + * to the user code how much OF THE USER BUFFER was + * consumed. + */ + + n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre); + wsi->ws->inside_frame = 1; + if (n <= 0) + return n; + + if (n == (int)len + pre) { + /* everything in the buffer was handled + * (or rebuffered...) */ + wsi->ws->inside_frame = 0; + return (int)orig_len; + } + + /* + * it is how many bytes of user buffer got sent... may + * be < orig_len in which case callback when writable + * has already been arranged and user code can call + * lws_write() again with the rest later. + */ + + return n - pre; + } + break; + default: + break; + } + +send_raw: + return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre); +} + +static int +rops_close_kill_connection_ws(struct lws *wsi, enum lws_close_status reason) +{ + /* deal with ws encapsulation in h2 */ +#if defined(LWS_WITH_HTTP2) + if (wsi->http2_substream && wsi->h2_stream_carries_ws) + return role_ops_h2.close_kill_connection(wsi, reason); + + return 0; +#else + return 0; +#endif +} + +static int +rops_callback_on_writable_ws(struct lws *wsi) +{ +#if defined(LWS_WITH_HTTP2) + if (lwsi_role_h2_ENCAPSULATION(wsi)) { + /* we know then that it has an h2 parent */ + struct lws *enc = role_ops_h2.encapsulation_parent(wsi); + + assert(enc); + if (enc->role_ops->callback_on_writable(wsi)) + return 1; + } +#endif + return 0; +} + +static int +rops_init_vhost_ws(struct lws_vhost *vh, + const struct lws_context_creation_info *info) +{ +#if !defined(LWS_WITHOUT_EXTENSIONS) +#ifdef LWS_WITH_PLUGINS + struct lws_plugin *plugin = vh->context->plugin_list; + int m; + + if (vh->context->plugin_extension_count) { + + m = 0; + while (info->extensions && info->extensions[m].callback) + m++; + + /* + * give the vhost a unified list of extensions including the + * ones that came from plugins + */ + vh->ws.extensions = lws_zalloc(sizeof(struct lws_extension) * + (m + vh->context->plugin_extension_count + 1), + "extensions"); + if (!vh->ws.extensions) + return 1; + + memcpy((struct lws_extension *)vh->ws.extensions, info->extensions, + sizeof(struct lws_extension) * m); + plugin = vh->context->plugin_list; + while (plugin) { + memcpy((struct lws_extension *)&vh->ws.extensions[m], + plugin->caps.extensions, + sizeof(struct lws_extension) * + plugin->caps.count_extensions); + m += plugin->caps.count_extensions; + plugin = plugin->list; + } + } else +#endif + vh->ws.extensions = info->extensions; +#endif + + return 0; +} + +static int +rops_destroy_vhost_ws(struct lws_vhost *vh) +{ +#ifdef LWS_WITH_PLUGINS +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (vh->context->plugin_extension_count) + lws_free((void *)vh->ws.extensions); +#endif +#endif + + return 0; +} + +static int +rops_destroy_role_ws(struct lws *wsi) +{ + lws_free_set_NULL(wsi->ws); + + return 0; +} + +struct lws_role_ops role_ops_ws = { + /* role name */ "ws", + /* alpn id */ NULL, + /* check_upgrades */ NULL, + /* init_context */ NULL, + /* init_vhost */ rops_init_vhost_ws, + /* destroy_vhost */ rops_destroy_vhost_ws, + /* periodic_checks */ rops_periodic_checks_ws, + /* service_flag_pending */ rops_service_flag_pending_ws, + /* handle_POLLIN */ rops_handle_POLLIN_ws, + /* handle_POLLOUT */ rops_handle_POLLOUT_ws, + /* perform_user_POLLOUT */ NULL, + /* callback_on_writable */ rops_callback_on_writable_ws, + /* tx_credit */ NULL, + /* write_role_protocol */ rops_write_role_protocol_ws, + /* encapsulation_parent */ NULL, + /* alpn_negotiated */ NULL, + /* close_via_role_protocol */ rops_close_via_role_protocol_ws, + /* close_role */ rops_close_role_ws, + /* close_kill_connection */ rops_close_kill_connection_ws, + /* destroy_role */ rops_destroy_role_ws, + /* writeable cb clnt, srv */ { LWS_CALLBACK_CLIENT_WRITEABLE, + LWS_CALLBACK_SERVER_WRITEABLE }, + /* close cb clnt, srv */ { LWS_CALLBACK_CLIENT_CLOSED, + LWS_CALLBACK_CLOSED }, + /* file handles */ 0 +}; diff --git a/thirdparty/libwebsockets/roles/ws/private.h b/thirdparty/libwebsockets/roles/ws/private.h new file mode 100644 index 0000000000..71ffcaea96 --- /dev/null +++ b/thirdparty/libwebsockets/roles/ws/private.h @@ -0,0 +1,164 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h if LWS_ROLE_WS + */ + +extern struct lws_role_ops role_ops_ws; + +#define lwsi_role_ws(wsi) (wsi->role_ops == &role_ops_ws) + +enum lws_rx_parse_state { + LWS_RXPS_NEW, + + LWS_RXPS_04_mask_1, + LWS_RXPS_04_mask_2, + LWS_RXPS_04_mask_3, + + LWS_RXPS_04_FRAME_HDR_1, + LWS_RXPS_04_FRAME_HDR_LEN, + LWS_RXPS_04_FRAME_HDR_LEN16_2, + LWS_RXPS_04_FRAME_HDR_LEN16_1, + LWS_RXPS_04_FRAME_HDR_LEN64_8, + LWS_RXPS_04_FRAME_HDR_LEN64_7, + LWS_RXPS_04_FRAME_HDR_LEN64_6, + LWS_RXPS_04_FRAME_HDR_LEN64_5, + LWS_RXPS_04_FRAME_HDR_LEN64_4, + LWS_RXPS_04_FRAME_HDR_LEN64_3, + LWS_RXPS_04_FRAME_HDR_LEN64_2, + LWS_RXPS_04_FRAME_HDR_LEN64_1, + + LWS_RXPS_07_COLLECT_FRAME_KEY_1, + LWS_RXPS_07_COLLECT_FRAME_KEY_2, + LWS_RXPS_07_COLLECT_FRAME_KEY_3, + LWS_RXPS_07_COLLECT_FRAME_KEY_4, + + LWS_RXPS_WS_FRAME_PAYLOAD +}; + +enum lws_websocket_opcodes_07 { + LWSWSOPC_CONTINUATION = 0, + LWSWSOPC_TEXT_FRAME = 1, + LWSWSOPC_BINARY_FRAME = 2, + + LWSWSOPC_NOSPEC__MUX = 7, + + /* control extensions 8+ */ + + LWSWSOPC_CLOSE = 8, + LWSWSOPC_PING = 9, + LWSWSOPC_PONG = 0xa, +}; + +/* this is not usable directly by user code any more, lws_close_reason() */ +#define LWS_WRITE_CLOSE 4 + +#define ALREADY_PROCESSED_IGNORE_CHAR 1 +#define ALREADY_PROCESSED_NO_CB 2 + +#if !defined(LWS_WITHOUT_EXTENSIONS) +struct lws_vhost_role_ws { + const struct lws_extension *extensions; +}; + +struct lws_pt_role_ws { + struct lws *rx_draining_ext_list; + struct lws *tx_draining_ext_list; +}; +#endif + +struct _lws_websocket_related { + char *rx_ubuf; +#if !defined(LWS_WITHOUT_EXTENSIONS) + const struct lws_extension *active_extensions[LWS_MAX_EXTENSIONS_ACTIVE]; + void *act_ext_user[LWS_MAX_EXTENSIONS_ACTIVE]; + struct lws *rx_draining_ext_list; + struct lws *tx_draining_ext_list; +#endif + /* Also used for close content... control opcode == < 128 */ + uint8_t ping_payload_buf[128 - 3 + LWS_PRE]; + uint8_t mask[4]; + + time_t time_next_ping_check; + size_t rx_packet_length; + uint32_t rx_ubuf_head; + uint32_t rx_ubuf_alloc; + + uint8_t ping_payload_len; + uint8_t mask_idx; + uint8_t opcode; + uint8_t rsv; + uint8_t rsv_first_msg; + /* zero if no info, or length including 2-byte close code */ + uint8_t close_in_ping_buffer_len; + uint8_t utf8; + uint8_t stashed_write_type; + uint8_t tx_draining_stashed_wp; + uint8_t ietf_spec_revision; + + unsigned int final:1; + unsigned int frame_is_binary:1; + unsigned int all_zero_nonce:1; + unsigned int this_frame_masked:1; + unsigned int inside_frame:1; /* next write will be more of frame */ + unsigned int clean_buffer:1; /* buffer not rewritten by extension */ + unsigned int payload_is_close:1; /* process as PONG, but it is close */ + unsigned int ping_pending_flag:1; + unsigned int continuation_possible:1; + unsigned int owed_a_fin:1; + unsigned int check_utf8:1; + unsigned int defeat_check_utf8:1; + unsigned int stashed_write_pending:1; + unsigned int send_check_ping:1; + unsigned int first_fragment:1; + unsigned int peer_has_sent_close:1; +#if !defined(LWS_WITHOUT_EXTENSIONS) + unsigned int extension_data_pending:1; + unsigned int rx_draining_ext:1; + unsigned int tx_draining_ext:1; + + uint8_t count_act_ext; +#endif +}; + +int +lws_ws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len); + +#if !defined(LWS_WITHOUT_EXTENSIONS) +LWS_VISIBLE void +lws_context_init_extensions(const struct lws_context_creation_info *info, + struct lws_context *context); +LWS_EXTERN int +lws_any_extension_handled(struct lws *wsi, enum lws_extension_callback_reasons r, + void *v, size_t len); + +LWS_EXTERN int +lws_ext_cb_active(struct lws *wsi, int reason, void *buf, int len); +LWS_EXTERN int +lws_ext_cb_all_exts(struct lws_context *context, struct lws *wsi, int reason, + void *arg, int len); +#endif + +int +handshake_0405(struct lws_context *context, struct lws *wsi); +int +lws_process_ws_upgrade(struct lws *wsi); +int +lws_server_init_wsi_for_ws(struct lws *wsi); diff --git a/thirdparty/libwebsockets/roles/ws/server-ws.c b/thirdparty/libwebsockets/roles/ws/server-ws.c new file mode 100644 index 0000000000..62bcd8524f --- /dev/null +++ b/thirdparty/libwebsockets/roles/ws/server-ws.c @@ -0,0 +1,836 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include <core/private.h> + +#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); } + +#if !defined(LWS_WITHOUT_EXTENSIONS) +static int +lws_extension_server_handshake(struct lws *wsi, char **p, int budget) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + char ext_name[64], *args, *end = (*p) + budget - 1; + const struct lws_ext_options *opts, *po; + const struct lws_extension *ext; + struct lws_ext_option_arg oa; + int n, m, more = 1; + int ext_count = 0; + char ignore; + char *c; + + /* + * Figure out which extensions the client has that we want to + * enable on this connection, and give him back the list + */ + if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) + return 0; + + /* + * break down the list of client extensions + * and go through them + */ + + if (lws_hdr_copy(wsi, (char *)pt->serv_buf, context->pt_serv_buf_size, + WSI_TOKEN_EXTENSIONS) < 0) + return 1; + + c = (char *)pt->serv_buf; + lwsl_parser("WSI_TOKEN_EXTENSIONS = '%s'\n", c); + wsi->ws->count_act_ext = 0; + ignore = 0; + n = 0; + args = NULL; + + /* + * We may get a simple request + * + * Sec-WebSocket-Extensions: permessage-deflate + * + * or an elaborated one with requested options + * + * Sec-WebSocket-Extensions: permessage-deflate; \ + * server_no_context_takeover; \ + * client_no_context_takeover + */ + + while (more) { + + if (c >= (char *)pt->serv_buf + 255) + return -1; + + if (*c && (*c != ',' && *c != '\t')) { + if (*c == ';') { + ignore = 1; + if (!args) + args = c + 1; + } + if (ignore || *c == ' ') { + c++; + continue; + } + ext_name[n] = *c++; + if (n < (int)sizeof(ext_name) - 1) + n++; + continue; + } + ext_name[n] = '\0'; + + ignore = 0; + if (!*c) + more = 0; + else { + c++; + if (!n) + continue; + } + + while (args && *args && *args == ' ') + args++; + + /* check a client's extension against our support */ + + ext = wsi->vhost->ws.extensions; + + while (ext && ext->callback) { + + if (strcmp(ext_name, ext->name)) { + ext++; + continue; + } + + /* + * oh, we do support this one he asked for... but let's + * confirm he only gave it once + */ + for (m = 0; m < wsi->ws->count_act_ext; m++) + if (wsi->ws->active_extensions[m] == ext) { + lwsl_info("extension mentioned twice\n"); + return 1; /* shenanigans */ + } + + /* + * ask user code if it's OK to apply it on this + * particular connection + protocol + */ + m = (wsi->protocol->callback)(wsi, + LWS_CALLBACK_CONFIRM_EXTENSION_OKAY, + wsi->user_space, ext_name, 0); + + /* + * zero return from callback means go ahead and allow + * the extension, it's what we get if the callback is + * unhandled + */ + if (m) { + ext++; + continue; + } + + /* apply it */ + + ext_count++; + + /* instantiate the extension on this conn */ + + wsi->ws->active_extensions[wsi->ws->count_act_ext] = ext; + + /* allow him to construct his context */ + + if (ext->callback(lws_get_context(wsi), ext, wsi, + LWS_EXT_CB_CONSTRUCT, + (void *)&wsi->ws->act_ext_user[ + wsi->ws->count_act_ext], + (void *)&opts, 0)) { + lwsl_info("ext %s failed construction\n", + ext_name); + ext_count--; + ext++; + + continue; + } + + if (ext_count > 1) + *(*p)++ = ','; + else + LWS_CPYAPP(*p, + "\x0d\x0aSec-WebSocket-Extensions: "); + *p += lws_snprintf(*p, (end - *p), "%s", ext_name); + + /* + * The client may send a bunch of different option + * sets for the same extension, we are supposed to + * pick one we like the look of. The option sets are + * separated by comma. + * + * Actually we just either accept the first one or + * nothing. + * + * Go through the options trying to apply the + * recognized ones + */ + + lwsl_info("ext args %s\n", args); + + while (args && *args && *args != ',') { + while (*args == ' ') + args++; + po = opts; + while (po->name) { + /* only support arg-less options... */ + if (po->type != EXTARG_NONE || + strncmp(args, po->name, + strlen(po->name))) { + po++; + continue; + } + oa.option_name = NULL; + oa.option_index = (int)(po - opts); + oa.start = NULL; + oa.len = 0; + lwsl_info("setting '%s'\n", po->name); + if (!ext->callback(lws_get_context(wsi), + ext, wsi, + LWS_EXT_CB_OPTION_SET, + wsi->ws->act_ext_user[ + wsi->ws->count_act_ext], + &oa, (end - *p))) { + + *p += lws_snprintf(*p, (end - *p), + "; %s", po->name); + lwsl_debug("adding option %s\n", + po->name); + } + po++; + } + while (*args && *args != ',' && *args != ';') + args++; + + if (*args == ';') + args++; + } + + wsi->ws->count_act_ext++; + lwsl_parser("cnt_act_ext <- %d\n", wsi->ws->count_act_ext); + + if (args && *args == ',') + more = 0; + + ext++; + } + + n = 0; + args = NULL; + } + + return 0; +} +#endif + + + +int +lws_process_ws_upgrade(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + char protocol_list[128], protocol_name[64], *p; + int protocol_len, hit, n = 0, non_space_char_found = 0; + + if (!wsi->protocol) + lwsl_err("NULL protocol at lws_read\n"); + + /* + * It's either websocket or h2->websocket + * + * Select the first protocol we support from the list + * the client sent us. + * + * Copy it to remove header fragmentation + */ + + if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1, + WSI_TOKEN_PROTOCOL) < 0) { + lwsl_err("protocol list too long"); + return 1; + } + + protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); + protocol_list[protocol_len] = '\0'; + p = protocol_list; + hit = 0; + + while (*p && !hit) { + n = 0; + non_space_char_found = 0; + while (n < (int)sizeof(protocol_name) - 1 && + *p && *p != ',') { + /* ignore leading spaces */ + if (!non_space_char_found && *p == ' ') { + n++; + continue; + } + non_space_char_found = 1; + protocol_name[n++] = *p++; + } + protocol_name[n] = '\0'; + if (*p) + p++; + + lwsl_debug("checking %s\n", protocol_name); + + n = 0; + while (wsi->vhost->protocols[n].callback) { + lwsl_debug("try %s\n", + wsi->vhost->protocols[n].name); + + if (wsi->vhost->protocols[n].name && + !strcmp(wsi->vhost->protocols[n].name, + protocol_name)) { + wsi->protocol = &wsi->vhost->protocols[n]; + hit = 1; + break; + } + + n++; + } + } + + /* we didn't find a protocol he wanted? */ + + if (!hit) { + if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) { + lwsl_notice("No protocol from \"%s\" supported\n", + protocol_list); + return 1; + } + /* + * some clients only have one protocol and + * do not send the protocol list header... + * allow it and match to the vhost's default + * protocol (which itself defaults to zero) + */ + lwsl_info("defaulting to prot handler %d\n", + wsi->vhost->default_protocol_index); + n = wsi->vhost->default_protocol_index; + wsi->protocol = &wsi->vhost->protocols[ + (int)wsi->vhost->default_protocol_index]; + } + + /* allocate the ws struct for the wsi */ + wsi->ws = lws_zalloc(sizeof(*wsi->ws), "ws struct"); + if (!wsi->ws) { + lwsl_notice("OOM\n"); + return 1; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION)) + wsi->ws->ietf_spec_revision = + atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION)); + + /* allocate wsi->user storage */ + if (lws_ensure_user_space(wsi)) { + lwsl_notice("problem with user space\n"); + return 1; + } + + /* + * Give the user code a chance to study the request and + * have the opportunity to deny it + */ + if ((wsi->protocol->callback)(wsi, + LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION, + wsi->user_space, + lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) { + lwsl_warn("User code denied connection\n"); + return 1; + } + + /* + * Perform the handshake according to the protocol version the + * client announced + */ + + switch (wsi->ws->ietf_spec_revision) { + default: + lwsl_notice("Unknown client spec version %d\n", + wsi->ws->ietf_spec_revision); + wsi->ws->ietf_spec_revision = 13; + //return 1; + /* fallthru */ + case 13: +#if defined(LWS_WITH_HTTP2) + if (wsi->h2_stream_carries_ws) { + if (lws_h2_ws_handshake(wsi)) { + lwsl_notice("h2 ws handshake failed\n"); + return 1; + } + } else +#endif + { + lwsl_parser("lws_parse calling handshake_04\n"); + if (handshake_0405(wsi->context, wsi)) { + lwsl_notice("hs0405 has failed the connection\n"); + return 1; + } + } + break; + } + + lws_same_vh_protocol_insert(wsi, n); + + /* + * We are upgrading to ws, so http/1.1 + h2 and keepalive + pipelined + * header considerations about keeping the ah around no longer apply. + * + * However it's common for the first ws protocol data to have been + * coalesced with the browser upgrade request and to already be in the + * ah rx buffer. + */ + + lws_pt_lock(pt, __func__); + + if (wsi->h2_stream_carries_ws) + lws_role_transition(wsi, LWSIFR_SERVER | LWSIFR_P_ENCAP_H2, + LRS_ESTABLISHED, &role_ops_ws); + else + lws_role_transition(wsi, LWSIFR_SERVER, LRS_ESTABLISHED, + &role_ops_ws); + + lws_pt_unlock(pt); + + lws_server_init_wsi_for_ws(wsi); + lwsl_parser("accepted v%02d connection\n", wsi->ws->ietf_spec_revision); + + lwsl_info("%s: %p: dropping ah on ws upgrade\n", __func__, wsi); + lws_header_table_detach(wsi, 1); + + return 0; +} + +int +handshake_0405(struct lws_context *context, struct lws *wsi) +{ + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + struct lws_process_html_args args; + unsigned char hash[20]; + int n, accept_len; + char *response; + char *p; + + if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST) || + !lws_hdr_total_length(wsi, WSI_TOKEN_KEY)) { + lwsl_info("handshake_04 missing pieces\n"); + /* completed header processing, but missing some bits */ + goto bail; + } + + if (lws_hdr_total_length(wsi, WSI_TOKEN_KEY) >= MAX_WEBSOCKET_04_KEY_LEN) { + lwsl_warn("Client key too long %d\n", MAX_WEBSOCKET_04_KEY_LEN); + goto bail; + } + + /* + * since key length is restricted above (currently 128), cannot + * overflow + */ + n = sprintf((char *)pt->serv_buf, + "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + lws_hdr_simple_ptr(wsi, WSI_TOKEN_KEY)); + + lws_SHA1(pt->serv_buf, n, hash); + + accept_len = lws_b64_encode_string((char *)hash, 20, + (char *)pt->serv_buf, context->pt_serv_buf_size); + if (accept_len < 0) { + lwsl_warn("Base64 encoded hash too long\n"); + goto bail; + } + + /* allocate the per-connection user memory (if any) */ + if (lws_ensure_user_space(wsi)) + goto bail; + + /* create the response packet */ + + /* make a buffer big enough for everything */ + + response = (char *)pt->serv_buf + MAX_WEBSOCKET_04_KEY_LEN + 256 + LWS_PRE; + p = response; + LWS_CPYAPP(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a" + "Upgrade: WebSocket\x0d\x0a" + "Connection: Upgrade\x0d\x0a" + "Sec-WebSocket-Accept: "); + strcpy(p, (char *)pt->serv_buf); + p += accept_len; + + /* we can only return the protocol header if: + * - one came in, and ... */ + if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) && + /* - it is not an empty string */ + wsi->protocol->name && + wsi->protocol->name[0]) { + LWS_CPYAPP(p, "\x0d\x0aSec-WebSocket-Protocol: "); + p += lws_snprintf(p, 128, "%s", wsi->protocol->name); + } + +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* + * Figure out which extensions the client has that we want to + * enable on this connection, and give him back the list. + * + * Give him a limited write bugdet + */ + if (lws_extension_server_handshake(wsi, &p, 192)) + goto bail; +#endif + LWS_CPYAPP(p, "\x0d\x0a"); + + args.p = p; + args.max_len = lws_ptr_diff((char *)pt->serv_buf + + context->pt_serv_buf_size, p); + if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, + LWS_CALLBACK_ADD_HEADERS, + wsi->user_space, &args, 0)) + goto bail; + + p = args.p; + + /* end of response packet */ + + LWS_CPYAPP(p, "\x0d\x0a"); + + /* okay send the handshake response accepting the connection */ + + lwsl_parser("issuing resp pkt %d len\n", + lws_ptr_diff(p, response)); +#if defined(DEBUG) + fwrite(response, 1, p - response, stderr); +#endif + n = lws_write(wsi, (unsigned char *)response, p - response, + LWS_WRITE_HTTP_HEADERS); + if (n != (p - response)) { + lwsl_info("%s: ERROR writing to socket %d\n", __func__, n); + goto bail; + } + + /* alright clean up and set ourselves into established state */ + + lwsi_set_state(wsi, LRS_ESTABLISHED); + wsi->lws_rx_parse_state = LWS_RXPS_NEW; + + { + const char * uri_ptr = + lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI); + int uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI); + const struct lws_http_mount *hit = + lws_find_mount(wsi, uri_ptr, uri_len); + if (hit && hit->cgienv && + wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_PMO, + wsi->user_space, (void *)hit->cgienv, 0)) + return 1; + } + + return 0; + +bail: + /* caller will free up his parsing allocations */ + return -1; +} + + + +/* + * Once we reach LWS_RXPS_WS_FRAME_PAYLOAD, we know how much + * to expect in that state and can deal with it in bulk more efficiently. + */ + +static int +lws_ws_frame_rest_is_payload(struct lws *wsi, uint8_t **buf, size_t len) +{ + uint8_t *buffer = *buf, mask[4]; + struct lws_tokens ebuf; + unsigned int avail = (unsigned int)len; +#if !defined(LWS_WITHOUT_EXTENSIONS) + unsigned int old_packet_length = (int)wsi->ws->rx_packet_length; +#endif + int n = 0; + + /* + * With zlib, we can give it as much input as we like. The pmd + * extension will draw it down in chunks (default 1024). + * + * If we try to restrict how much we give it, because we must go + * back to the event loop each time, we will drop the remainder... + */ + +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (!wsi->ws->count_act_ext) +#endif + { + if (wsi->protocol->rx_buffer_size) + avail = (int)wsi->protocol->rx_buffer_size; + else + avail = wsi->context->pt_serv_buf_size; + } + + /* do not consume more than we should */ + if (avail > wsi->ws->rx_packet_length) + avail = (unsigned int)wsi->ws->rx_packet_length; + + /* do not consume more than what is in the buffer */ + if (avail > len) + avail = (unsigned int)len; + + if (avail <= 0) + return 0; + + ebuf.token = (char *)buffer; + ebuf.len = avail; + + //lwsl_hexdump_notice(ebuf.token, ebuf.len); + + if (!wsi->ws->all_zero_nonce) { + + for (n = 0; n < 4; n++) + mask[n] = wsi->ws->mask[(wsi->ws->mask_idx + n) & 3]; + + /* deal with 4-byte chunks using unwrapped loop */ + n = avail >> 2; + while (n--) { + *(buffer) = *(buffer) ^ mask[0]; + buffer++; + *(buffer) = *(buffer) ^ mask[1]; + buffer++; + *(buffer) = *(buffer) ^ mask[2]; + buffer++; + *(buffer) = *(buffer) ^ mask[3]; + buffer++; + } + /* and the remaining bytes bytewise */ + for (n = 0; n < (int)(avail & 3); n++) { + *(buffer) = *(buffer) ^ mask[n]; + buffer++; + } + + wsi->ws->mask_idx = (wsi->ws->mask_idx + avail) & 3; + } + + lwsl_info("%s: using %d of raw input (total %d on offer)\n", __func__, + avail, (int)len); + + (*buf) += avail; + len -= avail; + +#if !defined(LWS_WITHOUT_EXTENSIONS) + n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &ebuf, 0); + lwsl_info("%s: ext says %d / ebuf.len %d\n", __func__, n, ebuf.len); +#endif + /* + * ebuf may be pointing somewhere completely different now, + * it's the output + */ + +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (n < 0) { + /* + * we may rely on this to get RX, just drop connection + */ + lwsl_notice("%s: LWS_EXT_CB_PAYLOAD_RX blew out\n", __func__); + wsi->socket_is_permanently_unusable = 1; + return -1; + } +#endif + + wsi->ws->rx_packet_length -= avail; + +#if !defined(LWS_WITHOUT_EXTENSIONS) + /* + * if we had an rx fragment right at the last compressed byte of the + * message, we can get a zero length inflated output, where no prior + * rx inflated output marked themselves with FIN, since there was + * raw ws payload still to drain at that time. + * + * Then we need to generate a zero length ws rx that can be understood + * as the message completion. + */ + + if (!ebuf.len && /* zero-length inflation output */ + !n && /* nothing left to drain from the inflator */ + wsi->ws->count_act_ext && /* we are using pmd */ + old_packet_length && /* we gave the inflator new input */ + !wsi->ws->rx_packet_length && /* raw ws packet payload all gone */ + wsi->ws->final && /* the raw ws packet is a FIN guy */ + wsi->protocol->callback && + !wsi->wsistate_pre_close) { + + if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, + LWS_CALLBACK_RECEIVE, + wsi->user_space, NULL, 0)) + return -1; + + return avail; + } +#endif + + if (!ebuf.len) + return avail; + + if ( +#if !defined(LWS_WITHOUT_EXTENSIONS) + n && +#endif + ebuf.len) + /* extension had more... main loop will come back */ + lws_add_wsi_to_draining_ext_list(wsi); + else + lws_remove_wsi_from_draining_ext_list(wsi); + + if (wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) { + if (lws_check_utf8(&wsi->ws->utf8, + (unsigned char *)ebuf.token, ebuf.len)) { + lws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"bad utf8", 8); + goto utf8_fail; + } + + /* we are ending partway through utf-8 character? */ + if (!wsi->ws->rx_packet_length && wsi->ws->final && + wsi->ws->utf8 && !n) { + lwsl_info("FINAL utf8 error\n"); + lws_close_reason(wsi, LWS_CLOSE_STATUS_INVALID_PAYLOAD, + (uint8_t *)"partial utf8", 12); + +utf8_fail: + lwsl_info("utf8 error\n"); + lwsl_hexdump_info(ebuf.token, ebuf.len); + + return -1; + } + } + + if (wsi->protocol->callback && !wsi->wsistate_pre_close) + if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, + LWS_CALLBACK_RECEIVE, + wsi->user_space, + ebuf.token, ebuf.len)) + return -1; + + wsi->ws->first_fragment = 0; + +#if !defined(LWS_WITHOUT_EXTENSIONS) + lwsl_info("%s: input used %d, output %d, rem len %d, rx_draining_ext %d\n", + __func__, avail, ebuf.len, (int)len, wsi->ws->rx_draining_ext); +#endif + + return avail; /* how much we used from the input */ +} + + +int +lws_parse_ws(struct lws *wsi, unsigned char **buf, size_t len) +{ + int m, bulk = 0; + + lwsl_debug("%s: received %d byte packet\n", __func__, (int)len); + + //lwsl_hexdump_notice(*buf, len); + + /* let the rx protocol state machine have as much as it needs */ + + while (len) { + /* + * we were accepting input but now we stopped doing so + */ + if (wsi->rxflow_bitmap) { + lwsl_info("%s: doing rxflow\n", __func__); + lws_rxflow_cache(wsi, *buf, 0, (int)len); + lwsl_parser("%s: cached %ld\n", __func__, (long)len); + *buf += len; /* stashing it is taking care of it */ + return 1; + } +#if !defined(LWS_WITHOUT_EXTENSIONS) + if (wsi->ws->rx_draining_ext) { + lwsl_debug("%s: draining rx ext\n", __func__); + m = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0); + if (m < 0) + return -1; + continue; + } +#endif + + /* consume payload bytes efficiently */ + while (wsi->lws_rx_parse_state == LWS_RXPS_WS_FRAME_PAYLOAD && + (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME || + wsi->ws->opcode == LWSWSOPC_BINARY_FRAME || + wsi->ws->opcode == LWSWSOPC_CONTINUATION) && + len) { + uint8_t *bin = *buf; + + bulk = 1; + m = lws_ws_frame_rest_is_payload(wsi, buf, len); + assert((int)lws_ptr_diff(*buf, bin) <= (int)len); + len -= lws_ptr_diff(*buf, bin); + + if (!m) { + + break; + } + if (m < 0) { + lwsl_info("%s: rest_is_payload bailed\n", + __func__); + return -1; + } + } + + if (!bulk) { + /* process the byte */ + m = lws_ws_rx_sm(wsi, 0, *(*buf)++); + len--; + } else { + /* + * We already handled this byte in bulk, just deal + * with the ramifications + */ +#if !defined(LWS_WITHOUT_EXTENSIONS) + lwsl_debug("%s: coming out of bulk with len %d, " + "wsi->ws->rx_draining_ext %d\n", + __func__, (int)len, + wsi->ws->rx_draining_ext); +#endif + m = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR | + ALREADY_PROCESSED_NO_CB, 0); + } + + if (m < 0) { + lwsl_info("%s: lws_ws_rx_sm bailed %d\n", __func__, + bulk); + + return -1; + } + + bulk = 0; + } + + lwsl_debug("%s: exit with %d unused\n", __func__, (int)len); + + return 0; +} diff --git a/thirdparty/libwebsockets/tls/mbedtls/lws-genhash.c b/thirdparty/libwebsockets/tls/mbedtls/lws-genhash.c new file mode 100644 index 0000000000..ce4ee6e382 --- /dev/null +++ b/thirdparty/libwebsockets/tls/mbedtls/lws-genhash.c @@ -0,0 +1,202 @@ +/* + * libwebsockets - generic hash and HMAC api hiding the backend + * + * Copyright (C) 2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * lws_genhash provides a hash / hmac abstraction api in lws that works the + * same whether you are using openssl or mbedtls hash functions underneath. + */ +#include "libwebsockets.h" +#include <mbedtls/version.h> + +#if (MBEDTLS_VERSION_NUMBER >= 0x02070000) +#define MBA(fn) fn##_ret +#else +#define MBA(fn) fn +#endif + +size_t +lws_genhash_size(enum lws_genhash_types type) +{ + switch(type) { + case LWS_GENHASH_TYPE_SHA1: + return 20; + case LWS_GENHASH_TYPE_SHA256: + return 32; + case LWS_GENHASH_TYPE_SHA384: + return 48; + case LWS_GENHASH_TYPE_SHA512: + return 64; + } + + return 0; +} + +int +lws_genhash_init(struct lws_genhash_ctx *ctx, enum lws_genhash_types type) +{ + ctx->type = type; + + switch (ctx->type) { + case LWS_GENHASH_TYPE_SHA1: + mbedtls_sha1_init(&ctx->u.sha1); + MBA(mbedtls_sha1_starts)(&ctx->u.sha1); + break; + case LWS_GENHASH_TYPE_SHA256: + mbedtls_sha256_init(&ctx->u.sha256); + MBA(mbedtls_sha256_starts)(&ctx->u.sha256, 0); + break; + case LWS_GENHASH_TYPE_SHA384: + mbedtls_sha512_init(&ctx->u.sha512); + MBA(mbedtls_sha512_starts)(&ctx->u.sha512, 1 /* is384 */); + break; + case LWS_GENHASH_TYPE_SHA512: + mbedtls_sha512_init(&ctx->u.sha512); + MBA(mbedtls_sha512_starts)(&ctx->u.sha512, 0); + break; + default: + return 1; + } + + return 0; +} + +int +lws_genhash_update(struct lws_genhash_ctx *ctx, const void *in, size_t len) +{ + switch (ctx->type) { + case LWS_GENHASH_TYPE_SHA1: + MBA(mbedtls_sha1_update)(&ctx->u.sha1, in, len); + break; + case LWS_GENHASH_TYPE_SHA256: + MBA(mbedtls_sha256_update)(&ctx->u.sha256, in, len); + break; + case LWS_GENHASH_TYPE_SHA384: + MBA(mbedtls_sha512_update)(&ctx->u.sha512, in, len); + break; + case LWS_GENHASH_TYPE_SHA512: + MBA(mbedtls_sha512_update)(&ctx->u.sha512, in, len); + break; + } + + return 0; +} + +int +lws_genhash_destroy(struct lws_genhash_ctx *ctx, void *result) +{ + switch (ctx->type) { + case LWS_GENHASH_TYPE_SHA1: + MBA(mbedtls_sha1_finish)(&ctx->u.sha1, result); + mbedtls_sha1_free(&ctx->u.sha1); + break; + case LWS_GENHASH_TYPE_SHA256: + MBA(mbedtls_sha256_finish)(&ctx->u.sha256, result); + mbedtls_sha256_free(&ctx->u.sha256); + break; + case LWS_GENHASH_TYPE_SHA384: + MBA(mbedtls_sha512_finish)(&ctx->u.sha512, result); + mbedtls_sha512_free(&ctx->u.sha512); + break; + case LWS_GENHASH_TYPE_SHA512: + MBA(mbedtls_sha512_finish)(&ctx->u.sha512, result); + mbedtls_sha512_free(&ctx->u.sha512); + break; + } + + return 0; +} + +size_t +lws_genhmac_size(enum lws_genhmac_types type) +{ + switch(type) { + case LWS_GENHMAC_TYPE_SHA256: + return 32; + case LWS_GENHMAC_TYPE_SHA384: + return 48; + case LWS_GENHMAC_TYPE_SHA512: + return 64; + } + + return 0; +} + +int +lws_genhmac_init(struct lws_genhmac_ctx *ctx, enum lws_genhmac_types type, + const uint8_t *key, size_t key_len) +{ + int t; + + ctx->type = type; + + switch (type) { + case LWS_GENHMAC_TYPE_SHA256: + t = MBEDTLS_MD_SHA256; + break; + case LWS_GENHMAC_TYPE_SHA384: + t = MBEDTLS_MD_SHA384; + break; + case LWS_GENHMAC_TYPE_SHA512: + t = MBEDTLS_MD_SHA512; + break; + default: + return -1; + } + + ctx->hmac = mbedtls_md_info_from_type(t); + if (!ctx->hmac) + return -1; + + if (mbedtls_md_init_ctx(&ctx->ctx, ctx->hmac)) + return -1; + + if (mbedtls_md_hmac_starts(&ctx->ctx, key, key_len)) { + mbedtls_md_free(&ctx->ctx); + ctx->hmac = NULL; + + return -1; + } + + return 0; +} + +int +lws_genhmac_update(struct lws_genhmac_ctx *ctx, const void *in, size_t len) +{ + if (mbedtls_md_hmac_update(&ctx->ctx, in, len)) + return -1; + + return 0; +} + +int +lws_genhmac_destroy(struct lws_genhmac_ctx *ctx, void *result) +{ + int n = 0; + + if (result) + n = mbedtls_md_hmac_finish(&ctx->ctx, result); + + mbedtls_md_free(&ctx->ctx); + ctx->hmac = NULL; + if (n) + return -1; + + return 0; +} diff --git a/thirdparty/libwebsockets/tls/mbedtls/lws-genrsa.c b/thirdparty/libwebsockets/tls/mbedtls/lws-genrsa.c new file mode 100644 index 0000000000..70a9fcf42c --- /dev/null +++ b/thirdparty/libwebsockets/tls/mbedtls/lws-genrsa.c @@ -0,0 +1,329 @@ +/* + * libwebsockets - generic RSA api hiding the backend + * + * Copyright (C) 2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * lws_genhash provides a hash / hmac abstraction api in lws that works the + * same whether you are using openssl or mbedtls hash functions underneath. + */ +#include "core/private.h" + +LWS_VISIBLE void +lws_jwk_destroy_genrsa_elements(struct lws_genrsa_elements *el) +{ + int n; + + for (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) + if (el->e[n].buf) + lws_free_set_NULL(el->e[n].buf); +} + +LWS_VISIBLE int +lws_genrsa_create(struct lws_genrsa_ctx *ctx, struct lws_genrsa_elements *el) +{ + int n; + + memset(ctx, 0, sizeof(*ctx)); + ctx->ctx = lws_zalloc(sizeof(*ctx->ctx), "genrsa"); + if (!ctx->ctx) + return 1; + + mbedtls_rsa_init(ctx->ctx, MBEDTLS_RSA_PKCS_V15, 0); + + { + mbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = { + &ctx->ctx->E, &ctx->ctx->N, &ctx->ctx->D, &ctx->ctx->P, + &ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ, + &ctx->ctx->QP, + }; + + for (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) + if (el->e[n].buf && + mbedtls_mpi_read_binary(mpi[n], el->e[n].buf, + el->e[n].len)) { + lwsl_notice("mpi load failed\n"); + lws_free_set_NULL(ctx->ctx); + + return -1; + } + } + + ctx->ctx->len = el->e[JWK_KEY_N].len; + + return 0; +} + +static int +_rngf(void *context, unsigned char *buf, size_t len) +{ + if ((size_t)lws_get_random(context, buf, len) == len) + return 0; + + return -1; +} + +LWS_VISIBLE int +lws_genrsa_new_keypair(struct lws_context *context, struct lws_genrsa_ctx *ctx, + struct lws_genrsa_elements *el, int bits) +{ + int n; + + memset(ctx, 0, sizeof(*ctx)); + ctx->ctx = lws_zalloc(sizeof(*ctx->ctx), "genrsa"); + if (!ctx->ctx) + return -1; + + mbedtls_rsa_init(ctx->ctx, MBEDTLS_RSA_PKCS_V15, 0); + + n = mbedtls_rsa_gen_key(ctx->ctx, _rngf, context, bits, 65537); + if (n) { + lwsl_err("mbedtls_rsa_gen_key failed 0x%x\n", -n); + goto cleanup_1; + } + + { + mbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = { + &ctx->ctx->E, &ctx->ctx->N, &ctx->ctx->D, &ctx->ctx->P, + &ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ, + &ctx->ctx->QP, + }; + + for (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) + if (mbedtls_mpi_size(mpi[n])) { + el->e[n].buf = lws_malloc( + mbedtls_mpi_size(mpi[n]), "genrsakey"); + if (!el->e[n].buf) + goto cleanup; + el->e[n].len = mbedtls_mpi_size(mpi[n]); + mbedtls_mpi_write_binary(mpi[n], el->e[n].buf, + el->e[n].len); + } + } + + return 0; + +cleanup: + for (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) + if (el->e[n].buf) + lws_free_set_NULL(el->e[n].buf); +cleanup_1: + lws_free(ctx->ctx); + + return -1; +} + +LWS_VISIBLE int +lws_genrsa_public_decrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in, + size_t in_len, uint8_t *out, size_t out_max) +{ + size_t olen = 0; + int n; + + ctx->ctx->len = in_len; + n = mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx->ctx, NULL, NULL, + MBEDTLS_RSA_PUBLIC, + &olen, in, out, out_max); + if (n) { + lwsl_notice("%s: -0x%x\n", __func__, -n); + + return -1; + } + + return olen; +} + +LWS_VISIBLE int +lws_genrsa_public_encrypt(struct lws_genrsa_ctx *ctx, const uint8_t *in, + size_t in_len, uint8_t *out) +{ + int n; + + ctx->ctx->len = in_len; + n = mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx->ctx, NULL, NULL, + MBEDTLS_RSA_PRIVATE, + in_len, in, out); + if (n) { + lwsl_notice("%s: -0x%x\n", __func__, -n); + + return -1; + } + + return 0; +} + +static int +lws_genrsa_genrsa_hash_to_mbed_hash(enum lws_genhash_types hash_type) +{ + int h = -1; + + switch (hash_type) { + case LWS_GENHASH_TYPE_SHA1: + h = MBEDTLS_MD_SHA1; + break; + case LWS_GENHASH_TYPE_SHA256: + h = MBEDTLS_MD_SHA256; + break; + case LWS_GENHASH_TYPE_SHA384: + h = MBEDTLS_MD_SHA384; + break; + case LWS_GENHASH_TYPE_SHA512: + h = MBEDTLS_MD_SHA512; + break; + } + + return h; +} + +LWS_VISIBLE int +lws_genrsa_public_verify(struct lws_genrsa_ctx *ctx, const uint8_t *in, + enum lws_genhash_types hash_type, const uint8_t *sig, + size_t sig_len) +{ + int n, h = lws_genrsa_genrsa_hash_to_mbed_hash(hash_type); + + if (h < 0) + return -1; + + n = mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx->ctx, NULL, NULL, + MBEDTLS_RSA_PUBLIC, + h, 0, in, sig); + if (n < 0) { + lwsl_notice("%s: -0x%x\n", __func__, -n); + + return -1; + } + + return n; +} + +LWS_VISIBLE int +lws_genrsa_public_sign(struct lws_genrsa_ctx *ctx, const uint8_t *in, + enum lws_genhash_types hash_type, uint8_t *sig, + size_t sig_len) +{ + int n, h = lws_genrsa_genrsa_hash_to_mbed_hash(hash_type); + + if (h < 0) + return -1; + + /* + * The "sig" buffer must be as large as the size of ctx->N + * (eg. 128 bytes if RSA-1024 is used). + */ + if (sig_len < ctx->ctx->len) + return -1; + + n = mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx->ctx, NULL, NULL, + MBEDTLS_RSA_PRIVATE, h, 0, in, + sig); + if (n < 0) { + lwsl_notice("%s: -0x%x\n", __func__, -n); + + return -1; + } + + return ctx->ctx->len; +} + +LWS_VISIBLE int +lws_genrsa_render_pkey_asn1(struct lws_genrsa_ctx *ctx, int _private, + uint8_t *pkey_asn1, size_t pkey_asn1_len) +{ + uint8_t *p = pkey_asn1, *totlen, *end = pkey_asn1 + pkey_asn1_len - 1; + mbedtls_mpi *mpi[LWS_COUNT_RSA_ELEMENTS] = { + &ctx->ctx->N, &ctx->ctx->E, &ctx->ctx->D, &ctx->ctx->P, + &ctx->ctx->Q, &ctx->ctx->DP, &ctx->ctx->DQ, + &ctx->ctx->QP, + }; + int n; + + /* 30 82 - sequence + * 09 29 <-- length(0x0929) less 4 bytes + * 02 01 <- length (1) + * 00 + * 02 82 + * 02 01 <- length (513) N + * ... + * + * 02 03 <- length (3) E + * 01 00 01 + * + * 02 82 + * 02 00 <- length (512) D P Q EXP1 EXP2 COEFF + * + * */ + + *p++ = 0x30; + *p++ = 0x82; + totlen = p; + p += 2; + + *p++ = 0x02; + *p++ = 0x01; + *p++ = 0x00; + + for (n = 0; n < LWS_COUNT_RSA_ELEMENTS; n++) { + int m = mbedtls_mpi_size(mpi[n]); + uint8_t *elen; + + *p++ = 0x02; + elen = p; + if (m < 0x7f) + *p++ = m; + else { + *p++ = 0x82; + *p++ = m >> 8; + *p++ = m & 0xff; + } + + if (p + m > end) + return -1; + + mbedtls_mpi_write_binary(mpi[n], p, m); + if (p[0] & 0x80) { + p[0] = 0x00; + mbedtls_mpi_write_binary(mpi[n], &p[1], m); + m++; + } + if (m < 0x7f) + *elen = m; + else { + *elen++ = 0x82; + *elen++ = m >> 8; + *elen = m & 0xff; + } + p += m; + } + + n = lws_ptr_diff(p, pkey_asn1); + + *totlen++ = (n - 4) >> 8; + *totlen = (n - 4) & 0xff; + + return n; +} + +LWS_VISIBLE void +lws_genrsa_destroy(struct lws_genrsa_ctx *ctx) +{ + if (!ctx->ctx) + return; + mbedtls_rsa_free(ctx->ctx); + lws_free(ctx->ctx); + ctx->ctx = NULL; +} diff --git a/thirdparty/libwebsockets/tls/mbedtls/mbedtls-client.c b/thirdparty/libwebsockets/tls/mbedtls/mbedtls-client.c new file mode 100644 index 0000000000..a7864ab790 --- /dev/null +++ b/thirdparty/libwebsockets/tls/mbedtls/mbedtls-client.c @@ -0,0 +1,240 @@ +/* + * libwebsockets - mbedtls-specific client TLS code + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +static int +OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) +{ + return 0; +} + +int +lws_ssl_client_bio_create(struct lws *wsi) +{ + X509_VERIFY_PARAM *param; + char hostname[128], *p; + const char *alpn_comma = wsi->context->tls.alpn_default; + struct alpn_ctx protos; + + if (lws_hdr_copy(wsi, hostname, sizeof(hostname), + _WSI_TOKEN_CLIENT_HOST) <= 0) { + lwsl_err("%s: Unable to get hostname\n", __func__); + + return -1; + } + + /* + * remove any :port part on the hostname... necessary for network + * connection but typical certificates do not contain it + */ + p = hostname; + while (*p) { + if (*p == ':') { + *p = '\0'; + break; + } + p++; + } + + wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_client_ctx); + if (!wsi->tls.ssl) + return -1; + + if (wsi->vhost->tls.ssl_info_event_mask) + SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback); + + if (!(wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) { + param = SSL_get0_param(wsi->tls.ssl); + /* Enable automatic hostname checks */ + // X509_VERIFY_PARAM_set_hostflags(param, + // X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + X509_VERIFY_PARAM_set1_host(param, hostname, 0); + } + + if (wsi->vhost->tls.alpn) + alpn_comma = wsi->vhost->tls.alpn; + + if (lws_hdr_copy(wsi, hostname, sizeof(hostname), + _WSI_TOKEN_CLIENT_ALPN) > 0) + alpn_comma = hostname; + + lwsl_info("%s: %p: client conn sending ALPN list '%s'\n", + __func__, wsi, alpn_comma); + + protos.len = lws_alpn_comma_to_openssl(alpn_comma, protos.data, + sizeof(protos.data) - 1); + + /* with mbedtls, protos is not pointed to after exit from this call */ + SSL_set_alpn_select_cb(wsi->tls.ssl, &protos); + + /* + * use server name indication (SNI), if supported, + * when establishing connection + */ + SSL_set_verify(wsi->tls.ssl, SSL_VERIFY_PEER, + OpenSSL_client_verify_callback); + + SSL_set_fd(wsi->tls.ssl, wsi->desc.sockfd); + + return 0; +} + +int ERR_get_error(void) +{ + return 0; +} + +enum lws_ssl_capable_status +lws_tls_client_connect(struct lws *wsi) +{ + int m, n = SSL_connect(wsi->tls.ssl); + const unsigned char *prot; + unsigned int len; + + if (n == 1) { + SSL_get0_alpn_selected(wsi->tls.ssl, &prot, &len); + lws_role_call_alpn_negotiated(wsi, (const char *)prot); + lwsl_info("client connect OK\n"); + return LWS_SSL_CAPABLE_DONE; + } + + m = SSL_get_error(wsi->tls.ssl, n); + + if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) + return LWS_SSL_CAPABLE_MORE_SERVICE_READ; + + if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) + return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE; + + if (!n) /* we don't know what he wants, but he says to retry */ + return LWS_SSL_CAPABLE_MORE_SERVICE; + + return LWS_SSL_CAPABLE_ERROR; +} + +int +lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len) +{ + int n; + X509 *peer = SSL_get_peer_certificate(wsi->tls.ssl); + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + char *sb = (char *)&pt->serv_buf[0]; + + if (!peer) { + lwsl_info("peer did not provide cert\n"); + + return -1; + } + lwsl_info("peer provided cert\n"); + + n = SSL_get_verify_result(wsi->tls.ssl); + lws_latency(wsi->context, wsi, + "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0); + + lwsl_debug("get_verify says %d\n", n); + + if (n == X509_V_OK) + return 0; + + if (n == X509_V_ERR_HOSTNAME_MISMATCH && + (wsi->tls.use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) { + lwsl_info("accepting certificate for invalid hostname\n"); + return 0; + } + + if (n == X509_V_ERR_INVALID_CA && + (wsi->tls.use_ssl & LCCSCF_ALLOW_SELFSIGNED)) { + lwsl_info("accepting certificate from untrusted CA\n"); + return 0; + } + + if ((n == X509_V_ERR_CERT_NOT_YET_VALID || + n == X509_V_ERR_CERT_HAS_EXPIRED) && + (wsi->tls.use_ssl & LCCSCF_ALLOW_EXPIRED)) { + lwsl_info("accepting expired or not yet valid certificate\n"); + + return 0; + } + lws_snprintf(ebuf, ebuf_len, + "server's cert didn't look good, X509_V_ERR = %d: %s\n", + n, ERR_error_string(n, sb)); + lwsl_info("%s\n", ebuf); + lws_ssl_elaborate_error(); + + return -1; +} + +int +lws_tls_client_create_vhost_context(struct lws_vhost *vh, + const struct lws_context_creation_info *info, + const char *cipher_list, + const char *ca_filepath, + const char *cert_filepath, + const char *private_key_filepath) +{ + X509 *d2i_X509(X509 **cert, const unsigned char *buffer, long len); + SSL_METHOD *method = (SSL_METHOD *)TLS_client_method(); + unsigned long error; + lws_filepos_t len; + uint8_t *buf; + + if (!method) { + error = ERR_get_error(); + lwsl_err("problem creating ssl method %lu: %s\n", + error, ERR_error_string(error, + (char *)vh->context->pt[0].serv_buf)); + return 1; + } + /* create context */ + vh->tls.ssl_client_ctx = SSL_CTX_new(method); + if (!vh->tls.ssl_client_ctx) { + error = ERR_get_error(); + lwsl_err("problem creating ssl context %lu: %s\n", + error, ERR_error_string(error, + (char *)vh->context->pt[0].serv_buf)); + return 1; + } + + if (!ca_filepath) + return 0; + + if (alloc_file(vh->context, ca_filepath, &buf, &len)) { + lwsl_err("Load CA cert file %s failed\n", ca_filepath); + return 1; + } + + vh->tls.x509_client_CA = d2i_X509(NULL, buf, len); + free(buf); + if (!vh->tls.x509_client_CA) { + lwsl_err("client CA: x509 parse failed\n"); + return 1; + } + + if (!vh->tls.ssl_ctx) + SSL_CTX_add_client_CA(vh->tls.ssl_client_ctx, vh->tls.x509_client_CA); + else + SSL_CTX_add_client_CA(vh->tls.ssl_ctx, vh->tls.x509_client_CA); + + lwsl_notice("client loaded CA for verification %s\n", ca_filepath); + + return 0; +} diff --git a/thirdparty/libwebsockets/tls/mbedtls/mbedtls-server.c b/thirdparty/libwebsockets/tls/mbedtls/mbedtls-server.c new file mode 100644 index 0000000000..2de6d422e3 --- /dev/null +++ b/thirdparty/libwebsockets/tls/mbedtls/mbedtls-server.c @@ -0,0 +1,694 @@ +/* + * libwebsockets - mbedTLS-specific server functions + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" +#include <mbedtls/x509_csr.h> + +int +lws_tls_server_client_cert_verify_config(struct lws_vhost *vh) +{ + int verify_options = SSL_VERIFY_PEER; + + /* as a server, are we requiring clients to identify themselves? */ + if (!lws_check_opt(vh->options, + LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT)) { + lwsl_notice("no client cert required\n"); + return 0; + } + + /* + * The wrapper has this messed-up mapping: + * + * else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT) + * mode = MBEDTLS_SSL_VERIFY_OPTIONAL; + * + * ie the meaning is inverted. So where we should test for ! we don't + */ + if (lws_check_opt(vh->options, LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED)) + verify_options = SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + + lwsl_notice("%s: vh %s requires client cert %d\n", __func__, vh->name, + verify_options); + + SSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options, NULL); + + return 0; +} + +static int +lws_mbedtls_sni_cb(void *arg, mbedtls_ssl_context *mbedtls_ctx, + const unsigned char *servername, size_t len) +{ + SSL *ssl = SSL_SSL_from_mbedtls_ssl_context(mbedtls_ctx); + struct lws_context *context = (struct lws_context *)arg; + struct lws_vhost *vhost, *vh; + + lwsl_notice("%s: %s\n", __func__, servername); + + /* + * We can only get ssl accepted connections by using a vhost's ssl_ctx + * find out which listening one took us and only match vhosts on the + * same port. + */ + vh = context->vhost_list; + while (vh) { + if (!vh->being_destroyed && + vh->tls.ssl_ctx == SSL_get_SSL_CTX(ssl)) + break; + vh = vh->vhost_next; + } + + if (!vh) { + assert(vh); /* can't match the incoming vh? */ + return 0; + } + + vhost = lws_select_vhost(context, vh->listen_port, + (const char *)servername); + if (!vhost) { + lwsl_info("SNI: none: %s:%d\n", servername, vh->listen_port); + + return 0; + } + + lwsl_info("SNI: Found: %s:%d at vhost '%s'\n", servername, + vh->listen_port, vhost->name); + + /* select the ssl ctx from the selected vhost for this conn */ + SSL_set_SSL_CTX(ssl, vhost->tls.ssl_ctx); + + return 0; +} + +int +lws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi, + const char *cert, const char *private_key, + const char *mem_cert, size_t len_mem_cert, + const char *mem_privkey, size_t mem_privkey_len) +{ + int n, f = 0; + const char *filepath = private_key; + uint8_t *mem = NULL, *p = NULL; + size_t mem_len = 0; + lws_filepos_t flen; + long err; + + if ((!cert || !private_key) && (!mem_cert || !mem_privkey)) { + lwsl_notice("%s: no usable input\n", __func__); + return 0; + } + + n = lws_tls_generic_cert_checks(vhost, cert, private_key); + + if (n == LWS_TLS_EXTANT_NO && (!mem_cert || !mem_privkey)) + return 0; + + /* + * we can't read the root-privs files. But if mem_cert is provided, + * we should use that. + */ + if (n == LWS_TLS_EXTANT_NO) + n = LWS_TLS_EXTANT_ALTERNATIVE; + + if (n == LWS_TLS_EXTANT_ALTERNATIVE && (!mem_cert || !mem_privkey)) + return 1; /* no alternative */ + + if (n == LWS_TLS_EXTANT_ALTERNATIVE) { + /* + * Although we have prepared update certs, we no longer have + * the rights to read our own cert + key we saved. + * + * If we were passed copies in memory buffers, use those + * instead. + * + * The passed memory-buffer cert image is in DER, and the + * memory-buffer private key image is PEM. + */ + /* mem cert is already DER */ + p = (uint8_t *)mem_cert; + flen = len_mem_cert; + /* mem private key is PEM, so go through the motions */ + mem = (uint8_t *)mem_privkey; + mem_len = mem_privkey_len; + filepath = NULL; + } else { + if (lws_tls_alloc_pem_to_der_file(vhost->context, cert, NULL, + 0, &p, &flen)) { + lwsl_err("couldn't find cert file %s\n", cert); + + return 1; + } + f = 1; + } + err = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx, flen, p); + if (!err) { + free(p); + lwsl_err("Problem loading cert\n"); + return 1; + } + + if (f) + free(p); + p = NULL; + + if (private_key || n == LWS_TLS_EXTANT_ALTERNATIVE) { + if (lws_tls_alloc_pem_to_der_file(vhost->context, filepath, + (char *)mem, mem_len, &p, + &flen)) { + lwsl_err("couldn't find private key file %s\n", + private_key); + + return 1; + } + err = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx, p, flen); + if (!err) { + free(p); + lwsl_err("Problem loading key\n"); + + return 1; + } + } + + if (p && !mem_privkey) { + free(p); + p = NULL; + } + + if (!private_key && !mem_privkey && + vhost->protocols[0].callback(wsi, + LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY, + vhost->tls.ssl_ctx, NULL, 0)) { + lwsl_err("ssl private key not set\n"); + + return 1; + } + + vhost->tls.skipped_certs = 0; + + return 0; +} + +int +lws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info, + struct lws_vhost *vhost, struct lws *wsi) +{ + const SSL_METHOD *method = TLS_server_method(); + uint8_t *p; + lws_filepos_t flen; + int n; + + vhost->tls.ssl_ctx = SSL_CTX_new(method); /* create context */ + if (!vhost->tls.ssl_ctx) { + lwsl_err("problem creating ssl context\n"); + return 1; + } + + if (!vhost->tls.use_ssl || !info->ssl_cert_filepath) + return 0; + + if (info->ssl_ca_filepath) { + lwsl_notice("%s: vh %s: loading CA filepath %s\n", __func__, + vhost->name, info->ssl_ca_filepath); + if (lws_tls_alloc_pem_to_der_file(vhost->context, + info->ssl_ca_filepath, NULL, 0, &p, &flen)) { + lwsl_err("couldn't find client CA file %s\n", + info->ssl_ca_filepath); + + return 1; + } + + if (SSL_CTX_add_client_CA_ASN1(vhost->tls.ssl_ctx, (int)flen, p) != 1) { + lwsl_err("%s: SSL_CTX_add_client_CA_ASN1 unhappy\n", + __func__); + free(p); + return 1; + } + free(p); + } + + n = lws_tls_server_certs_load(vhost, wsi, info->ssl_cert_filepath, + info->ssl_private_key_filepath, NULL, + 0, NULL, 0); + if (n) + return n; + + return 0; +} + +int +lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd) +{ + errno = 0; + wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_ctx); + if (wsi->tls.ssl == NULL) { + lwsl_err("SSL_new failed: errno %d\n", errno); + + lws_ssl_elaborate_error(); + return 1; + } + + SSL_set_fd(wsi->tls.ssl, accept_fd); + + if (wsi->vhost->tls.ssl_info_event_mask) + SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback); + + SSL_set_sni_callback(wsi->tls.ssl, lws_mbedtls_sni_cb, wsi->context); + + return 0; +} + +int +lws_tls_server_abort_connection(struct lws *wsi) +{ + __lws_tls_shutdown(wsi); + SSL_free(wsi->tls.ssl); + + return 0; +} + +enum lws_ssl_capable_status +lws_tls_server_accept(struct lws *wsi) +{ + union lws_tls_cert_info_results ir; + int m, n; + + n = SSL_accept(wsi->tls.ssl); + if (n == 1) { + + if (strstr(wsi->vhost->name, ".invalid")) { + lwsl_notice("%s: vhost has .invalid, rejecting accept\n", __func__); + + return LWS_SSL_CAPABLE_ERROR; + } + + n = lws_tls_peer_cert_info(wsi, LWS_TLS_CERT_INFO_COMMON_NAME, &ir, + sizeof(ir.ns.name)); + if (!n) + lwsl_notice("%s: client cert CN '%s'\n", + __func__, ir.ns.name); + else + lwsl_info("%s: couldn't get client cert CN\n", __func__); + return LWS_SSL_CAPABLE_DONE; + } + + m = SSL_get_error(wsi->tls.ssl, n); + lwsl_debug("%s: %p: accept SSL_get_error %d errno %d\n", __func__, + wsi, m, errno); + + // mbedtls wrapper only + if (m == SSL_ERROR_SYSCALL && errno == 11) + return LWS_SSL_CAPABLE_MORE_SERVICE_READ; + + if (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL) + return LWS_SSL_CAPABLE_ERROR; + + if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) { + if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { + lwsl_info("%s: WANT_READ change_pollfd failed\n", __func__); + return LWS_SSL_CAPABLE_ERROR; + } + + lwsl_info("SSL_ERROR_WANT_READ\n"); + return LWS_SSL_CAPABLE_MORE_SERVICE_READ; + } + if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) { + lwsl_debug("%s: WANT_WRITE\n", __func__); + + if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) { + lwsl_info("%s: WANT_WRITE change_pollfd failed\n", __func__); + return LWS_SSL_CAPABLE_ERROR; + } + return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE; + } + + return LWS_SSL_CAPABLE_ERROR; +} + +#if defined(LWS_WITH_ACME) +/* + * mbedtls doesn't support SAN for cert creation. So we use a known-good + * tls-sni-01 cert from OpenSSL that worked on Let's Encrypt, and just replace + * the pubkey n part and the signature part. + * + * This will need redoing for tls-sni-02... + */ + +static uint8_t ss_cert_leadin[] = { + 0x30, 0x82, + 0x05, 0x56, /* total length: LEN1 (+2 / +3) (correct for 513 + 512)*/ + + 0x30, 0x82, /* length: LEN2 (+6 / +7) (correct for 513) */ + 0x03, 0x3e, + + /* addition: v3 cert (+5 bytes)*/ + 0xa0, 0x03, + 0x02, 0x01, 0x02, + + 0x02, 0x01, 0x01, + 0x30, 0x0d, 0x06, 0x09, 0x2a, + 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x3f, + 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47, + 0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x0b, + 0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e, 0x79, 0x31, + 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x74, 0x65, + 0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e, 0x76, 0x61, + 0x6c, 0x69, 0x64, 0x30, 0x1e, 0x17, 0x0d, + + /* from 2017-10-29 ... */ + 0x31, 0x37, 0x31, 0x30, 0x32, 0x39, 0x31, 0x31, 0x34, 0x39, 0x34, 0x35, + 0x5a, 0x17, 0x0d, + + /* thru 2049-10-29 we immediately discard the private key, no worries */ + 0x34, 0x39, 0x31, 0x30, 0x32, 0x39, 0x31, 0x32, 0x34, 0x39, 0x34, 0x35, + 0x5a, + + 0x30, 0x3f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x47, 0x42, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0a, + 0x0c, 0x0b, 0x73, 0x6f, 0x6d, 0x65, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x6e, + 0x79, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, + 0x74, 0x65, 0x6d, 0x70, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, 0x6e, + 0x76, 0x61, 0x6c, 0x69, 0x64, 0x30, + + 0x82, + 0x02, 0x22, /* LEN3 (+C3 / C4) */ + 0x30, 0x0d, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, + 0x03, + + 0x82, + 0x02, 0x0f, /* LEN4 (+D6 / D7) */ + + 0x00, 0x30, 0x82, + + 0x02, 0x0a, /* LEN5 (+ DB / DC) */ + + 0x02, 0x82, + + //0x02, 0x01, /* length of n in bytes (including leading 00 if any) */ + }, + + /* 1 + (keybits / 8) bytes N */ + + ss_cert_san_leadin[] = { + /* e - fixed */ + 0x02, 0x03, 0x01, 0x00, 0x01, + + 0xa3, 0x5d, 0x30, 0x5b, 0x30, 0x59, 0x06, 0x03, 0x55, 0x1d, + 0x11, 0x04, 0x52, 0x30, 0x50, /* <-- SAN length + 2 */ + + 0x82, 0x4e, /* <-- SAN length */ + }, + + /* 78 bytes of SAN (tls-sni-01) + 0x61, 0x64, 0x34, 0x31, 0x61, 0x66, 0x62, 0x65, 0x30, 0x63, 0x61, 0x34, + 0x36, 0x34, 0x32, 0x66, 0x30, 0x61, 0x34, 0x34, 0x39, 0x64, 0x39, 0x63, + 0x61, 0x37, 0x36, 0x65, 0x62, 0x61, 0x61, 0x62, 0x2e, 0x32, 0x38, 0x39, + 0x34, 0x64, 0x34, 0x31, 0x36, 0x63, 0x39, 0x38, 0x33, 0x66, 0x31, 0x32, + 0x65, 0x64, 0x37, 0x33, 0x31, 0x61, 0x33, 0x30, 0x66, 0x35, 0x63, 0x34, + 0x34, 0x37, 0x37, 0x66, 0x65, 0x2e, 0x61, 0x63, 0x6d, 0x65, 0x2e, 0x69, + 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, */ + + /* end of LEN2 area */ + + ss_cert_sig_leadin[] = { + /* it's saying that the signature is SHA256 + RSA */ + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, + + 0x82, + 0x02, 0x01, + 0x00, + }; + + /* (keybits / 8) bytes signature to end of LEN1 area */ + +#define SAN_A_LENGTH 78 + +LWS_VISIBLE int +lws_tls_acme_sni_cert_create(struct lws_vhost *vhost, const char *san_a, + const char *san_b) +{ + int buflen = 0x560; + uint8_t *buf = lws_malloc(buflen, "tmp cert buf"), *p = buf, *pkey_asn1; + struct lws_genrsa_ctx ctx; + struct lws_genrsa_elements el; + uint8_t digest[32]; + struct lws_genhash_ctx hash_ctx; + int pkey_asn1_len = 3 * 1024; + int n, m, keybits = lws_plat_recommended_rsa_bits(), adj; + + if (!buf) + return 1; + + n = lws_genrsa_new_keypair(vhost->context, &ctx, &el, keybits); + if (n < 0) { + lws_jwk_destroy_genrsa_elements(&el); + goto bail1; + } + + n = sizeof(ss_cert_leadin); + memcpy(p, ss_cert_leadin, n); + p += n; + + adj = (0x0556 - 0x401) + (keybits / 4) + 1; + buf[2] = adj >> 8; + buf[3] = adj & 0xff; + + adj = (0x033e - 0x201) + (keybits / 8) + 1; + buf[6] = adj >> 8; + buf[7] = adj & 0xff; + + adj = (0x0222 - 0x201) + (keybits / 8) + 1; + buf[0xc3] = adj >> 8; + buf[0xc4] = adj & 0xff; + + adj = (0x020f - 0x201) + (keybits / 8) + 1; + buf[0xd6] = adj >> 8; + buf[0xd7] = adj & 0xff; + + adj = (0x020a - 0x201) + (keybits / 8) + 1; + buf[0xdb] = adj >> 8; + buf[0xdc] = adj & 0xff; + + *p++ = ((keybits / 8) + 1) >> 8; + *p++ = ((keybits / 8) + 1) & 0xff; + + /* we need to drop 1 + (keybits / 8) bytes of n in here, 00 + key */ + + *p++ = 0x00; + memcpy(p, el.e[JWK_KEY_N].buf, el.e[JWK_KEY_N].len); + p += el.e[JWK_KEY_N].len; + + memcpy(p, ss_cert_san_leadin, sizeof(ss_cert_san_leadin)); + p += sizeof(ss_cert_san_leadin); + + /* drop in 78 bytes of san_a */ + + memcpy(p, san_a, SAN_A_LENGTH); + p += SAN_A_LENGTH; + memcpy(p, ss_cert_sig_leadin, sizeof(ss_cert_sig_leadin)); + + p[17] = ((keybits / 8) + 1) >> 8; + p[18] = ((keybits / 8) + 1) & 0xff; + + p += sizeof(ss_cert_sig_leadin); + + /* hash the cert plaintext */ + + if (lws_genhash_init(&hash_ctx, LWS_GENHASH_TYPE_SHA256)) + goto bail2; + + if (lws_genhash_update(&hash_ctx, buf, lws_ptr_diff(p, buf))) { + lws_genhash_destroy(&hash_ctx, NULL); + + goto bail2; + } + if (lws_genhash_destroy(&hash_ctx, digest)) + goto bail2; + + /* sign the hash */ + + n = lws_genrsa_public_sign(&ctx, digest, LWS_GENHASH_TYPE_SHA256, p, + buflen - lws_ptr_diff(p, buf)); + if (n < 0) + goto bail2; + p += n; + + pkey_asn1 = lws_malloc(pkey_asn1_len, "mbed crt tmp"); + if (!pkey_asn1) + goto bail2; + + m = lws_genrsa_render_pkey_asn1(&ctx, 1, pkey_asn1, pkey_asn1_len); + if (m < 0) { + lws_free(pkey_asn1); + goto bail2; + } + +// lwsl_hexdump_level(LLL_DEBUG, buf, lws_ptr_diff(p, buf)); + n = SSL_CTX_use_certificate_ASN1(vhost->tls.ssl_ctx, + lws_ptr_diff(p, buf), buf); + if (n != 1) { + lws_free(pkey_asn1); + lwsl_err("%s: generated cert failed to load 0x%x\n", + __func__, -n); + } else { + //lwsl_debug("private key\n"); + //lwsl_hexdump_level(LLL_DEBUG, pkey_asn1, n); + + /* and to use our generated private key */ + n = SSL_CTX_use_PrivateKey_ASN1(0, vhost->tls.ssl_ctx, pkey_asn1, m); + lws_free(pkey_asn1); + if (n != 1) { + lwsl_err("%s: SSL_CTX_use_PrivateKey_ASN1 failed\n", + __func__); + } + } + + lws_genrsa_destroy(&ctx); + lws_jwk_destroy_genrsa_elements(&el); + + lws_free(buf); + + return n != 1; + +bail2: + lws_genrsa_destroy(&ctx); + lws_jwk_destroy_genrsa_elements(&el); +bail1: + lws_free(buf); + + return -1; +} + +void +lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost) +{ +} + +#if defined(LWS_WITH_JWS) +static int +_rngf(void *context, unsigned char *buf, size_t len) +{ + if ((size_t)lws_get_random(context, buf, len) == len) + return 0; + + return -1; +} + +static const char *x5[] = { "C", "ST", "L", "O", "CN" }; + +/* + * CSR is output formatted as b64url(DER) + * Private key is output as a PEM in memory + */ +LWS_VISIBLE LWS_EXTERN int +lws_tls_acme_sni_csr_create(struct lws_context *context, const char *elements[], + uint8_t *dcsr, size_t csr_len, char **privkey_pem, + size_t *privkey_len) +{ + mbedtls_x509write_csr csr; + mbedtls_pk_context mpk; + int buf_size = 4096, n; + char subject[200], *p = subject, *end = p + sizeof(subject) - 1; + uint8_t *buf = malloc(buf_size); /* malloc because given to user code */ + + if (!buf) + return -1; + + mbedtls_x509write_csr_init(&csr); + + mbedtls_pk_init(&mpk); + if (mbedtls_pk_setup(&mpk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA))) { + lwsl_notice("%s: pk_setup failed\n", __func__); + goto fail; + } + + n = mbedtls_rsa_gen_key(mbedtls_pk_rsa(mpk), _rngf, context, + lws_plat_recommended_rsa_bits(), 65537); + if (n) { + lwsl_notice("%s: failed to generate keys\n", __func__); + + goto fail1; + } + + /* subject must be formatted like "C=TW,O=warmcat,CN=myserver" */ + + for (n = 0; n < (int)ARRAY_SIZE(x5); n++) { + if (p != subject) + *p++ = ','; + if (elements[n]) + p += lws_snprintf(p, end - p, "%s=%s", x5[n], + elements[n]); + } + + if (mbedtls_x509write_csr_set_subject_name(&csr, subject)) + goto fail1; + + mbedtls_x509write_csr_set_key(&csr, &mpk); + mbedtls_x509write_csr_set_md_alg(&csr, MBEDTLS_MD_SHA256); + + /* + * data is written at the end of the buffer! Use the + * return value to determine where you should start + * using the buffer + */ + n = mbedtls_x509write_csr_der(&csr, buf, buf_size, _rngf, context); + if (n < 0) { + lwsl_notice("%s: write csr der failed\n", __func__); + goto fail1; + } + + /* we have it in DER, we need it in b64URL */ + + n = lws_jws_base64_enc((char *)(buf + buf_size) - n, n, + (char *)dcsr, csr_len); + if (n < 0) + goto fail1; + + /* + * okay, the CSR is done, last we need the private key in PEM + * re-use the DER CSR buf as the result buffer since we cn do it in + * one step + */ + + if (mbedtls_pk_write_key_pem(&mpk, buf, buf_size)) { + lwsl_notice("write key pem failed\n"); + goto fail1; + } + + *privkey_pem = (char *)buf; + *privkey_len = strlen((const char *)buf); + + mbedtls_pk_free(&mpk); + mbedtls_x509write_csr_free(&csr); + + return n; + +fail1: + mbedtls_pk_free(&mpk); +fail: + mbedtls_x509write_csr_free(&csr); + free(buf); + + return -1; +} +#endif +#endif diff --git a/thirdparty/libwebsockets/tls/mbedtls/ssl.c b/thirdparty/libwebsockets/tls/mbedtls/ssl.c new file mode 100644 index 0000000000..6ae9d2556b --- /dev/null +++ b/thirdparty/libwebsockets/tls/mbedtls/ssl.c @@ -0,0 +1,520 @@ +/* + * libwebsockets - mbedTLS-specific lws apis + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" +#include <mbedtls/oid.h> + +void +lws_ssl_elaborate_error(void) +{ +} + +int +lws_context_init_ssl_library(const struct lws_context_creation_info *info) +{ + lwsl_info(" Compiled with MbedTLS support\n"); + + if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) + lwsl_info(" SSL disabled: no LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\n"); + + return 0; +} + +LWS_VISIBLE void +lws_ssl_destroy(struct lws_vhost *vhost) +{ + if (!lws_check_opt(vhost->context->options, + LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) + return; + + if (vhost->tls.ssl_ctx) + SSL_CTX_free(vhost->tls.ssl_ctx); + if (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx) + SSL_CTX_free(vhost->tls.ssl_client_ctx); + + if (vhost->tls.x509_client_CA) + X509_free(vhost->tls.x509_client_CA); +} + +LWS_VISIBLE int +lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + int n = 0, m; + + if (!wsi->tls.ssl) + return lws_ssl_capable_read_no_ssl(wsi, buf, len); + + lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1); + + errno = 0; + n = SSL_read(wsi->tls.ssl, buf, len); +#if defined(LWS_WITH_ESP32) + if (!n && errno == ENOTCONN) { + lwsl_debug("%p: SSL_read ENOTCONN\n", wsi); + return LWS_SSL_CAPABLE_ERROR; + } +#endif +#if defined(LWS_WITH_STATS) + if (!wsi->seen_rx) { + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_MS_SSL_RX_DELAY, + time_in_microseconds() - wsi->accept_start_us); + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_SSL_CONNS_HAD_RX, 1); + wsi->seen_rx = 1; + } +#endif + + + lwsl_debug("%p: SSL_read says %d\n", wsi, n); + /* manpage: returning 0 means connection shut down */ + if (!n) { + wsi->socket_is_permanently_unusable = 1; + + return LWS_SSL_CAPABLE_ERROR; + } + + if (n < 0) { + m = SSL_get_error(wsi->tls.ssl, n); + lwsl_debug("%p: ssl err %d errno %d\n", wsi, m, errno); + if (m == SSL_ERROR_ZERO_RETURN || + m == SSL_ERROR_SYSCALL) + return LWS_SSL_CAPABLE_ERROR; + + if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) { + lwsl_debug("%s: WANT_READ\n", __func__); + lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi); + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) { + lwsl_debug("%s: WANT_WRITE\n", __func__); + lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi); + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + wsi->socket_is_permanently_unusable = 1; + + return LWS_SSL_CAPABLE_ERROR; + } + + lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n); + + if (wsi->vhost) + wsi->vhost->conn_stats.rx += n; + + lws_restart_ws_ping_pong_timer(wsi); + + /* + * if it was our buffer that limited what we read, + * check if SSL has additional data pending inside SSL buffers. + * + * Because these won't signal at the network layer with POLLIN + * and if we don't realize, this data will sit there forever + */ + if (n != len) + goto bail; + if (!wsi->tls.ssl) + goto bail; + + if (!SSL_pending(wsi->tls.ssl)) + goto bail; + + if (wsi->tls.pending_read_list_next) + return n; + if (wsi->tls.pending_read_list_prev) + return n; + if (pt->tls.pending_read_list == wsi) + return n; + + /* add us to the linked list of guys with pending ssl */ + if (pt->tls.pending_read_list) + pt->tls.pending_read_list->tls.pending_read_list_prev = wsi; + + wsi->tls.pending_read_list_next = pt->tls.pending_read_list; + wsi->tls.pending_read_list_prev = NULL; + pt->tls.pending_read_list = wsi; + + return n; +bail: + lws_ssl_remove_wsi_from_buffered_list(wsi); + + return n; +} + +LWS_VISIBLE int +lws_ssl_pending(struct lws *wsi) +{ + if (!wsi->tls.ssl) + return 0; + + return SSL_pending(wsi->tls.ssl); +} + +LWS_VISIBLE int +lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len) +{ + int n, m; + + if (!wsi->tls.ssl) + return lws_ssl_capable_write_no_ssl(wsi, buf, len); + + n = SSL_write(wsi->tls.ssl, buf, len); + if (n > 0) + return n; + + m = SSL_get_error(wsi->tls.ssl, n); + if (m != SSL_ERROR_SYSCALL) { + if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->tls.ssl)) { + lwsl_notice("%s: want read\n", __func__); + + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + + if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->tls.ssl)) { + lws_set_blocking_send(wsi); + lwsl_notice("%s: want write\n", __func__); + + return LWS_SSL_CAPABLE_MORE_SERVICE; + } + } + + lwsl_debug("%s failed: %d\n",__func__, m); + wsi->socket_is_permanently_unusable = 1; + + return LWS_SSL_CAPABLE_ERROR; +} + +int openssl_SSL_CTX_private_data_index; + +void +lws_ssl_info_callback(const SSL *ssl, int where, int ret) +{ + struct lws *wsi; + struct lws_context *context; + struct lws_ssl_info si; + + context = (struct lws_context *)SSL_CTX_get_ex_data( + SSL_get_SSL_CTX(ssl), + openssl_SSL_CTX_private_data_index); + if (!context) + return; + wsi = wsi_from_fd(context, SSL_get_fd(ssl)); + if (!wsi) + return; + + if (!(where & wsi->vhost->tls.ssl_info_event_mask)) + return; + + si.where = where; + si.ret = ret; + + if (user_callback_handle_rxflow(wsi->protocol->callback, + wsi, LWS_CALLBACK_SSL_INFO, + wsi->user_space, &si, 0)) + lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1); +} + + +LWS_VISIBLE int +lws_ssl_close(struct lws *wsi) +{ + lws_sockfd_type n; + + if (!wsi->tls.ssl) + return 0; /* not handled */ + +#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK) + /* kill ssl callbacks, becausse we will remove the fd from the + * table linking it to the wsi + */ + if (wsi->vhost->tls.ssl_info_event_mask) + SSL_set_info_callback(wsi->tls.ssl, NULL); +#endif + + n = SSL_get_fd(wsi->tls.ssl); + if (!wsi->socket_is_permanently_unusable) + SSL_shutdown(wsi->tls.ssl); + compatible_close(n); + SSL_free(wsi->tls.ssl); + wsi->tls.ssl = NULL; + + if (!lwsi_role_client(wsi) && + wsi->context->simultaneous_ssl_restriction && + wsi->context->simultaneous_ssl-- == + wsi->context->simultaneous_ssl_restriction) + /* we made space and can do an accept */ + lws_gate_accepts(wsi->context, 1); + +#if defined(LWS_WITH_STATS) + wsi->context->updated = 1; +#endif + + return 1; /* handled */ +} + +void +lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost) +{ + if (vhost->tls.ssl_ctx) + SSL_CTX_free(vhost->tls.ssl_ctx); + + if (!vhost->tls.user_supplied_ssl_ctx && vhost->tls.ssl_client_ctx) + SSL_CTX_free(vhost->tls.ssl_client_ctx); +#if defined(LWS_WITH_ACME) + lws_tls_acme_sni_cert_destroy(vhost); +#endif +} + +void +lws_ssl_context_destroy(struct lws_context *context) +{ +} + +lws_tls_ctx * +lws_tls_ctx_from_wsi(struct lws *wsi) +{ + if (!wsi->tls.ssl) + return NULL; + + return SSL_get_SSL_CTX(wsi->tls.ssl); +} + +enum lws_ssl_capable_status +__lws_tls_shutdown(struct lws *wsi) +{ + int n = SSL_shutdown(wsi->tls.ssl); + + lwsl_debug("SSL_shutdown=%d for fd %d\n", n, wsi->desc.sockfd); + + switch (n) { + case 1: /* successful completion */ + n = shutdown(wsi->desc.sockfd, SHUT_WR); + return LWS_SSL_CAPABLE_DONE; + + case 0: /* needs a retry */ + __lws_change_pollfd(wsi, 0, LWS_POLLIN); + return LWS_SSL_CAPABLE_MORE_SERVICE; + + default: /* fatal error, or WANT */ + n = SSL_get_error(wsi->tls.ssl, n); + if (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) { + if (SSL_want_read(wsi->tls.ssl)) { + lwsl_debug("(wants read)\n"); + __lws_change_pollfd(wsi, 0, LWS_POLLIN); + return LWS_SSL_CAPABLE_MORE_SERVICE_READ; + } + if (SSL_want_write(wsi->tls.ssl)) { + lwsl_debug("(wants write)\n"); + __lws_change_pollfd(wsi, 0, LWS_POLLOUT); + return LWS_SSL_CAPABLE_MORE_SERVICE_WRITE; + } + } + return LWS_SSL_CAPABLE_ERROR; + } +} + +static time_t +lws_tls_mbedtls_time_to_unix(mbedtls_x509_time *xtime) +{ + struct tm t; + + if (!xtime || !xtime->year || xtime->year < 0) + return (time_t)(long long)-1; + + memset(&t, 0, sizeof(t)); + + t.tm_year = xtime->year - 1900; + t.tm_mon = xtime->mon - 1; /* mbedtls months are 1+, tm are 0+ */ + t.tm_mday = xtime->day - 1; /* mbedtls days are 1+, tm are 0+ */ + t.tm_hour = xtime->hour; + t.tm_min = xtime->min; + t.tm_sec = xtime->sec; + t.tm_isdst = -1; + + return mktime(&t); +} + +static int +lws_tls_mbedtls_get_x509_name(mbedtls_x509_name *name, + union lws_tls_cert_info_results *buf, size_t len) +{ + while (name) { + if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid)) { + name = name->next; + continue; + } + + if (len - 1 < name->val.len) + return -1; + + memcpy(&buf->ns.name[0], name->val.p, name->val.len); + buf->ns.name[name->val.len] = '\0'; + buf->ns.len = name->val.len; + + return 0; + } + + return -1; +} + +static int +lws_tls_mbedtls_cert_info(mbedtls_x509_crt *x509, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len) +{ + if (!x509) + return -1; + + switch (type) { + case LWS_TLS_CERT_INFO_VALIDITY_FROM: + buf->time = lws_tls_mbedtls_time_to_unix(&x509->valid_from); + if (buf->time == (time_t)(long long)-1) + return -1; + break; + + case LWS_TLS_CERT_INFO_VALIDITY_TO: + buf->time = lws_tls_mbedtls_time_to_unix(&x509->valid_to); + if (buf->time == (time_t)(long long)-1) + return -1; + break; + + case LWS_TLS_CERT_INFO_COMMON_NAME: + return lws_tls_mbedtls_get_x509_name(&x509->subject, buf, len); + + case LWS_TLS_CERT_INFO_ISSUER_NAME: + return lws_tls_mbedtls_get_x509_name(&x509->issuer, buf, len); + + case LWS_TLS_CERT_INFO_USAGE: + buf->usage = x509->key_usage; + break; + + case LWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY: + { + char *p = buf->ns.name; + size_t r = len, u; + + switch (mbedtls_pk_get_type(&x509->pk)) { + case MBEDTLS_PK_RSA: + { + mbedtls_rsa_context *rsa = mbedtls_pk_rsa(x509->pk); + + if (mbedtls_mpi_write_string(&rsa->N, 16, p, r, &u)) + return -1; + r -= u; + p += u; + if (mbedtls_mpi_write_string(&rsa->E, 16, p, r, &u)) + return -1; + + p += u; + buf->ns.len = lws_ptr_diff(p, buf->ns.name); + break; + } + case MBEDTLS_PK_ECKEY: + { + mbedtls_ecp_keypair *ecp = mbedtls_pk_ec(x509->pk); + + if (mbedtls_mpi_write_string(&ecp->Q.X, 16, p, r, &u)) + return -1; + r -= u; + p += u; + if (mbedtls_mpi_write_string(&ecp->Q.Y, 16, p, r, &u)) + return -1; + r -= u; + p += u; + if (mbedtls_mpi_write_string(&ecp->Q.Z, 16, p, r, &u)) + return -1; + p += u; + buf->ns.len = lws_ptr_diff(p, buf->ns.name); + break; + } + default: + lwsl_notice("%s: x509 has unsupported pubkey type %d\n", + __func__, + mbedtls_pk_get_type(&x509->pk)); + + return -1; + } + break; + } + + default: + return -1; + } + + return 0; +} + +LWS_VISIBLE LWS_EXTERN int +lws_tls_vhost_cert_info(struct lws_vhost *vhost, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len) +{ + mbedtls_x509_crt *x509 = ssl_ctx_get_mbedtls_x509_crt(vhost->tls.ssl_ctx); + + return lws_tls_mbedtls_cert_info(x509, type, buf, len); +} + +LWS_VISIBLE int +lws_tls_peer_cert_info(struct lws *wsi, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len) +{ + mbedtls_x509_crt *x509; + + wsi = lws_get_network_wsi(wsi); + + x509 = ssl_get_peer_mbedtls_x509_crt(wsi->tls.ssl); + + if (!x509) + return -1; + + switch (type) { + case LWS_TLS_CERT_INFO_VERIFIED: + buf->verified = SSL_get_verify_result(wsi->tls.ssl) == X509_V_OK; + return 0; + default: + return lws_tls_mbedtls_cert_info(x509, type, buf, len); + } + + return -1; +} + +static int +tops_fake_POLLIN_for_buffered_mbedtls(struct lws_context_per_thread *pt) +{ + return lws_tls_fake_POLLIN_for_buffered(pt); +} + +static int +tops_periodic_housekeeping_mbedtls(struct lws_context *context, time_t now) +{ + int n; + + n = lws_compare_time_t(context, now, context->tls.last_cert_check_s); + if ((!context->tls.last_cert_check_s || n > (24 * 60 * 60)) && + !lws_tls_check_all_cert_lifetimes(context)) + context->tls.last_cert_check_s = now; + + return 0; +} + +const struct lws_tls_ops tls_ops_mbedtls = { + /* fake_POLLIN_for_buffered */ tops_fake_POLLIN_for_buffered_mbedtls, + /* periodic_housekeeping */ tops_periodic_housekeeping_mbedtls, +}; diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl3.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl3.h index 007b392f3e..007b392f3e 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl3.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl3.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_cert.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_cert.h index 86cf31ad51..86cf31ad51 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_cert.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_cert.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_code.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_code.h index 80fdbb20f3..80fdbb20f3 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_code.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_code.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_dbg.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_dbg.h index ad32cb92ff..ad32cb92ff 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_dbg.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_dbg.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_lib.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_lib.h index 42b2de7501..42b2de7501 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_lib.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_lib.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_methods.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_methods.h index cd2f8c0533..cd2f8c0533 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_methods.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_methods.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_pkey.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_pkey.h index e790fcc995..e790fcc995 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_pkey.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_pkey.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_stack.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_stack.h index 7a7051a026..7a7051a026 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_stack.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_stack.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_types.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_types.h index 2ca438c422..ba19663d9e 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_types.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_types.h @@ -203,6 +203,8 @@ struct ssl_st const SSL_METHOD *method; + const char **alpn_protos; + RECORD_LAYER rlayer; /* where we are */ diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_x509.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_x509.h index 7594d064b4..7594d064b4 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/ssl_x509.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/ssl_x509.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/tls1.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/tls1.h index 7af1b0157d..7af1b0157d 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/tls1.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/tls1.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/internal/x509_vfy.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/x509_vfy.h index 26bf6c88a8..26bf6c88a8 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/internal/x509_vfy.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/internal/x509_vfy.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/openssl/ssl.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/openssl/ssl.h index 5a84b4552e..e2b74fc6af 100644..100755 --- a/thirdparty/lws/mbedtls_wrapper/include/openssl/ssl.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/openssl/ssl.h @@ -35,6 +35,22 @@ #define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS (1 << 3) #define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS (1 << 4) + mbedtls_x509_crt * + ssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx); + + mbedtls_x509_crt * + ssl_get_peer_mbedtls_x509_crt(SSL *ssl); + + int SSL_set_sni_callback(SSL *ssl, int(*cb)(void *, mbedtls_ssl_context *, + const unsigned char *, size_t), void *param); + + void SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx); + + int SSL_CTX_add_client_CA_ASN1(SSL_CTX *ssl, int len, + const unsigned char *d); + + SSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc); + /** * @brief create a SSL context * @@ -305,6 +321,7 @@ void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, void *arg), void *arg); +void SSL_set_alpn_select_cb(SSL *ssl, void *arg); /** * @brief set the SSL context ALPN select protocol diff --git a/thirdparty/lws/mbedtls_wrapper/include/platform/ssl_pm.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_pm.h index cbbe3aa3a2..cbbe3aa3a2 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/platform/ssl_pm.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_pm.h diff --git a/thirdparty/lws/mbedtls_wrapper/include/platform/ssl_port.h b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_port.h index eca68f20d1..74c7634355 100644 --- a/thirdparty/lws/mbedtls_wrapper/include/platform/ssl_port.h +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/include/platform/ssl_port.h @@ -19,19 +19,11 @@ extern "C" { #endif -/* -#include "esp_types.h" -#include "esp_log.h" -*/ #include "string.h" - -/* GODOT ADDITION */ -#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) -#include <stdlib.h> -#else +#include "stdlib.h" +#if defined(LWS_HAVE_MALLOC_H) #include "malloc.h" #endif -/* END GODOT ADDITION */ void *ssl_mem_zalloc(size_t size); diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_cert.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_cert.c index 5c608125ac..5c608125ac 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_cert.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_cert.c diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_lib.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_lib.c index d8fdd06fad..2f688ca9ef 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_lib.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_lib.c @@ -19,6 +19,9 @@ #include "ssl_dbg.h" #include "ssl_port.h" +char * +lws_strncpy(char *dest, const char *src, size_t size); + #define SSL_SEND_DATA_MAX_LENGTH 1460 /** @@ -348,6 +351,9 @@ void SSL_free(SSL *ssl) SSL_SESSION_free(ssl->session); + if (ssl->alpn_protos) + ssl_mem_free(ssl->alpn_protos); + ssl_mem_free(ssl); } @@ -1582,7 +1588,7 @@ void SSL_set_verify(SSL *ssl, int mode, int (*verify_callback)(int, X509_STORE_C void ERR_error_string_n(unsigned long e, char *buf, size_t len) { - strncpy(buf, "unknown", len); + lws_strncpy(buf, "unknown", len); } void ERR_free_strings(void) @@ -1591,11 +1597,34 @@ void ERR_free_strings(void) char *ERR_error_string(unsigned long e, char *buf) { - if (buf) { - strcpy(buf, "unknown"); + if (!buf) + return "unknown"; + + switch(e) { + case X509_V_ERR_INVALID_CA: + strcpy(buf, "CA is not trusted"); + break; + case X509_V_ERR_HOSTNAME_MISMATCH: + strcpy(buf, "Hostname mismatch"); + break; + case X509_V_ERR_CA_KEY_TOO_SMALL: + strcpy(buf, "CA key too small"); + break; + case X509_V_ERR_CA_MD_TOO_WEAK: + strcpy(buf, "MD key too weak"); + break; + case X509_V_ERR_CERT_NOT_YET_VALID: + strcpy(buf, "Cert from the future"); + break; + case X509_V_ERR_CERT_HAS_EXPIRED: + strcpy(buf, "Cert expired"); + break; + default: + strcpy(buf, "unknown"); + break; } - return "unknown"; + return buf; } void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx) @@ -1619,15 +1648,16 @@ void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx) */ struct alpn_ctx { - unsigned char *data; - unsigned short len; + unsigned char data[23]; + unsigned char len; }; -void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg) +static void +_openssl_alpn_to_mbedtls(struct alpn_ctx *ac, char ***palpn_protos) { - struct alpn_ctx *ac = arg; unsigned char *p = ac->data, *q; unsigned char len; + char **alpn_protos; int count = 0; /* find out how many entries he gave us */ @@ -1644,23 +1674,28 @@ void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg) break; } + if (!len) + count++; + if (!count) return; /* allocate space for count + 1 pointers and the data afterwards */ - ctx->alpn_protos = ssl_mem_zalloc((count + 1) * sizeof(char *) + ac->len + 1); - if (!ctx->alpn_protos) + alpn_protos = ssl_mem_zalloc((count + 1) * sizeof(char *) + ac->len + 1); + if (!alpn_protos) return; + *palpn_protos = alpn_protos; + /* convert to mbedtls format */ - q = (unsigned char *)ctx->alpn_protos + (count + 1) * sizeof(char *); + q = (unsigned char *)alpn_protos + (count + 1) * sizeof(char *); p = ac->data; count = 0; len = *p++; - ctx->alpn_protos[count] = (char *)q; + alpn_protos[count] = (char *)q; while (p - ac->data < ac->len) { if (len--) { *q++ = *p++; @@ -1669,11 +1704,33 @@ void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg) *q++ = '\0'; count++; len = *p++; - ctx->alpn_protos[count] = (char *)q; + alpn_protos[count] = (char *)q; if (!len) break; } - ctx->alpn_protos[count] = NULL; /* last pointer ends list with NULL */ + if (!len) { + *q++ = '\0'; + count++; + len = *p++; + alpn_protos[count] = (char *)q; + } + alpn_protos[count] = NULL; /* last pointer ends list with NULL */ +} + +void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg) +{ + struct alpn_ctx *ac = arg; ctx->alpn_cb = cb; + + _openssl_alpn_to_mbedtls(ac, (char ***)&ctx->alpn_protos); +} + +void SSL_set_alpn_select_cb(SSL *ssl, void *arg) +{ + struct alpn_ctx *ac = arg; + + _openssl_alpn_to_mbedtls(ac, (char ***)&ssl->alpn_protos); + + _ssl_set_alpn_list(ssl); } diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_methods.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_methods.c index 0002360846..0002360846 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_methods.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_methods.c diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_pkey.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_pkey.c index 567a33e2c2..567a33e2c2 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_pkey.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_pkey.c diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_stack.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_stack.c index da836daf9c..da836daf9c 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_stack.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_stack.c diff --git a/thirdparty/lws/mbedtls_wrapper/library/ssl_x509.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_x509.c index 4441490a03..ed79150831 100644 --- a/thirdparty/lws/mbedtls_wrapper/library/ssl_x509.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/library/ssl_x509.c @@ -17,6 +17,8 @@ #include "ssl_dbg.h" #include "ssl_port.h" +#include <assert.h> + /** * @brief show X509 certification information */ @@ -155,7 +157,7 @@ int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x) { SSL_ASSERT1(ctx); SSL_ASSERT1(x); - + assert(ctx); if (ctx->client_CA == x) return 1; @@ -169,6 +171,28 @@ int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x) /** * @brief add CA client certification into the SSL */ +int SSL_CTX_add_client_CA_ASN1(SSL_CTX *ctx, int len, + const unsigned char *d) +{ + X509 *x; + + x = d2i_X509(NULL, d, len); + if (!x) { + SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_X509() return NULL"); + return 0; + } + SSL_ASSERT1(ctx); + + X509_free(ctx->client_CA); + + ctx->client_CA = x; + + return 1; +} + +/** + * @brief add CA client certification into the SSL + */ int SSL_add_client_CA(SSL *ssl, X509 *x) { SSL_ASSERT1(ssl); diff --git a/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/platform/ssl_pm.c index 4e3d611095..4716c1ff56 100644..100755 --- a/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/platform/ssl_pm.c @@ -25,6 +25,8 @@ #include "mbedtls/error.h" #include "mbedtls/certs.h" +#include <libwebsockets.h> + #define X509_INFO_STRING_LENGTH 8192 struct ssl_pm @@ -41,6 +43,8 @@ struct ssl_pm mbedtls_ssl_context ssl; mbedtls_entropy_context entropy; + + SSL *owner; }; struct x509_pm @@ -62,7 +66,7 @@ unsigned int max_content_len; /*********************************************************************************************/ /************************************ SSL arch interface *************************************/ -#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG +//#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG /* mbedtls debug level */ #define MBEDTLS_DEBUG_LEVEL 4 @@ -79,13 +83,13 @@ static void ssl_platform_debug(void *ctx, int level, This is a bit wasteful because the macros are compiled in with the full _FILE_ path in each case. */ - char *file_sep = rindex(file, '/'); - if(file_sep) - file = file_sep + 1; +// char *file_sep = rindex(file, '/'); + // if(file_sep) + // file = file_sep + 1; - SSL_DEBUG(SSL_DEBUG_ON, "%s:%d %s", file, line, str); + printf("%s:%d %s", file, line, str); } -#endif +//#endif /** * @brief create SSL low-level object @@ -109,6 +113,8 @@ int ssl_pm_new(SSL *ssl) goto no_mem; } + ssl_pm->owner = ssl; + if (!ssl->ctx->read_buffer_len) ssl->ctx->read_buffer_len = 2048; @@ -159,12 +165,12 @@ int ssl_pm_new(SSL *ssl) mbedtls_ssl_conf_rng(&ssl_pm->conf, mbedtls_ctr_drbg_random, &ssl_pm->ctr_drbg); -#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG - mbedtls_debug_set_threshold(MBEDTLS_DEBUG_LEVEL); +//#ifdef CONFIG_OPENSSL_LOWLEVEL_DEBUG + // mbedtls_debug_set_threshold(MBEDTLS_DEBUG_LEVEL); +// mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL); +//#else mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL); -#else - mbedtls_ssl_conf_dbg(&ssl_pm->conf, NULL, NULL); -#endif +//#endif ret = mbedtls_ssl_setup(&ssl_pm->ssl, &ssl_pm->conf); if (ret) { @@ -261,7 +267,7 @@ static int mbedtls_handshake( mbedtls_ssl_context *ssl ) while (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) { ret = mbedtls_ssl_handshake_step(ssl); - SSL_DEBUG(SSL_PLATFORM_DEBUG_LEVEL, "ssl ret %d state %d", ret, ssl->state); + lwsl_info("%s: ssl ret -%x state %d\n", __func__, -ret, ssl->state); if (ret != 0) break; @@ -270,14 +276,21 @@ static int mbedtls_handshake( mbedtls_ssl_context *ssl ) return ret; } +#include <errno.h> + int ssl_pm_handshake(SSL *ssl) { int ret; struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; + ssl->err = 0; + errno = 0; + ret = ssl_pm_reload_crt(ssl); - if (ret) + if (ret) { + printf("%s: cert reload failed\n", __func__); return 0; + } if (ssl_pm->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) { ssl_speed_up_enter(); @@ -298,6 +311,7 @@ int ssl_pm_handshake(SSL *ssl) * <0 = death */ if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + ssl->err = ret; SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_handshake() return -0x%x", -ret); return 0; /* OpenSSL: did not complete but may be retried */ } @@ -309,6 +323,14 @@ int ssl_pm_handshake(SSL *ssl) return 1; /* openssl successful */ } + if (errno == 11) { + ssl->err = ret == MBEDTLS_ERR_SSL_WANT_READ; + + return 0; + } + + printf("%s: mbedtls_ssl_handshake() returned -0x%x\n", __func__, -ret); + /* it's had it */ ssl->err = SSL_ERROR_SYSCALL; @@ -316,6 +338,28 @@ int ssl_pm_handshake(SSL *ssl) return -1; /* openssl death */ } +mbedtls_x509_crt * +ssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx) +{ + struct x509_pm *x509_pm = (struct x509_pm *)ssl_ctx->cert->x509->x509_pm; + + if (!x509_pm) + return NULL; + + return x509_pm->x509_crt; +} + +mbedtls_x509_crt * +ssl_get_peer_mbedtls_x509_crt(SSL *ssl) +{ + struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm; + + if (!x509_pm) + return NULL; + + return x509_pm->ex_crt; +} + int ssl_pm_shutdown(SSL *ssl) { int ret; @@ -351,8 +395,10 @@ int ssl_pm_read(SSL *ssl, void *buffer, int len) ret = mbedtls_ssl_read(&ssl_pm->ssl, buffer, len); if (ret < 0) { + // lwsl_notice("%s: mbedtls_ssl_read says -0x%x\n", __func__, -ret); SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_read() return -0x%x", -ret); - if (ret == MBEDTLS_ERR_NET_CONN_RESET) + if (ret == MBEDTLS_ERR_NET_CONN_RESET || + ret <= MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) /* fatal errors */ ssl->err = SSL_ERROR_SYSCALL; ret = -1; } @@ -392,6 +438,7 @@ int ssl_pm_send(SSL *ssl, const void *buffer, int len) if (ret < 0) { SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_write() return -0x%x", -ret); switch (ret) { + case MBEDTLS_ERR_NET_SEND_FAILED: case MBEDTLS_ERR_NET_CONN_RESET: ssl->err = SSL_ERROR_SYSCALL; break; @@ -589,22 +636,27 @@ int x509_pm_load(X509 *x, const unsigned char *buffer, int len) } } - load_buf = ssl_mem_malloc(len + 1); - if (!load_buf) { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (load_buf)"); - goto failed; - } - - ssl_memcpy(load_buf, buffer, len); - load_buf[len] = '\0'; - mbedtls_x509_crt_init(x509_pm->x509_crt); + if (buffer[0] != 0x30) { + load_buf = ssl_mem_malloc(len + 1); + if (!load_buf) { + SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (load_buf)"); + goto failed; + } + + ssl_memcpy(load_buf, buffer, len); + load_buf[len] = '\0'; + + ret = mbedtls_x509_crt_parse(x509_pm->x509_crt, load_buf, len + 1); + ssl_mem_free(load_buf); + } else { + printf("parsing as der\n"); - ret = mbedtls_x509_crt_parse(x509_pm->x509_crt, load_buf, len + 1); - ssl_mem_free(load_buf); + ret = mbedtls_x509_crt_parse_der(x509_pm->x509_crt, buffer, len); + } if (ret) { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_x509_crt_parse return -0x%x", -ret); + printf("mbedtls_x509_crt_parse return -0x%x", -ret); goto failed; } @@ -707,46 +759,44 @@ void ssl_pm_set_bufflen(SSL *ssl, int len) long ssl_pm_get_verify_result(const SSL *ssl) { - uint32_t ret; - long verify_result; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl); + uint32_t ret; + long verify_result; + struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - if (!ret) - return X509_V_OK; + ret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl); + if (!ret) + return X509_V_OK; - if (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED || - (ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED)) - // Allows us to use LCCSCF_ALLOW_SELFSIGNED to skip verification - verify_result = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; + if (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED || + (ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED)) + verify_result = X509_V_ERR_INVALID_CA; - else if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) - verify_result = X509_V_ERR_HOSTNAME_MISMATCH; + else if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) + verify_result = X509_V_ERR_HOSTNAME_MISMATCH; - else if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) || - (ret & MBEDTLS_X509_BADCRL_BAD_KEY)) - verify_result = X509_V_ERR_CA_KEY_TOO_SMALL; + else if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) || + (ret & MBEDTLS_X509_BADCRL_BAD_KEY)) + verify_result = X509_V_ERR_CA_KEY_TOO_SMALL; - else if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) || - (ret & MBEDTLS_X509_BADCRL_BAD_MD)) - verify_result = X509_V_ERR_CA_MD_TOO_WEAK; + else if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) || + (ret & MBEDTLS_X509_BADCRL_BAD_MD)) + verify_result = X509_V_ERR_CA_MD_TOO_WEAK; - else if ((ret & MBEDTLS_X509_BADCERT_FUTURE) || - (ret & MBEDTLS_X509_BADCRL_FUTURE)) - verify_result = X509_V_ERR_CERT_NOT_YET_VALID; + else if ((ret & MBEDTLS_X509_BADCERT_FUTURE) || + (ret & MBEDTLS_X509_BADCRL_FUTURE)) + verify_result = X509_V_ERR_CERT_NOT_YET_VALID; - else if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) || - (ret & MBEDTLS_X509_BADCRL_EXPIRED)) - verify_result = X509_V_ERR_CERT_HAS_EXPIRED; + else if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) || + (ret & MBEDTLS_X509_BADCRL_EXPIRED)) + verify_result = X509_V_ERR_CERT_HAS_EXPIRED; - else - verify_result = X509_V_ERR_UNSPECIFIED; + else + verify_result = X509_V_ERR_UNSPECIFIED; - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_get_verify_result() return 0x%x", ret); + SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, + "mbedtls_ssl_get_verify_result() return 0x%x", ret); - return verify_result; + return verify_result; } /** @@ -779,6 +829,12 @@ int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, void _ssl_set_alpn_list(const SSL *ssl) { + if (ssl->alpn_protos) { + if (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->alpn_protos)) + fprintf(stderr, "mbedtls_ssl_conf_alpn_protocols failed\n"); + + return; + } if (!ssl->ctx->alpn_protos) return; if (mbedtls_ssl_conf_alpn_protocols(&((struct ssl_pm *)(ssl->ssl_pm))->conf, ssl->ctx->alpn_protos)) @@ -797,3 +853,55 @@ void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data, *len = 0; } +int SSL_set_sni_callback(SSL *ssl, int(*cb)(void *, mbedtls_ssl_context *, + const unsigned char *, size_t), void *param) +{ + struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; + + mbedtls_ssl_conf_sni(&ssl_pm->conf, cb, param); + + return 0; +} + +SSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc) +{ + struct ssl_pm *ssl_pm = (struct ssl_pm *)((char *)msc - offsetof(struct ssl_pm, ssl)); + + return ssl_pm->owner; +} + +#include "ssl_cert.h" + +void SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx) +{ + struct ssl_pm *ssl_pm = ssl->ssl_pm; + struct x509_pm *x509_pm = (struct x509_pm *)ctx->cert->x509->x509_pm; + struct x509_pm *x509_pm_ca = (struct x509_pm *)ctx->client_CA->x509_pm; + + struct pkey_pm *pkey_pm = (struct pkey_pm *)ctx->cert->pkey->pkey_pm; + int mode; + + if (ssl->cert) + ssl_cert_free(ssl->cert); + ssl->ctx = ctx; + ssl->cert = __ssl_cert_new(ctx->cert); + + if (ctx->verify_mode == SSL_VERIFY_PEER) + mode = MBEDTLS_SSL_VERIFY_OPTIONAL; + else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT) + mode = MBEDTLS_SSL_VERIFY_OPTIONAL; + else if (ctx->verify_mode == SSL_VERIFY_CLIENT_ONCE) + mode = MBEDTLS_SSL_VERIFY_UNSET; + else + mode = MBEDTLS_SSL_VERIFY_NONE; + + // printf("ssl: %p, client ca x509_crt %p, mbedtls mode %d\n", ssl, x509_pm_ca->x509_crt, mode); + + /* apply new ctx cert to ssl */ + + ssl->verify_mode = ctx->verify_mode; + + mbedtls_ssl_set_hs_ca_chain(&ssl_pm->ssl, x509_pm_ca->x509_crt, NULL); + mbedtls_ssl_set_hs_own_cert(&ssl_pm->ssl, x509_pm->x509_crt, pkey_pm->pkey); + mbedtls_ssl_set_hs_authmode(&ssl_pm->ssl, mode); +} diff --git a/thirdparty/lws/mbedtls_wrapper/platform/ssl_port.c b/thirdparty/libwebsockets/tls/mbedtls/wrapper/platform/ssl_port.c index 8c7a31338b..8c7a31338b 100644 --- a/thirdparty/lws/mbedtls_wrapper/platform/ssl_port.c +++ b/thirdparty/libwebsockets/tls/mbedtls/wrapper/platform/ssl_port.c diff --git a/thirdparty/libwebsockets/tls/private.h b/thirdparty/libwebsockets/tls/private.h new file mode 100644 index 0000000000..606e2574dc --- /dev/null +++ b/thirdparty/libwebsockets/tls/private.h @@ -0,0 +1,281 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010 - 2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + * + * This is included from core/private.h if LWS_WITH_TLS + */ + +#if defined(LWS_WITH_TLS) + +#if defined(USE_WOLFSSL) + #if defined(USE_OLD_CYASSL) + #if defined(_WIN32) + #include <IDE/WIN/user_settings.h> + #include <cyassl/ctaocrypt/settings.h> + #else + #include <cyassl/options.h> + #endif + #include <cyassl/openssl/ssl.h> + #include <cyassl/error-ssl.h> + #else + #if defined(_WIN32) + #include <IDE/WIN/user_settings.h> + #include <wolfssl/wolfcrypt/settings.h> + #else + #include <wolfssl/options.h> + #endif + #include <wolfssl/openssl/ssl.h> + #include <wolfssl/error-ssl.h> + #define OPENSSL_NO_TLSEXT + #endif /* not USE_OLD_CYASSL */ +#else /* WOLFSSL */ + #if defined(LWS_WITH_ESP32) + #define OPENSSL_NO_TLSEXT + #undef MBEDTLS_CONFIG_FILE + #define MBEDTLS_CONFIG_FILE <mbedtls/esp_config.h> + #include <mbedtls/ssl.h> + #include <mbedtls/x509_crt.h> + #include "tls/mbedtls/wrapper/include/openssl/ssl.h" /* wrapper !!!! */ + #else /* not esp32 */ + #if defined(LWS_WITH_MBEDTLS) + #include <mbedtls/ssl.h> + #include <mbedtls/x509_crt.h> + #include <mbedtls/x509_csr.h> + #include "tls/mbedtls/wrapper/include/openssl/ssl.h" /* wrapper !!!! */ + #else + #include <openssl/ssl.h> + #include <openssl/evp.h> + #include <openssl/err.h> + #include <openssl/md5.h> + #include <openssl/sha.h> + #ifdef LWS_HAVE_OPENSSL_ECDH_H + #include <openssl/ecdh.h> + #endif + #include <openssl/x509v3.h> + #endif /* not mbedtls */ + #if defined(OPENSSL_VERSION_NUMBER) + #if (OPENSSL_VERSION_NUMBER < 0x0009080afL) +/* later openssl defines this to negate the presence of tlsext... but it was only + * introduced at 0.9.8j. Earlier versions don't know it exists so don't + * define it... making it look like the feature exists... + */ + #define OPENSSL_NO_TLSEXT + #endif + #endif + #endif /* not ESP32 */ +#endif /* not USE_WOLFSSL */ + +#endif /* LWS_WITH_TLS */ + +enum lws_tls_extant { + LWS_TLS_EXTANT_NO, + LWS_TLS_EXTANT_YES, + LWS_TLS_EXTANT_ALTERNATIVE +}; + +struct lws_context_per_thread; + +struct lws_tls_ops { + int (*fake_POLLIN_for_buffered)(struct lws_context_per_thread *pt); + int (*periodic_housekeeping)(struct lws_context *context, time_t now); +}; + +#if defined(LWS_WITH_TLS) + +typedef SSL lws_tls_conn; +typedef SSL_CTX lws_tls_ctx; +typedef BIO lws_tls_bio; +typedef X509 lws_tls_x509; + + +#define LWS_SSL_ENABLED(context) (context->tls.use_ssl) + +extern const struct lws_tls_ops tls_ops_openssl, tls_ops_mbedtls; + +struct lws_context_tls { + char alpn_discovered[32]; + const char *alpn_default; + time_t last_cert_check_s; +}; + +struct lws_pt_tls { + struct lws *pending_read_list; /* linked list */ +}; + +struct lws_tls_ss_pieces; + +struct alpn_ctx { + uint8_t data[23]; + uint8_t len; +}; + +struct lws_vhost_tls { + lws_tls_ctx *ssl_ctx; + lws_tls_ctx *ssl_client_ctx; + const char *alpn; + struct lws_tls_ss_pieces *ss; /* for acme tls certs */ + char *alloc_cert_path; + char *key_path; +#if defined(LWS_WITH_MBEDTLS) + lws_tls_x509 *x509_client_CA; +#endif + char ecdh_curve[16]; + struct alpn_ctx alpn_ctx; + + int use_ssl; + int allow_non_ssl_on_ssl_port; + int ssl_info_event_mask; + + unsigned int user_supplied_ssl_ctx:1; + unsigned int skipped_certs:1; +}; + +struct lws_lws_tls { + lws_tls_conn *ssl; + lws_tls_bio *client_bio; + struct lws *pending_read_list_prev, *pending_read_list_next; + unsigned int use_ssl; + unsigned int redirect_to_https:1; +}; + +LWS_EXTERN void +lws_context_init_alpn(struct lws_vhost *vhost); +LWS_EXTERN enum lws_tls_extant +lws_tls_use_any_upgrade_check_extant(const char *name); +LWS_EXTERN int openssl_websocket_private_data_index; +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len); +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len); +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_ssl_pending(struct lws *wsi); +LWS_EXTERN int +lws_context_init_ssl_library(const struct lws_context_creation_info *info); +LWS_EXTERN int LWS_WARN_UNUSED_RESULT +lws_server_socket_service_ssl(struct lws *new_wsi, lws_sockfd_type accept_fd); +LWS_EXTERN int +lws_ssl_close(struct lws *wsi); +LWS_EXTERN void +lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost); +LWS_EXTERN void +lws_ssl_context_destroy(struct lws_context *context); +void +__lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi); +LWS_VISIBLE void +lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi); +LWS_EXTERN int +lws_ssl_client_bio_create(struct lws *wsi); +LWS_EXTERN int +lws_ssl_client_connect1(struct lws *wsi); +LWS_EXTERN int +lws_ssl_client_connect2(struct lws *wsi, char *errbuf, int len); +LWS_EXTERN void +lws_ssl_elaborate_error(void); +LWS_EXTERN int +lws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt); +LWS_EXTERN int +lws_gate_accepts(struct lws_context *context, int on); +LWS_EXTERN void +lws_ssl_bind_passphrase(lws_tls_ctx *ssl_ctx, + const struct lws_context_creation_info *info); +LWS_EXTERN void +lws_ssl_info_callback(const lws_tls_conn *ssl, int where, int ret); +LWS_EXTERN int +lws_tls_openssl_cert_info(X509 *x509, enum lws_tls_cert_info type, + union lws_tls_cert_info_results *buf, size_t len); +LWS_EXTERN int +lws_tls_check_all_cert_lifetimes(struct lws_context *context); +LWS_EXTERN int +lws_tls_server_certs_load(struct lws_vhost *vhost, struct lws *wsi, + const char *cert, const char *private_key, + const char *mem_cert, size_t len_mem_cert, + const char *mem_privkey, size_t mem_privkey_len); +LWS_EXTERN enum lws_tls_extant +lws_tls_generic_cert_checks(struct lws_vhost *vhost, const char *cert, + const char *private_key); +LWS_EXTERN int +lws_tls_alloc_pem_to_der_file(struct lws_context *context, const char *filename, + const char *inbuf, lws_filepos_t inlen, + uint8_t **buf, lws_filepos_t *amount); + +#if !defined(LWS_NO_SERVER) + LWS_EXTERN int + lws_context_init_server_ssl(const struct lws_context_creation_info *info, + struct lws_vhost *vhost); + void + lws_tls_acme_sni_cert_destroy(struct lws_vhost *vhost); +#else + #define lws_context_init_server_ssl(_a, _b) (0) + #define lws_tls_acme_sni_cert_destroy(_a) +#endif + +LWS_EXTERN void +lws_ssl_destroy(struct lws_vhost *vhost); +LWS_EXTERN char * +lws_ssl_get_error_string(int status, int ret, char *buf, size_t len); + +/* + * lws_tls_ abstract backend implementations + */ + +LWS_EXTERN int +lws_tls_server_client_cert_verify_config(struct lws_vhost *vh); +LWS_EXTERN int +lws_tls_server_vhost_backend_init(const struct lws_context_creation_info *info, + struct lws_vhost *vhost, struct lws *wsi); +LWS_EXTERN int +lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd); + +LWS_EXTERN enum lws_ssl_capable_status +lws_tls_server_accept(struct lws *wsi); + +LWS_EXTERN enum lws_ssl_capable_status +lws_tls_server_abort_connection(struct lws *wsi); + +LWS_EXTERN enum lws_ssl_capable_status +__lws_tls_shutdown(struct lws *wsi); + +LWS_EXTERN enum lws_ssl_capable_status +lws_tls_client_connect(struct lws *wsi); +LWS_EXTERN int +lws_tls_client_confirm_peer_cert(struct lws *wsi, char *ebuf, int ebuf_len); +LWS_EXTERN int +lws_tls_client_create_vhost_context(struct lws_vhost *vh, + const struct lws_context_creation_info *info, + const char *cipher_list, + const char *ca_filepath, + const char *cert_filepath, + const char *private_key_filepath); + +LWS_EXTERN lws_tls_ctx * +lws_tls_ctx_from_wsi(struct lws *wsi); +LWS_EXTERN int +lws_ssl_get_error(struct lws *wsi, int n); + +LWS_EXTERN int +lws_context_init_client_ssl(const struct lws_context_creation_info *info, + struct lws_vhost *vhost); + +LWS_EXTERN void +lws_ssl_info_callback(const lws_tls_conn *ssl, int where, int ret); + +int +lws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt); + +#endif
\ No newline at end of file diff --git a/thirdparty/libwebsockets/tls/tls-client.c b/thirdparty/libwebsockets/tls/tls-client.c new file mode 100644 index 0000000000..70eb6f6078 --- /dev/null +++ b/thirdparty/libwebsockets/tls/tls-client.c @@ -0,0 +1,150 @@ +/* + * libwebsockets - client-related ssl code independent of backend + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +int +lws_ssl_client_connect1(struct lws *wsi) +{ + struct lws_context *context = wsi->context; + int n = 0; + + lws_latency_pre(context, wsi); + n = lws_tls_client_connect(wsi); + lws_latency(context, wsi, "SSL_connect hs", n, n > 0); + + switch (n) { + case LWS_SSL_CAPABLE_ERROR: + return -1; + case LWS_SSL_CAPABLE_DONE: + return 1; /* connected */ + case LWS_SSL_CAPABLE_MORE_SERVICE_WRITE: + lws_callback_on_writable(wsi); + /* fallthru */ + case LWS_SSL_CAPABLE_MORE_SERVICE_READ: + lwsi_set_state(wsi, LRS_WAITING_SSL); + break; + case LWS_SSL_CAPABLE_MORE_SERVICE: + break; + } + + return 0; /* retry */ +} + +int +lws_ssl_client_connect2(struct lws *wsi, char *errbuf, int len) +{ + int n = 0; + + if (lwsi_state(wsi) == LRS_WAITING_SSL) { + lws_latency_pre(wsi->context, wsi); + + n = lws_tls_client_connect(wsi); + lwsl_debug("%s: SSL_connect says %d\n", __func__, n); + lws_latency(wsi->context, wsi, + "SSL_connect LRS_WAITING_SSL", n, n > 0); + + switch (n) { + case LWS_SSL_CAPABLE_ERROR: + lws_snprintf(errbuf, len, "client connect failed"); + return -1; + case LWS_SSL_CAPABLE_DONE: + break; /* connected */ + case LWS_SSL_CAPABLE_MORE_SERVICE_WRITE: + lws_callback_on_writable(wsi); + /* fallthru */ + case LWS_SSL_CAPABLE_MORE_SERVICE_READ: + lwsi_set_state(wsi, LRS_WAITING_SSL); + /* fallthru */ + case LWS_SSL_CAPABLE_MORE_SERVICE: + return 0; + } + } + + if (lws_tls_client_confirm_peer_cert(wsi, errbuf, len)) + return -1; + + return 1; +} + + +int lws_context_init_client_ssl(const struct lws_context_creation_info *info, + struct lws_vhost *vhost) +{ + const char *ca_filepath = info->ssl_ca_filepath; + const char *cipher_list = info->ssl_cipher_list; + const char *private_key_filepath = info->ssl_private_key_filepath; + const char *cert_filepath = info->ssl_cert_filepath; + struct lws wsi; + + if (vhost->options & LWS_SERVER_OPTION_ONLY_RAW) + return 0; + + /* + * for backwards-compatibility default to using ssl_... members, but + * if the newer client-specific ones are given, use those + */ + if (info->client_ssl_cipher_list) + cipher_list = info->client_ssl_cipher_list; + if (info->client_ssl_cert_filepath) + cert_filepath = info->client_ssl_cert_filepath; + if (info->client_ssl_private_key_filepath) + private_key_filepath = info->client_ssl_private_key_filepath; + + if (info->client_ssl_ca_filepath) + ca_filepath = info->client_ssl_ca_filepath; + + if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) + return 0; + + if (vhost->tls.ssl_client_ctx) + return 0; + + if (info->provided_client_ssl_ctx) { + /* use the provided OpenSSL context if given one */ + vhost->tls.ssl_client_ctx = info->provided_client_ssl_ctx; + /* nothing for lib to delete */ + vhost->tls.user_supplied_ssl_ctx = 1; + + return 0; + } + + if (lws_tls_client_create_vhost_context(vhost, info, cipher_list, + ca_filepath, cert_filepath, + private_key_filepath)) + return 1; + + lwsl_notice("created client ssl context for %s\n", vhost->name); + + /* + * give him a fake wsi with context set, so he can use + * lws_get_context() in the callback + */ + memset(&wsi, 0, sizeof(wsi)); + wsi.vhost = vhost; + wsi.context = vhost->context; + + vhost->protocols[0].callback(&wsi, + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS, + vhost->tls.ssl_client_ctx, NULL, 0); + + return 0; +} diff --git a/thirdparty/libwebsockets/tls/tls-server.c b/thirdparty/libwebsockets/tls/tls-server.c new file mode 100644 index 0000000000..440e790660 --- /dev/null +++ b/thirdparty/libwebsockets/tls/tls-server.c @@ -0,0 +1,382 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \ + OPENSSL_VERSION_NUMBER >= 0x10002000L) +static int +alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, void *arg) +{ +#if !defined(LWS_WITH_MBEDTLS) + struct alpn_ctx *alpn_ctx = (struct alpn_ctx *)arg; + + if (SSL_select_next_proto((unsigned char **)out, outlen, alpn_ctx->data, + alpn_ctx->len, in, inlen) != + OPENSSL_NPN_NEGOTIATED) + return SSL_TLSEXT_ERR_NOACK; +#endif + + return SSL_TLSEXT_ERR_OK; +} +#endif + +void +lws_context_init_alpn(struct lws_vhost *vhost) +{ +#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \ + OPENSSL_VERSION_NUMBER >= 0x10002000L) + const char *alpn_comma = vhost->context->tls.alpn_default; + + if (vhost->tls.alpn) + alpn_comma = vhost->tls.alpn; + + lwsl_info(" Server '%s' advertising ALPN: %s\n", + vhost->name, alpn_comma); + vhost->tls.alpn_ctx.len = lws_alpn_comma_to_openssl(alpn_comma, + vhost->tls.alpn_ctx.data, + sizeof(vhost->tls.alpn_ctx.data) - 1); + + SSL_CTX_set_alpn_select_cb(vhost->tls.ssl_ctx, alpn_cb, &vhost->tls.alpn_ctx); +#else + lwsl_err( + " HTTP2 / ALPN configured but not supported by OpenSSL 0x%lx\n", + OPENSSL_VERSION_NUMBER); +#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L +} + +int +lws_tls_server_conn_alpn(struct lws *wsi) +{ +#if defined(LWS_WITH_MBEDTLS) || (defined(OPENSSL_VERSION_NUMBER) && \ + OPENSSL_VERSION_NUMBER >= 0x10002000L) + const unsigned char *name = NULL; + char cstr[10]; + unsigned len; + + SSL_get0_alpn_selected(wsi->tls.ssl, &name, &len); + if (!len) { + lwsl_info("no ALPN upgrade\n"); + return 0; + } + + if (len > sizeof(cstr) - 1) + len = sizeof(cstr) - 1; + + memcpy(cstr, name, len); + cstr[len] = '\0'; + + lwsl_info("negotiated '%s' using ALPN\n", cstr); + wsi->tls.use_ssl |= LCCSCF_USE_SSL; + + return lws_role_call_alpn_negotiated(wsi, (const char *)cstr); +#endif // OPENSSL_VERSION_NUMBER >= 0x10002000L + + return 0; +} + +LWS_VISIBLE int +lws_context_init_server_ssl(const struct lws_context_creation_info *info, + struct lws_vhost *vhost) +{ + struct lws_context *context = vhost->context; + struct lws wsi; + + if (!lws_check_opt(info->options, + LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) { + vhost->tls.use_ssl = 0; + + return 0; + } + + /* + * If he is giving a cert filepath, take it as a sign he wants to use + * it on this vhost. User code can leave the cert filepath NULL and + * set the LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX option itself, in + * which case he's expected to set up the cert himself at + * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which + * provides the vhost SSL_CTX * in the user parameter. + */ + if (info->ssl_cert_filepath) + vhost->options |= LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX; + + if (info->port != CONTEXT_PORT_NO_LISTEN) { + + vhost->tls.use_ssl = lws_check_opt(vhost->options, + LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX); + + if (vhost->tls.use_ssl && info->ssl_cipher_list) + lwsl_notice(" SSL ciphers: '%s'\n", + info->ssl_cipher_list); + + if (vhost->tls.use_ssl) + lwsl_notice(" Using SSL mode\n"); + else + lwsl_notice(" Using non-SSL mode\n"); + } + + /* + * give him a fake wsi with context + vhost set, so he can use + * lws_get_context() in the callback + */ + memset(&wsi, 0, sizeof(wsi)); + wsi.vhost = vhost; + wsi.context = context; + + /* + * as a server, if we are requiring clients to identify themselves + * then set the backend up for it + */ + if (lws_check_opt(info->options, + LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT)) + /* Normally SSL listener rejects non-ssl, optionally allow */ + vhost->tls.allow_non_ssl_on_ssl_port = 1; + + /* + * give user code a chance to load certs into the server + * allowing it to verify incoming client certs + */ + if (vhost->tls.use_ssl) { + if (lws_tls_server_vhost_backend_init(info, vhost, &wsi)) + return -1; + + lws_tls_server_client_cert_verify_config(vhost); + + if (vhost->protocols[0].callback(&wsi, + LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, + vhost->tls.ssl_ctx, vhost, 0)) + return -1; + } + + if (vhost->tls.use_ssl) + lws_context_init_alpn(vhost); + + return 0; +} + +LWS_VISIBLE int +lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd) +{ + struct lws_context *context = wsi->context; + struct lws_vhost *vh; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + int n; + char buf[256]; + + (void)buf; + + if (!LWS_SSL_ENABLED(wsi->vhost)) + return 0; + + switch (lwsi_state(wsi)) { + case LRS_SSL_INIT: + + if (wsi->tls.ssl) + lwsl_err("%s: leaking ssl\n", __func__); + if (accept_fd == LWS_SOCK_INVALID) + assert(0); + if (context->simultaneous_ssl_restriction && + context->simultaneous_ssl >= + context->simultaneous_ssl_restriction) { + lwsl_notice("unable to deal with SSL connection\n"); + return 1; + } + + if (lws_tls_server_new_nonblocking(wsi, accept_fd)) { + if (accept_fd != LWS_SOCK_INVALID) + compatible_close(accept_fd); + goto fail; + } + + if (context->simultaneous_ssl_restriction && + ++context->simultaneous_ssl == + context->simultaneous_ssl_restriction) + /* that was the last allowed SSL connection */ + lws_gate_accepts(context, 0); + +#if defined(LWS_WITH_STATS) + context->updated = 1; +#endif + /* + * we are not accepted yet, but we need to enter ourselves + * as a live connection. That way we can retry when more + * pieces come if we're not sorted yet + */ + lwsi_set_state(wsi, LRS_SSL_ACK_PENDING); + + lws_pt_lock(pt, __func__); + if (__insert_wsi_socket_into_fds(context, wsi)) { + lwsl_err("%s: failed to insert into fds\n", __func__); + goto fail; + } + lws_pt_unlock(pt); + + lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT, + context->timeout_secs); + + lwsl_debug("inserted SSL accept into fds, trying SSL_accept\n"); + + /* fallthru */ + + case LRS_SSL_ACK_PENDING: + + if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { + lwsl_err("%s: lws_change_pollfd failed\n", __func__); + goto fail; + } + + lws_latency_pre(context, wsi); + + if (wsi->vhost->tls.allow_non_ssl_on_ssl_port) { + + n = recv(wsi->desc.sockfd, (char *)pt->serv_buf, + context->pt_serv_buf_size, MSG_PEEK); + + /* + * optionally allow non-SSL connect on SSL listening socket + * This is disabled by default, if enabled it goes around any + * SSL-level access control (eg, client-side certs) so leave + * it disabled unless you know it's not a problem for you + */ + if (n >= 1 && pt->serv_buf[0] >= ' ') { + /* + * TLS content-type for Handshake is 0x16, and + * for ChangeCipherSpec Record, it's 0x14 + * + * A non-ssl session will start with the HTTP + * method in ASCII. If we see it's not a legit + * SSL handshake kill the SSL for this + * connection and try to handle as a HTTP + * connection upgrade directly. + */ + wsi->tls.use_ssl = 0; + + lws_tls_server_abort_connection(wsi); + /* + * care... this creates wsi with no ssl + * when ssl is enabled and normally + * mandatory + */ + wsi->tls.ssl = NULL; + if (lws_check_opt(context->options, + LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS)) + wsi->tls.redirect_to_https = 1; + lwsl_debug("accepted as non-ssl\n"); + goto accepted; + } + if (!n) { + /* + * connection is gone, fail out + */ + lwsl_debug("PEEKed 0\n"); + goto fail; + } + if (n < 0 && (LWS_ERRNO == LWS_EAGAIN || + LWS_ERRNO == LWS_EWOULDBLOCK)) { + /* + * well, we get no way to know ssl or not + * so go around again waiting for something + * to come and give us a hint, or timeout the + * connection. + */ + if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { + lwsl_info("%s: change_pollfd failed\n", + __func__); + return -1; + } + + lwsl_info("SSL_ERROR_WANT_READ\n"); + return 0; + } + } + + /* normal SSL connection processing path */ + +#if defined(LWS_WITH_STATS) + if (!wsi->accept_start_us) + wsi->accept_start_us = time_in_microseconds(); +#endif + errno = 0; + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN, 1); + n = lws_tls_server_accept(wsi); + lws_latency(context, wsi, + "SSL_accept LRS_SSL_ACK_PENDING\n", n, n == 1); + lwsl_info("SSL_accept says %d\n", n); + switch (n) { + case LWS_SSL_CAPABLE_DONE: + break; + case LWS_SSL_CAPABLE_ERROR: + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_SSL_CONNECTIONS_FAILED, 1); + lwsl_info("SSL_accept failed socket %u: %d\n", + wsi->desc.sockfd, n); + wsi->socket_is_permanently_unusable = 1; + goto fail; + + default: /* MORE_SERVICE */ + return 0; + } + + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, 1); +#if defined(LWS_WITH_STATS) + lws_stats_atomic_bump(wsi->context, pt, + LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, + time_in_microseconds() - wsi->accept_start_us); + wsi->accept_start_us = time_in_microseconds(); +#endif + +accepted: + + /* adapt our vhost to match the SNI SSL_CTX that was chosen */ + vh = context->vhost_list; + while (vh) { + if (!vh->being_destroyed && wsi->tls.ssl && + vh->tls.ssl_ctx == lws_tls_ctx_from_wsi(wsi)) { + lwsl_info("setting wsi to vh %s\n", vh->name); + wsi->vhost = vh; + break; + } + vh = vh->vhost_next; + } + + /* OK, we are accepted... give him some time to negotiate */ + lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, + context->timeout_secs); + + lwsi_set_state(wsi, LRS_ESTABLISHED); + if (lws_tls_server_conn_alpn(wsi)) + goto fail; + lwsl_debug("accepted new SSL conn\n"); + break; + + default: + break; + } + + return 0; + +fail: + return 1; +} + diff --git a/thirdparty/libwebsockets/tls/tls.c b/thirdparty/libwebsockets/tls/tls.c new file mode 100644 index 0000000000..92b7c5593c --- /dev/null +++ b/thirdparty/libwebsockets/tls/tls.c @@ -0,0 +1,522 @@ +/* + * libwebsockets - small server side websockets and web server implementation + * + * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation: + * version 2.1 of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301 USA + */ + +#include "core/private.h" + +/* + * fakes POLLIN on all tls guys with buffered rx + * + * returns nonzero if any tls guys had POLLIN faked + */ + +int +lws_tls_fake_POLLIN_for_buffered(struct lws_context_per_thread *pt) +{ + struct lws *wsi, *wsi_next; + int ret = 0; + + wsi = pt->tls.pending_read_list; + while (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) { + wsi_next = wsi->tls.pending_read_list_next; + pt->fds[wsi->position_in_fds_table].revents |= + pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; + ret |= pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN; + + wsi = wsi_next; + } + + return !!ret; +} + +void +__lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi) +{ + struct lws_context *context = wsi->context; + struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; + + if (!wsi->tls.pending_read_list_prev && + !wsi->tls.pending_read_list_next && + pt->tls.pending_read_list != wsi) + /* we are not on the list */ + return; + + /* point previous guy's next to our next */ + if (!wsi->tls.pending_read_list_prev) + pt->tls.pending_read_list = wsi->tls.pending_read_list_next; + else + wsi->tls.pending_read_list_prev->tls.pending_read_list_next = + wsi->tls.pending_read_list_next; + + /* point next guy's previous to our previous */ + if (wsi->tls.pending_read_list_next) + wsi->tls.pending_read_list_next->tls.pending_read_list_prev = + wsi->tls.pending_read_list_prev; + + wsi->tls.pending_read_list_prev = NULL; + wsi->tls.pending_read_list_next = NULL; +} + +void +lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi) +{ + struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; + + lws_pt_lock(pt, __func__); + __lws_ssl_remove_wsi_from_buffered_list(wsi); + lws_pt_unlock(pt); +} + +#if defined(LWS_WITH_ESP32) +int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, + lws_filepos_t *amount) +{ + nvs_handle nvh; + size_t s; + int n = 0; + + ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh)); + if (nvs_get_blob(nvh, filename, NULL, &s) != ESP_OK) { + n = 1; + goto bail; + } + *buf = lws_malloc(s + 1, "alloc_file"); + if (!*buf) { + n = 2; + goto bail; + } + if (nvs_get_blob(nvh, filename, (char *)*buf, &s) != ESP_OK) { + lws_free(*buf); + n = 1; + goto bail; + } + + *amount = s; + (*buf)[s] = '\0'; + + lwsl_notice("%s: nvs: read %s, %d bytes\n", __func__, filename, (int)s); + +bail: + nvs_close(nvh); + + return n; +} +#else +int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, + lws_filepos_t *amount) +{ + FILE *f; + size_t s; + int n = 0; + + f = fopen(filename, "rb"); + if (f == NULL) { + n = 1; + goto bail; + } + + if (fseek(f, 0, SEEK_END) != 0) { + n = 1; + goto bail; + } + + s = ftell(f); + if (s == (size_t)-1) { + n = 1; + goto bail; + } + + if (fseek(f, 0, SEEK_SET) != 0) { + n = 1; + goto bail; + } + + *buf = lws_malloc(s, "alloc_file"); + if (!*buf) { + n = 2; + goto bail; + } + + if (fread(*buf, s, 1, f) != 1) { + lws_free(*buf); + n = 1; + goto bail; + } + + *amount = s; + +bail: + if (f) + fclose(f); + + return n; + +} +#endif + +int +lws_tls_alloc_pem_to_der_file(struct lws_context *context, const char *filename, + const char *inbuf, lws_filepos_t inlen, + uint8_t **buf, lws_filepos_t *amount) +{ + const uint8_t *pem, *p, *end; + uint8_t *q; + lws_filepos_t len; + int n; + + if (filename) { + n = alloc_file(context, filename, (uint8_t **)&pem, &len); + if (n) + return n; + } else { + pem = (const uint8_t *)inbuf; + len = inlen; + } + + /* trim the first line */ + + p = pem; + end = p + len; + if (strncmp((char *)p, "-----", 5)) + goto bail; + p += 5; + while (p < end && *p != '\n' && *p != '-') + p++; + + if (*p != '-') + goto bail; + + while (p < end && *p != '\n') + p++; + + if (p >= end) + goto bail; + + p++; + + /* trim the last line */ + + q = (uint8_t *)end - 2; + + while (q > pem && *q != '\n') + q--; + + if (*q != '\n') + goto bail; + + *q = '\0'; + + *amount = lws_b64_decode_string((char *)p, (char *)pem, + (int)(long long)len); + *buf = (uint8_t *)pem; + + return 0; + +bail: + lws_free((uint8_t *)pem); + + return 4; +} + +int +lws_tls_check_cert_lifetime(struct lws_vhost *v) +{ + union lws_tls_cert_info_results ir; + time_t now = (time_t)lws_now_secs(), life = 0; + struct lws_acme_cert_aging_args caa; + int n; + + if (v->tls.ssl_ctx && !v->tls.skipped_certs) { + + if (now < 1464083026) /* May 2016 */ + /* our clock is wrong and we can't judge the certs */ + return -1; + + n = lws_tls_vhost_cert_info(v, LWS_TLS_CERT_INFO_VALIDITY_TO, &ir, 0); + if (n) + return 1; + + life = (ir.time - now) / (24 * 3600); + lwsl_notice(" vhost %s: cert expiry: %dd\n", v->name, (int)life); + } else + lwsl_notice(" vhost %s: no cert\n", v->name); + + memset(&caa, 0, sizeof(caa)); + caa.vh = v; + lws_broadcast(v->context, LWS_CALLBACK_VHOST_CERT_AGING, (void *)&caa, + (size_t)(ssize_t)life); + + return 0; +} + +int +lws_tls_check_all_cert_lifetimes(struct lws_context *context) +{ + struct lws_vhost *v = context->vhost_list; + + while (v) { + if (lws_tls_check_cert_lifetime(v) < 0) + return -1; + v = v->vhost_next; + } + + return 0; +} +#if !defined(LWS_WITH_ESP32) && !defined(LWS_PLAT_OPTEE) +static int +lws_tls_extant(const char *name) +{ + /* it exists if we can open it... */ + int fd = open(name, O_RDONLY), n; + char buf[1]; + + if (fd < 0) + return 1; + + /* and we can read at least one byte out of it */ + n = read(fd, buf, 1); + close(fd); + + return n != 1; +} +#endif +/* + * Returns 0 if the filepath "name" exists and can be read from. + * + * In addition, if "name".upd exists, backup "name" to "name.old.1" + * and rename "name".upd to "name" before reporting its existence. + * + * There are four situations and three results possible: + * + * 1) LWS_TLS_EXTANT_NO: There are no certs at all (we are waiting for them to + * be provisioned). We also feel like this if we need privs we don't have + * any more to look in the directory. + * + * 2) There are provisioned certs written (xxx.upd) and we still have root + * privs... in this case we rename any existing cert to have a backup name + * and move the upd cert into place with the correct name. This then becomes + * situation 4 for the caller. + * + * 3) LWS_TLS_EXTANT_ALTERNATIVE: There are provisioned certs written (xxx.upd) + * but we no longer have the privs needed to read or rename them. In this + * case, indicate that the caller should use temp copies if any we do have + * rights to access. This is normal after we have updated the cert. + * + * But if we dropped privs, we can't detect the provisioned xxx.upd cert + + * key, because we can't see in the dir. So we have to upgrade NO to + * ALTERNATIVE when we actually have the in-memory alternative. + * + * 4) LWS_TLS_EXTANT_YES: The certs are present with the correct name and we + * have the rights to read them. + */ +enum lws_tls_extant +lws_tls_use_any_upgrade_check_extant(const char *name) +{ +#if !defined(LWS_PLAT_OPTEE) + + int n; + +#if !defined(LWS_WITH_ESP32) + char buf[256]; + + lws_snprintf(buf, sizeof(buf) - 1, "%s.upd", name); + if (!lws_tls_extant(buf)) { + /* ah there is an updated file... how about the desired file? */ + if (!lws_tls_extant(name)) { + /* rename the desired file */ + for (n = 0; n < 50; n++) { + lws_snprintf(buf, sizeof(buf) - 1, + "%s.old.%d", name, n); + if (!rename(name, buf)) + break; + } + if (n == 50) { + lwsl_notice("unable to rename %s\n", name); + + return LWS_TLS_EXTANT_ALTERNATIVE; + } + lws_snprintf(buf, sizeof(buf) - 1, "%s.upd", name); + } + /* desired file is out of the way, rename the updated file */ + if (rename(buf, name)) { + lwsl_notice("unable to rename %s to %s\n", buf, name); + + return LWS_TLS_EXTANT_ALTERNATIVE; + } + } + + if (lws_tls_extant(name)) + return LWS_TLS_EXTANT_NO; +#else + nvs_handle nvh; + size_t s = 8192; + + if (nvs_open("lws-station", NVS_READWRITE, &nvh)) { + lwsl_notice("%s: can't open nvs\n", __func__); + return LWS_TLS_EXTANT_NO; + } + + n = nvs_get_blob(nvh, name, NULL, &s); + nvs_close(nvh); + + if (n) + return LWS_TLS_EXTANT_NO; +#endif +#endif + return LWS_TLS_EXTANT_YES; +} + +/* + * LWS_TLS_EXTANT_NO : skip adding the cert + * LWS_TLS_EXTANT_YES : use the cert and private key paths normally + * LWS_TLS_EXTANT_ALTERNATIVE: normal paths not usable, try alternate if poss + */ +enum lws_tls_extant +lws_tls_generic_cert_checks(struct lws_vhost *vhost, const char *cert, + const char *private_key) +{ + int n, m; + + /* + * The user code can choose to either pass the cert and + * key filepaths using the info members like this, or it can + * leave them NULL; force the vhost SSL_CTX init using the info + * options flag LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX; and + * set up the cert himself using the user callback + * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which + * happened just above and has the vhost SSL_CTX * in the user + * parameter. + */ + + if (!cert || !private_key) + return LWS_TLS_EXTANT_NO; + + n = lws_tls_use_any_upgrade_check_extant(cert); + if (n == LWS_TLS_EXTANT_ALTERNATIVE) + return LWS_TLS_EXTANT_ALTERNATIVE; + m = lws_tls_use_any_upgrade_check_extant(private_key); + if (m == LWS_TLS_EXTANT_ALTERNATIVE) + return LWS_TLS_EXTANT_ALTERNATIVE; + + if ((n == LWS_TLS_EXTANT_NO || m == LWS_TLS_EXTANT_NO) && + (vhost->options & LWS_SERVER_OPTION_IGNORE_MISSING_CERT)) { + lwsl_notice("Ignoring missing %s or %s\n", cert, private_key); + vhost->tls.skipped_certs = 1; + + return LWS_TLS_EXTANT_NO; + } + + /* + * the cert + key exist + */ + + return LWS_TLS_EXTANT_YES; +} + +#if !defined(LWS_NO_SERVER) +/* + * update the cert for every vhost using the given path + */ + +LWS_VISIBLE int +lws_tls_cert_updated(struct lws_context *context, const char *certpath, + const char *keypath, + const char *mem_cert, size_t len_mem_cert, + const char *mem_privkey, size_t len_mem_privkey) +{ + struct lws wsi; + + wsi.context = context; + + lws_start_foreach_ll(struct lws_vhost *, v, context->vhost_list) { + wsi.vhost = v; + if (v->tls.alloc_cert_path && v->tls.key_path && + !strcmp(v->tls.alloc_cert_path, certpath) && + !strcmp(v->tls.key_path, keypath)) { + lws_tls_server_certs_load(v, &wsi, certpath, keypath, + mem_cert, len_mem_cert, + mem_privkey, len_mem_privkey); + + if (v->tls.skipped_certs) + lwsl_notice("%s: vhost %s: cert unset\n", + __func__, v->name); + } + } lws_end_foreach_ll(v, vhost_next); + + return 0; +} +#endif + +int +lws_gate_accepts(struct lws_context *context, int on) +{ + struct lws_vhost *v = context->vhost_list; + + lwsl_notice("%s: on = %d\n", __func__, on); + +#if defined(LWS_WITH_STATS) + context->updated = 1; +#endif + + while (v) { + if (v->tls.use_ssl && v->lserv_wsi && + lws_change_pollfd(v->lserv_wsi, (LWS_POLLIN) * !on, + (LWS_POLLIN) * on)) + lwsl_notice("Unable to set accept POLLIN %d\n", on); + + v = v->vhost_next; + } + + return 0; +} + +/* comma-separated alpn list, like "h2,http/1.1" to openssl alpn format */ + +int +lws_alpn_comma_to_openssl(const char *comma, uint8_t *os, int len) +{ + uint8_t *oos = os, *plen = NULL; + + while (*comma && len > 1) { + if (!plen && *comma == ' ') { + comma++; + continue; + } + if (!plen) { + plen = os++; + len--; + } + + if (*comma == ',') { + *plen = lws_ptr_diff(os, plen + 1); + plen = NULL; + comma++; + } else { + *os++ = *comma++; + len--; + } + } + + if (plen) + *plen = lws_ptr_diff(os, plen + 1); + + return lws_ptr_diff(os, oos); +} + diff --git a/thirdparty/lws/win32helpers/getopt.c b/thirdparty/libwebsockets/win32helpers/getopt.c index 3bb21f6f28..2181f1cb12 100644 --- a/thirdparty/lws/win32helpers/getopt.c +++ b/thirdparty/libwebsockets/win32helpers/getopt.c @@ -1,153 +1,153 @@ -/* $NetBSD: getopt.c,v 1.16 1999/12/02 13:15:56 kleink Exp $ */ - -/* - * Copyright (c) 1987, 1993, 1994 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -#if 0 -static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; -#endif - -#include <assert.h> -#include <errno.h> -#include <stdio.h> -#include <string.h> - -#define __P(x) x -#define _DIAGASSERT(x) assert(x) - -#ifdef __weak_alias -__weak_alias(getopt,_getopt); -#endif - - -int opterr = 1, /* if error message should be printed */ - optind = 1, /* index into parent argv vector */ - optopt, /* character checked for validity */ - optreset; /* reset getopt */ -char *optarg; /* argument associated with option */ - -static char * _progname __P((char *)); -int getopt_internal __P((int, char * const *, const char *)); - -static char * -_progname(nargv0) - char * nargv0; -{ - char * tmp; - - _DIAGASSERT(nargv0 != NULL); - - tmp = strrchr(nargv0, '/'); - if (tmp) - tmp++; - else - tmp = nargv0; - return(tmp); -} - -#define BADCH (int)'?' -#define BADARG (int)':' -#define EMSG "" - -/* - * getopt -- - * Parse argc/argv argument vector. - */ -int -getopt(nargc, nargv, ostr) - int nargc; - char * const nargv[]; - const char *ostr; -{ - static char *__progname = 0; - static char *place = EMSG; /* option letter processing */ - char *oli; /* option letter list index */ - __progname = __progname?__progname:_progname(*nargv); - - _DIAGASSERT(nargv != NULL); - _DIAGASSERT(ostr != NULL); - - if (optreset || !*place) { /* update scanning pointer */ - optreset = 0; - if (optind >= nargc || *(place = nargv[optind]) != '-') { - place = EMSG; - return (-1); - } - if (place[1] && *++place == '-' /* found "--" */ - && place[1] == '\0') { - ++optind; - place = EMSG; - return (-1); - } - } /* option letter okay? */ - if ((optopt = (int)*place++) == (int)':' || - !(oli = strchr(ostr, optopt))) { - /* - * if the user didn't specify '-' as an option, - * assume it means -1. - */ - if (optopt == (int)'-') - return (-1); - if (!*place) - ++optind; - if (opterr && *ostr != ':') - (void)fprintf(stderr, - "%s: illegal option -- %c\n", __progname, optopt); - return (BADCH); - } - if (*++oli != ':') { /* don't need argument */ - optarg = NULL; - if (!*place) - ++optind; - } - else { /* need an argument */ - if (*place) /* no white space */ - optarg = place; - else if (nargc <= ++optind) { /* no arg */ - place = EMSG; - if (*ostr == ':') - return (BADARG); - if (opterr) - (void)fprintf(stderr, - "%s: option requires an argument -- %c\n", - __progname, optopt); - return (BADCH); - } - else /* white space */ - optarg = nargv[optind]; - place = EMSG; - ++optind; - } - return (optopt); /* dump back option letter */ -} - +/* $NetBSD: getopt.c,v 1.16 1999/12/02 13:15:56 kleink Exp $ */
+
+/*
+ * Copyright (c) 1987, 1993, 1994
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the University of
+ * California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if 0
+static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95";
+#endif
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#define __P(x) x
+#define _DIAGASSERT(x) assert(x)
+
+#ifdef __weak_alias
+__weak_alias(getopt,_getopt);
+#endif
+
+
+int opterr = 1, /* if error message should be printed */
+ optind = 1, /* index into parent argv vector */
+ optopt, /* character checked for validity */
+ optreset; /* reset getopt */
+char *optarg; /* argument associated with option */
+
+static char * _progname __P((char *));
+int getopt_internal __P((int, char * const *, const char *));
+
+static char *
+_progname(nargv0)
+ char * nargv0;
+{
+ char * tmp;
+
+ _DIAGASSERT(nargv0 != NULL);
+
+ tmp = strrchr(nargv0, '/');
+ if (tmp)
+ tmp++;
+ else
+ tmp = nargv0;
+ return(tmp);
+}
+
+#define BADCH (int)'?'
+#define BADARG (int)':'
+#define EMSG ""
+
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt(nargc, nargv, ostr)
+ int nargc;
+ char * const nargv[];
+ const char *ostr;
+{
+ static char *__progname = 0;
+ static char *place = EMSG; /* option letter processing */
+ char *oli; /* option letter list index */
+ __progname = __progname?__progname:_progname(*nargv);
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(ostr != NULL);
+
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc || *(place = nargv[optind]) != '-') {
+ place = EMSG;
+ return (-1);
+ }
+ if (place[1] && *++place == '-' /* found "--" */
+ && place[1] == '\0') {
+ ++optind;
+ place = EMSG;
+ return (-1);
+ }
+ } /* option letter okay? */
+ if ((optopt = (int)*place++) == (int)':' ||
+ !(oli = strchr(ostr, optopt))) {
+ /*
+ * if the user didn't specify '-' as an option,
+ * assume it means -1.
+ */
+ if (optopt == (int)'-')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (opterr && *ostr != ':')
+ (void)fprintf(stderr,
+ "%s: illegal option -- %c\n", __progname, optopt);
+ return (BADCH);
+ }
+ if (*++oli != ':') { /* don't need argument */
+ optarg = NULL;
+ if (!*place)
+ ++optind;
+ }
+ else { /* need an argument */
+ if (*place) /* no white space */
+ optarg = place;
+ else if (nargc <= ++optind) { /* no arg */
+ place = EMSG;
+ if (*ostr == ':')
+ return (BADARG);
+ if (opterr)
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ __progname, optopt);
+ return (BADCH);
+ }
+ else /* white space */
+ optarg = nargv[optind];
+ place = EMSG;
+ ++optind;
+ }
+ return (optopt); /* dump back option letter */
+}
+
diff --git a/thirdparty/lws/win32helpers/getopt.h b/thirdparty/libwebsockets/win32helpers/getopt.h index 7137f0379c..7137f0379c 100644 --- a/thirdparty/lws/win32helpers/getopt.h +++ b/thirdparty/libwebsockets/win32helpers/getopt.h diff --git a/thirdparty/lws/win32helpers/getopt_long.c b/thirdparty/libwebsockets/win32helpers/getopt_long.c index 5bcf40060f..22e5fa8945 100644 --- a/thirdparty/lws/win32helpers/getopt_long.c +++ b/thirdparty/libwebsockets/win32helpers/getopt_long.c @@ -1,237 +1,240 @@ - -/* - * Copyright (c) 1987, 1993, 1994, 1996 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ -#include <assert.h> -#include <errno.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include "getopt.h" - -extern int opterr; /* if error message should be printed */ -extern int optind; /* index into parent argv vector */ -extern int optopt; /* character checked for validity */ -extern int optreset; /* reset getopt */ -extern char *optarg; /* argument associated with option */ - -#define __P(x) x -#define _DIAGASSERT(x) assert(x) - -static char * __progname __P((char *)); -int getopt_internal __P((int, char * const *, const char *)); - -static char * -__progname(nargv0) - char * nargv0; -{ - char * tmp; - - _DIAGASSERT(nargv0 != NULL); - - tmp = strrchr(nargv0, '/'); - if (tmp) - tmp++; - else - tmp = nargv0; - return(tmp); -} - -#define BADCH (int)'?' -#define BADARG (int)':' -#define EMSG "" - -/* - * getopt -- - * Parse argc/argv argument vector. - */ -int -getopt_internal(nargc, nargv, ostr) - int nargc; - char * const *nargv; - const char *ostr; -{ - static char *place = EMSG; /* option letter processing */ - char *oli; /* option letter list index */ - - _DIAGASSERT(nargv != NULL); - _DIAGASSERT(ostr != NULL); - - if (optreset || !*place) { /* update scanning pointer */ - optreset = 0; - if (optind >= nargc || *(place = nargv[optind]) != '-') { - place = EMSG; - return (-1); - } - if (place[1] && *++place == '-') { /* found "--" */ - /* ++optind; */ - place = EMSG; - return (-2); - } - } /* option letter okay? */ - if ((optopt = (int)*place++) == (int)':' || - !(oli = strchr(ostr, optopt))) { - /* - * if the user didn't specify '-' as an option, - * assume it means -1. - */ - if (optopt == (int)'-') - return (-1); - if (!*place) - ++optind; - if (opterr && *ostr != ':') - (void)fprintf(stderr, - "%s: illegal option -- %c\n", __progname(nargv[0]), optopt); - return (BADCH); - } - if (*++oli != ':') { /* don't need argument */ - optarg = NULL; - if (!*place) - ++optind; - } else { /* need an argument */ - if (*place) /* no white space */ - optarg = place; - else if (nargc <= ++optind) { /* no arg */ - place = EMSG; - if ((opterr) && (*ostr != ':')) - (void)fprintf(stderr, - "%s: option requires an argument -- %c\n", - __progname(nargv[0]), optopt); - return (BADARG); - } else /* white space */ - optarg = nargv[optind]; - place = EMSG; - ++optind; - } - return (optopt); /* dump back option letter */ -} - -#if 0 -/* - * getopt -- - * Parse argc/argv argument vector. - */ -int -getopt2(nargc, nargv, ostr) - int nargc; - char * const *nargv; - const char *ostr; -{ - int retval; - - if ((retval = getopt_internal(nargc, nargv, ostr)) == -2) { - retval = -1; - ++optind; - } - return(retval); -} -#endif - -/* - * getopt_long -- - * Parse argc/argv argument vector. - */ -int -getopt_long(nargc, nargv, options, long_options, index) - int nargc; - char ** nargv; - char * options; - struct option * long_options; - int * index; -{ - int retval; - - _DIAGASSERT(nargv != NULL); - _DIAGASSERT(options != NULL); - _DIAGASSERT(long_options != NULL); - /* index may be NULL */ - - if ((retval = getopt_internal(nargc, nargv, options)) == -2) { - char *current_argv = nargv[optind++] + 2, *has_equal; - int i, current_argv_len, match = -1; - - if (*current_argv == '\0') { - return(-1); - } - if ((has_equal = strchr(current_argv, '=')) != NULL) { - current_argv_len = has_equal - current_argv; - has_equal++; - } else - current_argv_len = strlen(current_argv); - - for (i = 0; long_options[i].name; i++) { - if (strncmp(current_argv, long_options[i].name, current_argv_len)) - continue; - - if (strlen(long_options[i].name) == (unsigned)current_argv_len) { - match = i; - break; - } - if (match == -1) - match = i; - } - if (match != -1) { - if (long_options[match].has_arg == required_argument || - long_options[match].has_arg == optional_argument) { - if (has_equal) - optarg = has_equal; - else - optarg = nargv[optind++]; - } - if ((long_options[match].has_arg == required_argument) - && (optarg == NULL)) { - /* - * Missing argument, leading : - * indicates no error should be generated - */ - if ((opterr) && (*options != ':')) - (void)fprintf(stderr, - "%s: option requires an argument -- %s\n", - __progname(nargv[0]), current_argv); - return (BADARG); - } - } else { /* No matching argument */ - if ((opterr) && (*options != ':')) - (void)fprintf(stderr, - "%s: illegal option -- %s\n", __progname(nargv[0]), current_argv); - return (BADCH); - } - if (long_options[match].flag) { - *long_options[match].flag = long_options[match].val; - retval = 0; - } else - retval = long_options[match].val; - if (index) - *index = match; - } - return(retval); -} +
+/*
+ * Copyright (c) 1987, 1993, 1994, 1996
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the University of
+ * California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "getopt.h"
+
+#define lws_ptr_diff(head, tail) \
+ ((int)((char *)(head) - (char *)(tail)))
+
+extern int opterr; /* if error message should be printed */
+extern int optind; /* index into parent argv vector */
+extern int optopt; /* character checked for validity */
+extern int optreset; /* reset getopt */
+extern char *optarg; /* argument associated with option */
+
+#define __P(x) x
+#define _DIAGASSERT(x) assert(x)
+
+static char * __progname __P((char *));
+int getopt_internal __P((int, char * const *, const char *));
+
+static char *
+__progname(nargv0)
+ char * nargv0;
+{
+ char * tmp;
+
+ _DIAGASSERT(nargv0 != NULL);
+
+ tmp = strrchr(nargv0, '/');
+ if (tmp)
+ tmp++;
+ else
+ tmp = nargv0;
+ return(tmp);
+}
+
+#define BADCH (int)'?'
+#define BADARG (int)':'
+#define EMSG ""
+
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_internal(nargc, nargv, ostr)
+ int nargc;
+ char * const *nargv;
+ const char *ostr;
+{
+ static char *place = EMSG; /* option letter processing */
+ char *oli; /* option letter list index */
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(ostr != NULL);
+
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc || *(place = nargv[optind]) != '-') {
+ place = EMSG;
+ return (-1);
+ }
+ if (place[1] && *++place == '-') { /* found "--" */
+ /* ++optind; */
+ place = EMSG;
+ return (-2);
+ }
+ } /* option letter okay? */
+ if ((optopt = (int)*place++) == (int)':' ||
+ !(oli = strchr(ostr, optopt))) {
+ /*
+ * if the user didn't specify '-' as an option,
+ * assume it means -1.
+ */
+ if (optopt == (int)'-')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (opterr && *ostr != ':')
+ (void)fprintf(stderr,
+ "%s: illegal option -- %c\n", __progname(nargv[0]), optopt);
+ return (BADCH);
+ }
+ if (*++oli != ':') { /* don't need argument */
+ optarg = NULL;
+ if (!*place)
+ ++optind;
+ } else { /* need an argument */
+ if (*place) /* no white space */
+ optarg = place;
+ else if (nargc <= ++optind) { /* no arg */
+ place = EMSG;
+ if ((opterr) && (*ostr != ':'))
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ __progname(nargv[0]), optopt);
+ return (BADARG);
+ } else /* white space */
+ optarg = nargv[optind];
+ place = EMSG;
+ ++optind;
+ }
+ return (optopt); /* dump back option letter */
+}
+
+#if 0
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt2(nargc, nargv, ostr)
+ int nargc;
+ char * const *nargv;
+ const char *ostr;
+{
+ int retval;
+
+ if ((retval = getopt_internal(nargc, nargv, ostr)) == -2) {
+ retval = -1;
+ ++optind;
+ }
+ return(retval);
+}
+#endif
+
+/*
+ * getopt_long --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_long(nargc, nargv, options, long_options, index)
+ int nargc;
+ char ** nargv;
+ char * options;
+ struct option * long_options;
+ int * index;
+{
+ int retval;
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(options != NULL);
+ _DIAGASSERT(long_options != NULL);
+ /* index may be NULL */
+
+ if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
+ char *current_argv = nargv[optind++] + 2, *has_equal;
+ int i, current_argv_len, match = -1;
+
+ if (*current_argv == '\0') {
+ return(-1);
+ }
+ if ((has_equal = strchr(current_argv, '=')) != NULL) {
+ current_argv_len = lws_ptr_diff(has_equal, current_argv);
+ has_equal++;
+ } else
+ current_argv_len = (int)strlen(current_argv);
+
+ for (i = 0; long_options[i].name; i++) {
+ if (strncmp(current_argv, long_options[i].name, current_argv_len))
+ continue;
+
+ if (strlen(long_options[i].name) == (unsigned)current_argv_len) {
+ match = i;
+ break;
+ }
+ if (match == -1)
+ match = i;
+ }
+ if (match != -1) {
+ if (long_options[match].has_arg == required_argument ||
+ long_options[match].has_arg == optional_argument) {
+ if (has_equal)
+ optarg = has_equal;
+ else
+ optarg = nargv[optind++];
+ }
+ if ((long_options[match].has_arg == required_argument)
+ && (optarg == NULL)) {
+ /*
+ * Missing argument, leading :
+ * indicates no error should be generated
+ */
+ if ((opterr) && (*options != ':'))
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %s\n",
+ __progname(nargv[0]), current_argv);
+ return (BADARG);
+ }
+ } else { /* No matching argument */
+ if ((opterr) && (*options != ':'))
+ (void)fprintf(stderr,
+ "%s: illegal option -- %s\n", __progname(nargv[0]), current_argv);
+ return (BADCH);
+ }
+ if (long_options[match].flag) {
+ *long_options[match].flag = long_options[match].val;
+ retval = 0;
+ } else
+ retval = long_options[match].val;
+ if (index)
+ *index = match;
+ }
+ return(retval);
+}
diff --git a/thirdparty/lws/win32helpers/gettimeofday.c b/thirdparty/libwebsockets/win32helpers/gettimeofday.c index 35dd73531d..08385c2320 100644 --- a/thirdparty/lws/win32helpers/gettimeofday.c +++ b/thirdparty/libwebsockets/win32helpers/gettimeofday.c @@ -1,36 +1,36 @@ -#include <time.h> -#include <windows.h> //I've omitted context line - -#include "gettimeofday.h" - -int gettimeofday(struct timeval *tv, struct timezone *tz) -{ - FILETIME ft; - unsigned __int64 tmpres = 0; - static int tzflag; - - if (NULL != tv) { - GetSystemTimeAsFileTime(&ft); - - tmpres |= ft.dwHighDateTime; - tmpres <<= 32; - tmpres |= ft.dwLowDateTime; - - /*converting file time to unix epoch*/ - tmpres /= 10; /*convert into microseconds*/ +#include <time.h>
+#include <windows.h> //I've omitted context line
+
+#include "gettimeofday.h"
+
+int gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+ FILETIME ft;
+ unsigned __int64 tmpres = 0;
+ static int tzflag;
+
+ if (NULL != tv) {
+ GetSystemTimeAsFileTime(&ft);
+
+ tmpres |= ft.dwHighDateTime;
+ tmpres <<= 32;
+ tmpres |= ft.dwLowDateTime;
+
+ /*converting file time to unix epoch*/
+ tmpres /= 10; /*convert into microseconds*/
tmpres -= DELTA_EPOCH_IN_MICROSECS; - tv->tv_sec = (long)(tmpres / 1000000UL); - tv->tv_usec = (long)(tmpres % 1000000UL); - } - - if (NULL != tz) { - if (!tzflag) { - _tzset(); - tzflag++; - } - tz->tz_minuteswest = _timezone / 60; - tz->tz_dsttime = _daylight; - } - - return 0; -} + tv->tv_sec = (long)(tmpres / 1000000UL);
+ tv->tv_usec = (long)(tmpres % 1000000UL);
+ }
+
+ if (NULL != tz) {
+ if (!tzflag) {
+ _tzset();
+ tzflag++;
+ }
+ tz->tz_minuteswest = _timezone / 60;
+ tz->tz_dsttime = _daylight;
+ }
+
+ return 0;
+}
diff --git a/thirdparty/lws/win32helpers/gettimeofday.h b/thirdparty/libwebsockets/win32helpers/gettimeofday.h index 33e7a750fe..33e7a750fe 100644 --- a/thirdparty/lws/win32helpers/gettimeofday.h +++ b/thirdparty/libwebsockets/win32helpers/gettimeofday.h diff --git a/thirdparty/lws/client/client.c b/thirdparty/lws/client/client.c deleted file mode 100644 index ded4e4bf0b..0000000000 --- a/thirdparty/lws/client/client.c +++ /dev/null @@ -1,1304 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -int -lws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len) -{ - int m; - - switch (wsi->mode) { - case LWSCM_WSCL_WAITING_PROXY_REPLY: - case LWSCM_WSCL_ISSUE_HANDSHAKE: - case LWSCM_WSCL_WAITING_SERVER_REPLY: - case LWSCM_WSCL_WAITING_EXTENSION_CONNECT: - case LWSCM_WS_CLIENT: - while (len) { - /* - * we were accepting input but now we stopped doing so - */ - if (lws_is_flowcontrolled(wsi)) { - lwsl_debug("%s: caching %ld\n", __func__, (long)len); - lws_rxflow_cache(wsi, *buf, 0, len); - return 0; - } - if (wsi->u.ws.rx_draining_ext) { -#if !defined(LWS_NO_CLIENT) - if (wsi->mode == LWSCM_WS_CLIENT) - m = lws_client_rx_sm(wsi, 0); - else -#endif - m = lws_rx_sm(wsi, 0); - if (m < 0) - return -1; - continue; - } - /* account for what we're using in rxflow buffer */ - if (wsi->rxflow_buffer) - wsi->rxflow_pos++; - - if (lws_client_rx_sm(wsi, *(*buf)++)) { - lwsl_debug("client_rx_sm exited\n"); - return -1; - } - len--; - } - lwsl_debug("%s: finished with %ld\n", __func__, (long)len); - return 0; - default: - break; - } - - return 0; -} - -LWS_VISIBLE LWS_EXTERN void -lws_client_http_body_pending(struct lws *wsi, int something_left_to_send) -{ - wsi->client_http_body_pending = !!something_left_to_send; -} - -int -lws_client_socket_service(struct lws_context *context, struct lws *wsi, - struct lws_pollfd *pollfd) -{ - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - char *p = (char *)&pt->serv_buf[0]; - const char *cce = NULL; - unsigned char c; - char *sb = p; - int n = 0; - ssize_t len = 0; -#if defined(LWS_WITH_SOCKS5) - char conn_mode = 0, pending_timeout = 0; -#endif - - switch (wsi->mode) { - - case LWSCM_WSCL_WAITING_CONNECT: - - /* - * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE - * timeout protection set in client-handshake.c - */ - - if (!lws_client_connect_2(wsi)) { - /* closed */ - lwsl_client("closed\n"); - return -1; - } - - /* either still pending connection, or changed mode */ - return 0; - -#if defined(LWS_WITH_SOCKS5) - /* SOCKS Greeting Reply */ - case LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY: - case LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY: - case LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY: - - /* handle proxy hung up on us */ - - if (pollfd->revents & LWS_POLLHUP) { - lwsl_warn("SOCKS connection %p (fd=%d) dead\n", - (void *)wsi, pollfd->fd); - goto bail3; - } - - n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0); - if (n < 0) { - if (LWS_ERRNO == LWS_EAGAIN) { - lwsl_debug("SOCKS read EAGAIN, retrying\n"); - return 0; - } - lwsl_err("ERROR reading from SOCKS socket\n"); - goto bail3; - } - - switch (wsi->mode) { - - case LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY: - if (pt->serv_buf[0] != SOCKS_VERSION_5) - goto socks_reply_fail; - - if (pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH) { - lwsl_client("SOCKS greeting reply: No Auth Method\n"); - socks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len); - conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY; - pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY; - goto socks_send; - } - - if (pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD) { - lwsl_client("SOCKS greeting reply: User/Pw Method\n"); - socks_generate_msg(wsi, SOCKS_MSG_USERNAME_PASSWORD, &len); - conn_mode = LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY; - pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY; - goto socks_send; - } - goto socks_reply_fail; - - case LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY: - if (pt->serv_buf[0] != SOCKS_SUBNEGOTIATION_VERSION_1 || - pt->serv_buf[1] != SOCKS_SUBNEGOTIATION_STATUS_SUCCESS) - goto socks_reply_fail; - - lwsl_client("SOCKS password OK, sending connect\n"); - socks_generate_msg(wsi, SOCKS_MSG_CONNECT, &len); - conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY; - pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY; -socks_send: - n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len, - MSG_NOSIGNAL); - if (n < 0) { - lwsl_debug("ERROR writing to socks proxy\n"); - goto bail3; - } - - lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT); - wsi->mode = conn_mode; - break; - -socks_reply_fail: - lwsl_notice("socks reply: v%d, err %d\n", - pt->serv_buf[0], pt->serv_buf[1]); - goto bail3; - - case LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY: - if (pt->serv_buf[0] != SOCKS_VERSION_5 || - pt->serv_buf[1] != SOCKS_REQUEST_REPLY_SUCCESS) - goto socks_reply_fail; - - lwsl_client("socks connect OK\n"); - - /* free stash since we are done with it */ - lws_free_set_NULL(wsi->u.hdr.stash); - if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, - wsi->vhost->socks_proxy_address)) - goto bail3; - - wsi->c_port = wsi->vhost->socks_proxy_port; - - /* clear his proxy connection timeout */ - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - goto start_ws_handshake; - } - break; -#endif - - case LWSCM_WSCL_WAITING_PROXY_REPLY: - - /* handle proxy hung up on us */ - - if (pollfd->revents & LWS_POLLHUP) { - - lwsl_warn("Proxy connection %p (fd=%d) dead\n", - (void *)wsi, pollfd->fd); - - goto bail3; - } - - n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0); - if (n < 0) { - if (LWS_ERRNO == LWS_EAGAIN) { - lwsl_debug("Proxy read returned EAGAIN... retrying\n"); - return 0; - } - lwsl_err("ERROR reading from proxy socket\n"); - goto bail3; - } - - pt->serv_buf[13] = '\0'; - if (strcmp(sb, "HTTP/1.0 200 ") && - strcmp(sb, "HTTP/1.1 200 ")) { - lwsl_err("ERROR proxy: %s\n", sb); - goto bail3; - } - - /* clear his proxy connection timeout */ - - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - - /* fallthru */ - - case LWSCM_WSCL_ISSUE_HANDSHAKE: - - /* - * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE - * timeout protection set in client-handshake.c - * - * take care of our lws_callback_on_writable - * happening at a time when there's no real connection yet - */ -#if defined(LWS_WITH_SOCKS5) -start_ws_handshake: -#endif - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) - return -1; - -#ifdef LWS_OPENSSL_SUPPORT - /* we can retry this... just cook the SSL BIO the first time */ - - if (wsi->use_ssl && !wsi->ssl && - lws_ssl_client_bio_create(wsi) < 0) { - cce = "bio_create failed"; - goto bail3; - } - - if (wsi->use_ssl) { - n = lws_ssl_client_connect1(wsi); - if (!n) - return 0; - if (n < 0) { - cce = "lws_ssl_client_connect1 failed"; - goto bail3; - } - } else - wsi->ssl = NULL; - - /* fallthru */ - - case LWSCM_WSCL_WAITING_SSL: - - if (wsi->use_ssl) { - n = lws_ssl_client_connect2(wsi); - if (!n) - return 0; - if (n < 0) { - cce = "lws_ssl_client_connect2 failed"; - goto bail3; - } - } else - wsi->ssl = NULL; -#endif - - wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2; - lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND, - context->timeout_secs); - - /* fallthru */ - - case LWSCM_WSCL_ISSUE_HANDSHAKE2: - p = lws_generate_client_handshake(wsi, p); - if (p == NULL) { - if (wsi->mode == LWSCM_RAW) - return 0; - - lwsl_err("Failed to generate handshake for client\n"); - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - return 0; - } - - /* send our request to the server */ - lws_latency_pre(context, wsi); - - n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb); - lws_latency(context, wsi, "send lws_issue_raw", n, - n == p - sb); - switch (n) { - case LWS_SSL_CAPABLE_ERROR: - lwsl_debug("ERROR writing to client socket\n"); - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - return 0; - case LWS_SSL_CAPABLE_MORE_SERVICE: - lws_callback_on_writable(wsi); - break; - } - - if (wsi->client_http_body_pending) { - wsi->mode = LWSCM_WSCL_ISSUE_HTTP_BODY; - lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD, - context->timeout_secs); - /* user code must ask for writable callback */ - break; - } - - goto client_http_body_sent; - - case LWSCM_WSCL_ISSUE_HTTP_BODY: - if (wsi->client_http_body_pending) { - lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD, - context->timeout_secs); - /* user code must ask for writable callback */ - break; - } -client_http_body_sent: - wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; - wsi->u.hdr.lextable_pos = 0; - wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY; - lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, - context->timeout_secs); - break; - - case LWSCM_WSCL_WAITING_SERVER_REPLY: - /* - * handle server hanging up on us... - * but if there is POLLIN waiting, handle that first - */ - if ((pollfd->revents & (LWS_POLLIN | LWS_POLLHUP)) == - LWS_POLLHUP) { - - lwsl_debug("Server connection %p (fd=%d) dead\n", - (void *)wsi, pollfd->fd); - cce = "Peer hung up"; - goto bail3; - } - - if (!(pollfd->revents & LWS_POLLIN)) - break; - - /* interpret the server response - * - * HTTP/1.1 101 Switching Protocols - * Upgrade: websocket - * Connection: Upgrade - * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= - * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== - * Sec-WebSocket-Protocol: chat - * - * we have to take some care here to only take from the - * socket bytewise. The browser may (and has been seen to - * in the case that onopen() performs websocket traffic) - * coalesce both handshake response and websocket traffic - * in one packet, since at that point the connection is - * definitively ready from browser pov. - */ - len = 1; - while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && - len > 0) { - n = lws_ssl_capable_read(wsi, &c, 1); - lws_latency(context, wsi, "send lws_issue_raw", n, - n == 1); - switch (n) { - case 0: - case LWS_SSL_CAPABLE_ERROR: - cce = "read failed"; - goto bail3; - case LWS_SSL_CAPABLE_MORE_SERVICE: - return 0; - } - - if (lws_parse(wsi, c)) { - lwsl_warn("problems parsing header\n"); - goto bail3; - } - } - - /* - * hs may also be coming in multiple packets, there is a 5-sec - * libwebsocket timeout still active here too, so if parsing did - * not complete just wait for next packet coming in this state - */ - if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE) - break; - - /* - * otherwise deal with the handshake. If there's any - * packet traffic already arrived we'll trigger poll() again - * right away and deal with it that way - */ - return lws_client_interpret_server_handshake(wsi); - -bail3: - lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n"); - if (cce) - lwsl_info("reason: %s\n", cce); - wsi->protocol->callback(wsi, - LWS_CALLBACK_CLIENT_CONNECTION_ERROR, - wsi->user_space, (void *)cce, cce ? strlen(cce) : 0); - wsi->already_did_cce = 1; - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - return -1; - - case LWSCM_WSCL_WAITING_EXTENSION_CONNECT: - lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n"); - break; - - case LWSCM_WSCL_PENDING_CANDIDATE_CHILD: - lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n"); - break; - default: - break; - } - - return 0; -} - -/* - * In-place str to lower case - */ - -static void -strtolower(char *s) -{ - while (*s) { -#ifdef LWS_PLAT_OPTEE - int tolower_optee(int c); - *s = tolower_optee((int)*s); -#else - *s = tolower((int)*s); -#endif - s++; - } -} - -int LWS_WARN_UNUSED_RESULT -lws_http_transaction_completed_client(struct lws *wsi) -{ - lwsl_debug("%s: wsi %p\n", __func__, wsi); - /* if we can't go back to accept new headers, drop the connection */ - if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) { - lwsl_info("%s: %p: close connection\n", __func__, wsi); - return 1; - } - - /* we don't support chained client connections yet */ - return 1; -#if 0 - /* otherwise set ourselves up ready to go again */ - wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED; - wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED; - wsi->u.http.rx_content_length = 0; - wsi->hdr_parsing_completed = 0; - - /* He asked for it to stay alive indefinitely */ - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - - /* - * As client, nothing new is going to come until we ask for it - * we can drop the ah, if any - */ - if (wsi->u.hdr.ah) { - lws_header_table_force_to_detachable_state(wsi); - lws_header_table_detach(wsi, 0); - } - - /* If we're (re)starting on headers, need other implied init */ - wsi->u.hdr.ues = URIES_IDLE; - - lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi); - - return 0; -#endif -} - -LWS_VISIBLE LWS_EXTERN unsigned int -lws_http_client_http_response(struct lws *wsi) -{ - if (!wsi->u.http.ah) - return 0; - - return wsi->u.http.ah->http_response; -} - -int -lws_client_interpret_server_handshake(struct lws *wsi) -{ - int n, len, okay = 0, port = 0, ssl = 0; - int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; - struct lws_context *context = wsi->context; - const char *pc, *prot, *ads = NULL, *path, *cce = NULL; - struct allocated_headers *ah = NULL; - char *p, *q; - char new_path[300]; -#ifndef LWS_NO_EXTENSIONS - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - char *sb = (char *)&pt->serv_buf[0]; - const struct lws_ext_options *opts; - const struct lws_extension *ext; - char ext_name[128]; - const char *c, *a; - char ignore; - int more = 1; - void *v; -#endif - if (wsi->u.hdr.stash) - lws_free_set_NULL(wsi->u.hdr.stash); - - ah = wsi->u.hdr.ah; - if (!wsi->do_ws) { - /* we are being an http client... - */ - lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED); - wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED; - wsi->u.http.ah = ah; - ah->http_response = 0; - } - - /* - * well, what the server sent looked reasonable for syntax. - * Now let's confirm it sent all the necessary headers - * - * http (non-ws) client will expect something like this - * - * HTTP/1.0.200 - * server:.libwebsockets - * content-type:.text/html - * content-length:.17703 - * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000 - * - * - * - */ - - wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE; - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); - if (wsi->do_ws && !p) { - lwsl_info("no URI\n"); - cce = "HS: URI missing"; - goto bail3; - } - if (!p) { - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0); - wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE; - } - if (!p) { - cce = "HS: URI missing"; - lwsl_info("no URI\n"); - goto bail3; - } - n = atoi(p); - if (ah) - ah->http_response = n; - - if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) { - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION); - if (!p) { - cce = "HS: Redirect code but no Location"; - goto bail3; - } - - /* Relative reference absolute path */ - if (p[0] == '/') - { -#ifdef LWS_OPENSSL_SUPPORT - ssl = wsi->use_ssl; -#endif - ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS); - port = wsi->c_port; - path = p + 1; /* +1 as lws_client_reset expects leading / to be omitted */ - } - /* Absolute (Full) URI */ - else if (strchr(p, ':')) - { - if (lws_parse_uri(p, &prot, &ads, &port, &path)) { - cce = "HS: URI did not parse"; - goto bail3; - } - - if (!strcmp(prot, "wss") || !strcmp(prot, "https")) - ssl = 1; - } - /* Relative reference relative path */ - else - { - /* This doesn't try to calculate an absolute path, that will be left to the server */ -#ifdef LWS_OPENSSL_SUPPORT - ssl = wsi->use_ssl; -#endif - ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS); - port = wsi->c_port; - path = new_path + 1; /* +1 as lws_client_reset expects leading / to be omitted */ - strncpy(new_path, lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI), sizeof(new_path)); - new_path[sizeof(new_path) - 1] = '\0'; - q = strrchr(new_path, '/'); - if (q) - { - strncpy(q + 1, p, sizeof(new_path) - (q - new_path) - 1); - new_path[sizeof(new_path) - 1] = '\0'; - } - else - { - path = p; - } - } - -#ifdef LWS_OPENSSL_SUPPORT - if (wsi->use_ssl && !ssl) { - cce = "HS: Redirect attempted SSL downgrade"; - goto bail3; - } -#endif - - if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) { - /* there are two ways to fail out with NULL return... - * simple, early problem where the wsi is intact, or - * we went through with the reconnect attempt and the - * wsi is already closed. In the latter case, the wsi - * has beet set to NULL additionally. - */ - lwsl_err("Redirect failed\n"); - cce = "HS: Redirect failed"; - if (wsi) - goto bail3; - - return 1; - } - return 0; - } - - if (!wsi->do_ws) { - -#ifdef LWS_WITH_HTTP_PROXY - wsi->perform_rewrite = 0; - if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) { - if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE), - "text/html", 9)) - wsi->perform_rewrite = 1; - } -#endif - - /* allocate the per-connection user memory (if any) */ - if (lws_ensure_user_space(wsi)) { - lwsl_err("Problem allocating wsi user mem\n"); - cce = "HS: OOM"; - goto bail2; - } - - /* he may choose to send us stuff in chunked transfer-coding */ - wsi->chunked = 0; - wsi->chunk_remaining = 0; /* ie, next thing is chunk size */ - if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) { - wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi, - WSI_TOKEN_HTTP_TRANSFER_ENCODING), - "chunked"); - /* first thing is hex, after payload there is crlf */ - wsi->chunk_parser = ELCP_HEX; - } - - if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) { - wsi->u.http.rx_content_length = - atoll(lws_hdr_simple_ptr(wsi, - WSI_TOKEN_HTTP_CONTENT_LENGTH)); - lwsl_notice("%s: incoming content length %llu\n", __func__, - (unsigned long long)wsi->u.http.rx_content_length); - wsi->u.http.rx_content_remain = wsi->u.http.rx_content_length; - } else /* can't do 1.1 without a content length or chunked */ - if (!wsi->chunked) - wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE; - - /* - * we seem to be good to go, give client last chance to check - * headers and OK it - */ - if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, - wsi->user_space, NULL, 0)) { - - cce = "HS: disallowed by client filter"; - goto bail2; - } - - /* clear his proxy connection timeout */ - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - - wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; - - /* call him back to inform him he is up */ - if (wsi->protocol->callback(wsi, - LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP, - wsi->user_space, NULL, 0)) { - cce = "HS: disallowed at ESTABLISHED"; - goto bail3; - } - - /* free up his parsing allocations */ - lws_header_table_detach(wsi, 0); - - lwsl_notice("%s: client connection up\n", __func__); - - return 0; - } - - if (p && !strncmp(p, "401", 3)) { - lwsl_warn( - "lws_client_handshake: got bad HTTP response '%s'\n", p); - cce = "HS: ws upgrade unauthorized"; - goto bail3; - } - - if (p && strncmp(p, "101", 3)) { - lwsl_warn( - "lws_client_handshake: got bad HTTP response '%s'\n", p); - cce = "HS: ws upgrade response not 101"; - goto bail3; - } - - if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { - lwsl_info("no ACCEPT\n"); - cce = "HS: ACCEPT missing"; - goto bail3; - } - - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); - if (!p) { - lwsl_info("no UPGRADE\n"); - cce = "HS: UPGRADE missing"; - goto bail3; - } - strtolower(p); - if (strcmp(p, "websocket")) { - lwsl_warn( - "lws_client_handshake: got bad Upgrade header '%s'\n", p); - cce = "HS: Upgrade to something other than websocket"; - goto bail3; - } - - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); - if (!p) { - lwsl_info("no Connection hdr\n"); - cce = "HS: CONNECTION missing"; - goto bail3; - } - strtolower(p); - if (strcmp(p, "upgrade")) { - lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); - cce = "HS: UPGRADE malformed"; - goto bail3; - } - - pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); - if (!pc) { - lwsl_parser("lws_client_int_s_hs: no protocol list\n"); - } else - lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); - - /* - * confirm the protocol the server wants to talk was in the list - * of protocols we offered - */ - - len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); - if (!len) { - lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n"); - /* - * no protocol name to work from, - * default to first protocol - */ - n = 0; - wsi->protocol = &wsi->vhost->protocols[0]; - goto check_extensions; - } - - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); - len = strlen(p); - - while (pc && *pc && !okay) { - if (!strncmp(pc, p, len) && - (pc[len] == ',' || pc[len] == '\0')) { - okay = 1; - continue; - } - while (*pc && *pc++ != ',') - ; - while (*pc && *pc == ' ') - pc++; - } - - if (!okay) { - lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p); - cce = "HS: PROTOCOL malformed"; - goto bail2; - } - - /* - * identify the selected protocol struct and set it - */ - n = 0; - wsi->protocol = NULL; - while (wsi->vhost->protocols[n].callback && !wsi->protocol) { - if (strcmp(p, wsi->vhost->protocols[n].name) == 0) { - wsi->protocol = &wsi->vhost->protocols[n]; - break; - } - n++; - } - - if (wsi->protocol == NULL) { - lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p); - cce = "HS: Cannot match protocol"; - goto bail2; - } - -check_extensions: - /* - * stitch protocol choice into the vh protocol linked list - * We always insert ourselves at the start of the list - * - * X <-> B - * X <-> pAn <-> pB - */ - //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n", - // __func__, - // wsi->vhost->same_vh_protocol_list[n], - // wsi->same_vh_protocol_prev); - wsi->same_vh_protocol_prev = /* guy who points to us */ - &wsi->vhost->same_vh_protocol_list[n]; - wsi->same_vh_protocol_next = /* old first guy is our next */ - wsi->vhost->same_vh_protocol_list[n]; - /* we become the new first guy */ - wsi->vhost->same_vh_protocol_list[n] = wsi; - - if (wsi->same_vh_protocol_next) - /* old first guy points back to us now */ - wsi->same_vh_protocol_next->same_vh_protocol_prev = - &wsi->same_vh_protocol_next; - -#ifndef LWS_NO_EXTENSIONS - /* instantiate the accepted extensions */ - - if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { - lwsl_ext("no client extensions allowed by server\n"); - goto check_accept; - } - - /* - * break down the list of server accepted extensions - * and go through matching them or identifying bogons - */ - - if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) { - lwsl_warn("ext list from server failed to copy\n"); - cce = "HS: EXT: list too big"; - goto bail2; - } - - c = sb; - n = 0; - ignore = 0; - a = NULL; - while (more) { - - if (*c && (*c != ',' && *c != '\t')) { - if (*c == ';') { - ignore = 1; - if (!a) - a = c + 1; - } - if (ignore || *c == ' ') { - c++; - continue; - } - - ext_name[n] = *c++; - if (n < sizeof(ext_name) - 1) - n++; - continue; - } - ext_name[n] = '\0'; - ignore = 0; - if (!*c) - more = 0; - else { - c++; - if (!n) - continue; - } - - /* check we actually support it */ - - lwsl_notice("checking client ext %s\n", ext_name); - - n = 0; - ext = wsi->vhost->extensions; - while (ext && ext->callback) { - if (strcmp(ext_name, ext->name)) { - ext++; - continue; - } - - n = 1; - lwsl_notice("instantiating client ext %s\n", ext_name); - - /* instantiate the extension on this conn */ - - wsi->active_extensions[wsi->count_act_ext] = ext; - - /* allow him to construct his ext instance */ - - if (ext->callback(lws_get_context(wsi), ext, wsi, - LWS_EXT_CB_CLIENT_CONSTRUCT, - (void *)&wsi->act_ext_user[wsi->count_act_ext], - (void *)&opts, 0)) { - lwsl_info(" ext %s failed construction\n", ext_name); - ext++; - continue; - } - - /* - * allow the user code to override ext defaults if it - * wants to - */ - ext_name[0] = '\0'; - if (user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_WS_EXT_DEFAULTS, - (char *)ext->name, ext_name, - sizeof(ext_name))) { - cce = "HS: EXT: failed setting defaults"; - goto bail2; - } - - if (ext_name[0] && - lws_ext_parse_options(ext, wsi, wsi->act_ext_user[ - wsi->count_act_ext], opts, ext_name, - strlen(ext_name))) { - lwsl_err("%s: unable to parse user defaults '%s'", - __func__, ext_name); - cce = "HS: EXT: failed parsing defaults"; - goto bail2; - } - - /* - * give the extension the server options - */ - if (a && lws_ext_parse_options(ext, wsi, - wsi->act_ext_user[wsi->count_act_ext], - opts, a, c - a)) { - lwsl_err("%s: unable to parse remote def '%s'", - __func__, a); - cce = "HS: EXT: failed parsing options"; - goto bail2; - } - - if (ext->callback(lws_get_context(wsi), ext, wsi, - LWS_EXT_CB_OPTION_CONFIRM, - wsi->act_ext_user[wsi->count_act_ext], - NULL, 0)) { - lwsl_err("%s: ext %s rejects server options %s", - __func__, ext->name, a); - cce = "HS: EXT: Rejects server options"; - goto bail2; - } - - wsi->count_act_ext++; - - ext++; - } - - if (n == 0) { - lwsl_warn("Unknown ext '%s'!\n", ext_name); - cce = "HS: EXT: unknown ext"; - goto bail2; - } - - a = NULL; - n = 0; - } - -check_accept: -#endif - - /* - * Confirm his accept token is the one we precomputed - */ - - p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); - if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) { - lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p, - wsi->u.hdr.ah->initial_handshake_hash_base64); - cce = "HS: Accept hash wrong"; - goto bail2; - } - - /* allocate the per-connection user memory (if any) */ - if (lws_ensure_user_space(wsi)) { - lwsl_err("Problem allocating wsi user mem\n"); - cce = "HS: OOM"; - goto bail2; - } - - /* - * we seem to be good to go, give client last chance to check - * headers and OK it - */ - if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, - wsi->user_space, NULL, 0)) { - cce = "HS: Rejected by filter cb"; - goto bail2; - } - - /* clear his proxy connection timeout */ - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - - /* free up his parsing allocations */ - lws_header_table_detach(wsi, 0); - - lws_union_transition(wsi, LWSCM_WS_CLIENT); - wsi->state = LWSS_ESTABLISHED; - lws_restart_ws_ping_pong_timer(wsi); - - wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; - - /* - * create the frame buffer for this connection according to the - * size mentioned in the protocol definition. If 0 there, then - * use a big default for compatibility - */ - n = wsi->protocol->rx_buffer_size; - if (!n) - n = context->pt_serv_buf_size; - n += LWS_PRE; - wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, "client frame buffer"); - if (!wsi->u.ws.rx_ubuf) { - lwsl_err("Out of Mem allocating rx buffer %d\n", n); - cce = "HS: OOM"; - goto bail2; - } - wsi->u.ws.rx_ubuf_alloc = n; - lwsl_info("Allocating client RX buffer %d\n", n); - -#if !defined(LWS_WITH_ESP32) - if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&n, - sizeof n)) { - lwsl_warn("Failed to set SNDBUF to %d", n); - cce = "HS: SO_SNDBUF failed"; - goto bail3; - } -#endif - - lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); - - /* call him back to inform him he is up */ - - if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, - wsi->user_space, NULL, 0)) { - cce = "HS: Rejected at CLIENT_ESTABLISHED"; - goto bail3; - } -#ifndef LWS_NO_EXTENSIONS - /* - * inform all extensions, not just active ones since they - * already know - */ - ext = wsi->vhost->extensions; - - while (ext && ext->callback) { - v = NULL; - for (n = 0; n < wsi->count_act_ext; n++) - if (wsi->active_extensions[n] == ext) - v = wsi->act_ext_user[n]; - - ext->callback(context, ext, wsi, - LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0); - ext++; - } -#endif - - return 0; - -bail3: - close_reason = LWS_CLOSE_STATUS_NOSTATUS; - -bail2: - if (wsi->protocol) - wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, - wsi->user_space, (void *)cce, - (unsigned int)strlen(cce)); - wsi->already_did_cce = 1; - - lwsl_info("closing connection due to bail2 connection error\n"); - - /* closing will free up his parsing allocations */ - lws_close_free_wsi(wsi, close_reason); - - return 1; -} - - -char * -lws_generate_client_handshake(struct lws *wsi, char *pkt) -{ - char buf[128], hash[20], key_b64[40], *p = pkt; - struct lws_context *context = wsi->context; - const char *meth; - int n; -#ifndef LWS_NO_EXTENSIONS - const struct lws_extension *ext; - int ext_count = 0; -#endif - const char *pp = lws_hdr_simple_ptr(wsi, - _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); - - meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD); - if (!meth) { - meth = "GET"; - wsi->do_ws = 1; - } else { - wsi->do_ws = 0; - } - - if (!strcmp(meth, "RAW")) { - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - lwsl_notice("client transition to raw\n"); - - if (pp) { - const struct lws_protocols *pr; - - pr = lws_vhost_name_to_protocol(wsi->vhost, pp); - - if (!pr) { - lwsl_err("protocol %s not enabled on vhost\n", - pp); - return NULL; - } - - lws_bind_protocol(wsi, pr); - } - - if ((wsi->protocol->callback)(wsi, - LWS_CALLBACK_RAW_ADOPT, - wsi->user_space, NULL, 0)) - return NULL; - - lws_header_table_force_to_detachable_state(wsi); - lws_union_transition(wsi, LWSCM_RAW); - lws_header_table_detach(wsi, 1); - - return NULL; - } - - if (wsi->do_ws) { - /* - * create the random key - */ - n = lws_get_random(context, hash, 16); - if (n != 16) { - lwsl_err("Unable to read from random dev %s\n", - SYSTEM_RANDOM_FILEPATH); - return NULL; - } - - lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64)); - } - - /* - * 04 example client handshake - * - * GET /chat HTTP/1.1 - * Host: server.example.com - * Upgrade: websocket - * Connection: Upgrade - * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== - * Sec-WebSocket-Origin: http://example.com - * Sec-WebSocket-Protocol: chat, superchat - * Sec-WebSocket-Version: 4 - */ - - p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth, - lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI)); - - p += sprintf(p, "Pragma: no-cache\x0d\x0a" - "Cache-Control: no-cache\x0d\x0a"); - - p += sprintf(p, "Host: %s\x0d\x0a", - lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST)); - - if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) { - if (lws_check_opt(context->options, LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN)) - p += sprintf(p, "Origin: %s\x0d\x0a", - lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)); - else - p += sprintf(p, "Origin: http://%s\x0d\x0a", - lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)); - } - - if (wsi->do_ws) { - p += sprintf(p, "Upgrade: websocket\x0d\x0a" - "Connection: Upgrade\x0d\x0a" - "Sec-WebSocket-Key: "); - strcpy(p, key_b64); - p += strlen(key_b64); - p += sprintf(p, "\x0d\x0a"); - if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS)) - p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a", - lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS)); - - /* tell the server what extensions we could support */ - -#ifndef LWS_NO_EXTENSIONS - ext = wsi->vhost->extensions; - while (ext && ext->callback) { - n = lws_ext_cb_all_exts(context, wsi, - LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION, - (char *)ext->name, 0); - if (n) { /* an extension vetos us */ - lwsl_ext("ext %s vetoed\n", (char *)ext->name); - ext++; - continue; - } - n = wsi->vhost->protocols[0].callback(wsi, - LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED, - wsi->user_space, (char *)ext->name, 0); - - /* - * zero return from callback means - * go ahead and allow the extension, - * it's what we get if the callback is - * unhandled - */ - - if (n) { - ext++; - continue; - } - - /* apply it */ - - if (ext_count) - *p++ = ','; - else - p += sprintf(p, "Sec-WebSocket-Extensions: "); - p += sprintf(p, "%s", ext->client_offer); - ext_count++; - - ext++; - } - if (ext_count) - p += sprintf(p, "\x0d\x0a"); -#endif - - if (wsi->ietf_spec_revision) - p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a", - wsi->ietf_spec_revision); - - /* prepare the expected server accept response */ - - key_b64[39] = '\0'; /* enforce composed length below buf sizeof */ - n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64); - - lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash); - - lws_b64_encode_string(hash, 20, - wsi->u.hdr.ah->initial_handshake_hash_base64, - sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64)); - } - - /* give userland a chance to append, eg, cookies */ - - if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER, - wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12)) - return NULL; - - p += sprintf(p, "\x0d\x0a"); - - return p; -} - diff --git a/thirdparty/lws/client/ssl-client.c b/thirdparty/lws/client/ssl-client.c deleted file mode 100644 index 962c6e3cb5..0000000000 --- a/thirdparty/lws/client/ssl-client.c +++ /dev/null @@ -1,625 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -extern int openssl_websocket_private_data_index, - openssl_SSL_CTX_private_data_index; - -extern void -lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info); - -extern int lws_ssl_get_error(struct lws *wsi, int n); - -#if defined(USE_WOLFSSL) -#else - -static int -OpenSSL_client_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) -{ -#if defined(LWS_WITH_MBEDTLS) - lwsl_notice("%s\n", __func__); - - return 0; -#else - SSL *ssl; - int n; - struct lws *wsi; - - /* keep old behaviour accepting self-signed server certs */ - if (!preverify_ok) { - int err = X509_STORE_CTX_get_error(x509_ctx); - - if (err != X509_V_OK) { - ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); - wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index); - - if ((err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || - err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && - wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED) { - lwsl_notice("accepting self-signed certificate (verify_callback)\n"); - X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); - return 1; // ok - } else if ((err == X509_V_ERR_CERT_NOT_YET_VALID || - err == X509_V_ERR_CERT_HAS_EXPIRED) && - wsi->use_ssl & LCCSCF_ALLOW_EXPIRED) { - if (err == X509_V_ERR_CERT_NOT_YET_VALID) - lwsl_notice("accepting not yet valid certificate (verify_callback)\n"); - else if (err == X509_V_ERR_CERT_HAS_EXPIRED) - lwsl_notice("accepting expired certificate (verify_callback)\n"); - X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); - return 1; // ok - } - } - } - - ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); - wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index); - - n = lws_get_context_protocol(wsi->context, 0).callback(wsi, - LWS_CALLBACK_OPENSSL_PERFORM_SERVER_CERT_VERIFICATION, - x509_ctx, ssl, preverify_ok); - - /* keep old behaviour if something wrong with server certs */ - /* if ssl error is overruled in callback and cert is ok, - * X509_STORE_CTX_set_error(x509_ctx, X509_V_OK); must be set and - * return value is 0 from callback */ - if (!preverify_ok) { - int err = X509_STORE_CTX_get_error(x509_ctx); - - if (err != X509_V_OK) { /* cert validation error was not handled in callback */ - int depth = X509_STORE_CTX_get_error_depth(x509_ctx); - const char* msg = X509_verify_cert_error_string(err); - lwsl_err("SSL error: %s (preverify_ok=%d;err=%d;depth=%d)\n", msg, preverify_ok, err, depth); - return preverify_ok; // not ok - } - } - /* convert callback return code from 0 = OK to verify callback return value 1 = OK */ - return !n; -#endif -} -#endif - -int -lws_ssl_client_bio_create(struct lws *wsi) -{ - char hostname[128], *p; - - if (lws_hdr_copy(wsi, hostname, sizeof(hostname), - _WSI_TOKEN_CLIENT_HOST) <= 0) { - lwsl_err("%s: Unable to get hostname\n", __func__); - - return -1; - } - - /* - * remove any :port part on the hostname... necessary for network - * connection but typical certificates do not contain it - */ - p = hostname; - while (*p) { - if (*p == ':') { - *p = '\0'; - break; - } - p++; - } - - wsi->ssl = SSL_new(wsi->vhost->ssl_client_ctx); - if (!wsi->ssl) { - lwsl_err("SSL_new failed: %s\n", - ERR_error_string(lws_ssl_get_error(wsi, 0), NULL)); - lws_ssl_elaborate_error(); - return -1; - } - -#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK) - if (wsi->vhost->ssl_info_event_mask) - SSL_set_info_callback(wsi->ssl, lws_ssl_info_callback); -#endif - -#if defined LWS_HAVE_X509_VERIFY_PARAM_set1_host - X509_VERIFY_PARAM *param; - (void)param; - - if (!(wsi->use_ssl & LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK)) { - param = SSL_get0_param(wsi->ssl); - /* Enable automatic hostname checks */ - X509_VERIFY_PARAM_set_hostflags(param, - X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - X509_VERIFY_PARAM_set1_host(param, hostname, 0); - } - -#endif - -#if !defined(USE_WOLFSSL) && !defined(LWS_WITH_MBEDTLS) -#ifndef USE_OLD_CYASSL - /* OpenSSL_client_verify_callback will be called @ SSL_connect() */ - SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback); -#endif -#endif - -#if !defined(USE_WOLFSSL) && !defined(LWS_WITH_MBEDTLS) - SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); -#endif - /* - * use server name indication (SNI), if supported, - * when establishing connection - */ -#ifdef USE_WOLFSSL -#ifdef USE_OLD_CYASSL -#ifdef CYASSL_SNI_HOST_NAME - CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME, hostname, strlen(hostname)); -#endif -#else -#ifdef WOLFSSL_SNI_HOST_NAME - wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME, hostname, strlen(hostname)); -#endif -#endif -#else -#if defined(LWS_WITH_MBEDTLS) - SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback); -#else -#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name(wsi->ssl, hostname); -#endif -#endif -#endif - -#ifdef USE_WOLFSSL - /* - * wolfSSL/CyaSSL does certificate verification differently - * from OpenSSL. - * If we should ignore the certificate, we need to set - * this before SSL_new and SSL_connect is called. - * Otherwise the connect will simply fail with error code -155 - */ -#ifdef USE_OLD_CYASSL - if (wsi->use_ssl == 2) - CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL); -#else - if (wsi->use_ssl == 2) - wolfSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL); -#endif -#endif /* USE_WOLFSSL */ - -#if !defined(LWS_WITH_MBEDTLS) - wsi->client_bio = BIO_new_socket(wsi->desc.sockfd, BIO_NOCLOSE); - SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio); -#else - SSL_set_fd(wsi->ssl, wsi->desc.sockfd); -#endif - -#ifdef USE_WOLFSSL -#ifdef USE_OLD_CYASSL - CyaSSL_set_using_nonblock(wsi->ssl, 1); -#else - wolfSSL_set_using_nonblock(wsi->ssl, 1); -#endif -#else -#if !defined(LWS_WITH_MBEDTLS) - BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */ -#endif -#endif - -#if !defined(LWS_WITH_MBEDTLS) - SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index, - wsi); -#endif - - return 0; -} - -#if defined(LWS_WITH_MBEDTLS) -int ERR_get_error(void) -{ - return 0; -} -#endif - -int -lws_ssl_client_connect1(struct lws *wsi) -{ - struct lws_context *context = wsi->context; - int n = 0; - - lws_latency_pre(context, wsi); - - n = SSL_connect(wsi->ssl); - - lws_latency(context, wsi, - "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0); - - if (n < 0) { - n = lws_ssl_get_error(wsi, n); - - if (n == SSL_ERROR_WANT_READ) - goto some_wait; - - if (n == SSL_ERROR_WANT_WRITE) { - /* - * wants us to retry connect due to - * state of the underlying ssl layer... - * but since it may be stalled on - * blocked write, no incoming data may - * arrive to trigger the retry. - * Force (possibly many times if the SSL - * state persists in returning the - * condition code, but other sockets - * are getting serviced inbetweentimes) - * us to get called back when writable. - */ - lwsl_info("%s: WANT_WRITE... retrying\n", __func__); - lws_callback_on_writable(wsi); -some_wait: - wsi->mode = LWSCM_WSCL_WAITING_SSL; - - return 0; /* no error */ - } - - { - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - char *p = (char *)&pt->serv_buf[0]; - char *sb = p; - - lwsl_err("ssl hs1 error, X509_V_ERR = %d: errno %d: %s\n", - n, errno, ERR_error_string(n, sb)); - lws_ssl_elaborate_error(); -#if defined(LWS_WITH_MBEDTLS) - if (n == SSL_ERROR_SYSCALL) - return -1; -#endif - } - - n = -1; - } - - if (n <= 0) { - /* - * retry if new data comes until we - * run into the connection timeout or win - */ - - unsigned long error = ERR_get_error(); - - if (error != SSL_ERROR_NONE) { - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - char *p = (char *)&pt->serv_buf[0]; - char *sb = p; - lwsl_err("SSL connect error %lu: %s\n", - error, ERR_error_string(error, sb)); - return -1; - } - - return 0; - } - - return 1; -} - -int -lws_ssl_client_connect2(struct lws *wsi) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - char *p = (char *)&pt->serv_buf[0]; - char *sb = p; - int n = 0; - - if (wsi->mode == LWSCM_WSCL_WAITING_SSL) { - lws_latency_pre(context, wsi); - n = SSL_connect(wsi->ssl); - lwsl_debug("%s: SSL_connect says %d\n", __func__, n); - - lws_latency(context, wsi, - "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0); - - if (n < 0) { - n = lws_ssl_get_error(wsi, n); - - if (n == SSL_ERROR_WANT_READ) { - lwsl_info("SSL_connect WANT_READ... retrying\n"); - - wsi->mode = LWSCM_WSCL_WAITING_SSL; - - return 0; /* no error */ - } - - if (n == SSL_ERROR_WANT_WRITE) { - /* - * wants us to retry connect due to - * state of the underlying ssl layer... - * but since it may be stalled on - * blocked write, no incoming data may - * arrive to trigger the retry. - * Force (possibly many times if the SSL - * state persists in returning the - * condition code, but other sockets - * are getting serviced inbetweentimes) - * us to get called back when writable. - */ - lwsl_info("SSL_connect WANT_WRITE... retrying\n"); - lws_callback_on_writable(wsi); - - wsi->mode = LWSCM_WSCL_WAITING_SSL; - - return 0; /* no error */ - } - - n = -1; - } - - if (n <= 0) { - /* - * retry if new data comes until we - * run into the connection timeout or win - */ - unsigned long error = ERR_get_error(); - if (error != SSL_ERROR_NONE) { - lwsl_err("SSL connect error %lu: %s\n", - error, ERR_error_string(error, sb)); - return -1; - } - } - } - -#if defined(LWS_WITH_MBEDTLS) - { - X509 *peer = SSL_get_peer_certificate(wsi->ssl); - - if (!peer) { - lwsl_notice("peer did not provide cert\n"); - - return -1; - } - lwsl_notice("peer provided cert\n"); - } -#endif - -#ifndef USE_WOLFSSL - /* - * See comment above about wolfSSL certificate - * verification - */ - lws_latency_pre(context, wsi); - n = SSL_get_verify_result(wsi->ssl); - lws_latency(context, wsi, - "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE", n, n > 0); - - lwsl_debug("get_verify says %d\n", n); - - if (n != X509_V_OK) { - if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || - n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && - (wsi->use_ssl & LCCSCF_ALLOW_SELFSIGNED)) { - lwsl_notice("accepting self-signed certificate\n"); - } else if ((n == X509_V_ERR_CERT_NOT_YET_VALID || - n == X509_V_ERR_CERT_HAS_EXPIRED) && - (wsi->use_ssl & LCCSCF_ALLOW_EXPIRED)) { - lwsl_notice("accepting expired certificate\n"); - } else if (n == X509_V_ERR_CERT_NOT_YET_VALID) { - lwsl_notice("Cert is from the future... " - "probably our clock... accepting...\n"); - } else { - lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n", - n, ERR_error_string(n, sb)); - lws_ssl_elaborate_error(); - return -1; - } - } - -#endif /* USE_WOLFSSL */ - - return 1; -} - - -int lws_context_init_client_ssl(struct lws_context_creation_info *info, - struct lws_vhost *vhost) -{ - SSL_METHOD *method = NULL; - struct lws wsi; - unsigned long error; - const char *ca_filepath = info->ssl_ca_filepath; -#if !defined(LWS_WITH_MBEDTLS) - const char *cipher_list = info->ssl_cipher_list; - const char *private_key_filepath = info->ssl_private_key_filepath; - const char *cert_filepath = info->ssl_cert_filepath; - int n; - - if (vhost->options & LWS_SERVER_OPTION_ONLY_RAW) - return 0; - - /* - * for backwards-compatibility default to using ssl_... members, but - * if the newer client-specific ones are given, use those - */ - if (info->client_ssl_cipher_list) - cipher_list = info->client_ssl_cipher_list; - if (info->client_ssl_cert_filepath) - cert_filepath = info->client_ssl_cert_filepath; - if (info->client_ssl_private_key_filepath) - private_key_filepath = info->client_ssl_private_key_filepath; -#endif - if (info->client_ssl_ca_filepath) - ca_filepath = info->client_ssl_ca_filepath; - - if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) - return 0; - - if (vhost->ssl_client_ctx) - return 0; - - if (info->provided_client_ssl_ctx) { - /* use the provided OpenSSL context if given one */ - vhost->ssl_client_ctx = info->provided_client_ssl_ctx; - /* nothing for lib to delete */ - vhost->user_supplied_ssl_ctx = 1; - - return 0; - } - - /* basic openssl init already happened in context init */ - - /* choose the most recent spin of the api */ -#if defined(LWS_HAVE_TLS_CLIENT_METHOD) - method = (SSL_METHOD *)TLS_client_method(); -#elif defined(LWS_HAVE_TLSV1_2_CLIENT_METHOD) - method = (SSL_METHOD *)TLSv1_2_client_method(); -#else - method = (SSL_METHOD *)SSLv23_client_method(); -#endif - if (!method) { - error = ERR_get_error(); - lwsl_err("problem creating ssl method %lu: %s\n", - error, ERR_error_string(error, - (char *)vhost->context->pt[0].serv_buf)); - return 1; - } - /* create context */ - vhost->ssl_client_ctx = SSL_CTX_new(method); - if (!vhost->ssl_client_ctx) { - error = ERR_get_error(); - lwsl_err("problem creating ssl context %lu: %s\n", - error, ERR_error_string(error, - (char *)vhost->context->pt[0].serv_buf)); - return 1; - } - - lwsl_notice("created client ssl context for %s\n", vhost->name); - -#ifdef SSL_OP_NO_COMPRESSION - SSL_CTX_set_options(vhost->ssl_client_ctx, SSL_OP_NO_COMPRESSION); -#endif - -#if defined(LWS_WITH_MBEDTLS) - if (ca_filepath) { - lws_filepos_t len; - uint8_t *buf; - /* - * prototype this here, the shim does not export it in the - * header, and we need to use the shim unchanged for ESP32 case - */ - X509 *d2i_X509(X509 **cert, const unsigned char *buffer, long len); - - if (alloc_file(vhost->context, ca_filepath, &buf, &len)) { - lwsl_err("Load CA cert file %s failed\n", ca_filepath); - return 1; - } - - vhost->x509_client_CA = d2i_X509(NULL, buf, len); - free(buf); - if (!vhost->x509_client_CA) { - lwsl_err("client CA: x509 parse failed\n"); - return 1; - } - - SSL_CTX_add_client_CA(vhost->ssl_client_ctx, - vhost->x509_client_CA); - - lwsl_notice("client loaded CA for verification %s\n", ca_filepath); - } -#else - SSL_CTX_set_options(vhost->ssl_client_ctx, - SSL_OP_CIPHER_SERVER_PREFERENCE); - - if (cipher_list) - SSL_CTX_set_cipher_list(vhost->ssl_client_ctx, cipher_list); - -#ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS - if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS)) - /* loads OS default CA certs */ - SSL_CTX_set_default_verify_paths(vhost->ssl_client_ctx); -#endif - - /* openssl init for cert verification (for client sockets) */ - if (!ca_filepath) { - if (!SSL_CTX_load_verify_locations( - vhost->ssl_client_ctx, NULL, LWS_OPENSSL_CLIENT_CERTS)) - lwsl_err("Unable to load SSL Client certs from %s " - "(set by LWS_OPENSSL_CLIENT_CERTS) -- " - "client ssl isn't going to work\n", - LWS_OPENSSL_CLIENT_CERTS); - } else - if (!SSL_CTX_load_verify_locations( - vhost->ssl_client_ctx, ca_filepath, NULL)) { - lwsl_err( - "Unable to load SSL Client certs " - "file from %s -- client ssl isn't " - "going to work\n", info->client_ssl_ca_filepath); - lws_ssl_elaborate_error(); - } - else - lwsl_info("loaded ssl_ca_filepath\n"); - - /* - * callback allowing user code to load extra verification certs - * helping the client to verify server identity - */ - - /* support for client-side certificate authentication */ - if (cert_filepath) { - lwsl_notice("%s: doing cert filepath\n", __func__); - n = SSL_CTX_use_certificate_chain_file(vhost->ssl_client_ctx, - cert_filepath); - if (n < 1) { - lwsl_err("problem %d getting cert '%s'\n", n, - cert_filepath); - lws_ssl_elaborate_error(); - return 1; - } - lwsl_notice("Loaded client cert %s\n", cert_filepath); - } - if (private_key_filepath) { - lwsl_notice("%s: doing private key filepath\n", __func__); - lws_ssl_bind_passphrase(vhost->ssl_client_ctx, info); - /* set the private key from KeyFile */ - if (SSL_CTX_use_PrivateKey_file(vhost->ssl_client_ctx, - private_key_filepath, SSL_FILETYPE_PEM) != 1) { - lwsl_err("use_PrivateKey_file '%s'\n", - private_key_filepath); - lws_ssl_elaborate_error(); - return 1; - } - lwsl_notice("Loaded client cert private key %s\n", - private_key_filepath); - - /* verify private key */ - if (!SSL_CTX_check_private_key(vhost->ssl_client_ctx)) { - lwsl_err("Private SSL key doesn't match cert\n"); - return 1; - } - } -#endif - /* - * give him a fake wsi with context set, so he can use - * lws_get_context() in the callback - */ - memset(&wsi, 0, sizeof(wsi)); - wsi.vhost = vhost; - wsi.context = vhost->context; - - vhost->protocols[0].callback(&wsi, - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS, - vhost->ssl_client_ctx, NULL, 0); - - return 0; -} diff --git a/thirdparty/lws/ext/extension-permessage-deflate.c b/thirdparty/lws/ext/extension-permessage-deflate.c deleted file mode 100644 index e2be2ae615..0000000000 --- a/thirdparty/lws/ext/extension-permessage-deflate.c +++ /dev/null @@ -1,473 +0,0 @@ -/* - * ./lib/extension-permessage-deflate.c - * - * Copyright (C) 2016 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" -#include "extension-permessage-deflate.h" -#include <stdio.h> -#include <string.h> -#include <assert.h> - -#define LWS_ZLIB_MEMLEVEL 8 - -const struct lws_ext_options lws_ext_pm_deflate_options[] = { - /* public RFC7692 settings */ - { "server_no_context_takeover", EXTARG_NONE }, - { "client_no_context_takeover", EXTARG_NONE }, - { "server_max_window_bits", EXTARG_OPT_DEC }, - { "client_max_window_bits", EXTARG_OPT_DEC }, - /* ones only user code can set */ - { "rx_buf_size", EXTARG_DEC }, - { "tx_buf_size", EXTARG_DEC }, - { "compression_level", EXTARG_DEC }, - { "mem_level", EXTARG_DEC }, - { NULL, 0 }, /* sentinel */ -}; - -static void -lws_extension_pmdeflate_restrict_args(struct lws *wsi, - struct lws_ext_pm_deflate_priv *priv) -{ - int n, extra; - - /* cap the RX buf at the nearest power of 2 to protocol rx buf */ - - n = wsi->context->pt_serv_buf_size; - if (wsi->protocol->rx_buffer_size) - n = wsi->protocol->rx_buffer_size; - - extra = 7; - while (n >= 1 << (extra + 1)) - extra++; - - if (extra < priv->args[PMD_RX_BUF_PWR2]) { - priv->args[PMD_RX_BUF_PWR2] = extra; - lwsl_info(" Capping pmd rx to %d\n", 1 << extra); - } -} - -LWS_VISIBLE int -lws_extension_callback_pm_deflate(struct lws_context *context, - const struct lws_extension *ext, - struct lws *wsi, - enum lws_extension_callback_reasons reason, - void *user, void *in, size_t len) -{ - struct lws_ext_pm_deflate_priv *priv = - (struct lws_ext_pm_deflate_priv *)user; - struct lws_tokens *eff_buf = (struct lws_tokens *)in; - static unsigned char trail[] = { 0, 0, 0xff, 0xff }; - int n, ret = 0, was_fin = 0, extra; - struct lws_ext_option_arg *oa; - - switch (reason) { - case LWS_EXT_CB_NAMED_OPTION_SET: - oa = in; - if (!oa->option_name) - break; - for (n = 0; n < ARRAY_SIZE(lws_ext_pm_deflate_options); n++) - if (!strcmp(lws_ext_pm_deflate_options[n].name, oa->option_name)) - break; - - if (n == ARRAY_SIZE(lws_ext_pm_deflate_options)) - break; - oa->option_index = n; - - /* fallthru */ - - case LWS_EXT_CB_OPTION_SET: - oa = in; - lwsl_notice("%s: option set: idx %d, %s, len %d\n", __func__, - oa->option_index, oa->start, oa->len); - if (oa->start) - priv->args[oa->option_index] = atoi(oa->start); - else - priv->args[oa->option_index] = 1; - - if (priv->args[PMD_CLIENT_MAX_WINDOW_BITS] == 8) - priv->args[PMD_CLIENT_MAX_WINDOW_BITS] = 9; - - lws_extension_pmdeflate_restrict_args(wsi, priv); - break; - - case LWS_EXT_CB_OPTION_CONFIRM: - if (priv->args[PMD_SERVER_MAX_WINDOW_BITS] < 8 || - priv->args[PMD_SERVER_MAX_WINDOW_BITS] > 15 || - priv->args[PMD_CLIENT_MAX_WINDOW_BITS] < 8 || - priv->args[PMD_CLIENT_MAX_WINDOW_BITS] > 15) - return -1; - break; - - case LWS_EXT_CB_CLIENT_CONSTRUCT: - case LWS_EXT_CB_CONSTRUCT: - - n = context->pt_serv_buf_size; - if (wsi->protocol->rx_buffer_size) - n = wsi->protocol->rx_buffer_size; - - if (n < 128) { - lwsl_info(" permessage-deflate requires the protocol (%s) to have an RX buffer >= 128\n", - wsi->protocol->name); - return -1; - } - - /* fill in **user */ - priv = lws_zalloc(sizeof(*priv), "pmd priv"); - *((void **)user) = priv; - lwsl_ext("%s: LWS_EXT_CB_*CONSTRUCT\n", __func__); - memset(priv, 0, sizeof(*priv)); - - /* fill in pointer to options list */ - if (in) - *((const struct lws_ext_options **)in) = - lws_ext_pm_deflate_options; - - /* fallthru */ - - case LWS_EXT_CB_OPTION_DEFAULT: - - /* set the public, RFC7692 defaults... */ - - priv->args[PMD_SERVER_NO_CONTEXT_TAKEOVER] = 0, - priv->args[PMD_CLIENT_NO_CONTEXT_TAKEOVER] = 0; - priv->args[PMD_SERVER_MAX_WINDOW_BITS] = 15; - priv->args[PMD_CLIENT_MAX_WINDOW_BITS] = 15; - - /* ...and the ones the user code can override */ - - priv->args[PMD_RX_BUF_PWR2] = 10; /* ie, 1024 */ - priv->args[PMD_TX_BUF_PWR2] = 10; /* ie, 1024 */ - priv->args[PMD_COMP_LEVEL] = 1; - priv->args[PMD_MEM_LEVEL] = 8; - - lws_extension_pmdeflate_restrict_args(wsi, priv); - break; - - case LWS_EXT_CB_DESTROY: - lwsl_ext("%s: LWS_EXT_CB_DESTROY\n", __func__); - lws_free(priv->buf_rx_inflated); - lws_free(priv->buf_tx_deflated); - if (priv->rx_init) - (void)inflateEnd(&priv->rx); - if (priv->tx_init) - (void)deflateEnd(&priv->tx); - lws_free(priv); - return ret; - - case LWS_EXT_CB_PAYLOAD_RX: - lwsl_ext(" %s: LWS_EXT_CB_PAYLOAD_RX: in %d, existing in %d\n", - __func__, eff_buf->token_len, priv->rx.avail_in); - if (!(wsi->u.ws.rsv_first_msg & 0x40)) - return 0; - -#if 0 - for (n = 0; n < eff_buf->token_len; n++) { - printf("%02X ", (unsigned char)eff_buf->token[n]); - if ((n & 15) == 15) - printf("\n"); - } - printf("\n"); -#endif - if (!priv->rx_init) - if (inflateInit2(&priv->rx, -priv->args[PMD_SERVER_MAX_WINDOW_BITS]) != Z_OK) { - lwsl_err("%s: iniflateInit failed\n", __func__); - return -1; - } - priv->rx_init = 1; - if (!priv->buf_rx_inflated) - priv->buf_rx_inflated = lws_malloc(LWS_PRE + 7 + 5 + - (1 << priv->args[PMD_RX_BUF_PWR2]), "pmd rx inflate buf"); - if (!priv->buf_rx_inflated) { - lwsl_err("%s: OOM\n", __func__); - return -1; - } - - /* - * We have to leave the input stream alone if we didn't - * finish with it yet. The input stream is held in the wsi - * rx buffer by the caller, so this assumption is safe while - * we block new rx while draining the existing rx - */ - if (!priv->rx.avail_in && eff_buf->token && eff_buf->token_len) { - priv->rx.next_in = (unsigned char *)eff_buf->token; - priv->rx.avail_in = eff_buf->token_len; - } - priv->rx.next_out = priv->buf_rx_inflated + LWS_PRE; - eff_buf->token = (char *)priv->rx.next_out; - priv->rx.avail_out = 1 << priv->args[PMD_RX_BUF_PWR2]; - - if (priv->rx_held_valid) { - lwsl_ext("-- RX piling on held byte --\n"); - *(priv->rx.next_out++) = priv->rx_held; - priv->rx.avail_out--; - priv->rx_held_valid = 0; - } - - /* if... - * - * - he has no remaining input content for this message, and - * - and this is the final fragment, and - * - we used everything that could be drained on the input side - * - * ...then put back the 00 00 FF FF the sender stripped as our - * input to zlib - */ - if (!priv->rx.avail_in && wsi->u.ws.final && - !wsi->u.ws.rx_packet_length) { - lwsl_ext("RX APPEND_TRAILER-DO\n"); - was_fin = 1; - priv->rx.next_in = trail; - priv->rx.avail_in = sizeof(trail); - } - - n = inflate(&priv->rx, Z_NO_FLUSH); - lwsl_ext("inflate ret %d, avi %d, avo %d, wsifinal %d\n", n, - priv->rx.avail_in, priv->rx.avail_out, wsi->u.ws.final); - switch (n) { - case Z_NEED_DICT: - case Z_STREAM_ERROR: - case Z_DATA_ERROR: - case Z_MEM_ERROR: - lwsl_info("zlib error inflate %d: %s\n", - n, priv->rx.msg); - return -1; - } - /* - * If we did not already send in the 00 00 FF FF, and he's - * out of input, he did not EXACTLY fill the output buffer - * (which is ambiguous and we will force it to go around - * again by withholding a byte), and he's otherwise working on - * being a FIN fragment, then do the FIN message processing - * of faking up the 00 00 FF FF that the sender stripped. - */ - if (!priv->rx.avail_in && wsi->u.ws.final && - !wsi->u.ws.rx_packet_length && !was_fin && - priv->rx.avail_out /* ambiguous as to if it is the end */ - ) { - lwsl_ext("RX APPEND_TRAILER-DO\n"); - was_fin = 1; - priv->rx.next_in = trail; - priv->rx.avail_in = sizeof(trail); - n = inflate(&priv->rx, Z_SYNC_FLUSH); - lwsl_ext("RX trailer inf returned %d, avi %d, avo %d\n", n, - priv->rx.avail_in, priv->rx.avail_out); - switch (n) { - case Z_NEED_DICT: - case Z_STREAM_ERROR: - case Z_DATA_ERROR: - case Z_MEM_ERROR: - lwsl_info("zlib error inflate %d: %s\n", - n, priv->rx.msg); - return -1; - } - } - /* - * we must announce in our returncode now if there is more - * output to be expected from inflate, so we can decide to - * set the FIN bit on this bufferload or not. However zlib - * is ambiguous when we exactly filled the inflate buffer. It - * does not give us a clue as to whether we should understand - * that to mean he ended on a buffer boundary, or if there is - * more in the pipeline. - * - * So to work around that safely, if it used all output space - * exactly, we ALWAYS say there is more coming and we withhold - * the last byte of the buffer to guarantee that is true. - * - * That still leaves us at least one byte to finish with a FIN - * on, even if actually nothing more is coming from the next - * inflate action itself. - */ - if (!priv->rx.avail_out) { /* he used all available out buf */ - lwsl_ext("-- rx grabbing held --\n"); - /* snip the last byte and hold it for next time */ - priv->rx_held = *(--priv->rx.next_out); - priv->rx_held_valid = 1; - } - - eff_buf->token_len = (char *)priv->rx.next_out - eff_buf->token; - priv->count_rx_between_fin += eff_buf->token_len; - - lwsl_ext(" %s: RX leaving with new effbuff len %d, " - "ret %d, rx.avail_in=%d, TOTAL RX since FIN %lu\n", - __func__, eff_buf->token_len, priv->rx_held_valid, - priv->rx.avail_in, - (unsigned long)priv->count_rx_between_fin); - - if (was_fin) { - priv->count_rx_between_fin = 0; - if (priv->args[PMD_SERVER_NO_CONTEXT_TAKEOVER]) { - (void)inflateEnd(&priv->rx); - priv->rx_init = 0; - } - } -#if 0 - for (n = 0; n < eff_buf->token_len; n++) - putchar(eff_buf->token[n]); - puts("\n"); -#endif - - return priv->rx_held_valid; - - case LWS_EXT_CB_PAYLOAD_TX: - - if (!priv->tx_init) { - n = deflateInit2(&priv->tx, priv->args[PMD_COMP_LEVEL], - Z_DEFLATED, - -priv->args[PMD_SERVER_MAX_WINDOW_BITS + - (wsi->vhost->listen_port <= 0)], - priv->args[PMD_MEM_LEVEL], - Z_DEFAULT_STRATEGY); - if (n != Z_OK) { - lwsl_ext("inflateInit2 failed %d\n", n); - return 1; - } - } - priv->tx_init = 1; - if (!priv->buf_tx_deflated) - priv->buf_tx_deflated = lws_malloc(LWS_PRE + 7 + 5 + - (1 << priv->args[PMD_TX_BUF_PWR2]), "pmd tx deflate buf"); - if (!priv->buf_tx_deflated) { - lwsl_err("%s: OOM\n", __func__); - return -1; - } - - if (eff_buf->token) { - lwsl_ext("%s: TX: eff_buf length %d\n", __func__, - eff_buf->token_len); - priv->tx.next_in = (unsigned char *)eff_buf->token; - priv->tx.avail_in = eff_buf->token_len; - } - -#if 0 - for (n = 0; n < eff_buf->token_len; n++) { - printf("%02X ", (unsigned char)eff_buf->token[n]); - if ((n & 15) == 15) - printf("\n"); - } - printf("\n"); -#endif - - priv->tx.next_out = priv->buf_tx_deflated + LWS_PRE + 5; - eff_buf->token = (char *)priv->tx.next_out; - priv->tx.avail_out = 1 << priv->args[PMD_TX_BUF_PWR2]; - - n = deflate(&priv->tx, Z_SYNC_FLUSH); - if (n == Z_STREAM_ERROR) { - lwsl_ext("%s: Z_STREAM_ERROR\n", __func__); - return -1; - } - - if (priv->tx_held_valid) { - priv->tx_held_valid = 0; - if (priv->tx.avail_out == 1 << priv->args[PMD_TX_BUF_PWR2]) - /* - * we can get a situation he took something in - * but did not generate anything out, at the end - * of a message (eg, next thing he sends is 80 - * 00, a zero length FIN, like Authobahn can - * send). - * If we have come back as a FIN, we must not - * place the pending trailer 00 00 FF FF, just - * the 1 byte of live data - */ - *(--eff_buf->token) = priv->tx_held[0]; - else { - /* he generated data, prepend whole pending */ - eff_buf->token -= 5; - for (n = 0; n < 5; n++) - eff_buf->token[n] = priv->tx_held[n]; - - } - } - priv->compressed_out = 1; - eff_buf->token_len = (int)(priv->tx.next_out - - (unsigned char *)eff_buf->token); - - /* - * we must announce in our returncode now if there is more - * output to be expected from inflate, so we can decide to - * set the FIN bit on this bufferload or not. However zlib - * is ambiguous when we exactly filled the inflate buffer. It - * does not give us a clue as to whether we should understand - * that to mean he ended on a buffer boundary, or if there is - * more in the pipeline. - * - * Worse, the guy providing the stuff we are sending may not - * know until after that this was, actually, the last chunk, - * that can happen even if we did not fill the output buf, ie - * he may send after this a zero-length FIN fragment. - * - * This is super difficult because we must snip the last 4 - * bytes in the case this is the last compressed output of the - * message. The only way to deal with it is defer sending the - * last 5 bytes of each frame until the next one, when we will - * be in a position to understand if that has a FIN or not. - */ - - extra = !!(len & LWS_WRITE_NO_FIN) || !priv->tx.avail_out; - - if (eff_buf->token_len >= 4 + extra) { - lwsl_ext("tx held %d\n", 4 + extra); - priv->tx_held_valid = extra; - for (n = 3 + extra; n >= 0; n--) - priv->tx_held[n] = *(--priv->tx.next_out); - eff_buf->token_len -= 4 + extra; - } - lwsl_ext(" TX rewritten with new effbuff len %d, ret %d\n", - eff_buf->token_len, !priv->tx.avail_out); - - return !priv->tx.avail_out; /* 1 == have more tx pending */ - - case LWS_EXT_CB_PACKET_TX_PRESEND: - if (!priv->compressed_out) - break; - priv->compressed_out = 0; - - if ((*(eff_buf->token) & 0x80) && - priv->args[PMD_CLIENT_NO_CONTEXT_TAKEOVER]) { - lwsl_debug("PMD_CLIENT_NO_CONTEXT_TAKEOVER\n"); - (void)deflateEnd(&priv->tx); - priv->tx_init = 0; - } - - n = *(eff_buf->token) & 15; - /* set RSV1, but not on CONTINUATION */ - if (n == LWSWSOPC_TEXT_FRAME || n == LWSWSOPC_BINARY_FRAME) - *eff_buf->token |= 0x40; -#if 0 - for (n = 0; n < eff_buf->token_len; n++) { - printf("%02X ", (unsigned char)eff_buf->token[n]); - if ((n & 15) == 15) - puts("\n"); - } - puts("\n"); -#endif - lwsl_ext("%s: tx opcode 0x%02X\n", __func__, - (unsigned char)*eff_buf->token); - break; - - default: - break; - } - - return 0; -} - diff --git a/thirdparty/lws/ext/extension-permessage-deflate.h b/thirdparty/lws/ext/extension-permessage-deflate.h deleted file mode 100644 index 8737736897..0000000000 --- a/thirdparty/lws/ext/extension-permessage-deflate.h +++ /dev/null @@ -1,41 +0,0 @@ - -#include <zlib.h> - -#define DEFLATE_FRAME_COMPRESSION_LEVEL_SERVER 1 -#define DEFLATE_FRAME_COMPRESSION_LEVEL_CLIENT Z_DEFAULT_COMPRESSION - -enum arg_indexes { - PMD_SERVER_NO_CONTEXT_TAKEOVER, - PMD_CLIENT_NO_CONTEXT_TAKEOVER, - PMD_SERVER_MAX_WINDOW_BITS, - PMD_CLIENT_MAX_WINDOW_BITS, - PMD_RX_BUF_PWR2, - PMD_TX_BUF_PWR2, - PMD_COMP_LEVEL, - PMD_MEM_LEVEL, - - PMD_ARG_COUNT -}; - -struct lws_ext_pm_deflate_priv { - z_stream rx; - z_stream tx; - - unsigned char *buf_rx_inflated; /* RX inflated output buffer */ - unsigned char *buf_tx_deflated; /* TX deflated output buffer */ - - size_t count_rx_between_fin; - - unsigned char args[PMD_ARG_COUNT]; - unsigned char tx_held[5]; - unsigned char rx_held; - - unsigned char tx_init:1; - unsigned char rx_init:1; - unsigned char compressed_out:1; - unsigned char rx_held_valid:1; - unsigned char tx_held_valid:1; - unsigned char rx_append_trailer:1; - unsigned char pending_tx_trailer:1; -}; - diff --git a/thirdparty/lws/ext/extension.c b/thirdparty/lws/ext/extension.c deleted file mode 100644 index ac28204034..0000000000 --- a/thirdparty/lws/ext/extension.c +++ /dev/null @@ -1,344 +0,0 @@ -#include "private-libwebsockets.h" - -#include "extension-permessage-deflate.h" - -LWS_VISIBLE void -lws_context_init_extensions(struct lws_context_creation_info *info, - struct lws_context *context) -{ - lwsl_info(" LWS_MAX_EXTENSIONS_ACTIVE: %u\n", LWS_MAX_EXTENSIONS_ACTIVE); -} - -enum lws_ext_option_parser_states { - LEAPS_SEEK_NAME, - LEAPS_EAT_NAME, - LEAPS_SEEK_VAL, - LEAPS_EAT_DEC, - LEAPS_SEEK_ARG_TERM -}; - -LWS_VISIBLE int -lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi, - void *ext_user, const struct lws_ext_options *opts, - const char *in, int len) -{ - enum lws_ext_option_parser_states leap = LEAPS_SEEK_NAME; - unsigned int match_map = 0, n, m, w = 0, count_options = 0, - pending_close_quote = 0; - struct lws_ext_option_arg oa; - - oa.option_name = NULL; - - while (opts[count_options].name) - count_options++; - while (len) { - lwsl_ext("'%c' %d", *in, leap); - switch (leap) { - case LEAPS_SEEK_NAME: - if (*in == ' ') - break; - if (*in == ',') { - len = 1; - break; - } - match_map = (1 << count_options) - 1; - leap = LEAPS_EAT_NAME; - w = 0; - - /* fallthru */ - - case LEAPS_EAT_NAME: - oa.start = NULL; - oa.len = 0; - m = match_map; - n = 0; - pending_close_quote = 0; - while (m) { - if (m & 1) { - lwsl_ext(" m=%d, n=%d, w=%d\n", m, n, w); - - if (*in == opts[n].name[w]) { - if (!opts[n].name[w + 1]) { - oa.option_index = n; - lwsl_ext("hit %d\n", oa.option_index); - leap = LEAPS_SEEK_VAL; - if (len == 1) - goto set_arg; - break; - } - } else { - match_map &= ~(1 << n); - if (!match_map) { - lwsl_ext("empty match map\n"); - return -1; - } - } - } - m >>= 1; - n++; - } - w++; - break; - case LEAPS_SEEK_VAL: - if (*in == ' ') - break; - if (*in == ',') { - len = 1; - break; - } - if (*in == ';' || len == 1) { /* ie,nonoptional */ - if (opts[oa.option_index].type == EXTARG_DEC) - return -1; - leap = LEAPS_SEEK_NAME; - goto set_arg; - } - if (*in == '=') { - w = 0; - pending_close_quote = 0; - if (opts[oa.option_index].type == EXTARG_NONE) - return -1; - - leap = LEAPS_EAT_DEC; - break; - } - return -1; - - case LEAPS_EAT_DEC: - if (*in >= '0' && *in <= '9') { - if (!w) - oa.start = in; - w++; - if (len != 1) - break; - } - if (!w && *in =='"') { - pending_close_quote = 1; - break; - } - if (!w) - return -1; - if (pending_close_quote && *in != '"' && len != 1) - return -1; - leap = LEAPS_SEEK_ARG_TERM; - if (oa.start) - oa.len = in - oa.start; - if (len == 1) - oa.len++; - -set_arg: - ext->callback(lws_get_context(wsi), - ext, wsi, LWS_EXT_CB_OPTION_SET, - ext_user, (char *)&oa, 0); - if (len == 1) - break; - if (pending_close_quote && *in == '"') - break; - - /* fallthru */ - - case LEAPS_SEEK_ARG_TERM: - if (*in == ' ') - break; - if (*in == ';') { - leap = LEAPS_SEEK_NAME; - break; - } - if (*in == ',') { - len = 1; - break; - } - return -1; - } - len--; - in++; - } - - return 0; -} - - -/* 0 = nobody had nonzero return, 1 = somebody had positive return, -1 = fail */ - -int lws_ext_cb_active(struct lws *wsi, int reason, void *arg, int len) -{ - int n, m, handled = 0; - - for (n = 0; n < wsi->count_act_ext; n++) { - m = wsi->active_extensions[n]->callback(lws_get_context(wsi), - wsi->active_extensions[n], wsi, reason, - wsi->act_ext_user[n], arg, len); - if (m < 0) { - lwsl_ext("Ext '%s' failed to handle callback %d!\n", - wsi->active_extensions[n]->name, reason); - return -1; - } - /* valgrind... */ - if (reason == LWS_EXT_CB_DESTROY) - wsi->act_ext_user[n] = NULL; - if (m > handled) - handled = m; - } - - return handled; -} - -int lws_ext_cb_all_exts(struct lws_context *context, struct lws *wsi, - int reason, void *arg, int len) -{ - int n = 0, m, handled = 0; - const struct lws_extension *ext; - - if (!wsi || !wsi->vhost) - return 0; - - ext = wsi->vhost->extensions; - - while (ext && ext->callback && !handled) { - m = ext->callback(context, ext, wsi, reason, - (void *)(lws_intptr_t)n, arg, len); - if (m < 0) { - lwsl_ext("Ext '%s' failed to handle callback %d!\n", - wsi->active_extensions[n]->name, reason); - return -1; - } - if (m) - handled = 1; - - ext++; - n++; - } - - return 0; -} - -int -lws_issue_raw_ext_access(struct lws *wsi, unsigned char *buf, size_t len) -{ - struct lws_tokens eff_buf; - int ret, m, n = 0; - - eff_buf.token = (char *)buf; - eff_buf.token_len = len; - - /* - * while we have original buf to spill ourselves, or extensions report - * more in their pipeline - */ - - ret = 1; - while (ret == 1) { - - /* default to nobody has more to spill */ - - ret = 0; - - /* show every extension the new incoming data */ - m = lws_ext_cb_active(wsi, - LWS_EXT_CB_PACKET_TX_PRESEND, &eff_buf, 0); - if (m < 0) - return -1; - if (m) /* handled */ - ret = 1; - - if ((char *)buf != eff_buf.token) - /* - * extension recreated it: - * need to buffer this if not all sent - */ - wsi->u.ws.clean_buffer = 0; - - /* assuming they left us something to send, send it */ - - if (eff_buf.token_len) { - n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, - eff_buf.token_len); - if (n < 0) { - lwsl_info("closing from ext access\n"); - return -1; - } - - /* always either sent it all or privately buffered */ - if (wsi->u.ws.clean_buffer) - len = n; - } - - lwsl_parser("written %d bytes to client\n", n); - - /* no extension has more to spill? Then we can go */ - - if (!ret) - break; - - /* we used up what we had */ - - eff_buf.token = NULL; - eff_buf.token_len = 0; - - /* - * Did that leave the pipe choked? - * Or we had to hold on to some of it? - */ - - if (!lws_send_pipe_choked(wsi) && !wsi->trunc_len) - /* no we could add more, lets's do that */ - continue; - - lwsl_debug("choked\n"); - - /* - * Yes, he's choked. Don't spill the rest now get a callback - * when he is ready to send and take care of it there - */ - lws_callback_on_writable(wsi); - wsi->extension_data_pending = 1; - ret = 0; - } - - return len; -} - -int -lws_any_extension_handled(struct lws *wsi, enum lws_extension_callback_reasons r, - void *v, size_t len) -{ - struct lws_context *context = wsi->context; - int n, handled = 0; - - /* maybe an extension will take care of it for us */ - - for (n = 0; n < wsi->count_act_ext && !handled; n++) { - if (!wsi->active_extensions[n]->callback) - continue; - - handled |= wsi->active_extensions[n]->callback(context, - wsi->active_extensions[n], wsi, - r, wsi->act_ext_user[n], v, len); - } - - return handled; -} - -int -lws_set_extension_option(struct lws *wsi, const char *ext_name, - const char *opt_name, const char *opt_val) -{ - struct lws_ext_option_arg oa; - int idx = 0; - - /* first identify if the ext is active on this wsi */ - while (idx < wsi->count_act_ext && - strcmp(wsi->active_extensions[idx]->name, ext_name)) - idx++; - - if (idx == wsi->count_act_ext) - return -1; /* request ext not active on this wsi */ - - oa.option_name = opt_name; - oa.option_index = 0; - oa.start = opt_val; - oa.len = 0; - - return wsi->active_extensions[idx]->callback( - wsi->context, wsi->active_extensions[idx], wsi, - LWS_EXT_CB_NAMED_OPTION_SET, wsi->act_ext_user[idx], &oa, 0); -} diff --git a/thirdparty/lws/handshake.c b/thirdparty/lws/handshake.c deleted file mode 100644 index bc7609d920..0000000000 --- a/thirdparty/lws/handshake.c +++ /dev/null @@ -1,280 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -/* - * -04 of the protocol (actually the 80th version) has a radically different - * handshake. The 04 spec gives the following idea - * - * The handshake from the client looks as follows: - * - * GET /chat HTTP/1.1 - * Host: server.example.com - * Upgrade: websocket - * Connection: Upgrade - * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== - * Sec-WebSocket-Origin: http://example.com - * Sec-WebSocket-Protocol: chat, superchat - * Sec-WebSocket-Version: 4 - * - * The handshake from the server looks as follows: - * - * HTTP/1.1 101 Switching Protocols - * Upgrade: websocket - * Connection: Upgrade - * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo= - * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC== - * Sec-WebSocket-Protocol: chat - */ - -#ifndef min -#define min(a, b) ((a) < (b) ? (a) : (b)) -#endif - -/* - * We have to take care about parsing because the headers may be split - * into multiple fragments. They may contain unknown headers with arbitrary - * argument lengths. So, we parse using a single-character at a time state - * machine that is completely independent of packet size. - * - * Returns <0 for error or length of chars consumed from buf (up to len) - */ - -LWS_VISIBLE int -lws_read(struct lws *wsi, unsigned char *buf, lws_filepos_t len) -{ - unsigned char *last_char, *oldbuf = buf; - lws_filepos_t body_chunk_len; - size_t n; - - switch (wsi->state) { -#ifdef LWS_WITH_HTTP2 - case LWSS_HTTP2_AWAIT_CLIENT_PREFACE: - case LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS: - case LWSS_HTTP2_ESTABLISHED: - n = 0; - //lwsl_debug("%s: starting new block of %d\n", __func__, (int)len); - /* - * wsi here is always the network connection wsi, not a stream - * wsi. - */ - while (n < len) { - /* - * we were accepting input but now we stopped doing so - */ - if (lws_is_flowcontrolled(wsi)) { - lws_rxflow_cache(wsi, buf, n, len); - - return 1; - } - - /* account for what we're using in rxflow buffer */ - if (wsi->rxflow_buffer) { - wsi->rxflow_pos++; - assert(wsi->rxflow_pos <= wsi->rxflow_len); - } - - if (lws_h2_parser(wsi, buf[n++])) { - lwsl_debug("%s: http2_parser bailed\n", __func__); - goto bail; - } - } - lwsl_debug("%s: used up block of %d\n", __func__, (int)len); - break; -#endif - - case LWSS_HTTP_ISSUING_FILE: - return 0; - - case LWSS_CLIENT_HTTP_ESTABLISHED: - break; - - case LWSS_HTTP: - wsi->hdr_parsing_completed = 0; - - /* fallthru */ - - case LWSS_HTTP_HEADERS: - if (!wsi->u.hdr.ah) { - lwsl_err("%s: LWSS_HTTP_HEADERS: NULL ah\n", __func__); - assert(0); - } - lwsl_parser("issuing %d bytes to parser\n", (int)len); - - lwsl_hexdump(buf, (size_t)len); - - if (lws_handshake_client(wsi, &buf, (size_t)len)) - goto bail; - - last_char = buf; - if (lws_handshake_server(wsi, &buf, (size_t)len)) - /* Handshake indicates this session is done. */ - goto bail; - - /* we might have transitioned to RAW */ - if (wsi->mode == LWSCM_RAW) - /* we gave the read buffer to RAW handler already */ - goto read_ok; - - /* - * It's possible that we've exhausted our data already, or - * rx flow control has stopped us dealing with this early, - * but lws_handshake_server doesn't update len for us. - * Figure out how much was read, so that we can proceed - * appropriately: - */ - len -= (buf - last_char); - lwsl_debug("%s: thinks we have used %ld\n", __func__, (long)len); - - if (!wsi->hdr_parsing_completed) - /* More header content on the way */ - goto read_ok; - - switch (wsi->state) { - case LWSS_HTTP: - case LWSS_HTTP_HEADERS: - goto read_ok; - case LWSS_HTTP_ISSUING_FILE: - goto read_ok; - case LWSS_HTTP_BODY: - wsi->u.http.rx_content_remain = - wsi->u.http.rx_content_length; - if (wsi->u.http.rx_content_remain) - goto http_postbody; - - /* there is no POST content */ - goto postbody_completion; - default: - break; - } - break; - - case LWSS_HTTP_BODY: -http_postbody: - //lwsl_notice("http post body\n"); - while (len && wsi->u.http.rx_content_remain) { - /* Copy as much as possible, up to the limit of: - * what we have in the read buffer (len) - * remaining portion of the POST body (content_remain) - */ - body_chunk_len = min(wsi->u.http.rx_content_remain, len); - wsi->u.http.rx_content_remain -= body_chunk_len; - len -= body_chunk_len; -#ifdef LWS_WITH_CGI - if (wsi->cgi) { - struct lws_cgi_args args; - - args.ch = LWS_STDIN; - args.stdwsi = &wsi->cgi->stdwsi[0]; - args.data = buf; - args.len = body_chunk_len; - - /* returns how much used */ - n = user_callback_handle_rxflow( - wsi->protocol->callback, - wsi, LWS_CALLBACK_CGI_STDIN_DATA, - wsi->user_space, - (void *)&args, 0); - if ((int)n < 0) - goto bail; - } else { -#endif - n = wsi->protocol->callback(wsi, - LWS_CALLBACK_HTTP_BODY, wsi->user_space, - buf, (size_t)body_chunk_len); - if (n) - goto bail; - n = (size_t)body_chunk_len; -#ifdef LWS_WITH_CGI - } -#endif - buf += n; - - if (wsi->u.http.rx_content_remain) { - lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, - wsi->context->timeout_secs); - break; - } - /* he sent all the content in time */ -postbody_completion: -#ifdef LWS_WITH_CGI - /* - * If we're running a cgi, we can't let him off the - * hook just because he sent his POST data - */ - if (wsi->cgi) - lws_set_timeout(wsi, PENDING_TIMEOUT_CGI, - wsi->context->timeout_secs); - else -#endif - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); -#ifdef LWS_WITH_CGI - if (!wsi->cgi) -#endif - { - lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n"); - n = wsi->protocol->callback(wsi, - LWS_CALLBACK_HTTP_BODY_COMPLETION, - wsi->user_space, NULL, 0); - if (n) - goto bail; - - if (wsi->http2_substream) - wsi->state = LWSS_HTTP2_ESTABLISHED; - } - - break; - } - break; - - case LWSS_ESTABLISHED: - case LWSS_AWAITING_CLOSE_ACK: - case LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION: - case LWSS_SHUTDOWN: - if (lws_handshake_client(wsi, &buf, (size_t)len)) - goto bail; - switch (wsi->mode) { - case LWSCM_WS_SERVING: - - if (lws_interpret_incoming_packet(wsi, &buf, (size_t)len) < 0) { - lwsl_info("interpret_incoming_packet has bailed\n"); - goto bail; - } - break; - } - break; - default: - lwsl_err("%s: Unhandled state %d\n", __func__, wsi->state); - break; - } - -read_ok: - /* Nothing more to do for now */ - lwsl_info("%s: read_ok, used %ld\n", __func__, (long)(buf - oldbuf)); - - return buf - oldbuf; - -bail: - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - - return -1; -} diff --git a/thirdparty/lws/lextable.h b/thirdparty/lws/lextable.h deleted file mode 100644 index f940afd25b..0000000000 --- a/thirdparty/lws/lextable.h +++ /dev/null @@ -1,805 +0,0 @@ -/* pos 0000: 0 */ 0x67 /* 'g' */, 0x40, 0x00 /* (to 0x0040 state 1) */, - 0x70 /* 'p' */, 0x42, 0x00 /* (to 0x0045 state 5) */, - 0x6F /* 'o' */, 0x51, 0x00 /* (to 0x0057 state 10) */, - 0x68 /* 'h' */, 0x5D, 0x00 /* (to 0x0066 state 18) */, - 0x63 /* 'c' */, 0x69, 0x00 /* (to 0x0075 state 23) */, - 0x75 /* 'u' */, 0x8A, 0x00 /* (to 0x0099 state 34) */, - 0x73 /* 's' */, 0xA0, 0x00 /* (to 0x00B2 state 48) */, - 0x0D /* '.' */, 0xD9, 0x00 /* (to 0x00EE state 68) */, - 0x61 /* 'a' */, 0x31, 0x01 /* (to 0x0149 state 129) */, - 0x69 /* 'i' */, 0x70, 0x01 /* (to 0x018B state 163) */, - 0x64 /* 'd' */, 0x19, 0x02 /* (to 0x0237 state 265) */, - 0x72 /* 'r' */, 0x22, 0x02 /* (to 0x0243 state 270) */, - 0x3A /* ':' */, 0x53, 0x02 /* (to 0x0277 state 299) */, - 0x65 /* 'e' */, 0xDF, 0x02 /* (to 0x0306 state 409) */, - 0x66 /* 'f' */, 0xFB, 0x02 /* (to 0x0325 state 425) */, - 0x6C /* 'l' */, 0x1D, 0x03 /* (to 0x034A state 458) */, - 0x6D /* 'm' */, 0x40, 0x03 /* (to 0x0370 state 484) */, - 0x74 /* 't' */, 0xAF, 0x03 /* (to 0x03E2 state 578) */, - 0x76 /* 'v' */, 0xD0, 0x03 /* (to 0x0406 state 606) */, - 0x77 /* 'w' */, 0xDD, 0x03 /* (to 0x0416 state 614) */, - 0x78 /* 'x' */, 0x04, 0x04 /* (to 0x0440 state 650) */, - 0x08, /* fail */ -/* pos 0040: 1 */ 0xE5 /* 'e' -> */, -/* pos 0041: 2 */ 0xF4 /* 't' -> */, -/* pos 0042: 3 */ 0xA0 /* ' ' -> */, -/* pos 0043: 4 */ 0x00, 0x00 /* - terminal marker 0 - */, -/* pos 0045: 5 */ 0x6F /* 'o' */, 0x0D, 0x00 /* (to 0x0052 state 6) */, - 0x72 /* 'r' */, 0x95, 0x01 /* (to 0x01DD state 211) */, - 0x61 /* 'a' */, 0xDD, 0x03 /* (to 0x0428 state 631) */, - 0x75 /* 'u' */, 0xDF, 0x03 /* (to 0x042D state 635) */, - 0x08, /* fail */ -/* pos 0052: 6 */ 0xF3 /* 's' -> */, -/* pos 0053: 7 */ 0xF4 /* 't' -> */, -/* pos 0054: 8 */ 0xA0 /* ' ' -> */, -/* pos 0055: 9 */ 0x00, 0x01 /* - terminal marker 1 - */, -/* pos 0057: 10 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x005E state 11) */, - 0x72 /* 'r' */, 0x51, 0x00 /* (to 0x00AB state 42) */, - 0x08, /* fail */ -/* pos 005e: 11 */ 0xF4 /* 't' -> */, -/* pos 005f: 12 */ 0xE9 /* 'i' -> */, -/* pos 0060: 13 */ 0xEF /* 'o' -> */, -/* pos 0061: 14 */ 0xEE /* 'n' -> */, -/* pos 0062: 15 */ 0xF3 /* 's' -> */, -/* pos 0063: 16 */ 0xA0 /* ' ' -> */, -/* pos 0064: 17 */ 0x00, 0x02 /* - terminal marker 2 - */, -/* pos 0066: 18 */ 0x6F /* 'o' */, 0x0A, 0x00 /* (to 0x0070 state 19) */, - 0x74 /* 't' */, 0xBF, 0x00 /* (to 0x0128 state 110) */, - 0x65 /* 'e' */, 0xF8, 0x03 /* (to 0x0464 state 676) */, - 0x08, /* fail */ -/* pos 0070: 19 */ 0xF3 /* 's' -> */, -/* pos 0071: 20 */ 0xF4 /* 't' -> */, -/* pos 0072: 21 */ 0xBA /* ':' -> */, -/* pos 0073: 22 */ 0x00, 0x03 /* - terminal marker 3 - */, -/* pos 0075: 23 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x007C state 24) */, - 0x61 /* 'a' */, 0x72, 0x01 /* (to 0x01EA state 217) */, - 0x08, /* fail */ -/* pos 007c: 24 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x0083 state 25) */, - 0x6F /* 'o' */, 0x87, 0x01 /* (to 0x0206 state 243) */, - 0x08, /* fail */ -/* pos 0083: 25 */ 0x6E /* 'n' */, 0x07, 0x00 /* (to 0x008A state 26) */, - 0x74 /* 't' */, 0x86, 0x01 /* (to 0x020C state 248) */, - 0x08, /* fail */ -/* pos 008a: 26 */ 0xE5 /* 'e' -> */, -/* pos 008b: 27 */ 0xE3 /* 'c' -> */, -/* pos 008c: 28 */ 0xF4 /* 't' -> */, -/* pos 008d: 29 */ 0x69 /* 'i' */, 0x07, 0x00 /* (to 0x0094 state 30) */, - 0x20 /* ' ' */, 0xD2, 0x03 /* (to 0x0462 state 675) */, - 0x08, /* fail */ -/* pos 0094: 30 */ 0xEF /* 'o' -> */, -/* pos 0095: 31 */ 0xEE /* 'n' -> */, -/* pos 0096: 32 */ 0xBA /* ':' -> */, -/* pos 0097: 33 */ 0x00, 0x04 /* - terminal marker 4 - */, -/* pos 0099: 34 */ 0x70 /* 'p' */, 0x0A, 0x00 /* (to 0x00A3 state 35) */, - 0x73 /* 's' */, 0x5F, 0x03 /* (to 0x03FB state 596) */, - 0x72 /* 'r' */, 0x97, 0x03 /* (to 0x0436 state 642) */, - 0x08, /* fail */ -/* pos 00a3: 35 */ 0xE7 /* 'g' -> */, -/* pos 00a4: 36 */ 0xF2 /* 'r' -> */, -/* pos 00a5: 37 */ 0xE1 /* 'a' -> */, -/* pos 00a6: 38 */ 0xE4 /* 'd' -> */, -/* pos 00a7: 39 */ 0xE5 /* 'e' -> */, -/* pos 00a8: 40 */ 0xBA /* ':' -> */, -/* pos 00a9: 41 */ 0x00, 0x05 /* - terminal marker 5 - */, -/* pos 00ab: 42 */ 0xE9 /* 'i' -> */, -/* pos 00ac: 43 */ 0xE7 /* 'g' -> */, -/* pos 00ad: 44 */ 0xE9 /* 'i' -> */, -/* pos 00ae: 45 */ 0xEE /* 'n' -> */, -/* pos 00af: 46 */ 0xBA /* ':' -> */, -/* pos 00b0: 47 */ 0x00, 0x06 /* - terminal marker 6 - */, -/* pos 00b2: 48 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x00B9 state 49) */, - 0x74 /* 't' */, 0x13, 0x03 /* (to 0x03C8 state 553) */, - 0x08, /* fail */ -/* pos 00b9: 49 */ 0x63 /* 'c' */, 0x0A, 0x00 /* (to 0x00C3 state 50) */, - 0x72 /* 'r' */, 0xFC, 0x02 /* (to 0x03B8 state 539) */, - 0x74 /* 't' */, 0xFF, 0x02 /* (to 0x03BE state 544) */, - 0x08, /* fail */ -/* pos 00c3: 50 */ 0xAD /* '-' -> */, -/* pos 00c4: 51 */ 0xF7 /* 'w' -> */, -/* pos 00c5: 52 */ 0xE5 /* 'e' -> */, -/* pos 00c6: 53 */ 0xE2 /* 'b' -> */, -/* pos 00c7: 54 */ 0xF3 /* 's' -> */, -/* pos 00c8: 55 */ 0xEF /* 'o' -> */, -/* pos 00c9: 56 */ 0xE3 /* 'c' -> */, -/* pos 00ca: 57 */ 0xEB /* 'k' -> */, -/* pos 00cb: 58 */ 0xE5 /* 'e' -> */, -/* pos 00cc: 59 */ 0xF4 /* 't' -> */, -/* pos 00cd: 60 */ 0xAD /* '-' -> */, -/* pos 00ce: 61 */ 0x64 /* 'd' */, 0x19, 0x00 /* (to 0x00E7 state 62) */, - 0x65 /* 'e' */, 0x20, 0x00 /* (to 0x00F1 state 70) */, - 0x6B /* 'k' */, 0x29, 0x00 /* (to 0x00FD state 81) */, - 0x70 /* 'p' */, 0x38, 0x00 /* (to 0x010F state 88) */, - 0x61 /* 'a' */, 0x3F, 0x00 /* (to 0x0119 state 97) */, - 0x6E /* 'n' */, 0x44, 0x00 /* (to 0x0121 state 104) */, - 0x76 /* 'v' */, 0x86, 0x01 /* (to 0x0266 state 284) */, - 0x6F /* 'o' */, 0x8C, 0x01 /* (to 0x026F state 292) */, - 0x08, /* fail */ -/* pos 00e7: 62 */ 0xF2 /* 'r' -> */, -/* pos 00e8: 63 */ 0xE1 /* 'a' -> */, -/* pos 00e9: 64 */ 0xE6 /* 'f' -> */, -/* pos 00ea: 65 */ 0xF4 /* 't' -> */, -/* pos 00eb: 66 */ 0xBA /* ':' -> */, -/* pos 00ec: 67 */ 0x00, 0x07 /* - terminal marker 7 - */, -/* pos 00ee: 68 */ 0x8A /* '.' -> */, -/* pos 00ef: 69 */ 0x00, 0x08 /* - terminal marker 8 - */, -/* pos 00f1: 70 */ 0xF8 /* 'x' -> */, -/* pos 00f2: 71 */ 0xF4 /* 't' -> */, -/* pos 00f3: 72 */ 0xE5 /* 'e' -> */, -/* pos 00f4: 73 */ 0xEE /* 'n' -> */, -/* pos 00f5: 74 */ 0xF3 /* 's' -> */, -/* pos 00f6: 75 */ 0xE9 /* 'i' -> */, -/* pos 00f7: 76 */ 0xEF /* 'o' -> */, -/* pos 00f8: 77 */ 0xEE /* 'n' -> */, -/* pos 00f9: 78 */ 0xF3 /* 's' -> */, -/* pos 00fa: 79 */ 0xBA /* ':' -> */, -/* pos 00fb: 80 */ 0x00, 0x09 /* - terminal marker 9 - */, -/* pos 00fd: 81 */ 0xE5 /* 'e' -> */, -/* pos 00fe: 82 */ 0xF9 /* 'y' -> */, -/* pos 00ff: 83 */ 0x31 /* '1' */, 0x0A, 0x00 /* (to 0x0109 state 84) */, - 0x32 /* '2' */, 0x0A, 0x00 /* (to 0x010C state 86) */, - 0x3A /* ':' */, 0x5F, 0x01 /* (to 0x0264 state 283) */, - 0x08, /* fail */ -/* pos 0109: 84 */ 0xBA /* ':' -> */, -/* pos 010a: 85 */ 0x00, 0x0A /* - terminal marker 10 - */, -/* pos 010c: 86 */ 0xBA /* ':' -> */, -/* pos 010d: 87 */ 0x00, 0x0B /* - terminal marker 11 - */, -/* pos 010f: 88 */ 0xF2 /* 'r' -> */, -/* pos 0110: 89 */ 0xEF /* 'o' -> */, -/* pos 0111: 90 */ 0xF4 /* 't' -> */, -/* pos 0112: 91 */ 0xEF /* 'o' -> */, -/* pos 0113: 92 */ 0xE3 /* 'c' -> */, -/* pos 0114: 93 */ 0xEF /* 'o' -> */, -/* pos 0115: 94 */ 0xEC /* 'l' -> */, -/* pos 0116: 95 */ 0xBA /* ':' -> */, -/* pos 0117: 96 */ 0x00, 0x0C /* - terminal marker 12 - */, -/* pos 0119: 97 */ 0xE3 /* 'c' -> */, -/* pos 011a: 98 */ 0xE3 /* 'c' -> */, -/* pos 011b: 99 */ 0xE5 /* 'e' -> */, -/* pos 011c: 100 */ 0xF0 /* 'p' -> */, -/* pos 011d: 101 */ 0xF4 /* 't' -> */, -/* pos 011e: 102 */ 0xBA /* ':' -> */, -/* pos 011f: 103 */ 0x00, 0x0D /* - terminal marker 13 - */, -/* pos 0121: 104 */ 0xEF /* 'o' -> */, -/* pos 0122: 105 */ 0xEE /* 'n' -> */, -/* pos 0123: 106 */ 0xE3 /* 'c' -> */, -/* pos 0124: 107 */ 0xE5 /* 'e' -> */, -/* pos 0125: 108 */ 0xBA /* ':' -> */, -/* pos 0126: 109 */ 0x00, 0x0E /* - terminal marker 14 - */, -/* pos 0128: 110 */ 0xF4 /* 't' -> */, -/* pos 0129: 111 */ 0xF0 /* 'p' -> */, -/* pos 012a: 112 */ 0x2F /* '/' */, 0x07, 0x00 /* (to 0x0131 state 113) */, - 0x32 /* '2' */, 0x10, 0x00 /* (to 0x013D state 118) */, - 0x08, /* fail */ -/* pos 0131: 113 */ 0xB1 /* '1' -> */, -/* pos 0132: 114 */ 0xAE /* '.' -> */, -/* pos 0133: 115 */ 0x31 /* '1' */, 0x07, 0x00 /* (to 0x013A state 116) */, - 0x30 /* '0' */, 0x1B, 0x03 /* (to 0x0451 state 660) */, - 0x08, /* fail */ -/* pos 013a: 116 */ 0xA0 /* ' ' -> */, -/* pos 013b: 117 */ 0x00, 0x0F /* - terminal marker 15 - */, -/* pos 013d: 118 */ 0xAD /* '-' -> */, -/* pos 013e: 119 */ 0xF3 /* 's' -> */, -/* pos 013f: 120 */ 0xE5 /* 'e' -> */, -/* pos 0140: 121 */ 0xF4 /* 't' -> */, -/* pos 0141: 122 */ 0xF4 /* 't' -> */, -/* pos 0142: 123 */ 0xE9 /* 'i' -> */, -/* pos 0143: 124 */ 0xEE /* 'n' -> */, -/* pos 0144: 125 */ 0xE7 /* 'g' -> */, -/* pos 0145: 126 */ 0xF3 /* 's' -> */, -/* pos 0146: 127 */ 0xBA /* ':' -> */, -/* pos 0147: 128 */ 0x00, 0x10 /* - terminal marker 16 - */, -/* pos 0149: 129 */ 0x63 /* 'c' */, 0x0D, 0x00 /* (to 0x0156 state 130) */, - 0x75 /* 'u' */, 0xAC, 0x00 /* (to 0x01F8 state 230) */, - 0x67 /* 'g' */, 0x7D, 0x01 /* (to 0x02CC state 358) */, - 0x6C /* 'l' */, 0x7E, 0x01 /* (to 0x02D0 state 361) */, - 0x08, /* fail */ -/* pos 0156: 130 */ 0xE3 /* 'c' -> */, -/* pos 0157: 131 */ 0xE5 /* 'e' -> */, -/* pos 0158: 132 */ 0x70 /* 'p' */, 0x07, 0x00 /* (to 0x015F state 133) */, - 0x73 /* 's' */, 0x0E, 0x00 /* (to 0x0169 state 136) */, - 0x08, /* fail */ -/* pos 015f: 133 */ 0xF4 /* 't' -> */, -/* pos 0160: 134 */ 0x3A /* ':' */, 0x07, 0x00 /* (to 0x0167 state 135) */, - 0x2D /* '-' */, 0x59, 0x00 /* (to 0x01BC state 192) */, - 0x08, /* fail */ -/* pos 0167: 135 */ 0x00, 0x11 /* - terminal marker 17 - */, -/* pos 0169: 136 */ 0xF3 /* 's' -> */, -/* pos 016a: 137 */ 0xAD /* '-' -> */, -/* pos 016b: 138 */ 0xE3 /* 'c' -> */, -/* pos 016c: 139 */ 0xEF /* 'o' -> */, -/* pos 016d: 140 */ 0xEE /* 'n' -> */, -/* pos 016e: 141 */ 0xF4 /* 't' -> */, -/* pos 016f: 142 */ 0xF2 /* 'r' -> */, -/* pos 0170: 143 */ 0xEF /* 'o' -> */, -/* pos 0171: 144 */ 0xEC /* 'l' -> */, -/* pos 0172: 145 */ 0xAD /* '-' -> */, -/* pos 0173: 146 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x017A state 147) */, - 0x61 /* 'a' */, 0x48, 0x01 /* (to 0x02BE state 345) */, - 0x08, /* fail */ -/* pos 017a: 147 */ 0xE5 /* 'e' -> */, -/* pos 017b: 148 */ 0xF1 /* 'q' -> */, -/* pos 017c: 149 */ 0xF5 /* 'u' -> */, -/* pos 017d: 150 */ 0xE5 /* 'e' -> */, -/* pos 017e: 151 */ 0xF3 /* 's' -> */, -/* pos 017f: 152 */ 0xF4 /* 't' -> */, -/* pos 0180: 153 */ 0xAD /* '-' -> */, -/* pos 0181: 154 */ 0xE8 /* 'h' -> */, -/* pos 0182: 155 */ 0xE5 /* 'e' -> */, -/* pos 0183: 156 */ 0xE1 /* 'a' -> */, -/* pos 0184: 157 */ 0xE4 /* 'd' -> */, -/* pos 0185: 158 */ 0xE5 /* 'e' -> */, -/* pos 0186: 159 */ 0xF2 /* 'r' -> */, -/* pos 0187: 160 */ 0xF3 /* 's' -> */, -/* pos 0188: 161 */ 0xBA /* ':' -> */, -/* pos 0189: 162 */ 0x00, 0x12 /* - terminal marker 18 - */, -/* pos 018b: 163 */ 0xE6 /* 'f' -> */, -/* pos 018c: 164 */ 0xAD /* '-' -> */, -/* pos 018d: 165 */ 0x6D /* 'm' */, 0x0D, 0x00 /* (to 0x019A state 166) */, - 0x6E /* 'n' */, 0x20, 0x00 /* (to 0x01B0 state 181) */, - 0x72 /* 'r' */, 0x9E, 0x01 /* (to 0x0331 state 435) */, - 0x75 /* 'u' */, 0xA2, 0x01 /* (to 0x0338 state 441) */, - 0x08, /* fail */ -/* pos 019a: 166 */ 0x6F /* 'o' */, 0x07, 0x00 /* (to 0x01A1 state 167) */, - 0x61 /* 'a' */, 0x8E, 0x01 /* (to 0x032B state 430) */, - 0x08, /* fail */ -/* pos 01a1: 167 */ 0xE4 /* 'd' -> */, -/* pos 01a2: 168 */ 0xE9 /* 'i' -> */, -/* pos 01a3: 169 */ 0xE6 /* 'f' -> */, -/* pos 01a4: 170 */ 0xE9 /* 'i' -> */, -/* pos 01a5: 171 */ 0xE5 /* 'e' -> */, -/* pos 01a6: 172 */ 0xE4 /* 'd' -> */, -/* pos 01a7: 173 */ 0xAD /* '-' -> */, -/* pos 01a8: 174 */ 0xF3 /* 's' -> */, -/* pos 01a9: 175 */ 0xE9 /* 'i' -> */, -/* pos 01aa: 176 */ 0xEE /* 'n' -> */, -/* pos 01ab: 177 */ 0xE3 /* 'c' -> */, -/* pos 01ac: 178 */ 0xE5 /* 'e' -> */, -/* pos 01ad: 179 */ 0xBA /* ':' -> */, -/* pos 01ae: 180 */ 0x00, 0x13 /* - terminal marker 19 - */, -/* pos 01b0: 181 */ 0xEF /* 'o' -> */, -/* pos 01b1: 182 */ 0xEE /* 'n' -> */, -/* pos 01b2: 183 */ 0xE5 /* 'e' -> */, -/* pos 01b3: 184 */ 0xAD /* '-' -> */, -/* pos 01b4: 185 */ 0xED /* 'm' -> */, -/* pos 01b5: 186 */ 0xE1 /* 'a' -> */, -/* pos 01b6: 187 */ 0xF4 /* 't' -> */, -/* pos 01b7: 188 */ 0xE3 /* 'c' -> */, -/* pos 01b8: 189 */ 0xE8 /* 'h' -> */, -/* pos 01b9: 190 */ 0xBA /* ':' -> */, -/* pos 01ba: 191 */ 0x00, 0x14 /* - terminal marker 20 - */, -/* pos 01bc: 192 */ 0x65 /* 'e' */, 0x0D, 0x00 /* (to 0x01C9 state 193) */, - 0x6C /* 'l' */, 0x14, 0x00 /* (to 0x01D3 state 202) */, - 0x63 /* 'c' */, 0xEB, 0x00 /* (to 0x02AD state 330) */, - 0x72 /* 'r' */, 0xF1, 0x00 /* (to 0x02B6 state 338) */, - 0x08, /* fail */ -/* pos 01c9: 193 */ 0xEE /* 'n' -> */, -/* pos 01ca: 194 */ 0xE3 /* 'c' -> */, -/* pos 01cb: 195 */ 0xEF /* 'o' -> */, -/* pos 01cc: 196 */ 0xE4 /* 'd' -> */, -/* pos 01cd: 197 */ 0xE9 /* 'i' -> */, -/* pos 01ce: 198 */ 0xEE /* 'n' -> */, -/* pos 01cf: 199 */ 0xE7 /* 'g' -> */, -/* pos 01d0: 200 */ 0xBA /* ':' -> */, -/* pos 01d1: 201 */ 0x00, 0x15 /* - terminal marker 21 - */, -/* pos 01d3: 202 */ 0xE1 /* 'a' -> */, -/* pos 01d4: 203 */ 0xEE /* 'n' -> */, -/* pos 01d5: 204 */ 0xE7 /* 'g' -> */, -/* pos 01d6: 205 */ 0xF5 /* 'u' -> */, -/* pos 01d7: 206 */ 0xE1 /* 'a' -> */, -/* pos 01d8: 207 */ 0xE7 /* 'g' -> */, -/* pos 01d9: 208 */ 0xE5 /* 'e' -> */, -/* pos 01da: 209 */ 0xBA /* ':' -> */, -/* pos 01db: 210 */ 0x00, 0x16 /* - terminal marker 22 - */, -/* pos 01dd: 211 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x01E4 state 212) */, - 0x6F /* 'o' */, 0x9E, 0x01 /* (to 0x037E state 497) */, - 0x08, /* fail */ -/* pos 01e4: 212 */ 0xE7 /* 'g' -> */, -/* pos 01e5: 213 */ 0xED /* 'm' -> */, -/* pos 01e6: 214 */ 0xE1 /* 'a' -> */, -/* pos 01e7: 215 */ 0xBA /* ':' -> */, -/* pos 01e8: 216 */ 0x00, 0x17 /* - terminal marker 23 - */, -/* pos 01ea: 217 */ 0xE3 /* 'c' -> */, -/* pos 01eb: 218 */ 0xE8 /* 'h' -> */, -/* pos 01ec: 219 */ 0xE5 /* 'e' -> */, -/* pos 01ed: 220 */ 0xAD /* '-' -> */, -/* pos 01ee: 221 */ 0xE3 /* 'c' -> */, -/* pos 01ef: 222 */ 0xEF /* 'o' -> */, -/* pos 01f0: 223 */ 0xEE /* 'n' -> */, -/* pos 01f1: 224 */ 0xF4 /* 't' -> */, -/* pos 01f2: 225 */ 0xF2 /* 'r' -> */, -/* pos 01f3: 226 */ 0xEF /* 'o' -> */, -/* pos 01f4: 227 */ 0xEC /* 'l' -> */, -/* pos 01f5: 228 */ 0xBA /* ':' -> */, -/* pos 01f6: 229 */ 0x00, 0x18 /* - terminal marker 24 - */, -/* pos 01f8: 230 */ 0xF4 /* 't' -> */, -/* pos 01f9: 231 */ 0xE8 /* 'h' -> */, -/* pos 01fa: 232 */ 0xEF /* 'o' -> */, -/* pos 01fb: 233 */ 0xF2 /* 'r' -> */, -/* pos 01fc: 234 */ 0xE9 /* 'i' -> */, -/* pos 01fd: 235 */ 0xFA /* 'z' -> */, -/* pos 01fe: 236 */ 0xE1 /* 'a' -> */, -/* pos 01ff: 237 */ 0xF4 /* 't' -> */, -/* pos 0200: 238 */ 0xE9 /* 'i' -> */, -/* pos 0201: 239 */ 0xEF /* 'o' -> */, -/* pos 0202: 240 */ 0xEE /* 'n' -> */, -/* pos 0203: 241 */ 0xBA /* ':' -> */, -/* pos 0204: 242 */ 0x00, 0x19 /* - terminal marker 25 - */, -/* pos 0206: 243 */ 0xEB /* 'k' -> */, -/* pos 0207: 244 */ 0xE9 /* 'i' -> */, -/* pos 0208: 245 */ 0xE5 /* 'e' -> */, -/* pos 0209: 246 */ 0xBA /* ':' -> */, -/* pos 020a: 247 */ 0x00, 0x1A /* - terminal marker 26 - */, -/* pos 020c: 248 */ 0xE5 /* 'e' -> */, -/* pos 020d: 249 */ 0xEE /* 'n' -> */, -/* pos 020e: 250 */ 0xF4 /* 't' -> */, -/* pos 020f: 251 */ 0xAD /* '-' -> */, -/* pos 0210: 252 */ 0x6C /* 'l' */, 0x10, 0x00 /* (to 0x0220 state 253) */, - 0x74 /* 't' */, 0x1E, 0x00 /* (to 0x0231 state 260) */, - 0x64 /* 'd' */, 0xC0, 0x00 /* (to 0x02D6 state 366) */, - 0x65 /* 'e' */, 0xCA, 0x00 /* (to 0x02E3 state 378) */, - 0x72 /* 'r' */, 0xE3, 0x00 /* (to 0x02FF state 403) */, - 0x08, /* fail */ -/* pos 0220: 253 */ 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x022A state 254) */, - 0x61 /* 'a' */, 0xCA, 0x00 /* (to 0x02ED state 387) */, - 0x6F /* 'o' */, 0xD0, 0x00 /* (to 0x02F6 state 395) */, - 0x08, /* fail */ -/* pos 022a: 254 */ 0xEE /* 'n' -> */, -/* pos 022b: 255 */ 0xE7 /* 'g' -> */, -/* pos 022c: 256 */ 0xF4 /* 't' -> */, -/* pos 022d: 257 */ 0xE8 /* 'h' -> */, -/* pos 022e: 258 */ 0xBA /* ':' -> */, -/* pos 022f: 259 */ 0x00, 0x1B /* - terminal marker 27 - */, -/* pos 0231: 260 */ 0xF9 /* 'y' -> */, -/* pos 0232: 261 */ 0xF0 /* 'p' -> */, -/* pos 0233: 262 */ 0xE5 /* 'e' -> */, -/* pos 0234: 263 */ 0xBA /* ':' -> */, -/* pos 0235: 264 */ 0x00, 0x1C /* - terminal marker 28 - */, -/* pos 0237: 265 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x023E state 266) */, - 0x65 /* 'e' */, 0xF6, 0x01 /* (to 0x0430 state 637) */, - 0x08, /* fail */ -/* pos 023e: 266 */ 0xF4 /* 't' -> */, -/* pos 023f: 267 */ 0xE5 /* 'e' -> */, -/* pos 0240: 268 */ 0xBA /* ':' -> */, -/* pos 0241: 269 */ 0x00, 0x1D /* - terminal marker 29 - */, -/* pos 0243: 270 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x024A state 271) */, - 0x65 /* 'e' */, 0x0A, 0x00 /* (to 0x0250 state 276) */, - 0x08, /* fail */ -/* pos 024a: 271 */ 0xEE /* 'n' -> */, -/* pos 024b: 272 */ 0xE7 /* 'g' -> */, -/* pos 024c: 273 */ 0xE5 /* 'e' -> */, -/* pos 024d: 274 */ 0xBA /* ':' -> */, -/* pos 024e: 275 */ 0x00, 0x1E /* - terminal marker 30 - */, -/* pos 0250: 276 */ 0x66 /* 'f' */, 0x07, 0x00 /* (to 0x0257 state 277) */, - 0x74 /* 't' */, 0x5A, 0x01 /* (to 0x03AD state 529) */, - 0x08, /* fail */ -/* pos 0257: 277 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x025E state 278) */, - 0x72 /* 'r' */, 0x4D, 0x01 /* (to 0x03A7 state 524) */, - 0x08, /* fail */ -/* pos 025e: 278 */ 0xF2 /* 'r' -> */, -/* pos 025f: 279 */ 0xE5 /* 'e' -> */, -/* pos 0260: 280 */ 0xF2 /* 'r' -> */, -/* pos 0261: 281 */ 0xBA /* ':' -> */, -/* pos 0262: 282 */ 0x00, 0x1F /* - terminal marker 31 - */, -/* pos 0264: 283 */ 0x00, 0x20 /* - terminal marker 32 - */, -/* pos 0266: 284 */ 0xE5 /* 'e' -> */, -/* pos 0267: 285 */ 0xF2 /* 'r' -> */, -/* pos 0268: 286 */ 0xF3 /* 's' -> */, -/* pos 0269: 287 */ 0xE9 /* 'i' -> */, -/* pos 026a: 288 */ 0xEF /* 'o' -> */, -/* pos 026b: 289 */ 0xEE /* 'n' -> */, -/* pos 026c: 290 */ 0xBA /* ':' -> */, -/* pos 026d: 291 */ 0x00, 0x21 /* - terminal marker 33 - */, -/* pos 026f: 292 */ 0xF2 /* 'r' -> */, -/* pos 0270: 293 */ 0xE9 /* 'i' -> */, -/* pos 0271: 294 */ 0xE7 /* 'g' -> */, -/* pos 0272: 295 */ 0xE9 /* 'i' -> */, -/* pos 0273: 296 */ 0xEE /* 'n' -> */, -/* pos 0274: 297 */ 0xBA /* ':' -> */, -/* pos 0275: 298 */ 0x00, 0x22 /* - terminal marker 34 - */, -/* pos 0277: 299 */ 0x61 /* 'a' */, 0x0D, 0x00 /* (to 0x0284 state 300) */, - 0x6D /* 'm' */, 0x14, 0x00 /* (to 0x028E state 309) */, - 0x70 /* 'p' */, 0x18, 0x00 /* (to 0x0295 state 315) */, - 0x73 /* 's' */, 0x1A, 0x00 /* (to 0x029A state 319) */, - 0x08, /* fail */ -/* pos 0284: 300 */ 0xF5 /* 'u' -> */, -/* pos 0285: 301 */ 0xF4 /* 't' -> */, -/* pos 0286: 302 */ 0xE8 /* 'h' -> */, -/* pos 0287: 303 */ 0xEF /* 'o' -> */, -/* pos 0288: 304 */ 0xF2 /* 'r' -> */, -/* pos 0289: 305 */ 0xE9 /* 'i' -> */, -/* pos 028a: 306 */ 0xF4 /* 't' -> */, -/* pos 028b: 307 */ 0xF9 /* 'y' -> */, -/* pos 028c: 308 */ 0x00, 0x23 /* - terminal marker 35 - */, -/* pos 028e: 309 */ 0xE5 /* 'e' -> */, -/* pos 028f: 310 */ 0xF4 /* 't' -> */, -/* pos 0290: 311 */ 0xE8 /* 'h' -> */, -/* pos 0291: 312 */ 0xEF /* 'o' -> */, -/* pos 0292: 313 */ 0xE4 /* 'd' -> */, -/* pos 0293: 314 */ 0x00, 0x24 /* - terminal marker 36 - */, -/* pos 0295: 315 */ 0xE1 /* 'a' -> */, -/* pos 0296: 316 */ 0xF4 /* 't' -> */, -/* pos 0297: 317 */ 0xE8 /* 'h' -> */, -/* pos 0298: 318 */ 0x00, 0x25 /* - terminal marker 37 - */, -/* pos 029a: 319 */ 0x63 /* 'c' */, 0x07, 0x00 /* (to 0x02A1 state 320) */, - 0x74 /* 't' */, 0x0A, 0x00 /* (to 0x02A7 state 325) */, - 0x08, /* fail */ -/* pos 02a1: 320 */ 0xE8 /* 'h' -> */, -/* pos 02a2: 321 */ 0xE5 /* 'e' -> */, -/* pos 02a3: 322 */ 0xED /* 'm' -> */, -/* pos 02a4: 323 */ 0xE5 /* 'e' -> */, -/* pos 02a5: 324 */ 0x00, 0x26 /* - terminal marker 38 - */, -/* pos 02a7: 325 */ 0xE1 /* 'a' -> */, -/* pos 02a8: 326 */ 0xF4 /* 't' -> */, -/* pos 02a9: 327 */ 0xF5 /* 'u' -> */, -/* pos 02aa: 328 */ 0xF3 /* 's' -> */, -/* pos 02ab: 329 */ 0x00, 0x27 /* - terminal marker 39 - */, -/* pos 02ad: 330 */ 0xE8 /* 'h' -> */, -/* pos 02ae: 331 */ 0xE1 /* 'a' -> */, -/* pos 02af: 332 */ 0xF2 /* 'r' -> */, -/* pos 02b0: 333 */ 0xF3 /* 's' -> */, -/* pos 02b1: 334 */ 0xE5 /* 'e' -> */, -/* pos 02b2: 335 */ 0xF4 /* 't' -> */, -/* pos 02b3: 336 */ 0xBA /* ':' -> */, -/* pos 02b4: 337 */ 0x00, 0x28 /* - terminal marker 40 - */, -/* pos 02b6: 338 */ 0xE1 /* 'a' -> */, -/* pos 02b7: 339 */ 0xEE /* 'n' -> */, -/* pos 02b8: 340 */ 0xE7 /* 'g' -> */, -/* pos 02b9: 341 */ 0xE5 /* 'e' -> */, -/* pos 02ba: 342 */ 0xF3 /* 's' -> */, -/* pos 02bb: 343 */ 0xBA /* ':' -> */, -/* pos 02bc: 344 */ 0x00, 0x29 /* - terminal marker 41 - */, -/* pos 02be: 345 */ 0xEC /* 'l' -> */, -/* pos 02bf: 346 */ 0xEC /* 'l' -> */, -/* pos 02c0: 347 */ 0xEF /* 'o' -> */, -/* pos 02c1: 348 */ 0xF7 /* 'w' -> */, -/* pos 02c2: 349 */ 0xAD /* '-' -> */, -/* pos 02c3: 350 */ 0xEF /* 'o' -> */, -/* pos 02c4: 351 */ 0xF2 /* 'r' -> */, -/* pos 02c5: 352 */ 0xE9 /* 'i' -> */, -/* pos 02c6: 353 */ 0xE7 /* 'g' -> */, -/* pos 02c7: 354 */ 0xE9 /* 'i' -> */, -/* pos 02c8: 355 */ 0xEE /* 'n' -> */, -/* pos 02c9: 356 */ 0xBA /* ':' -> */, -/* pos 02ca: 357 */ 0x00, 0x2A /* - terminal marker 42 - */, -/* pos 02cc: 358 */ 0xE5 /* 'e' -> */, -/* pos 02cd: 359 */ 0xBA /* ':' -> */, -/* pos 02ce: 360 */ 0x00, 0x2B /* - terminal marker 43 - */, -/* pos 02d0: 361 */ 0xEC /* 'l' -> */, -/* pos 02d1: 362 */ 0xEF /* 'o' -> */, -/* pos 02d2: 363 */ 0xF7 /* 'w' -> */, -/* pos 02d3: 364 */ 0xBA /* ':' -> */, -/* pos 02d4: 365 */ 0x00, 0x2C /* - terminal marker 44 - */, -/* pos 02d6: 366 */ 0xE9 /* 'i' -> */, -/* pos 02d7: 367 */ 0xF3 /* 's' -> */, -/* pos 02d8: 368 */ 0xF0 /* 'p' -> */, -/* pos 02d9: 369 */ 0xEF /* 'o' -> */, -/* pos 02da: 370 */ 0xF3 /* 's' -> */, -/* pos 02db: 371 */ 0xE9 /* 'i' -> */, -/* pos 02dc: 372 */ 0xF4 /* 't' -> */, -/* pos 02dd: 373 */ 0xE9 /* 'i' -> */, -/* pos 02de: 374 */ 0xEF /* 'o' -> */, -/* pos 02df: 375 */ 0xEE /* 'n' -> */, -/* pos 02e0: 376 */ 0xBA /* ':' -> */, -/* pos 02e1: 377 */ 0x00, 0x2D /* - terminal marker 45 - */, -/* pos 02e3: 378 */ 0xEE /* 'n' -> */, -/* pos 02e4: 379 */ 0xE3 /* 'c' -> */, -/* pos 02e5: 380 */ 0xEF /* 'o' -> */, -/* pos 02e6: 381 */ 0xE4 /* 'd' -> */, -/* pos 02e7: 382 */ 0xE9 /* 'i' -> */, -/* pos 02e8: 383 */ 0xEE /* 'n' -> */, -/* pos 02e9: 384 */ 0xE7 /* 'g' -> */, -/* pos 02ea: 385 */ 0xBA /* ':' -> */, -/* pos 02eb: 386 */ 0x00, 0x2E /* - terminal marker 46 - */, -/* pos 02ed: 387 */ 0xEE /* 'n' -> */, -/* pos 02ee: 388 */ 0xE7 /* 'g' -> */, -/* pos 02ef: 389 */ 0xF5 /* 'u' -> */, -/* pos 02f0: 390 */ 0xE1 /* 'a' -> */, -/* pos 02f1: 391 */ 0xE7 /* 'g' -> */, -/* pos 02f2: 392 */ 0xE5 /* 'e' -> */, -/* pos 02f3: 393 */ 0xBA /* ':' -> */, -/* pos 02f4: 394 */ 0x00, 0x2F /* - terminal marker 47 - */, -/* pos 02f6: 395 */ 0xE3 /* 'c' -> */, -/* pos 02f7: 396 */ 0xE1 /* 'a' -> */, -/* pos 02f8: 397 */ 0xF4 /* 't' -> */, -/* pos 02f9: 398 */ 0xE9 /* 'i' -> */, -/* pos 02fa: 399 */ 0xEF /* 'o' -> */, -/* pos 02fb: 400 */ 0xEE /* 'n' -> */, -/* pos 02fc: 401 */ 0xBA /* ':' -> */, -/* pos 02fd: 402 */ 0x00, 0x30 /* - terminal marker 48 - */, -/* pos 02ff: 403 */ 0xE1 /* 'a' -> */, -/* pos 0300: 404 */ 0xEE /* 'n' -> */, -/* pos 0301: 405 */ 0xE7 /* 'g' -> */, -/* pos 0302: 406 */ 0xE5 /* 'e' -> */, -/* pos 0303: 407 */ 0xBA /* ':' -> */, -/* pos 0304: 408 */ 0x00, 0x31 /* - terminal marker 49 - */, -/* pos 0306: 409 */ 0x74 /* 't' */, 0x07, 0x00 /* (to 0x030D state 410) */, - 0x78 /* 'x' */, 0x09, 0x00 /* (to 0x0312 state 414) */, - 0x08, /* fail */ -/* pos 030d: 410 */ 0xE1 /* 'a' -> */, -/* pos 030e: 411 */ 0xE7 /* 'g' -> */, -/* pos 030f: 412 */ 0xBA /* ':' -> */, -/* pos 0310: 413 */ 0x00, 0x32 /* - terminal marker 50 - */, -/* pos 0312: 414 */ 0xF0 /* 'p' -> */, -/* pos 0313: 415 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x031A state 416) */, - 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x031F state 420) */, - 0x08, /* fail */ -/* pos 031a: 416 */ 0xE3 /* 'c' -> */, -/* pos 031b: 417 */ 0xF4 /* 't' -> */, -/* pos 031c: 418 */ 0xBA /* ':' -> */, -/* pos 031d: 419 */ 0x00, 0x33 /* - terminal marker 51 - */, -/* pos 031f: 420 */ 0xF2 /* 'r' -> */, -/* pos 0320: 421 */ 0xE5 /* 'e' -> */, -/* pos 0321: 422 */ 0xF3 /* 's' -> */, -/* pos 0322: 423 */ 0xBA /* ':' -> */, -/* pos 0323: 424 */ 0x00, 0x34 /* - terminal marker 52 - */, -/* pos 0325: 425 */ 0xF2 /* 'r' -> */, -/* pos 0326: 426 */ 0xEF /* 'o' -> */, -/* pos 0327: 427 */ 0xED /* 'm' -> */, -/* pos 0328: 428 */ 0xBA /* ':' -> */, -/* pos 0329: 429 */ 0x00, 0x35 /* - terminal marker 53 - */, -/* pos 032b: 430 */ 0xF4 /* 't' -> */, -/* pos 032c: 431 */ 0xE3 /* 'c' -> */, -/* pos 032d: 432 */ 0xE8 /* 'h' -> */, -/* pos 032e: 433 */ 0xBA /* ':' -> */, -/* pos 032f: 434 */ 0x00, 0x36 /* - terminal marker 54 - */, -/* pos 0331: 435 */ 0xE1 /* 'a' -> */, -/* pos 0332: 436 */ 0xEE /* 'n' -> */, -/* pos 0333: 437 */ 0xE7 /* 'g' -> */, -/* pos 0334: 438 */ 0xE5 /* 'e' -> */, -/* pos 0335: 439 */ 0xBA /* ':' -> */, -/* pos 0336: 440 */ 0x00, 0x37 /* - terminal marker 55 - */, -/* pos 0338: 441 */ 0xEE /* 'n' -> */, -/* pos 0339: 442 */ 0xED /* 'm' -> */, -/* pos 033a: 443 */ 0xEF /* 'o' -> */, -/* pos 033b: 444 */ 0xE4 /* 'd' -> */, -/* pos 033c: 445 */ 0xE9 /* 'i' -> */, -/* pos 033d: 446 */ 0xE6 /* 'f' -> */, -/* pos 033e: 447 */ 0xE9 /* 'i' -> */, -/* pos 033f: 448 */ 0xE5 /* 'e' -> */, -/* pos 0340: 449 */ 0xE4 /* 'd' -> */, -/* pos 0341: 450 */ 0xAD /* '-' -> */, -/* pos 0342: 451 */ 0xF3 /* 's' -> */, -/* pos 0343: 452 */ 0xE9 /* 'i' -> */, -/* pos 0344: 453 */ 0xEE /* 'n' -> */, -/* pos 0345: 454 */ 0xE3 /* 'c' -> */, -/* pos 0346: 455 */ 0xE5 /* 'e' -> */, -/* pos 0347: 456 */ 0xBA /* ':' -> */, -/* pos 0348: 457 */ 0x00, 0x38 /* - terminal marker 56 - */, -/* pos 034a: 458 */ 0x61 /* 'a' */, 0x0A, 0x00 /* (to 0x0354 state 459) */, - 0x69 /* 'i' */, 0x15, 0x00 /* (to 0x0362 state 472) */, - 0x6F /* 'o' */, 0x17, 0x00 /* (to 0x0367 state 476) */, - 0x08, /* fail */ -/* pos 0354: 459 */ 0xF3 /* 's' -> */, -/* pos 0355: 460 */ 0xF4 /* 't' -> */, -/* pos 0356: 461 */ 0xAD /* '-' -> */, -/* pos 0357: 462 */ 0xED /* 'm' -> */, -/* pos 0358: 463 */ 0xEF /* 'o' -> */, -/* pos 0359: 464 */ 0xE4 /* 'd' -> */, -/* pos 035a: 465 */ 0xE9 /* 'i' -> */, -/* pos 035b: 466 */ 0xE6 /* 'f' -> */, -/* pos 035c: 467 */ 0xE9 /* 'i' -> */, -/* pos 035d: 468 */ 0xE5 /* 'e' -> */, -/* pos 035e: 469 */ 0xE4 /* 'd' -> */, -/* pos 035f: 470 */ 0xBA /* ':' -> */, -/* pos 0360: 471 */ 0x00, 0x39 /* - terminal marker 57 - */, -/* pos 0362: 472 */ 0xEE /* 'n' -> */, -/* pos 0363: 473 */ 0xEB /* 'k' -> */, -/* pos 0364: 474 */ 0xBA /* ':' -> */, -/* pos 0365: 475 */ 0x00, 0x3A /* - terminal marker 58 - */, -/* pos 0367: 476 */ 0xE3 /* 'c' -> */, -/* pos 0368: 477 */ 0xE1 /* 'a' -> */, -/* pos 0369: 478 */ 0xF4 /* 't' -> */, -/* pos 036a: 479 */ 0xE9 /* 'i' -> */, -/* pos 036b: 480 */ 0xEF /* 'o' -> */, -/* pos 036c: 481 */ 0xEE /* 'n' -> */, -/* pos 036d: 482 */ 0xBA /* ':' -> */, -/* pos 036e: 483 */ 0x00, 0x3B /* - terminal marker 59 - */, -/* pos 0370: 484 */ 0xE1 /* 'a' -> */, -/* pos 0371: 485 */ 0xF8 /* 'x' -> */, -/* pos 0372: 486 */ 0xAD /* '-' -> */, -/* pos 0373: 487 */ 0xE6 /* 'f' -> */, -/* pos 0374: 488 */ 0xEF /* 'o' -> */, -/* pos 0375: 489 */ 0xF2 /* 'r' -> */, -/* pos 0376: 490 */ 0xF7 /* 'w' -> */, -/* pos 0377: 491 */ 0xE1 /* 'a' -> */, -/* pos 0378: 492 */ 0xF2 /* 'r' -> */, -/* pos 0379: 493 */ 0xE4 /* 'd' -> */, -/* pos 037a: 494 */ 0xF3 /* 's' -> */, -/* pos 037b: 495 */ 0xBA /* ':' -> */, -/* pos 037c: 496 */ 0x00, 0x3C /* - terminal marker 60 - */, -/* pos 037e: 497 */ 0xF8 /* 'x' -> */, -/* pos 037f: 498 */ 0xF9 /* 'y' -> */, -/* pos 0380: 499 */ 0x2D /* '-' */, 0x07, 0x00 /* (to 0x0387 state 500) */, - 0x20 /* ' ' */, 0xBB, 0x00 /* (to 0x043E state 649) */, - 0x08, /* fail */ -/* pos 0387: 500 */ 0xE1 /* 'a' -> */, -/* pos 0388: 501 */ 0xF5 /* 'u' -> */, -/* pos 0389: 502 */ 0xF4 /* 't' -> */, -/* pos 038a: 503 */ 0xE8 /* 'h' -> */, -/* pos 038b: 504 */ 0x65 /* 'e' */, 0x07, 0x00 /* (to 0x0392 state 505) */, - 0x6F /* 'o' */, 0x0E, 0x00 /* (to 0x039C state 514) */, - 0x08, /* fail */ -/* pos 0392: 505 */ 0xEE /* 'n' -> */, -/* pos 0393: 506 */ 0xF4 /* 't' -> */, -/* pos 0394: 507 */ 0xE9 /* 'i' -> */, -/* pos 0395: 508 */ 0xE3 /* 'c' -> */, -/* pos 0396: 509 */ 0xE1 /* 'a' -> */, -/* pos 0397: 510 */ 0xF4 /* 't' -> */, -/* pos 0398: 511 */ 0xE5 /* 'e' -> */, -/* pos 0399: 512 */ 0xBA /* ':' -> */, -/* pos 039a: 513 */ 0x00, 0x3D /* - terminal marker 61 - */, -/* pos 039c: 514 */ 0xF2 /* 'r' -> */, -/* pos 039d: 515 */ 0xE9 /* 'i' -> */, -/* pos 039e: 516 */ 0xFA /* 'z' -> */, -/* pos 039f: 517 */ 0xE1 /* 'a' -> */, -/* pos 03a0: 518 */ 0xF4 /* 't' -> */, -/* pos 03a1: 519 */ 0xE9 /* 'i' -> */, -/* pos 03a2: 520 */ 0xEF /* 'o' -> */, -/* pos 03a3: 521 */ 0xEE /* 'n' -> */, -/* pos 03a4: 522 */ 0xBA /* ':' -> */, -/* pos 03a5: 523 */ 0x00, 0x3E /* - terminal marker 62 - */, -/* pos 03a7: 524 */ 0xE5 /* 'e' -> */, -/* pos 03a8: 525 */ 0xF3 /* 's' -> */, -/* pos 03a9: 526 */ 0xE8 /* 'h' -> */, -/* pos 03aa: 527 */ 0xBA /* ':' -> */, -/* pos 03ab: 528 */ 0x00, 0x3F /* - terminal marker 63 - */, -/* pos 03ad: 529 */ 0xF2 /* 'r' -> */, -/* pos 03ae: 530 */ 0xF9 /* 'y' -> */, -/* pos 03af: 531 */ 0xAD /* '-' -> */, -/* pos 03b0: 532 */ 0xE1 /* 'a' -> */, -/* pos 03b1: 533 */ 0xE6 /* 'f' -> */, -/* pos 03b2: 534 */ 0xF4 /* 't' -> */, -/* pos 03b3: 535 */ 0xE5 /* 'e' -> */, -/* pos 03b4: 536 */ 0xF2 /* 'r' -> */, -/* pos 03b5: 537 */ 0xBA /* ':' -> */, -/* pos 03b6: 538 */ 0x00, 0x40 /* - terminal marker 64 - */, -/* pos 03b8: 539 */ 0xF6 /* 'v' -> */, -/* pos 03b9: 540 */ 0xE5 /* 'e' -> */, -/* pos 03ba: 541 */ 0xF2 /* 'r' -> */, -/* pos 03bb: 542 */ 0xBA /* ':' -> */, -/* pos 03bc: 543 */ 0x00, 0x41 /* - terminal marker 65 - */, -/* pos 03be: 544 */ 0xAD /* '-' -> */, -/* pos 03bf: 545 */ 0xE3 /* 'c' -> */, -/* pos 03c0: 546 */ 0xEF /* 'o' -> */, -/* pos 03c1: 547 */ 0xEF /* 'o' -> */, -/* pos 03c2: 548 */ 0xEB /* 'k' -> */, -/* pos 03c3: 549 */ 0xE9 /* 'i' -> */, -/* pos 03c4: 550 */ 0xE5 /* 'e' -> */, -/* pos 03c5: 551 */ 0xBA /* ':' -> */, -/* pos 03c6: 552 */ 0x00, 0x42 /* - terminal marker 66 - */, -/* pos 03c8: 553 */ 0xF2 /* 'r' -> */, -/* pos 03c9: 554 */ 0xE9 /* 'i' -> */, -/* pos 03ca: 555 */ 0xE3 /* 'c' -> */, -/* pos 03cb: 556 */ 0xF4 /* 't' -> */, -/* pos 03cc: 557 */ 0xAD /* '-' -> */, -/* pos 03cd: 558 */ 0xF4 /* 't' -> */, -/* pos 03ce: 559 */ 0xF2 /* 'r' -> */, -/* pos 03cf: 560 */ 0xE1 /* 'a' -> */, -/* pos 03d0: 561 */ 0xEE /* 'n' -> */, -/* pos 03d1: 562 */ 0xF3 /* 's' -> */, -/* pos 03d2: 563 */ 0xF0 /* 'p' -> */, -/* pos 03d3: 564 */ 0xEF /* 'o' -> */, -/* pos 03d4: 565 */ 0xF2 /* 'r' -> */, -/* pos 03d5: 566 */ 0xF4 /* 't' -> */, -/* pos 03d6: 567 */ 0xAD /* '-' -> */, -/* pos 03d7: 568 */ 0xF3 /* 's' -> */, -/* pos 03d8: 569 */ 0xE5 /* 'e' -> */, -/* pos 03d9: 570 */ 0xE3 /* 'c' -> */, -/* pos 03da: 571 */ 0xF5 /* 'u' -> */, -/* pos 03db: 572 */ 0xF2 /* 'r' -> */, -/* pos 03dc: 573 */ 0xE9 /* 'i' -> */, -/* pos 03dd: 574 */ 0xF4 /* 't' -> */, -/* pos 03de: 575 */ 0xF9 /* 'y' -> */, -/* pos 03df: 576 */ 0xBA /* ':' -> */, -/* pos 03e0: 577 */ 0x00, 0x43 /* - terminal marker 67 - */, -/* pos 03e2: 578 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x03E9 state 579) */, - 0x65 /* 'e' */, 0x84, 0x00 /* (to 0x0469 state 680) */, - 0x08, /* fail */ -/* pos 03e9: 579 */ 0xE1 /* 'a' -> */, -/* pos 03ea: 580 */ 0xEE /* 'n' -> */, -/* pos 03eb: 581 */ 0xF3 /* 's' -> */, -/* pos 03ec: 582 */ 0xE6 /* 'f' -> */, -/* pos 03ed: 583 */ 0xE5 /* 'e' -> */, -/* pos 03ee: 584 */ 0xF2 /* 'r' -> */, -/* pos 03ef: 585 */ 0xAD /* '-' -> */, -/* pos 03f0: 586 */ 0xE5 /* 'e' -> */, -/* pos 03f1: 587 */ 0xEE /* 'n' -> */, -/* pos 03f2: 588 */ 0xE3 /* 'c' -> */, -/* pos 03f3: 589 */ 0xEF /* 'o' -> */, -/* pos 03f4: 590 */ 0xE4 /* 'd' -> */, -/* pos 03f5: 591 */ 0xE9 /* 'i' -> */, -/* pos 03f6: 592 */ 0xEE /* 'n' -> */, -/* pos 03f7: 593 */ 0xE7 /* 'g' -> */, -/* pos 03f8: 594 */ 0xBA /* ':' -> */, -/* pos 03f9: 595 */ 0x00, 0x44 /* - terminal marker 68 - */, -/* pos 03fb: 596 */ 0xE5 /* 'e' -> */, -/* pos 03fc: 597 */ 0xF2 /* 'r' -> */, -/* pos 03fd: 598 */ 0xAD /* '-' -> */, -/* pos 03fe: 599 */ 0xE1 /* 'a' -> */, -/* pos 03ff: 600 */ 0xE7 /* 'g' -> */, -/* pos 0400: 601 */ 0xE5 /* 'e' -> */, -/* pos 0401: 602 */ 0xEE /* 'n' -> */, -/* pos 0402: 603 */ 0xF4 /* 't' -> */, -/* pos 0403: 604 */ 0xBA /* ':' -> */, -/* pos 0404: 605 */ 0x00, 0x45 /* - terminal marker 69 - */, -/* pos 0406: 606 */ 0x61 /* 'a' */, 0x07, 0x00 /* (to 0x040D state 607) */, - 0x69 /* 'i' */, 0x09, 0x00 /* (to 0x0412 state 611) */, - 0x08, /* fail */ -/* pos 040d: 607 */ 0xF2 /* 'r' -> */, -/* pos 040e: 608 */ 0xF9 /* 'y' -> */, -/* pos 040f: 609 */ 0xBA /* ':' -> */, -/* pos 0410: 610 */ 0x00, 0x46 /* - terminal marker 70 - */, -/* pos 0412: 611 */ 0xE1 /* 'a' -> */, -/* pos 0413: 612 */ 0xBA /* ':' -> */, -/* pos 0414: 613 */ 0x00, 0x47 /* - terminal marker 71 - */, -/* pos 0416: 614 */ 0xF7 /* 'w' -> */, -/* pos 0417: 615 */ 0xF7 /* 'w' -> */, -/* pos 0418: 616 */ 0xAD /* '-' -> */, -/* pos 0419: 617 */ 0xE1 /* 'a' -> */, -/* pos 041a: 618 */ 0xF5 /* 'u' -> */, -/* pos 041b: 619 */ 0xF4 /* 't' -> */, -/* pos 041c: 620 */ 0xE8 /* 'h' -> */, -/* pos 041d: 621 */ 0xE5 /* 'e' -> */, -/* pos 041e: 622 */ 0xEE /* 'n' -> */, -/* pos 041f: 623 */ 0xF4 /* 't' -> */, -/* pos 0420: 624 */ 0xE9 /* 'i' -> */, -/* pos 0421: 625 */ 0xE3 /* 'c' -> */, -/* pos 0422: 626 */ 0xE1 /* 'a' -> */, -/* pos 0423: 627 */ 0xF4 /* 't' -> */, -/* pos 0424: 628 */ 0xE5 /* 'e' -> */, -/* pos 0425: 629 */ 0xBA /* ':' -> */, -/* pos 0426: 630 */ 0x00, 0x48 /* - terminal marker 72 - */, -/* pos 0428: 631 */ 0xF4 /* 't' -> */, -/* pos 0429: 632 */ 0xE3 /* 'c' -> */, -/* pos 042a: 633 */ 0xE8 /* 'h' -> */, -/* pos 042b: 634 */ 0x00, 0x49 /* - terminal marker 73 - */, -/* pos 042d: 635 */ 0xF4 /* 't' -> */, -/* pos 042e: 636 */ 0x00, 0x4A /* - terminal marker 74 - */, -/* pos 0430: 637 */ 0xEC /* 'l' -> */, -/* pos 0431: 638 */ 0xE5 /* 'e' -> */, -/* pos 0432: 639 */ 0xF4 /* 't' -> */, -/* pos 0433: 640 */ 0xE5 /* 'e' -> */, -/* pos 0434: 641 */ 0x00, 0x4B /* - terminal marker 75 - */, -/* pos 0436: 642 */ 0xE9 /* 'i' -> */, -/* pos 0437: 643 */ 0xAD /* '-' -> */, -/* pos 0438: 644 */ 0xE1 /* 'a' -> */, -/* pos 0439: 645 */ 0xF2 /* 'r' -> */, -/* pos 043a: 646 */ 0xE7 /* 'g' -> */, -/* pos 043b: 647 */ 0xF3 /* 's' -> */, -/* pos 043c: 648 */ 0x00, 0x4C /* - terminal marker 76 - */, -/* pos 043e: 649 */ 0x00, 0x4D /* - terminal marker 77 - */, -/* pos 0440: 650 */ 0xAD /* '-' -> */, -/* pos 0441: 651 */ 0x72 /* 'r' */, 0x07, 0x00 /* (to 0x0448 state 652) */, - 0x66 /* 'f' */, 0x10, 0x00 /* (to 0x0454 state 662) */, - 0x08, /* fail */ -/* pos 0448: 652 */ 0xE5 /* 'e' -> */, -/* pos 0449: 653 */ 0xE1 /* 'a' -> */, -/* pos 044a: 654 */ 0xEC /* 'l' -> */, -/* pos 044b: 655 */ 0xAD /* '-' -> */, -/* pos 044c: 656 */ 0xE9 /* 'i' -> */, -/* pos 044d: 657 */ 0xF0 /* 'p' -> */, -/* pos 044e: 658 */ 0xBA /* ':' -> */, -/* pos 044f: 659 */ 0x00, 0x4E /* - terminal marker 78 - */, -/* pos 0451: 660 */ 0xA0 /* ' ' -> */, -/* pos 0452: 661 */ 0x00, 0x4F /* - terminal marker 79 - */, -/* pos 0454: 662 */ 0xEF /* 'o' -> */, -/* pos 0455: 663 */ 0xF2 /* 'r' -> */, -/* pos 0456: 664 */ 0xF7 /* 'w' -> */, -/* pos 0457: 665 */ 0xE1 /* 'a' -> */, -/* pos 0458: 666 */ 0xF2 /* 'r' -> */, -/* pos 0459: 667 */ 0xE4 /* 'd' -> */, -/* pos 045a: 668 */ 0xE5 /* 'e' -> */, -/* pos 045b: 669 */ 0xE4 /* 'd' -> */, -/* pos 045c: 670 */ 0xAD /* '-' -> */, -/* pos 045d: 671 */ 0xE6 /* 'f' -> */, -/* pos 045e: 672 */ 0xEF /* 'o' -> */, -/* pos 045f: 673 */ 0xF2 /* 'r' -> */, -/* pos 0460: 674 */ 0x00, 0x50 /* - terminal marker 80 - */, -/* pos 0462: 675 */ 0x00, 0x51 /* - terminal marker 81 - */, -/* pos 0464: 676 */ 0xE1 /* 'a' -> */, -/* pos 0465: 677 */ 0xE4 /* 'd' -> */, -/* pos 0466: 678 */ 0xA0 /* ' ' -> */, -/* pos 0467: 679 */ 0x00, 0x52 /* - terminal marker 82 - */, -/* pos 0469: 680 */ 0xBA /* ':' -> */, -/* pos 046a: 681 */ 0x00, 0x53 /* - terminal marker 83 - */, -/* total size 1132 bytes */ diff --git a/thirdparty/lws/mbedtls_verify.diff b/thirdparty/lws/mbedtls_verify.diff deleted file mode 100644 index d320645d67..0000000000 --- a/thirdparty/lws/mbedtls_verify.diff +++ /dev/null @@ -1,74 +0,0 @@ -diff --git a/thirdparty/lws/client/ssl-client.c b/thirdparty/lws/client/ssl-client.c -index 6626e0844..962c6e3cb 100644 ---- a/thirdparty/lws/client/ssl-client.c -+++ b/thirdparty/lws/client/ssl-client.c -@@ -176,11 +176,7 @@ lws_ssl_client_bio_create(struct lws *wsi) - #endif - #else - #if defined(LWS_WITH_MBEDTLS) -- if (wsi->vhost->x509_client_CA) -- SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback); -- else -- SSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, OpenSSL_client_verify_callback); -- -+ SSL_set_verify(wsi->ssl, SSL_VERIFY_PEER, OpenSSL_client_verify_callback); - #else - #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME - SSL_set_tlsext_host_name(wsi->ssl, hostname); -diff --git a/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c b/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c -index 63504919c..4e3d61109 100644 ---- a/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c -+++ b/thirdparty/lws/mbedtls_wrapper/platform/ssl_pm.c -@@ -218,7 +218,7 @@ static int ssl_pm_reload_crt(SSL *ssl) - struct x509_pm *crt_pm = (struct x509_pm *)ssl->cert->x509->x509_pm; - - if (ssl->verify_mode == SSL_VERIFY_PEER) -- mode = MBEDTLS_SSL_VERIFY_REQUIRED; -+ mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - else if (ssl->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT) - mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - else if (ssl->verify_mode == SSL_VERIFY_CLIENT_ONCE) -@@ -712,11 +712,39 @@ long ssl_pm_get_verify_result(const SSL *ssl) - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl); -- if (ret) { -- SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "mbedtls_ssl_get_verify_result() return 0x%x", ret); -+ -+ if (!ret) -+ return X509_V_OK; -+ -+ if (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED || -+ (ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED)) -+ // Allows us to use LCCSCF_ALLOW_SELFSIGNED to skip verification -+ verify_result = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN; -+ -+ else if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) -+ verify_result = X509_V_ERR_HOSTNAME_MISMATCH; -+ -+ else if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) || -+ (ret & MBEDTLS_X509_BADCRL_BAD_KEY)) -+ verify_result = X509_V_ERR_CA_KEY_TOO_SMALL; -+ -+ else if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) || -+ (ret & MBEDTLS_X509_BADCRL_BAD_MD)) -+ verify_result = X509_V_ERR_CA_MD_TOO_WEAK; -+ -+ else if ((ret & MBEDTLS_X509_BADCERT_FUTURE) || -+ (ret & MBEDTLS_X509_BADCRL_FUTURE)) -+ verify_result = X509_V_ERR_CERT_NOT_YET_VALID; -+ -+ else if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) || -+ (ret & MBEDTLS_X509_BADCRL_EXPIRED)) -+ verify_result = X509_V_ERR_CERT_HAS_EXPIRED; -+ -+ else - verify_result = X509_V_ERR_UNSPECIFIED; -- } else -- verify_result = X509_V_OK; -+ -+ SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, -+ "mbedtls_ssl_get_verify_result() return 0x%x", ret); - - return verify_result; - } diff --git a/thirdparty/lws/misc/lejp.h b/thirdparty/lws/misc/lejp.h deleted file mode 100644 index 0b37bb3e42..0000000000 --- a/thirdparty/lws/misc/lejp.h +++ /dev/null @@ -1,232 +0,0 @@ -#include "libwebsockets.h" -struct lejp_ctx; - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(_x) (sizeof(_x) / sizeof(_x[0])) -#endif -#define LEJP_FLAG_WS_KEEP 64 -#define LEJP_FLAG_WS_COMMENTLINE 32 - -enum lejp_states { - LEJP_IDLE = 0, - LEJP_MEMBERS = 1, - LEJP_M_P = 2, - LEJP_MP_STRING = LEJP_FLAG_WS_KEEP | 3, - LEJP_MP_STRING_ESC = LEJP_FLAG_WS_KEEP | 4, - LEJP_MP_STRING_ESC_U1 = LEJP_FLAG_WS_KEEP | 5, - LEJP_MP_STRING_ESC_U2 = LEJP_FLAG_WS_KEEP | 6, - LEJP_MP_STRING_ESC_U3 = LEJP_FLAG_WS_KEEP | 7, - LEJP_MP_STRING_ESC_U4 = LEJP_FLAG_WS_KEEP | 8, - LEJP_MP_DELIM = 9, - LEJP_MP_VALUE = 10, - LEJP_MP_VALUE_NUM_INT = LEJP_FLAG_WS_KEEP | 11, - LEJP_MP_VALUE_NUM_EXP = LEJP_FLAG_WS_KEEP | 12, - LEJP_MP_VALUE_TOK = LEJP_FLAG_WS_KEEP | 13, - LEJP_MP_COMMA_OR_END = 14, - LEJP_MP_ARRAY_END = 15, -}; - -enum lejp_reasons { - LEJP_CONTINUE = -1, - LEJP_REJECT_IDLE_NO_BRACE = -2, - LEJP_REJECT_MEMBERS_NO_CLOSE = -3, - LEJP_REJECT_MP_NO_OPEN_QUOTE = -4, - LEJP_REJECT_MP_STRING_UNDERRUN = -5, - LEJP_REJECT_MP_ILLEGAL_CTRL = -6, - LEJP_REJECT_MP_STRING_ESC_ILLEGAL_ESC = -7, - LEJP_REJECT_ILLEGAL_HEX = -8, - LEJP_REJECT_MP_DELIM_MISSING_COLON = -9, - LEJP_REJECT_MP_DELIM_BAD_VALUE_START = -10, - LEJP_REJECT_MP_VAL_NUM_INT_NO_FRAC = -11, - LEJP_REJECT_MP_VAL_NUM_FORMAT = -12, - LEJP_REJECT_MP_VAL_NUM_EXP_BAD_EXP = -13, - LEJP_REJECT_MP_VAL_TOK_UNKNOWN = -14, - LEJP_REJECT_MP_C_OR_E_UNDERF = -15, - LEJP_REJECT_MP_C_OR_E_NOTARRAY = -16, - LEJP_REJECT_MP_ARRAY_END_MISSING = -17, - LEJP_REJECT_STACK_OVERFLOW = -18, - LEJP_REJECT_MP_DELIM_ISTACK = -19, - LEJP_REJECT_NUM_TOO_LONG = -20, - LEJP_REJECT_MP_C_OR_E_NEITHER = -21, - LEJP_REJECT_UNKNOWN = -22, - LEJP_REJECT_CALLBACK = -23 -}; - -#define LEJP_FLAG_CB_IS_VALUE 64 - -enum lejp_callbacks { - LEJPCB_CONSTRUCTED = 0, - LEJPCB_DESTRUCTED = 1, - - LEJPCB_START = 2, - LEJPCB_COMPLETE = 3, - LEJPCB_FAILED = 4, - - LEJPCB_PAIR_NAME = 5, - - LEJPCB_VAL_TRUE = LEJP_FLAG_CB_IS_VALUE | 6, - LEJPCB_VAL_FALSE = LEJP_FLAG_CB_IS_VALUE | 7, - LEJPCB_VAL_NULL = LEJP_FLAG_CB_IS_VALUE | 8, - LEJPCB_VAL_NUM_INT = LEJP_FLAG_CB_IS_VALUE | 9, - LEJPCB_VAL_NUM_FLOAT = LEJP_FLAG_CB_IS_VALUE | 10, - LEJPCB_VAL_STR_START = 11, /* notice handle separately */ - LEJPCB_VAL_STR_CHUNK = LEJP_FLAG_CB_IS_VALUE | 12, - LEJPCB_VAL_STR_END = LEJP_FLAG_CB_IS_VALUE | 13, - - LEJPCB_ARRAY_START = 14, - LEJPCB_ARRAY_END = 15, - - LEJPCB_OBJECT_START = 16, - LEJPCB_OBJECT_END = 17 -}; - -/** - * _lejp_callback() - User parser actions - * \param ctx: LEJP context - * \param reason: Callback reason - * - * Your user callback is associated with the context at construction time, - * and receives calls as the parsing progresses. - * - * All of the callbacks may be ignored and just return 0. - * - * The reasons it might get called, found in @reason, are: - * - * LEJPCB_CONSTRUCTED: The context was just constructed... you might want to - * perform one-time allocation for the life of the context. - * - * LEJPCB_DESTRUCTED: The context is being destructed... if you made any - * allocations at construction-time, you can free them now - * - * LEJPCB_START: Parsing is beginning at the first byte of input - * - * LEJPCB_COMPLETE: Parsing has completed successfully. You'll get a 0 or - * positive return code from lejp_parse indicating the - * amount of unused bytes left in the input buffer - * - * LEJPCB_FAILED: Parsing failed. You'll get a negative error code - * returned from lejp_parse - * - * LEJPCB_PAIR_NAME: When a "name":"value" pair has had the name parsed, - * this callback occurs. You can find the new name at - * the end of ctx->path[] - * - * LEJPCB_VAL_TRUE: The "true" value appeared - * - * LEJPCB_VAL_FALSE: The "false" value appeared - * - * LEJPCB_VAL_NULL: The "null" value appeared - * - * LEJPCB_VAL_NUM_INT: A string representing an integer is in ctx->buf - * - * LEJPCB_VAL_NUM_FLOAT: A string representing a float is in ctx->buf - * - * LEJPCB_VAL_STR_START: We are starting to parse a string, no data yet - * - * LEJPCB_VAL_STR_CHUNK: We parsed LEJP_STRING_CHUNK -1 bytes of string data in - * ctx->buf, which is as much as we can buffer, so we are - * spilling it. If all your strings are less than - * LEJP_STRING_CHUNK - 1 bytes, you will never see this - * callback. - * - * LEJPCB_VAL_STR_END: String parsing has completed, the last chunk of the - * string is in ctx->buf. - * - * LEJPCB_ARRAY_START: An array started - * - * LEJPCB_ARRAY_END: An array ended - * - * LEJPCB_OBJECT_START: An object started - * - * LEJPCB_OBJECT_END: An object ended - */ -LWS_EXTERN signed char _lejp_callback(struct lejp_ctx *ctx, char reason); - -typedef signed char (*lejp_callback)(struct lejp_ctx *ctx, char reason); - -#ifndef LEJP_MAX_DEPTH -#define LEJP_MAX_DEPTH 12 -#endif -#ifndef LEJP_MAX_INDEX_DEPTH -#define LEJP_MAX_INDEX_DEPTH 5 -#endif -#ifndef LEJP_MAX_PATH -#define LEJP_MAX_PATH 128 -#endif -#ifndef LEJP_STRING_CHUNK -/* must be >= 30 to assemble floats */ -#define LEJP_STRING_CHUNK 255 -#endif - -enum num_flags { - LEJP_SEEN_MINUS = (1 << 0), - LEJP_SEEN_POINT = (1 << 1), - LEJP_SEEN_POST_POINT = (1 << 2), - LEJP_SEEN_EXP = (1 << 3) -}; - -struct _lejp_stack { - char s; /* lejp_state stack*/ - char p; /* path length */ - char i; /* index array length */ - char b; /* user bitfield */ -}; - -struct lejp_ctx { - - /* sorted by type for most compact alignment - * - * pointers - */ - - signed char (*callback)(struct lejp_ctx *ctx, char reason); - void *user; - const char * const *paths; - - /* arrays */ - - struct _lejp_stack st[LEJP_MAX_DEPTH]; - unsigned short i[LEJP_MAX_INDEX_DEPTH]; /* index array */ - unsigned short wild[LEJP_MAX_INDEX_DEPTH]; /* index array */ - char path[LEJP_MAX_PATH]; - char buf[LEJP_STRING_CHUNK]; - - /* int */ - - unsigned int line; - - /* short */ - - unsigned short uni; - - /* char */ - - unsigned char npos; - unsigned char dcount; - unsigned char f; - unsigned char sp; /* stack head */ - unsigned char ipos; /* index stack depth */ - unsigned char ppos; - unsigned char count_paths; - unsigned char path_match; - unsigned char path_match_len; - unsigned char wildcount; -}; - -LWS_VISIBLE LWS_EXTERN void -lejp_construct(struct lejp_ctx *ctx, - signed char (*callback)(struct lejp_ctx *ctx, char reason), - void *user, const char * const *paths, unsigned char paths_count); - -LWS_VISIBLE LWS_EXTERN void -lejp_destruct(struct lejp_ctx *ctx); - -LWS_VISIBLE LWS_EXTERN int -lejp_parse(struct lejp_ctx *ctx, const unsigned char *json, int len); - -LWS_VISIBLE LWS_EXTERN void -lejp_change_callback(struct lejp_ctx *ctx, - signed char (*callback)(struct lejp_ctx *ctx, char reason)); - -LWS_VISIBLE LWS_EXTERN int -lejp_get_wildcard(struct lejp_ctx *ctx, int wildcard, char *dest, int len); diff --git a/thirdparty/lws/output.c b/thirdparty/lws/output.c deleted file mode 100644 index 375ff3ef99..0000000000 --- a/thirdparty/lws/output.c +++ /dev/null @@ -1,883 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -static int -lws_0405_frame_mask_generate(struct lws *wsi) -{ -#if 0 - wsi->u.ws.mask[0] = 0; - wsi->u.ws.mask[1] = 0; - wsi->u.ws.mask[2] = 0; - wsi->u.ws.mask[3] = 0; -#else - int n; - /* fetch the per-frame nonce */ - - n = lws_get_random(lws_get_context(wsi), wsi->u.ws.mask, 4); - if (n != 4) { - lwsl_parser("Unable to read from random device %s %d\n", - SYSTEM_RANDOM_FILEPATH, n); - return 1; - } -#endif - /* start masking from first byte of masking key buffer */ - wsi->u.ws.mask_idx = 0; - - return 0; -} - -/* - * notice this returns number of bytes consumed, or -1 - */ -int lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len) -{ - struct lws_context *context = lws_get_context(wsi); - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - size_t real_len = len; - unsigned int n; - int m; - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_WRITE, 1); - - if (!len) - return 0; - /* just ignore sends after we cleared the truncation buffer */ - if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE && - !wsi->trunc_len) - return len; - - if (wsi->trunc_len && (buf < wsi->trunc_alloc || - buf > (wsi->trunc_alloc + wsi->trunc_len + wsi->trunc_offset))) { - char dump[20]; - strncpy(dump, (char *)buf, sizeof(dump) - 1); - dump[sizeof(dump) - 1] = '\0'; -#if defined(LWS_WITH_ESP8266) - lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n", - wsi, (unsigned long)len, dump); -#else - lwsl_err("****** %p: Sending new %lu (%s), pending truncated ...\n" - " It's illegal to do an lws_write outside of\n" - " the writable callback: fix your code\n", - wsi, (unsigned long)len, dump); -#endif - assert(0); - - return -1; - } - - m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_DO_SEND, &buf, len); - if (m < 0) - return -1; - if (m) /* handled */ { - n = m; - goto handle_truncated_send; - } - - if (!wsi->http2_substream && !lws_socket_is_valid(wsi->desc.sockfd)) - lwsl_warn("** error invalid sock but expected to send\n"); - - /* limit sending */ - if (wsi->protocol->tx_packet_size) - n = wsi->protocol->tx_packet_size; - else { - n = wsi->protocol->rx_buffer_size; - if (!n) - n = context->pt_serv_buf_size; - } - n += LWS_PRE + 4; - if (n > len) - n = len; -#if defined(LWS_WITH_ESP8266) - if (wsi->pending_send_completion) { - n = 0; - goto handle_truncated_send; - } -#endif - - /* nope, send it on the socket directly */ - lws_latency_pre(context, wsi); - n = lws_ssl_capable_write(wsi, buf, n); - lws_latency(context, wsi, "send lws_issue_raw", n, n == len); - - switch (n) { - case LWS_SSL_CAPABLE_ERROR: - /* we're going to close, let close know sends aren't possible */ - wsi->socket_is_permanently_unusable = 1; - return -1; - case LWS_SSL_CAPABLE_MORE_SERVICE: - /* nothing got sent, not fatal, retry the whole thing later */ - n = 0; - break; - } - -handle_truncated_send: - /* - * we were already handling a truncated send? - */ - if (wsi->trunc_len) { - lwsl_info("%p partial adv %d (vs %ld)\n", wsi, n, (long)real_len); - wsi->trunc_offset += n; - wsi->trunc_len -= n; - - if (!wsi->trunc_len) { - lwsl_info("***** %p partial send completed\n", wsi); - /* done with it, but don't free it */ - n = real_len; - if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) { - lwsl_info("***** %p signalling to close now\n", wsi); - return -1; /* retry closing now */ - } - } - /* always callback on writeable */ - lws_callback_on_writable(wsi); - - return n; - } - - if ((unsigned int)n == real_len) - /* what we just sent went out cleanly */ - return n; - - /* - * Newly truncated send. Buffer the remainder (it will get - * first priority next time the socket is writable) - */ - lwsl_debug("%p new partial sent %d from %lu total\n", wsi, n, - (unsigned long)real_len); - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITE_PARTIALS, 1); - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, n); - - /* - * - if we still have a suitable malloc lying around, use it - * - or, if too small, reallocate it - * - or, if no buffer, create it - */ - if (!wsi->trunc_alloc || real_len - n > wsi->trunc_alloc_len) { - lws_free(wsi->trunc_alloc); - - wsi->trunc_alloc_len = real_len - n; - wsi->trunc_alloc = lws_malloc(real_len - n, "truncated send alloc"); - if (!wsi->trunc_alloc) { - lwsl_err("truncated send: unable to malloc %lu\n", - (unsigned long)(real_len - n)); - return -1; - } - } - wsi->trunc_offset = 0; - wsi->trunc_len = real_len - n; - memcpy(wsi->trunc_alloc, buf + n, real_len - n); - - /* since something buffered, force it to get another chance to send */ - lws_callback_on_writable(wsi); - - return real_len; -} - -LWS_VISIBLE int lws_write(struct lws *wsi, unsigned char *buf, size_t len, - enum lws_write_protocol wp) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - int masked7 = (wsi->mode == LWSCM_WS_CLIENT); - unsigned char is_masked_bit = 0; - unsigned char *dropmask = NULL; - struct lws_tokens eff_buf; - size_t orig_len = len; - int pre = 0, n; - - if (wsi->parent_carries_io) { - struct lws_write_passthru pas; - - pas.buf = buf; - pas.len = len; - pas.wp = wp; - pas.wsi = wsi; - - if (wsi->parent->protocol->callback(wsi->parent, - LWS_CALLBACK_CHILD_WRITE_VIA_PARENT, - wsi->parent->user_space, - (void *)&pas, 0)) - return 1; - - return len; - } - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_API_LWS_WRITE, 1); - - if ((int)len < 0) { - lwsl_err("%s: suspicious len int %d, ulong %lu\n", __func__, - (int)len, (unsigned long)len); - return -1; - } - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_B_WRITE, len); - -#ifdef LWS_WITH_ACCESS_LOG - wsi->access_log.sent += len; -#endif - if (wsi->vhost) - wsi->vhost->conn_stats.tx += len; - - if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) { - /* remove us from the list */ - struct lws **w = &pt->tx_draining_ext_list; - - wsi->u.ws.tx_draining_ext = 0; - /* remove us from context draining ext list */ - while (*w) { - if (*w == wsi) { - *w = wsi->u.ws.tx_draining_ext_list; - break; - } - w = &((*w)->u.ws.tx_draining_ext_list); - } - wsi->u.ws.tx_draining_ext_list = NULL; - wp = (wsi->u.ws.tx_draining_stashed_wp & 0xc0) | - LWS_WRITE_CONTINUATION; - - lwsl_ext("FORCED draining wp to 0x%02X\n", wp); - } - - lws_restart_ws_ping_pong_timer(wsi); - - if ((wp & 0x1f) == LWS_WRITE_HTTP || - (wp & 0x1f) == LWS_WRITE_HTTP_FINAL || - (wp & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION || - (wp & 0x1f) == LWS_WRITE_HTTP_HEADERS) - goto send_raw; - - /* if not in a state to send stuff, then just send nothing */ - - if (wsi->state != LWSS_ESTABLISHED && - ((wsi->state != LWSS_RETURNED_CLOSE_ALREADY && - wsi->state != LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION && - wsi->state != LWSS_AWAITING_CLOSE_ACK) || - wp != LWS_WRITE_CLOSE)) { - lwsl_debug("binning\n"); - return 0; - } - - /* if we are continuing a frame that already had its header done */ - - if (wsi->u.ws.inside_frame) { - lwsl_debug("INSIDE FRAME\n"); - goto do_more_inside_frame; - } - - wsi->u.ws.clean_buffer = 1; - - /* - * give a chance to the extensions to modify payload - * the extension may decide to produce unlimited payload erratically - * (eg, compression extension), so we require only that if he produces - * something, it will be a complete fragment of the length known at - * the time (just the fragment length known), and if he has - * more we will come back next time he is writeable and allow him to - * produce more fragments until he's drained. - * - * This allows what is sent each time it is writeable to be limited to - * a size that can be sent without partial sends or blocking, allows - * interleaving of control frames and other connection service. - */ - eff_buf.token = (char *)buf; - eff_buf.token_len = len; - - switch ((int)wp) { - case LWS_WRITE_PING: - case LWS_WRITE_PONG: - case LWS_WRITE_CLOSE: - break; - default: - lwsl_debug("LWS_EXT_CB_PAYLOAD_TX\n"); - n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &eff_buf, wp); - if (n < 0) - return -1; - - if (n && eff_buf.token_len) { - lwsl_debug("drain len %d\n", (int)eff_buf.token_len); - /* extension requires further draining */ - wsi->u.ws.tx_draining_ext = 1; - wsi->u.ws.tx_draining_ext_list = pt->tx_draining_ext_list; - pt->tx_draining_ext_list = wsi; - /* we must come back to do more */ - lws_callback_on_writable(wsi); - /* - * keep a copy of the write type for the overall - * action that has provoked generation of these - * fragments, so the last guy can use its FIN state. - */ - wsi->u.ws.tx_draining_stashed_wp = wp; - /* this is definitely not actually the last fragment - * because the extension asserted he has more coming - * So make sure this intermediate one doesn't go out - * with a FIN. - */ - wp |= LWS_WRITE_NO_FIN; - } - - if (eff_buf.token_len && wsi->u.ws.stashed_write_pending) { - wsi->u.ws.stashed_write_pending = 0; - wp = (wp &0xc0) | (int)wsi->u.ws.stashed_write_type; - } - } - - /* - * an extension did something we need to keep... for example, if - * compression extension, it has already updated its state according - * to this being issued - */ - if ((char *)buf != eff_buf.token) { - /* - * ext might eat it, but not have anything to issue yet. - * In that case we have to follow his lead, but stash and - * replace the write type that was lost here the first time. - */ - if (len && !eff_buf.token_len) { - if (!wsi->u.ws.stashed_write_pending) - wsi->u.ws.stashed_write_type = (char)wp & 0x3f; - wsi->u.ws.stashed_write_pending = 1; - return len; - } - /* - * extension recreated it: - * need to buffer this if not all sent - */ - wsi->u.ws.clean_buffer = 0; - } - - buf = (unsigned char *)eff_buf.token; - len = eff_buf.token_len; - - if (!buf) { - lwsl_err("null buf (%d)\n", (int)len); - return -1; - } - - switch (wsi->ietf_spec_revision) { - case 13: - if (masked7) { - pre += 4; - dropmask = &buf[0 - pre]; - is_masked_bit = 0x80; - } - - switch (wp & 0xf) { - case LWS_WRITE_TEXT: - n = LWSWSOPC_TEXT_FRAME; - break; - case LWS_WRITE_BINARY: - n = LWSWSOPC_BINARY_FRAME; - break; - case LWS_WRITE_CONTINUATION: - n = LWSWSOPC_CONTINUATION; - break; - - case LWS_WRITE_CLOSE: - n = LWSWSOPC_CLOSE; - break; - case LWS_WRITE_PING: - n = LWSWSOPC_PING; - break; - case LWS_WRITE_PONG: - n = LWSWSOPC_PONG; - break; - default: - lwsl_warn("lws_write: unknown write opc / wp\n"); - return -1; - } - - if (!(wp & LWS_WRITE_NO_FIN)) - n |= 1 << 7; - - if (len < 126) { - pre += 2; - buf[-pre] = n; - buf[-pre + 1] = (unsigned char)(len | is_masked_bit); - } else { - if (len < 65536) { - pre += 4; - buf[-pre] = n; - buf[-pre + 1] = 126 | is_masked_bit; - buf[-pre + 2] = (unsigned char)(len >> 8); - buf[-pre + 3] = (unsigned char)len; - } else { - pre += 10; - buf[-pre] = n; - buf[-pre + 1] = 127 | is_masked_bit; -#if defined __LP64__ - buf[-pre + 2] = (len >> 56) & 0x7f; - buf[-pre + 3] = len >> 48; - buf[-pre + 4] = len >> 40; - buf[-pre + 5] = len >> 32; -#else - buf[-pre + 2] = 0; - buf[-pre + 3] = 0; - buf[-pre + 4] = 0; - buf[-pre + 5] = 0; -#endif - buf[-pre + 6] = (unsigned char)(len >> 24); - buf[-pre + 7] = (unsigned char)(len >> 16); - buf[-pre + 8] = (unsigned char)(len >> 8); - buf[-pre + 9] = (unsigned char)len; - } - } - break; - } - -do_more_inside_frame: - - /* - * Deal with masking if we are in client -> server direction and - * the wp demands it - */ - - if (masked7) { - if (!wsi->u.ws.inside_frame) - if (lws_0405_frame_mask_generate(wsi)) { - lwsl_err("frame mask generation failed\n"); - return -1; - } - - /* - * in v7, just mask the payload - */ - if (dropmask) { /* never set if already inside frame */ - for (n = 4; n < (int)len + 4; n++) - dropmask[n] = dropmask[n] ^ wsi->u.ws.mask[ - (wsi->u.ws.mask_idx++) & 3]; - - /* copy the frame nonce into place */ - memcpy(dropmask, wsi->u.ws.mask, 4); - } - } - -send_raw: - switch ((int)(wp & 0x1f)) { - case LWS_WRITE_CLOSE: -/* lwsl_hexdump(&buf[-pre], len); */ - case LWS_WRITE_HTTP: - case LWS_WRITE_HTTP_FINAL: - case LWS_WRITE_HTTP_HEADERS: - case LWS_WRITE_HTTP_HEADERS_CONTINUATION: - case LWS_WRITE_PONG: - case LWS_WRITE_PING: -#ifdef LWS_WITH_HTTP2 - if (wsi->mode == LWSCM_HTTP2_SERVING) { - unsigned char flags = 0; - - n = LWS_H2_FRAME_TYPE_DATA; - if ((wp & 0x1f) == LWS_WRITE_HTTP_HEADERS) { - n = LWS_H2_FRAME_TYPE_HEADERS; - if (!(wp & LWS_WRITE_NO_FIN)) - flags = LWS_H2_FLAG_END_HEADERS; - if (wsi->u.h2.send_END_STREAM || (wp & LWS_WRITE_H2_STREAM_END)) { - flags |= LWS_H2_FLAG_END_STREAM; - wsi->u.h2.send_END_STREAM = 1; - } - } - - if ((wp & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION) { - n = LWS_H2_FRAME_TYPE_CONTINUATION; - if (!(wp & LWS_WRITE_NO_FIN)) - flags = LWS_H2_FLAG_END_HEADERS; - if (wsi->u.h2.send_END_STREAM || (wp & LWS_WRITE_H2_STREAM_END)) { - flags |= LWS_H2_FLAG_END_STREAM; - wsi->u.h2.send_END_STREAM = 1; - } - } - - if (((wp & 0x1f) == LWS_WRITE_HTTP || - (wp & 0x1f) == LWS_WRITE_HTTP_FINAL) && - wsi->u.http.tx_content_length) { - wsi->u.http.tx_content_remain -= len; - lwsl_info("%s: wsi %p: tx_content_remain = %llu\n", __func__, wsi, - (unsigned long long)wsi->u.http.tx_content_remain); - if (!wsi->u.http.tx_content_remain) { - lwsl_info("%s: selecting final write mode\n", __func__); - wp = LWS_WRITE_HTTP_FINAL; - } - } - - if ((wp & 0x1f) == LWS_WRITE_HTTP_FINAL || (wp & LWS_WRITE_H2_STREAM_END)) { - //lws_get_network_wsi(wsi)->u.h2.END_STREAM) { - lwsl_info("%s: setting END_STREAM\n", __func__); - flags |= LWS_H2_FLAG_END_STREAM; - wsi->u.h2.send_END_STREAM = 1; - } - - return lws_h2_frame_write(wsi, n, flags, - wsi->u.h2.my_sid, len, buf); - } -#endif - return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre); - default: - break; - } - - /* - * give any active extensions a chance to munge the buffer - * before send. We pass in a pointer to an lws_tokens struct - * prepared with the default buffer and content length that's in - * there. Rather than rewrite the default buffer, extensions - * that expect to grow the buffer can adapt .token to - * point to their own per-connection buffer in the extension - * user allocation. By default with no extensions or no - * extension callback handling, just the normal input buffer is - * used then so it is efficient. - * - * callback returns 1 in case it wants to spill more buffers - * - * This takes care of holding the buffer if send is incomplete, ie, - * if wsi->u.ws.clean_buffer is 0 (meaning an extension meddled with - * the buffer). If wsi->u.ws.clean_buffer is 1, it will instead - * return to the user code how much OF THE USER BUFFER was consumed. - */ - - n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre); - wsi->u.ws.inside_frame = 1; - if (n <= 0) - return n; - - if (n == (int)len + pre) { - /* everything in the buffer was handled (or rebuffered...) */ - wsi->u.ws.inside_frame = 0; - return orig_len; - } - - /* - * it is how many bytes of user buffer got sent... may be < orig_len - * in which case callback when writable has already been arranged - * and user code can call lws_write() again with the rest - * later. - */ - - return n - pre; -} - -LWS_VISIBLE int lws_serve_http_file_fragment(struct lws *wsi) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - struct lws_process_html_args args; - lws_filepos_t amount, poss; - unsigned char *p, *pstart; -#if defined(LWS_WITH_RANGES) - unsigned char finished = 0; -#endif - int n, m; - - lwsl_debug("wsi->http2_substream %d\n", wsi->http2_substream); - - while (!lws_send_pipe_choked(wsi)) { - - if (wsi->trunc_len) { - if (lws_issue_raw(wsi, wsi->trunc_alloc + - wsi->trunc_offset, - wsi->trunc_len) < 0) { - lwsl_info("%s: closing\n", __func__); - goto file_had_it; - } - continue; - } - - if (wsi->u.http.filepos == wsi->u.http.filelen) - goto all_sent; - - n = 0; - - pstart = pt->serv_buf + LWS_H2_FRAME_HEADER_LENGTH; - - p = pstart; - -#if defined(LWS_WITH_RANGES) - if (wsi->u.http.range.count_ranges && !wsi->u.http.range.inside) { - - lwsl_notice("%s: doing range start %llu\n", __func__, wsi->u.http.range.start); - - if ((long long)lws_vfs_file_seek_cur(wsi->u.http.fop_fd, - wsi->u.http.range.start - - wsi->u.http.filepos) < 0) - goto file_had_it; - - wsi->u.http.filepos = wsi->u.http.range.start; - - if (wsi->u.http.range.count_ranges > 1) { - n = lws_snprintf((char *)p, context->pt_serv_buf_size - LWS_H2_FRAME_HEADER_LENGTH, - "_lws\x0d\x0a" - "Content-Type: %s\x0d\x0a" - "Content-Range: bytes %llu-%llu/%llu\x0d\x0a" - "\x0d\x0a", - wsi->u.http.multipart_content_type, - wsi->u.http.range.start, - wsi->u.http.range.end, - wsi->u.http.range.extent); - p += n; - } - - wsi->u.http.range.budget = wsi->u.http.range.end - - wsi->u.http.range.start + 1; - wsi->u.http.range.inside = 1; - } -#endif - - poss = context->pt_serv_buf_size - n - LWS_H2_FRAME_HEADER_LENGTH; - - if (poss > wsi->u.http.tx_content_remain) - poss = wsi->u.http.tx_content_remain; - - /* - * if there is a hint about how much we will do well to send at one time, - * restrict ourselves to only trying to send that. - */ - if (wsi->protocol->tx_packet_size && - poss > wsi->protocol->tx_packet_size) - poss = wsi->protocol->tx_packet_size; - -#if defined(LWS_WITH_HTTP2) - m = lws_h2_tx_cr_get(wsi); - if (!m) { - lwsl_info("%s: came here with no tx credit", __func__); - return 0; - } - if (m < poss) - poss = m; - /* - * consumption of the actual payload amount sent will be handled - * when the http2 data frame is sent - */ -#endif - -#if defined(LWS_WITH_RANGES) - if (wsi->u.http.range.count_ranges) { - if (wsi->u.http.range.count_ranges > 1) - poss -= 7; /* allow for final boundary */ - if (poss > wsi->u.http.range.budget) - poss = wsi->u.http.range.budget; - } -#endif - if (wsi->sending_chunked) { - /* we need to drop the chunk size in here */ - p += 10; - /* allow for the chunk to grow by 128 in translation */ - poss -= 10 + 128; - } - - if (lws_vfs_file_read(wsi->u.http.fop_fd, &amount, p, poss) < 0) - goto file_had_it; /* caller will close */ - - if (wsi->sending_chunked) - n = (int)amount; - else - n = (p - pstart) + (int)amount; - - lwsl_debug("%s: sending %d\n", __func__, n); - - if (n) { - lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, - context->timeout_secs); - - if (wsi->sending_chunked) { - args.p = (char *)p; - args.len = n; - args.max_len = (unsigned int)poss + 128; - args.final = wsi->u.http.filepos + n == - wsi->u.http.filelen; - if (user_callback_handle_rxflow( - wsi->vhost->protocols[(int)wsi->protocol_interpret_idx].callback, wsi, - LWS_CALLBACK_PROCESS_HTML, - wsi->user_space, &args, 0) < 0) - goto file_had_it; - n = args.len; - p = (unsigned char *)args.p; - } else - p = pstart; - -#if defined(LWS_WITH_RANGES) - if (wsi->u.http.range.send_ctr + 1 == - wsi->u.http.range.count_ranges && // last range - wsi->u.http.range.count_ranges > 1 && // was 2+ ranges (ie, multipart) - wsi->u.http.range.budget - amount == 0) {// final part - n += lws_snprintf((char *)pstart + n, 6, - "_lws\x0d\x0a"); // append trailing boundary - lwsl_debug("added trailing boundary\n"); - } -#endif - m = lws_write(wsi, p, n, - wsi->u.http.filepos == wsi->u.http.filelen ? - LWS_WRITE_HTTP_FINAL : - LWS_WRITE_HTTP - ); - if (m < 0) - goto file_had_it; - - wsi->u.http.filepos += amount; - -#if defined(LWS_WITH_RANGES) - if (wsi->u.http.range.count_ranges >= 1) { - wsi->u.http.range.budget -= amount; - if (wsi->u.http.range.budget == 0) { - lwsl_notice("range budget exhausted\n"); - wsi->u.http.range.inside = 0; - wsi->u.http.range.send_ctr++; - - if (lws_ranges_next(&wsi->u.http.range) < 1) { - finished = 1; - goto all_sent; - } - } - } -#endif - - if (m != n) { - /* adjust for what was not sent */ - if (lws_vfs_file_seek_cur(wsi->u.http.fop_fd, - m - n) == - (unsigned long)-1) - goto file_had_it; - } - } - -all_sent: - if ((!wsi->trunc_len && wsi->u.http.filepos >= wsi->u.http.filelen) -#if defined(LWS_WITH_RANGES) - || finished) -#else - ) -#endif - { - wsi->state = LWSS_HTTP; - /* we might be in keepalive, so close it off here */ - lws_vfs_file_close(&wsi->u.http.fop_fd); - - lwsl_debug("file completed\n"); - - if (wsi->protocol->callback && - user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_HTTP_FILE_COMPLETION, - wsi->user_space, NULL, - 0) < 0) { - /* - * For http/1.x, the choices from - * transaction_completed are either - * 0 to use the connection for pipelined - * or nonzero to hang it up. - * - * However for http/2. while we are - * still interested in hanging up the - * nwsi if there was a network-level - * fatal error, simply completing the - * transaction is a matter of the stream - * state, not the root connection at the - * network level - */ - if (wsi->http2_substream) - return 1; - else - return -1; - } - - return 1; /* >0 indicates completed */ - } - } - - lws_callback_on_writable(wsi); - - return 0; /* indicates further processing must be done */ - -file_had_it: - lws_vfs_file_close(&wsi->u.http.fop_fd); - - return -1; -} - -#if LWS_POSIX -LWS_VISIBLE int -lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - int n; - - lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1); - - n = recv(wsi->desc.sockfd, (char *)buf, len, 0); - if (n >= 0) { - if (wsi->vhost) - wsi->vhost->conn_stats.rx += n; - lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n); - lws_restart_ws_ping_pong_timer(wsi); - return n; - } -#if LWS_POSIX - if (LWS_ERRNO == LWS_EAGAIN || - LWS_ERRNO == LWS_EWOULDBLOCK || - LWS_ERRNO == LWS_EINTR) - return LWS_SSL_CAPABLE_MORE_SERVICE; -#endif - lwsl_notice("error on reading from skt : %d\n", LWS_ERRNO); - return LWS_SSL_CAPABLE_ERROR; -} - -LWS_VISIBLE int -lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len) -{ - int n = 0; - -#if LWS_POSIX - n = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL); -// lwsl_info("%s: sent len %d result %d", __func__, len, n); - if (n >= 0) - return n; - - if (LWS_ERRNO == LWS_EAGAIN || - LWS_ERRNO == LWS_EWOULDBLOCK || - LWS_ERRNO == LWS_EINTR) { - if (LWS_ERRNO == LWS_EWOULDBLOCK) { - lws_set_blocking_send(wsi); - } - - return LWS_SSL_CAPABLE_MORE_SERVICE; - } -#else - (void)n; - (void)wsi; - (void)buf; - (void)len; - // !!! -#endif - - lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n", - len, wsi->desc.sockfd, n, LWS_ERRNO); - return LWS_SSL_CAPABLE_ERROR; -} -#endif -LWS_VISIBLE int -lws_ssl_pending_no_ssl(struct lws *wsi) -{ - (void)wsi; -#if defined(LWS_WITH_ESP32) - return 100; -#else - return 0; -#endif -} diff --git a/thirdparty/lws/private-libwebsockets.h b/thirdparty/lws/private-libwebsockets.h deleted file mode 100644 index 535fa0be57..0000000000 --- a/thirdparty/lws/private-libwebsockets.h +++ /dev/null @@ -1,2615 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010 - 2016 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "lws_config.h" -#include "lws_config_private.h" - - -#if defined(LWS_WITH_CGI) && defined(LWS_HAVE_VFORK) -#define _GNU_SOURCE -#endif - -#if defined(__COVERITY__) -typedef struct { long double x, y; } _Float128; -#endif - -#ifdef LWS_HAVE_SYS_TYPES_H -#include <sys/types.h> -#endif - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <time.h> -#include <ctype.h> -#include <limits.h> -#include <stdarg.h> -#include <inttypes.h> - -#if defined(LWS_WITH_ESP32) -#define MSG_NOSIGNAL 0 -#define SOMAXCONN 3 -#endif - -#if defined(LWS_WITH_ESP8266) -#include <user_interface.h> -#define assert(n) - -/* rom-provided stdc functions for free, ensure use these instead of libc ones */ - -int ets_vsprintf(char *str, const char *format, va_list argptr); -int ets_vsnprintf(char *buffer, size_t sizeOfBuffer, const char *format, va_list argptr); -int ets_snprintf(char *str, size_t size, const char *format, ...); -int ets_sprintf(char *str, const char *format, ...); -int os_printf_plus(const char *format, ...); -#undef malloc -#undef realloc -#undef free -void *pvPortMalloc(size_t s, const char *f, int line); -#define malloc(s) pvPortMalloc(s, "", 0) -void *pvPortRealloc(void *p, size_t s, const char *f, int line); -#define realloc(p, s) pvPortRealloc(p, s, "", 0) -void vPortFree(void *p, const char *f, int line); -#define free(p) vPortFree(p, "", 0) -#undef memcpy -void *ets_memcpy(void *dest, const void *src, size_t n); -#define memcpy ets_memcpy -void *ets_memset(void *dest, int v, size_t n); -#define memset ets_memset -char *ets_strcpy(char *dest, const char *src); -#define strcpy ets_strcpy -char *ets_strncpy(char *dest, const char *src, size_t n); -#define strncpy ets_strncpy -char *ets_strstr(const char *haystack, const char *needle); -#define strstr ets_strstr -int ets_strcmp(const char *s1, const char *s2); -int ets_strncmp(const char *s1, const char *s2, size_t n); -#define strcmp ets_strcmp -#define strncmp ets_strncmp -size_t ets_strlen(const char *s); -#define strlen ets_strlen -void *ets_memmove(void *dest, const void *src, size_t n); -#define memmove ets_memmove -char *ets_strchr(const char *s, int c); -#define strchr_ets_strchr -#undef _DEBUG -#include <osapi.h> - -#else -#define STORE_IN_ROM -#include <assert.h> -#endif -#if LWS_MAX_SMP > 1 -#include <pthread.h> -#endif - -#ifdef LWS_HAVE_SYS_STAT_H -#include <sys/stat.h> -#endif - -#if defined(WIN32) || defined(_WIN32) - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#if (WINVER < 0x0501) -#undef WINVER -#undef _WIN32_WINNT -#define WINVER 0x0501 -#define _WIN32_WINNT WINVER -#endif -#define LWS_NO_DAEMONIZE -#define LWS_ERRNO WSAGetLastError() -#define LWS_EAGAIN WSAEWOULDBLOCK -#define LWS_EALREADY WSAEALREADY -#define LWS_EINPROGRESS WSAEINPROGRESS -#define LWS_EINTR WSAEINTR -#define LWS_EISCONN WSAEISCONN -#define LWS_EWOULDBLOCK WSAEWOULDBLOCK -#define MSG_NOSIGNAL 0 -#define SHUT_RDWR SD_BOTH -#define SOL_TCP IPPROTO_TCP -#define SHUT_WR SD_SEND - -#define compatible_close(fd) closesocket(fd) -#define lws_set_blocking_send(wsi) wsi->sock_send_blocking = 1 -#define lws_socket_is_valid(x) (!!x) -#define LWS_SOCK_INVALID 0 -#include <winsock2.h> -#include <ws2tcpip.h> -#include <windows.h> -#include <tchar.h> -#ifdef LWS_HAVE_IN6ADDR_H -#include <in6addr.h> -#endif -#include <mstcpip.h> -#include <io.h> - -#if !defined(LWS_HAVE_ATOLL) -#if defined(LWS_HAVE__ATOI64) -#define atoll _atoi64 -#else -#warning No atoll or _atoi64 available, using atoi -#define atoll atoi -#endif -#endif - -#ifndef __func__ -#define __func__ __FUNCTION__ -#endif - -#ifdef LWS_HAVE__VSNPRINTF -#define vsnprintf _vsnprintf -#endif - -/* we don't have an implementation for this on windows... */ -int kill(int pid, int sig); -int fork(void); -#ifndef SIGINT -#define SIGINT 2 -#endif - -#else /* not windows --> */ - -#include <fcntl.h> -#include <strings.h> -#include <unistd.h> -#include <sys/types.h> - -#ifndef __cplusplus -#include <errno.h> -#endif -#include <netdb.h> -#include <signal.h> -#ifdef LWS_WITH_ESP8266 -#include <sockets.h> -#define vsnprintf ets_vsnprintf -#define snprintf ets_snprintf -#define sprintf ets_sprintf - -int kill(int pid, int sig); - -#else -#include <sys/socket.h> -#endif -#ifdef LWS_WITH_HTTP_PROXY -#include <hubbub/hubbub.h> -#include <hubbub/parser.h> -#endif -#if defined(LWS_BUILTIN_GETIFADDRS) - #include "./misc/getifaddrs.h" -#else - #if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) - #if defined(__HAIKU__) - #define _BSD_SOURCE - #endif - #include <ifaddrs.h> - #endif -#endif -#if defined (__ANDROID__) -#include <syslog.h> -#include <sys/resource.h> -#elif defined (__sun) || defined(__HAIKU__) -#include <syslog.h> -#else -#if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) -#include <sys/syslog.h> -#endif -#endif -#include <netdb.h> -#if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) -#include <sys/mman.h> -#include <sys/un.h> -#include <netinet/in.h> -#include <netinet/tcp.h> -#include <arpa/inet.h> -#include <poll.h> -#endif -#ifdef LWS_WITH_LIBEV -#include <ev.h> -#endif -#ifdef LWS_WITH_LIBUV -#include <uv.h> -#endif -#ifdef LWS_WITH_LIBEVENT -#include <event2/event.h> -#endif - -#ifndef LWS_NO_FORK -#ifdef LWS_HAVE_SYS_PRCTL_H -#include <sys/prctl.h> -#endif -#endif - -#include <sys/time.h> - -#define LWS_ERRNO errno -#define LWS_EAGAIN EAGAIN -#define LWS_EALREADY EALREADY -#define LWS_EINPROGRESS EINPROGRESS -#define LWS_EINTR EINTR -#define LWS_EISCONN EISCONN -#define LWS_EWOULDBLOCK EWOULDBLOCK - -#define lws_set_blocking_send(wsi) - -#if defined(LWS_WITH_ESP8266) -#define lws_socket_is_valid(x) ((x) != NULL) -#define LWS_SOCK_INVALID (NULL) -struct lws; -const char * -lws_plat_get_peer_simple(struct lws *wsi, char *name, int namelen); -#else -#define lws_socket_is_valid(x) (x >= 0) -#define LWS_SOCK_INVALID (-1) -#endif -#endif - -#ifndef LWS_HAVE_BZERO -#ifndef bzero -#define bzero(b, len) (memset((b), '\0', (len)), (void) 0) -#endif -#endif - -#ifndef LWS_HAVE_STRERROR -#define strerror(x) "" -#endif - -#ifdef LWS_OPENSSL_SUPPORT - -#ifdef USE_WOLFSSL -#ifdef USE_OLD_CYASSL -#include <cyassl/openssl/ssl.h> -#include <cyassl/error-ssl.h> -#else -#include <wolfssl/openssl/ssl.h> -#include <wolfssl/error-ssl.h> -#define OPENSSL_NO_TLSEXT -#endif /* not USE_OLD_CYASSL */ -#else -#if defined(LWS_WITH_ESP32) -#define OPENSSL_NO_TLSEXT -#else -#if defined(LWS_WITH_MBEDTLS) -#include <mbedtls/ssl.h> -#include <mbedtls/x509_crt.h> -#else -#include <openssl/ssl.h> -#include <openssl/evp.h> -#include <openssl/err.h> -#include <openssl/md5.h> -#include <openssl/sha.h> -#ifdef LWS_HAVE_OPENSSL_ECDH_H -#include <openssl/ecdh.h> -#endif -#include <openssl/x509v3.h> -#endif -#if defined(OPENSSL_VERSION_NUMBER) -#if (OPENSSL_VERSION_NUMBER < 0x0009080afL) -/* later openssl defines this to negate the presence of tlsext... but it was only - * introduced at 0.9.8j. Earlier versions don't know it exists so don't - * define it... making it look like the feature exists... - */ -#define OPENSSL_NO_TLSEXT -#endif -#endif -#endif /* not ESP32 */ -#endif /* not USE_WOLFSSL */ -#endif - -#include "libwebsockets.h" -#if defined(WIN32) || defined(_WIN32) -#else -static inline int compatible_close(int fd) { return close(fd); } -#endif - -#if defined(WIN32) || defined(_WIN32) -#include <gettimeofday.h> -#endif - -#if defined(LWS_WITH_ESP8266) -#undef compatible_close -#define compatible_close(fd) { fd->state=ESPCONN_CLOSE; espconn_delete(fd); } -lws_sockfd_type -esp8266_create_tcp_stream_socket(void); -void -esp8266_tcp_stream_bind(lws_sockfd_type fd, int port, struct lws *wsi); -#ifndef BIG_ENDIAN -#define BIG_ENDIAN 4321 /* to show byte order (taken from gcc) */ -#endif -#ifndef LITTLE_ENDIAN -#define LITTLE_ENDIAN 1234 -#endif -#ifndef BYTE_ORDER -#define BYTE_ORDER LITTLE_ENDIAN -#endif -#endif - - -#if defined(WIN32) || defined(_WIN32) - -#ifndef BIG_ENDIAN -#define BIG_ENDIAN 4321 /* to show byte order (taken from gcc) */ -#endif -#ifndef LITTLE_ENDIAN -#define LITTLE_ENDIAN 1234 -#endif -#ifndef BYTE_ORDER -#define BYTE_ORDER LITTLE_ENDIAN -#endif - -#undef __P -#ifndef __P -#if __STDC__ -#define __P(protos) protos -#else -#define __P(protos) () -#endif -#endif - -#else - -#include <sys/stat.h> -#include <sys/time.h> - -#if defined(__APPLE__) -#include <machine/endian.h> -#elif defined(__FreeBSD__) -#include <sys/endian.h> -#elif defined(__linux__) -#include <endian.h> -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(__QNX__) - #include <gulliver.h> - #if defined(__LITTLEENDIAN__) - #define BYTE_ORDER __LITTLEENDIAN__ - #define LITTLE_ENDIAN __LITTLEENDIAN__ - #define BIG_ENDIAN 4321 /* to show byte order (taken from gcc); for suppres warning that BIG_ENDIAN is not defined. */ - #endif - #if defined(__BIGENDIAN__) - #define BYTE_ORDER __BIGENDIAN__ - #define LITTLE_ENDIAN 1234 /* to show byte order (taken from gcc); for suppres warning that LITTLE_ENDIAN is not defined. */ - #define BIG_ENDIAN __BIGENDIAN__ - #endif -#endif - -#if defined(__sun) && defined(__GNUC__) - -#include <arpa/nameser_compat.h> - -#if !defined (BYTE_ORDER) -# define BYTE_ORDER __BYTE_ORDER__ -#endif - -#if !defined(LITTLE_ENDIAN) -# define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ -#endif - -#if !defined(BIG_ENDIAN) -# define BIG_ENDIAN __ORDER_BIG_ENDIAN__ -#endif - -#endif /* sun + GNUC */ - -#if !defined(BYTE_ORDER) -# define BYTE_ORDER __BYTE_ORDER -#endif -#if !defined(LITTLE_ENDIAN) -# define LITTLE_ENDIAN __LITTLE_ENDIAN -#endif -#if !defined(BIG_ENDIAN) -# define BIG_ENDIAN __BIG_ENDIAN -#endif - -#endif - -/* - * Mac OSX as well as iOS do not define the MSG_NOSIGNAL flag, - * but happily have something equivalent in the SO_NOSIGPIPE flag. - */ -#ifdef __APPLE__ -#define MSG_NOSIGNAL SO_NOSIGPIPE -#endif - -/* - * Solaris 11.X only supports POSIX 2001, MSG_NOSIGNAL appears in - * POSIX 2008. - */ -#ifdef __sun -#define MSG_NOSIGNAL 0 -#endif - -#ifdef _WIN32 -#ifndef FD_HASHTABLE_MODULUS -#define FD_HASHTABLE_MODULUS 32 -#endif -#endif - -#ifndef LWS_DEF_HEADER_LEN -#define LWS_DEF_HEADER_LEN 4096 -#endif -#ifndef LWS_DEF_HEADER_POOL -#define LWS_DEF_HEADER_POOL 4 -#endif -#ifndef LWS_MAX_PROTOCOLS -#define LWS_MAX_PROTOCOLS 5 -#endif -#ifndef LWS_MAX_EXTENSIONS_ACTIVE -#define LWS_MAX_EXTENSIONS_ACTIVE 2 -#endif -#ifndef LWS_MAX_EXT_OFFERS -#define LWS_MAX_EXT_OFFERS 8 -#endif -#ifndef SPEC_LATEST_SUPPORTED -#define SPEC_LATEST_SUPPORTED 13 -#endif -#ifndef AWAITING_TIMEOUT -#define AWAITING_TIMEOUT 20 -#endif -#ifndef CIPHERS_LIST_STRING -#define CIPHERS_LIST_STRING "DEFAULT" -#endif -#ifndef LWS_SOMAXCONN -#define LWS_SOMAXCONN SOMAXCONN -#endif - -#define MAX_WEBSOCKET_04_KEY_LEN 128 - -#ifndef SYSTEM_RANDOM_FILEPATH -#define SYSTEM_RANDOM_FILEPATH "/dev/urandom" -#endif - -enum lws_websocket_opcodes_07 { - LWSWSOPC_CONTINUATION = 0, - LWSWSOPC_TEXT_FRAME = 1, - LWSWSOPC_BINARY_FRAME = 2, - - LWSWSOPC_NOSPEC__MUX = 7, - - /* control extensions 8+ */ - - LWSWSOPC_CLOSE = 8, - LWSWSOPC_PING = 9, - LWSWSOPC_PONG = 0xa, -}; - - -enum lws_connection_states { - LWSS_HTTP, - LWSS_HTTP_ISSUING_FILE, - LWSS_HTTP_HEADERS, - LWSS_HTTP_BODY, - LWSS_DEAD_SOCKET, - LWSS_ESTABLISHED, - LWSS_CLIENT_HTTP_ESTABLISHED, - LWSS_CLIENT_UNCONNECTED, - LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION, - LWSS_RETURNED_CLOSE_ALREADY, - LWSS_AWAITING_CLOSE_ACK, - LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE, - LWSS_SHUTDOWN, - - LWSS_HTTP2_AWAIT_CLIENT_PREFACE, - LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS, - LWSS_HTTP2_ESTABLISHED, - - LWSS_CGI, -}; - -enum http_version { - HTTP_VERSION_1_0, - HTTP_VERSION_1_1, - HTTP_VERSION_2 -}; - -enum http_connection_type { - HTTP_CONNECTION_CLOSE, - HTTP_CONNECTION_KEEP_ALIVE -}; - -enum lws_rx_parse_state { - LWS_RXPS_NEW, - - LWS_RXPS_04_mask_1, - LWS_RXPS_04_mask_2, - LWS_RXPS_04_mask_3, - - LWS_RXPS_04_FRAME_HDR_1, - LWS_RXPS_04_FRAME_HDR_LEN, - LWS_RXPS_04_FRAME_HDR_LEN16_2, - LWS_RXPS_04_FRAME_HDR_LEN16_1, - LWS_RXPS_04_FRAME_HDR_LEN64_8, - LWS_RXPS_04_FRAME_HDR_LEN64_7, - LWS_RXPS_04_FRAME_HDR_LEN64_6, - LWS_RXPS_04_FRAME_HDR_LEN64_5, - LWS_RXPS_04_FRAME_HDR_LEN64_4, - LWS_RXPS_04_FRAME_HDR_LEN64_3, - LWS_RXPS_04_FRAME_HDR_LEN64_2, - LWS_RXPS_04_FRAME_HDR_LEN64_1, - - LWS_RXPS_07_COLLECT_FRAME_KEY_1, - LWS_RXPS_07_COLLECT_FRAME_KEY_2, - LWS_RXPS_07_COLLECT_FRAME_KEY_3, - LWS_RXPS_07_COLLECT_FRAME_KEY_4, - - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED -}; - -#define LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP 32 - -enum connection_mode { - LWSCM_HTTP_SERVING, - LWSCM_HTTP_SERVING_ACCEPTED, /* actual HTTP service going on */ - LWSCM_PRE_WS_SERVING_ACCEPT, - - LWSCM_WS_SERVING, - LWSCM_WS_CLIENT, - - LWSCM_HTTP2_SERVING, - - /* transient, ssl delay hiding */ - LWSCM_SSL_ACK_PENDING, - LWSCM_SSL_INIT, - /* as above, but complete into LWSCM_RAW */ - LWSCM_SSL_ACK_PENDING_RAW, - LWSCM_SSL_INIT_RAW, - - /* special internal types */ - LWSCM_SERVER_LISTENER, - LWSCM_CGI, /* stdin, stdout, stderr for another cgi master wsi */ - LWSCM_RAW, /* raw with bulk handling */ - LWSCM_RAW_FILEDESC, /* raw without bulk handling */ - - /* HTTP Client related */ - LWSCM_HTTP_CLIENT = LWSCM_FLAG_IMPLIES_CALLBACK_CLOSED_CLIENT_HTTP, - LWSCM_HTTP_CLIENT_ACCEPTED, /* actual HTTP service going on */ - LWSCM_WSCL_WAITING_CONNECT, - LWSCM_WSCL_WAITING_PROXY_REPLY, - LWSCM_WSCL_ISSUE_HANDSHAKE, - LWSCM_WSCL_ISSUE_HANDSHAKE2, - LWSCM_WSCL_ISSUE_HTTP_BODY, - LWSCM_WSCL_WAITING_SSL, - LWSCM_WSCL_WAITING_SERVER_REPLY, - LWSCM_WSCL_WAITING_EXTENSION_CONNECT, - LWSCM_WSCL_PENDING_CANDIDATE_CHILD, - LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY, - LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY, - LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY, - - /****** add new things just above ---^ ******/ - - -}; - -/* enums of socks version */ -enum socks_version { - SOCKS_VERSION_4 = 4, - SOCKS_VERSION_5 = 5 -}; - -/* enums of subnegotiation version */ -enum socks_subnegotiation_version { - SOCKS_SUBNEGOTIATION_VERSION_1 = 1, -}; - -/* enums of socks commands */ -enum socks_command { - SOCKS_COMMAND_CONNECT = 1, - SOCKS_COMMAND_BIND = 2, - SOCKS_COMMAND_UDP_ASSOCIATE = 3 -}; - -/* enums of socks address type */ -enum socks_atyp { - SOCKS_ATYP_IPV4 = 1, - SOCKS_ATYP_DOMAINNAME = 3, - SOCKS_ATYP_IPV6 = 4 -}; - -/* enums of socks authentication methods */ -enum socks_auth_method { - SOCKS_AUTH_NO_AUTH = 0, - SOCKS_AUTH_GSSAPI = 1, - SOCKS_AUTH_USERNAME_PASSWORD = 2 -}; - -/* enums of subnegotiation status */ -enum socks_subnegotiation_status { - SOCKS_SUBNEGOTIATION_STATUS_SUCCESS = 0, -}; - -/* enums of socks request reply */ -enum socks_request_reply { - SOCKS_REQUEST_REPLY_SUCCESS = 0, - SOCKS_REQUEST_REPLY_FAILURE_GENERAL = 1, - SOCKS_REQUEST_REPLY_CONNECTION_NOT_ALLOWED = 2, - SOCKS_REQUEST_REPLY_NETWORK_UNREACHABLE = 3, - SOCKS_REQUEST_REPLY_HOST_UNREACHABLE = 4, - SOCKS_REQUEST_REPLY_CONNECTION_REFUSED = 5, - SOCKS_REQUEST_REPLY_TTL_EXPIRED = 6, - SOCKS_REQUEST_REPLY_COMMAND_NOT_SUPPORTED = 7, - SOCKS_REQUEST_REPLY_ATYP_NOT_SUPPORTED = 8 -}; - -/* enums used to generate socks messages */ -enum socks_msg_type { - /* greeting */ - SOCKS_MSG_GREETING, - /* credential, user name and password */ - SOCKS_MSG_USERNAME_PASSWORD, - /* connect command */ - SOCKS_MSG_CONNECT -}; - -enum { - LWS_RXFLOW_ALLOW = (1 << 0), - LWS_RXFLOW_PENDING_CHANGE = (1 << 1), -}; - -struct lws_ring { - void *buf; - void (*destroy_element)(void *element); - size_t buflen; - size_t element_len; - uint32_t head; - uint32_t oldest_tail; -}; - -/* this is not usable directly by user code any more, lws_close_reason() */ -#define LWS_WRITE_CLOSE 4 - -struct lws_protocols; -struct lws; - -#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) - -struct lws_io_watcher { -#ifdef LWS_WITH_LIBEV - ev_io ev_watcher; -#endif -#ifdef LWS_WITH_LIBUV - uv_poll_t uv_watcher; -#endif -#ifdef LWS_WITH_LIBEVENT - struct event *event_watcher; -#endif - struct lws_context *context; - - uint8_t actual_events; -}; - -struct lws_signal_watcher { -#ifdef LWS_WITH_LIBEV - ev_signal ev_watcher; -#endif -#ifdef LWS_WITH_LIBUV - uv_signal_t uv_watcher; -#endif -#ifdef LWS_WITH_LIBEVENT - struct event *event_watcher; -#endif - struct lws_context *context; -}; -#endif - -#ifdef _WIN32 -#define LWS_FD_HASH(fd) ((fd ^ (fd >> 8) ^ (fd >> 16)) % FD_HASHTABLE_MODULUS) -struct lws_fd_hashtable { - struct lws **wsi; - int length; -}; -#endif - -/* - * This is totally opaque to code using the library. It's exported as a - * forward-reference pointer-only declaration; the user can use the pointer with - * other APIs to get information out of it. - */ - -#if defined(LWS_WITH_ESP32) -typedef uint16_t ah_data_idx_t; -#else -typedef uint32_t ah_data_idx_t; -#endif - -struct lws_fragments { - ah_data_idx_t offset; - uint16_t len; - uint8_t nfrag; /* which ah->frag[] continues this content, or 0 */ - uint8_t flags; /* only http2 cares */ -}; - -/* - * these are assigned from a pool held in the context. - * Both client and server mode uses them for http header analysis - */ - -struct allocated_headers { - struct allocated_headers *next; /* linked list */ - struct lws *wsi; /* owner */ - char *data; /* prepared by context init to point to dedicated storage */ - ah_data_idx_t data_length; - /* - * the randomly ordered fragments, indexed by frag_index and - * lws_fragments->nfrag for continuation. - */ - struct lws_fragments frags[WSI_TOKEN_COUNT]; - time_t assigned; - /* - * for each recognized token, frag_index says which frag[] his data - * starts in (0 means the token did not appear) - * the actual header data gets dumped as it comes in, into data[] - */ - uint8_t frag_index[WSI_TOKEN_COUNT]; -#if defined(LWS_WITH_ESP32) - uint8_t rx[256]; -#else - uint8_t rx[2048]; -#endif - - int16_t rxpos; - int16_t rxlen; - uint32_t pos; - uint32_t http_response; - int hdr_token_idx; - -#ifndef LWS_NO_CLIENT - char initial_handshake_hash_base64[30]; -#endif - - uint8_t in_use; - uint8_t nfrag; -}; - -/* - * so we can have n connections being serviced simultaneously, - * these things need to be isolated per-thread. - */ - -struct lws_context_per_thread { -#if LWS_MAX_SMP > 1 - pthread_mutex_t lock; -#endif - struct lws_pollfd *fds; -#if defined(LWS_WITH_ESP8266) - struct lws **lws_vs_fds_index; -#endif - struct lws *rx_draining_ext_list; - struct lws *tx_draining_ext_list; - struct lws *timeout_list; -#if defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) - struct lws_context *context; -#endif -#ifdef LWS_WITH_CGI - struct lws_cgi *cgi_list; -#endif - void *http_header_data; - struct allocated_headers *ah_list; - struct lws *ah_wait_list; - int ah_wait_list_length; -#ifdef LWS_OPENSSL_SUPPORT - struct lws *pending_read_list; /* linked list */ -#endif -#if defined(LWS_WITH_LIBEV) - struct ev_loop *io_loop_ev; -#endif -#if defined(LWS_WITH_LIBUV) - uv_loop_t *io_loop_uv; - uv_signal_t signals[8]; - uv_timer_t uv_timeout_watcher; - uv_idle_t uv_idle; -#endif -#if defined(LWS_WITH_LIBEVENT) - struct event_base *io_loop_event_base; -#endif -#if defined(LWS_WITH_LIBEV) - struct lws_io_watcher w_accept; -#endif -#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) - struct lws_signal_watcher w_sigint; - unsigned char ev_loop_foreign:1; -#endif - - unsigned long count_conns; - /* - * usable by anything in the service code, but only if the scope - * does not last longer than the service action (since next service - * of any socket can likewise use it and overwrite) - */ - unsigned char *serv_buf; -#ifdef _WIN32 - WSAEVENT *events; -#else - lws_sockfd_type dummy_pipe_fds[2]; -#endif - unsigned int fds_count; - uint32_t ah_pool_length; - - short ah_count_in_use; - unsigned char tid; - unsigned char lock_depth; -}; - -struct lws_conn_stats { - unsigned long long rx, tx; - unsigned long h1_conn, h1_trans, h2_trans, ws_upg, h2_alpn, h2_subs, - h2_upg, rejected; -}; - -void -lws_sum_stats(const struct lws_context *ctx, struct lws_conn_stats *cs); - - -enum lws_h2_settings { - H2SET_HEADER_TABLE_SIZE = 1, - H2SET_ENABLE_PUSH, - H2SET_MAX_CONCURRENT_STREAMS, - H2SET_INITIAL_WINDOW_SIZE, - H2SET_MAX_FRAME_SIZE, - H2SET_MAX_HEADER_LIST_SIZE, - - H2SET_COUNT /* always last */ -}; - -struct http2_settings { - uint32_t s[H2SET_COUNT]; -}; - -/* - * virtual host -related context information - * vhostwide SSL context - * vhostwide proxy - * - * hierarchy: - * - * context -> vhost -> wsi - * - * incoming connection non-SSL vhost binding: - * - * listen socket -> wsi -> select vhost after first headers - * - * incoming connection SSL vhost binding: - * - * SSL SNI -> wsi -> bind after SSL negotiation - */ - -struct lws_vhost { -#if !defined(LWS_WITH_ESP8266) - char http_proxy_address[128]; - char proxy_basic_auth_token[128]; -#if defined(LWS_WITH_HTTP2) - struct http2_settings set; -#endif -#if defined(LWS_WITH_SOCKS5) - char socks_proxy_address[128]; - char socks_user[96]; - char socks_password[96]; -#endif -#endif -#if defined(LWS_WITH_ESP8266) - /* listen sockets need a place to hang their hat */ - esp_tcp tcp; -#endif - struct lws_conn_stats conn_stats; - struct lws_context *context; - struct lws_vhost *vhost_next; - const struct lws_http_mount *mount_list; - struct lws *lserv_wsi; - const char *name; - const char *iface; -#if !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32) && !defined(OPTEE_TA) && !defined(WIN32) - int bind_iface; -#endif - const struct lws_protocols *protocols; - void **protocol_vh_privs; - const struct lws_protocol_vhost_options *pvo; - const struct lws_protocol_vhost_options *headers; - struct lws **same_vh_protocol_list; -#ifdef LWS_OPENSSL_SUPPORT - SSL_CTX *ssl_ctx; - SSL_CTX *ssl_client_ctx; -#endif -#if defined(LWS_WITH_MBEDTLS) - X509 *x509_client_CA; -#endif -#ifndef LWS_NO_EXTENSIONS - const struct lws_extension *extensions; -#endif - void *user; - - int listen_port; - unsigned int http_proxy_port; -#if defined(LWS_WITH_SOCKS5) - unsigned int socks_proxy_port; -#endif - unsigned int options; - int count_protocols; - int ka_time; - int ka_probes; - int ka_interval; - int keepalive_timeout; - int timeout_secs_ah_idle; - int ssl_info_event_mask; -#ifdef LWS_WITH_ACCESS_LOG - int log_fd; -#endif - -#ifdef LWS_OPENSSL_SUPPORT - int use_ssl; - int allow_non_ssl_on_ssl_port; - unsigned int user_supplied_ssl_ctx:1; -#endif - - unsigned int created_vhost_protocols:1; - unsigned int being_destroyed:1; - - unsigned char default_protocol_index; - unsigned char raw_protocol_index; -}; - -struct lws_deferred_free -{ - struct lws_deferred_free *next; - time_t deadline; - void *payload; -}; - -typedef union { -#ifdef LWS_WITH_IPV6 - struct sockaddr_in6 sa6; -#endif - struct sockaddr_in sa4; -} sockaddr46; - - -#if defined(LWS_WITH_PEER_LIMITS) -struct lws_peer { - struct lws_peer *next; - struct lws_peer *peer_wait_list; - - time_t time_created; - time_t time_closed_all; - - uint8_t addr[32]; - uint32_t hash; - uint32_t count_wsi; - uint32_t count_ah; - - uint32_t total_wsi; - uint32_t total_ah; - - uint8_t af; -}; -#endif - -/* - * the rest is managed per-context, that includes - * - * - processwide single fd -> wsi lookup - * - contextwide headers pool - */ - -struct lws_context { - time_t last_timeout_check_s; - time_t last_ws_ping_pong_check_s; - time_t time_up; - const struct lws_plat_file_ops *fops; - struct lws_plat_file_ops fops_platform; -#if defined(LWS_WITH_HTTP2) - struct http2_settings set; -#endif -#if defined(LWS_WITH_ZIP_FOPS) - struct lws_plat_file_ops fops_zip; -#endif - struct lws_context_per_thread pt[LWS_MAX_SMP]; - struct lws_conn_stats conn_stats; -#if LWS_MAX_SMP > 1 - pthread_mutex_t lock; - int lock_depth; -#endif -#ifdef _WIN32 -/* different implementation between unix and windows */ - struct lws_fd_hashtable fd_hashtable[FD_HASHTABLE_MODULUS]; -#else -#if defined(LWS_WITH_ESP8266) - struct espconn **connpool; /* .reverse points to the wsi */ - void *rxd; - int rxd_len; - os_timer_t to_timer; -#else - struct lws **lws_lookup; /* fd to wsi */ -#endif -#endif - struct lws_vhost *vhost_list; - struct lws_vhost *vhost_pending_destruction_list; - struct lws_plugin *plugin_list; - struct lws_deferred_free *deferred_free_list; -#if defined(LWS_WITH_PEER_LIMITS) - struct lws_peer **pl_hash_table; - struct lws_peer *peer_wait_list; - time_t next_cull; -#endif - - void *external_baggage_free_on_destroy; - const struct lws_token_limits *token_limits; - void *user_space; - const char *server_string; - const struct lws_protocol_vhost_options *reject_service_keywords; - lws_reload_func deprecation_cb; - -#if defined(LWS_HAVE_SYS_CAPABILITY_H) && defined(LWS_HAVE_LIBCAP) - cap_value_t caps[4]; - char count_caps; -#endif - -#if defined(LWS_WITH_LIBEV) - lws_ev_signal_cb_t * lws_ev_sigint_cb; -#endif -#if defined(LWS_WITH_LIBUV) - uv_signal_cb lws_uv_sigint_cb; - uv_loop_t pu_loop; -#endif -#if defined(LWS_WITH_LIBEVENT) - lws_event_signal_cb_t * lws_event_sigint_cb; -#endif - char canonical_hostname[128]; -#ifdef LWS_LATENCY - unsigned long worst_latency; - char worst_latency_info[256]; -#endif - -#if defined(LWS_WITH_STATS) - uint64_t lws_stats[LWSSTATS_SIZE]; - uint64_t last_dump; - int updated; -#endif -#if defined(LWS_WITH_ESP32) - unsigned long time_last_state_dump; - uint32_t last_free_heap; -#endif - - int max_fds; -#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) - int use_ev_sigint; -#endif - int started_with_parent; - int uid, gid; - - int fd_random; - - int count_wsi_allocated; - int count_cgi_spawned; - unsigned int options; - unsigned int fd_limit_per_thread; - unsigned int timeout_secs; - unsigned int pt_serv_buf_size; - int max_http_header_data; - int simultaneous_ssl_restriction; - int simultaneous_ssl; -#if defined(LWS_WITH_PEER_LIMITS) - uint32_t pl_hash_elements; /* protected by context->lock */ - uint32_t count_peers; /* protected by context->lock */ - unsigned short ip_limit_ah; - unsigned short ip_limit_wsi; -#endif - unsigned int deprecated:1; - unsigned int being_destroyed:1; - unsigned int being_destroyed1:1; - unsigned int requested_kill:1; - unsigned int protocol_init_done:1; - unsigned int ssl_gate_accepts:1; - unsigned int doing_protocol_init; - /* - * set to the Thread ID that's doing the service loop just before entry - * to poll indicates service thread likely idling in poll() - * volatile because other threads may check it as part of processing - * for pollfd event change. - */ - volatile int service_tid; - int service_tid_detected; - - short max_http_header_pool; - short count_threads; - short plugin_protocol_count; - short plugin_extension_count; - short server_string_len; - unsigned short ws_ping_pong_interval; - unsigned short deprecation_pending_listen_close_count; - - uint8_t max_fi; -}; - -int -lws_check_deferred_free(struct lws_context *context, int force); - -#define lws_get_context_protocol(ctx, x) ctx->vhost_list->protocols[x] -#define lws_get_vh_protocol(vh, x) vh->protocols[x] - -LWS_EXTERN void -lws_close_free_wsi_final(struct lws *wsi); -LWS_EXTERN void -lws_libuv_closehandle(struct lws *wsi); -LWS_EXTERN void -lws_libuv_closehandle_manually(struct lws *wsi); -LWS_EXTERN int -lws_libuv_check_watcher_active(struct lws *wsi); - -LWS_VISIBLE LWS_EXTERN int -lws_plat_plugins_init(struct lws_context * context, const char * const *d); - -LWS_VISIBLE LWS_EXTERN int -lws_plat_plugins_destroy(struct lws_context * context); - -LWS_EXTERN void -lws_restart_ws_ping_pong_timer(struct lws *wsi); - -struct lws * -lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd); - - -enum { - LWS_EV_READ = (1 << 0), - LWS_EV_WRITE = (1 << 1), - LWS_EV_START = (1 << 2), - LWS_EV_STOP = (1 << 3), - - LWS_EV_PREPARE_DELETION = (1 << 31), -}; - -#if defined(LWS_WITH_LIBEV) -LWS_EXTERN void -lws_libev_accept(struct lws *new_wsi, lws_sock_file_fd_type desc); -LWS_EXTERN void -lws_libev_io(struct lws *wsi, int flags); -LWS_EXTERN int -lws_libev_init_fd_table(struct lws_context *context); -LWS_EXTERN void -lws_libev_destroyloop(struct lws_context *context, int tsi); -LWS_EXTERN void -lws_libev_run(const struct lws_context *context, int tsi); -#define LWS_LIBEV_ENABLED(context) lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEV) -LWS_EXTERN void lws_feature_status_libev(struct lws_context_creation_info *info); -#else -#define lws_libev_accept(_a, _b) ((void) 0) -#define lws_libev_io(_a, _b) ((void) 0) -#define lws_libev_init_fd_table(_a) (0) -#define lws_libev_run(_a, _b) ((void) 0) -#define lws_libev_destroyloop(_a, _b) ((void) 0) -#define LWS_LIBEV_ENABLED(context) (0) -#if LWS_POSIX && !defined(LWS_WITH_ESP32) -#define lws_feature_status_libev(_a) \ - lwsl_info("libev support not compiled in\n") -#else -#define lws_feature_status_libev(_a) -#endif -#endif - -#if defined(LWS_WITH_LIBUV) -LWS_EXTERN void -lws_libuv_accept(struct lws *new_wsi, lws_sock_file_fd_type desc); -LWS_EXTERN void -lws_libuv_io(struct lws *wsi, int flags); -LWS_EXTERN int -lws_libuv_init_fd_table(struct lws_context *context); -LWS_EXTERN void -lws_libuv_run(const struct lws_context *context, int tsi); -LWS_EXTERN void -lws_libuv_destroyloop(struct lws_context *context, int tsi); -LWS_EXTERN int -lws_uv_initvhost(struct lws_vhost* vh, struct lws*); -#define LWS_LIBUV_ENABLED(context) lws_check_opt(context->options, LWS_SERVER_OPTION_LIBUV) -LWS_EXTERN void lws_feature_status_libuv(struct lws_context_creation_info *info); -#else -#define lws_libuv_accept(_a, _b) ((void) 0) -#define lws_libuv_io(_a, _b) ((void) 0) -#define lws_libuv_init_fd_table(_a) (0) -#define lws_libuv_run(_a, _b) ((void) 0) -#define lws_libuv_destroyloop(_a, _b) ((void) 0) -#define LWS_LIBUV_ENABLED(context) (0) -#if LWS_POSIX && !defined(LWS_WITH_ESP32) -#define lws_feature_status_libuv(_a) \ - lwsl_notice("libuv support not compiled in\n") -#else -#define lws_feature_status_libuv(_a) -#endif -#endif - -#if defined(LWS_WITH_LIBEVENT) -LWS_EXTERN void -lws_libevent_accept(struct lws *new_wsi, lws_sock_file_fd_type desc); -LWS_EXTERN void -lws_libevent_io(struct lws *wsi, int flags); -LWS_EXTERN int -lws_libevent_init_fd_table(struct lws_context *context); -LWS_EXTERN void -lws_libevent_destroyloop(struct lws_context *context, int tsi); -LWS_EXTERN void -lws_libevent_run(const struct lws_context *context, int tsi); -#define LWS_LIBEVENT_ENABLED(context) lws_check_opt(context->options, LWS_SERVER_OPTION_LIBEVENT) -LWS_EXTERN void lws_feature_status_libevent(struct lws_context_creation_info *info); -#else -#define lws_libevent_accept(_a, _b) ((void) 0) -#define lws_libevent_io(_a, _b) ((void) 0) -#define lws_libevent_init_fd_table(_a) (0) -#define lws_libevent_run(_a, _b) ((void) 0) -#define lws_libevent_destroyloop(_a, _b) ((void) 0) -#define LWS_LIBEVENT_ENABLED(context) (0) -#if LWS_POSIX && !defined(LWS_WITH_ESP32) -#define lws_feature_status_libevent(_a) \ - lwsl_notice("libevent support not compiled in\n") -#else -#define lws_feature_status_libevent(_a) -#endif -#endif - - -#ifdef LWS_WITH_IPV6 -#define LWS_IPV6_ENABLED(vh) \ - (!lws_check_opt(vh->context->options, LWS_SERVER_OPTION_DISABLE_IPV6) && \ - !lws_check_opt(vh->options, LWS_SERVER_OPTION_DISABLE_IPV6)) -#else -#define LWS_IPV6_ENABLED(context) (0) -#endif - -#ifdef LWS_WITH_UNIX_SOCK -#define LWS_UNIX_SOCK_ENABLED(vhost) \ - (vhost->options & LWS_SERVER_OPTION_UNIX_SOCK) -#else -#define LWS_UNIX_SOCK_ENABLED(vhost) (0) -#endif - -enum uri_path_states { - URIPS_IDLE, - URIPS_SEEN_SLASH, - URIPS_SEEN_SLASH_DOT, - URIPS_SEEN_SLASH_DOT_DOT, -}; - -enum uri_esc_states { - URIES_IDLE, - URIES_SEEN_PERCENT, - URIES_SEEN_PERCENT_H1, -}; - -/* notice that these union members: - * - * hdr - * http - * http2 - * - * all have a pointer to allocated_headers struct as their first member. - * - * It means for allocated_headers access, the three union paths can all be - * used interchangeably to access the same data - */ - - -#ifndef LWS_NO_CLIENT -struct client_info_stash { - char address[256]; - char path[4096]; - char host[256]; - char origin[256]; - char protocol[256]; - char method[16]; - char iface[16]; -}; -#endif - -struct _lws_header_related { - /* MUST be first in struct */ - struct allocated_headers *ah; - struct lws *ah_wait_list; - unsigned char *preamble_rx; -#ifndef LWS_NO_CLIENT - struct client_info_stash *stash; -#endif - unsigned int preamble_rx_len; - enum uri_path_states ups; - enum uri_esc_states ues; - short lextable_pos; - unsigned int current_token_limit; - - char esc_stash; - char post_literal_equal; - unsigned char parser_state; /* enum lws_token_indexes */ -}; - -#if defined(LWS_WITH_RANGES) -enum range_states { - LWSRS_NO_ACTIVE_RANGE, - LWSRS_BYTES_EQ, - LWSRS_FIRST, - LWSRS_STARTING, - LWSRS_ENDING, - LWSRS_COMPLETED, - LWSRS_SYNTAX, -}; - -struct lws_range_parsing { - unsigned long long start, end, extent, agg, budget; - const char buf[128]; - int pos; - enum range_states state; - char start_valid, end_valid, ctr, count_ranges, did_try, inside, send_ctr; -}; - -int -lws_ranges_init(struct lws *wsi, struct lws_range_parsing *rp, unsigned long long extent); -int -lws_ranges_next(struct lws_range_parsing *rp); -void -lws_ranges_reset(struct lws_range_parsing *rp); -#endif - -struct _lws_http_mode_related { - /* MUST be first in struct */ - struct allocated_headers *ah; /* mirroring _lws_header_related */ - struct lws *ah_wait_list; - unsigned char *preamble_rx; -#ifndef LWS_NO_CLIENT - struct client_info_stash *stash; -#endif - unsigned int preamble_rx_len; - struct lws *new_wsi_list; - lws_filepos_t filepos; - lws_filepos_t filelen; - lws_fop_fd_t fop_fd; - -#if defined(LWS_WITH_RANGES) - struct lws_range_parsing range; - char multipart_content_type[64]; -#endif - - enum http_version request_version; - enum http_connection_type connection_type; - lws_filepos_t tx_content_length; - lws_filepos_t tx_content_remain; - lws_filepos_t rx_content_length; - lws_filepos_t rx_content_remain; -}; - -#define LWS_H2_FRAME_HEADER_LENGTH 9 - -#ifdef LWS_WITH_HTTP2 - -enum lws_h2_wellknown_frame_types { - LWS_H2_FRAME_TYPE_DATA, - LWS_H2_FRAME_TYPE_HEADERS, - LWS_H2_FRAME_TYPE_PRIORITY, - LWS_H2_FRAME_TYPE_RST_STREAM, - LWS_H2_FRAME_TYPE_SETTINGS, - LWS_H2_FRAME_TYPE_PUSH_PROMISE, - LWS_H2_FRAME_TYPE_PING, - LWS_H2_FRAME_TYPE_GOAWAY, - LWS_H2_FRAME_TYPE_WINDOW_UPDATE, - LWS_H2_FRAME_TYPE_CONTINUATION, - - LWS_H2_FRAME_TYPE_COUNT /* always last */ -}; - -enum lws_h2_flags { - LWS_H2_FLAG_END_STREAM = 1, - LWS_H2_FLAG_END_HEADERS = 4, - LWS_H2_FLAG_PADDED = 8, - LWS_H2_FLAG_PRIORITY = 0x20, - - LWS_H2_FLAG_SETTINGS_ACK = 1, -}; - -enum lws_h2_errors { - H2_ERR_NO_ERROR, /* Graceful shutdown */ - H2_ERR_PROTOCOL_ERROR, /* Protocol error detected */ - H2_ERR_INTERNAL_ERROR, /* Implementation fault */ - H2_ERR_FLOW_CONTROL_ERROR, /* Flow-control limits exceeded */ - H2_ERR_SETTINGS_TIMEOUT, /* Settings not acknowledged */ - H2_ERR_STREAM_CLOSED, /* Frame received for closed stream */ - H2_ERR_FRAME_SIZE_ERROR, /* Frame size incorrect */ - H2_ERR_REFUSED_STREAM, /* Stream not processed */ - H2_ERR_CANCEL, /* Stream cancelled */ - H2_ERR_COMPRESSION_ERROR, /* Compression state not updated */ - H2_ERR_CONNECT_ERROR, /* TCP connection error for CONNECT method */ - H2_ERR_ENHANCE_YOUR_CALM, /* Processing capacity exceeded */ - H2_ERR_INADEQUATE_SECURITY, /* Negotiated TLS parameters not acceptable */ - H2_ERR_HTTP_1_1_REQUIRED, /* Use HTTP/1.1 for the request */ -}; - -enum lws_h2_states { - LWS_H2_STATE_IDLE, - /* - * Send PUSH_PROMISE -> LWS_H2_STATE_RESERVED_LOCAL - * Recv PUSH_PROMISE -> LWS_H2_STATE_RESERVED_REMOTE - * Send HEADERS -> LWS_H2_STATE_OPEN - * Recv HEADERS -> LWS_H2_STATE_OPEN - * - * - Only PUSH_PROMISE + HEADERS valid to send - * - Only HEADERS or PRIORITY valid to receive - */ - LWS_H2_STATE_RESERVED_LOCAL, - /* - * Send RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv RST_STREAM -> LWS_H2_STATE_CLOSED - * Send HEADERS -> LWS_H2_STATE_HALF_CLOSED_REMOTE - * - * - Only HEADERS, RST_STREAM, or PRIORITY valid to send - * - Only RST_STREAM, PRIORITY, or WINDOW_UPDATE valid to receive - */ - LWS_H2_STATE_RESERVED_REMOTE, - /* - * Send RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv HEADERS -> LWS_H2_STATE_HALF_CLOSED_LOCAL - * - * - Only RST_STREAM, WINDOW_UPDATE, or PRIORITY valid to send - * - Only HEADERS, RST_STREAM, or PRIORITY valid to receive - */ - LWS_H2_STATE_OPEN, - /* - * Send RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv RST_STREAM -> LWS_H2_STATE_CLOSED - * Send END_STREAM flag -> LWS_H2_STATE_HALF_CLOSED_LOCAL - * Recv END_STREAM flag -> LWS_H2_STATE_HALF_CLOSED_REMOTE - */ - LWS_H2_STATE_HALF_CLOSED_REMOTE, - /* - * Send RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv RST_STREAM -> LWS_H2_STATE_CLOSED - * Send END_STREAM flag -> LWS_H2_STATE_CLOSED - * - * - Any frame valid to send - * - Only WINDOW_UPDATE, PRIORITY, or RST_STREAM valid to receive - */ - LWS_H2_STATE_HALF_CLOSED_LOCAL, - /* - * Send RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv RST_STREAM -> LWS_H2_STATE_CLOSED - * Recv END_STREAM flag -> LWS_H2_STATE_CLOSED - * - * - Only WINDOW_UPDATE, PRIORITY, and RST_STREAM valid to send - * - Any frame valid to receive - */ - LWS_H2_STATE_CLOSED, - /* - * - Only PRIORITY, WINDOW_UPDATE (IGNORE) and RST_STREAM (IGNORE) - * may be received - * - * - Only PRIORITY valid to send - */ -}; - -#define LWS_H2_STREAM_ID_MASTER 0 -#define LWS_H2_SETTINGS_LEN 6 - -enum http2_hpack_state { - HPKS_TYPE, - - HPKS_IDX_EXT, - - HPKS_HLEN, - HPKS_HLEN_EXT, - - HPKS_DATA, -}; - -/* - * lws general parsimonious header strategy is only store values from known - * headers, and refer to them by index. - * - * That means if we can't map the peer header name to one that lws knows, we - * will drop the content but track the indexing with associated_lws_hdr_idx = - * LWS_HPACK_IGNORE_ENTRY. - */ - -enum http2_hpack_type { - HPKT_INDEXED_HDR_7, /* 1xxxxxxx: just "header field" */ - HPKT_INDEXED_HDR_6_VALUE_INCR, /* 01xxxxxx: NEW indexed hdr with value */ - HPKT_LITERAL_HDR_VALUE_INCR, /* 01000000: NEW literal hdr with value */ - HPKT_INDEXED_HDR_4_VALUE, /* 0000xxxx: indexed hdr with value */ - HPKT_INDEXED_HDR_4_VALUE_NEVER, /* 0001xxxx: indexed hdr with value NEVER NEW */ - HPKT_LITERAL_HDR_VALUE, /* 00000000: literal hdr with value */ - HPKT_LITERAL_HDR_VALUE_NEVER, /* 00010000: literal hdr with value NEVER NEW */ - HPKT_SIZE_5 -}; - -#define LWS_HPACK_IGNORE_ENTRY 0xffff - - -struct hpack_dt_entry { - char *value; /* malloc'd */ - uint16_t value_len; - uint16_t hdr_len; /* virtual, for accounting */ - uint16_t lws_hdr_idx; /* LWS_HPACK_IGNORE_ENTRY = IGNORE */ -}; - -struct hpack_dynamic_table { - struct hpack_dt_entry *entries; /* malloc'd */ - uint32_t virtual_payload_usage; - uint32_t virtual_payload_max; - uint16_t pos; - uint16_t used_entries; - uint16_t num_entries; -}; - -enum lws_h2_protocol_send_type { - LWS_PPS_NONE, - LWS_H2_PPS_MY_SETTINGS, - LWS_H2_PPS_ACK_SETTINGS, - LWS_H2_PPS_PONG, - LWS_H2_PPS_GOAWAY, - LWS_H2_PPS_RST_STREAM, - LWS_H2_PPS_UPDATE_WINDOW, -}; - -struct lws_h2_protocol_send { - struct lws_h2_protocol_send *next; /* linked list */ - enum lws_h2_protocol_send_type type; - - union uu { - struct { - char str[32]; - uint32_t highest_sid; - uint32_t err; - } ga; - struct { - uint32_t sid; - uint32_t err; - } rs; - struct { - uint8_t ping_payload[8]; - } ping; - struct { - uint32_t sid; - uint32_t credit; - } update_window; - } u; -}; - -struct lws_h2_ghost_sid { - struct lws_h2_ghost_sid *next; - uint32_t sid; -}; - -#define LWS_H2_RX_SCRATCH_SIZE 512 - -/* - * http/2 connection info that is only used by the root connection that has - * the network connection. - * - * h2 tends to spawn many child connections from one network connection, so - * it's necessary to make members only needed by the network connection - * distinct and only malloc'd on network connections. - * - * There's only one HPACK parser per network connection. - * - * But there is an ah per logical child connection... the network connection - * fills it but it belongs to the logical child. - */ -struct lws_h2_netconn { - struct http2_settings set; - struct hpack_dynamic_table hpack_dyn_table; - uint8_t ping_payload[8]; - uint8_t one_setting[LWS_H2_SETTINGS_LEN]; - char goaway_str[32]; /* for rx */ - struct lws *swsi; - struct lws_h2_protocol_send *pps; /* linked list */ - char *rx_scratch; - - enum http2_hpack_state hpack; - enum http2_hpack_type hpack_type; - - unsigned int huff:1; - unsigned int value:1; - unsigned int unknown_header:1; - unsigned int cont_exp:1; - unsigned int cont_exp_headers:1; - unsigned int we_told_goaway:1; - unsigned int pad_length:1; - unsigned int collected_priority:1; - unsigned int is_first_header_char:1; - unsigned int zero_huff_padding:1; - unsigned int last_action_dyntable_resize:1; - - uint32_t hdr_idx; - uint32_t hpack_len; - uint32_t hpack_e_dep; - uint32_t count; - uint32_t preamble; - uint32_t length; - uint32_t sid; - uint32_t inside; - uint32_t highest_sid; - uint32_t highest_sid_opened; - uint32_t cont_exp_sid; - uint32_t dep; - uint32_t goaway_last_sid; - uint32_t goaway_err; - uint32_t hpack_hdr_len; - - uint32_t rx_scratch_pos; - uint32_t rx_scratch_len; - - uint16_t hpack_pos; - - uint8_t frame_state; - uint8_t type; - uint8_t flags; - uint8_t padding; - uint8_t weight_temp; - uint8_t huff_pad; - char first_hdr_char; - uint8_t hpack_m; - uint8_t ext_count; -}; - -struct _lws_h2_related { - /* - * having this first lets us also re-use all HTTP union code - * and in turn, http_mode_related has allocated headers in right - * place so we can use the header apis on the wsi directly still - */ - struct _lws_http_mode_related http; /* MUST BE FIRST IN STRUCT */ - - struct lws_h2_netconn *h2n; /* malloc'd for root net conn */ - struct lws *parent_wsi; - struct lws *child_list; - struct lws *sibling_list; - - char *pending_status_body; - - int tx_cr; - int peer_tx_cr_est; - unsigned int my_sid; - unsigned int child_count; - int my_priority; - uint32_t dependent_on; - - unsigned int END_STREAM:1; - unsigned int END_HEADERS:1; - unsigned int send_END_STREAM:1; - unsigned int GOING_AWAY; - unsigned int requested_POLLOUT:1; - unsigned int skint:1; - - uint16_t round_robin_POLLOUT; - uint16_t count_POLLOUT_children; - uint8_t h2_state; /* the RFC7540 state of the connection */ - uint8_t weight; - - uint8_t initialized; -}; - -#define HTTP2_IS_TOPLEVEL_WSI(wsi) (!wsi->u.h2.parent_wsi) - -#endif - -struct _lws_websocket_related { - /* cheapest way to deal with ah overlap with ws union transition */ - struct _lws_header_related hdr; - char *rx_ubuf; - unsigned int rx_ubuf_alloc; - struct lws *rx_draining_ext_list; - struct lws *tx_draining_ext_list; - time_t time_next_ping_check; - size_t rx_packet_length; - unsigned int rx_ubuf_head; - unsigned char mask[4]; - /* Also used for close content... control opcode == < 128 */ - unsigned char ping_payload_buf[128 - 3 + LWS_PRE]; - - unsigned char ping_payload_len; - unsigned char mask_idx; - unsigned char opcode; - unsigned char rsv; - unsigned char rsv_first_msg; - /* zero if no info, or length including 2-byte close code */ - unsigned char close_in_ping_buffer_len; - unsigned char utf8; - unsigned char stashed_write_type; - unsigned char tx_draining_stashed_wp; - - unsigned int final:1; - unsigned int frame_is_binary:1; - unsigned int all_zero_nonce:1; - unsigned int this_frame_masked:1; - unsigned int inside_frame:1; /* next write will be more of frame */ - unsigned int clean_buffer:1; /* buffer not rewritten by extension */ - unsigned int payload_is_close:1; /* process as PONG, but it is close */ - unsigned int ping_pending_flag:1; - unsigned int continuation_possible:1; - unsigned int owed_a_fin:1; - unsigned int check_utf8:1; - unsigned int defeat_check_utf8:1; - unsigned int pmce_compressed_message:1; - unsigned int stashed_write_pending:1; - unsigned int rx_draining_ext:1; - unsigned int tx_draining_ext:1; - unsigned int send_check_ping:1; - unsigned int first_fragment:1; -}; - -#ifdef LWS_WITH_CGI - -#define LWS_HTTP_CHUNK_HDR_SIZE 16 - -enum { - SIGNIFICANT_HDR_CONTENT_LENGTH, - SIGNIFICANT_HDR_LOCATION, - SIGNIFICANT_HDR_STATUS, - SIGNIFICANT_HDR_TRANSFER_ENCODING, - - SIGNIFICANT_HDR_COUNT -}; - -/* wsi who is master of the cgi points to an lws_cgi */ - -struct lws_cgi { - struct lws_cgi *cgi_list; - struct lws *stdwsi[3]; /* points to the associated stdin/out/err wsis */ - struct lws *wsi; /* owner */ - unsigned char *headers_buf; - unsigned char *headers_start; - unsigned char *headers_pos; - unsigned char *headers_dumped; - unsigned char *headers_end; - lws_filepos_t content_length; - lws_filepos_t content_length_seen; - int pipe_fds[3][2]; - int match[SIGNIFICANT_HDR_COUNT]; - int pid; - int response_code; - int lp; - char l[12]; - - unsigned int being_closed:1; - unsigned int explicitly_chunked:1; - - unsigned char chunked_grace; -}; -#endif - -signed char char_to_hex(const char c); - -#ifndef LWS_NO_CLIENT -enum lws_chunk_parser { - ELCP_HEX, - ELCP_CR, - ELCP_CONTENT, - ELCP_POST_CR, - ELCP_POST_LF, -}; -#endif - -enum lws_parse_urldecode_results { - LPUR_CONTINUE, - LPUR_SWALLOW, - LPUR_FORBID, - LPUR_EXCESSIVE, -}; - -struct lws_rewrite; - -#ifdef LWS_WITH_ACCESS_LOG -struct lws_access_log { - char *header_log; - char *user_agent; - char *referrer; - unsigned long sent; - int response; -}; -#endif - -struct lws { - - /* structs */ - /* members with mutually exclusive lifetimes are unionized */ - - union u { - struct _lws_http_mode_related http; -#ifdef LWS_WITH_HTTP2 - struct _lws_h2_related h2; -#endif - struct _lws_header_related hdr; - struct _lws_websocket_related ws; - } u; - - /* lifetime members */ - -#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBUV) || defined(LWS_WITH_LIBEVENT) - struct lws_io_watcher w_read; -#endif -#if defined(LWS_WITH_LIBEV) || defined(LWS_WITH_LIBEVENT) - struct lws_io_watcher w_write; -#endif -#ifdef LWS_WITH_ACCESS_LOG - struct lws_access_log access_log; -#endif - time_t pending_timeout_limit; - - /* pointers */ - - struct lws_context *context; - struct lws_vhost *vhost; - struct lws *parent; /* points to parent, if any */ - struct lws *child_list; /* points to first child */ - struct lws *sibling_list; /* subsequent children at same level */ -#ifdef LWS_WITH_CGI - struct lws_cgi *cgi; /* wsi being cgi master have one of these */ -#endif - const struct lws_protocols *protocol; - struct lws **same_vh_protocol_prev, *same_vh_protocol_next; - struct lws *timeout_list; - struct lws **timeout_list_prev; -#if defined(LWS_WITH_PEER_LIMITS) - struct lws_peer *peer; -#endif - - void *user_space; - void *opaque_parent_data; - /* rxflow handling */ - unsigned char *rxflow_buffer; - /* truncated send handling */ - unsigned char *trunc_alloc; /* non-NULL means buffering in progress */ - -#if defined (LWS_WITH_ESP8266) - void *premature_rx; - unsigned short prem_rx_size, prem_rx_pos; -#endif - -#ifndef LWS_NO_EXTENSIONS - const struct lws_extension *active_extensions[LWS_MAX_EXTENSIONS_ACTIVE]; - void *act_ext_user[LWS_MAX_EXTENSIONS_ACTIVE]; -#endif -#ifdef LWS_OPENSSL_SUPPORT - SSL *ssl; - BIO *client_bio; - struct lws *pending_read_list_prev, *pending_read_list_next; -#if defined(LWS_WITH_STATS) - uint64_t accept_start_us; - char seen_rx; -#endif -#endif -#ifdef LWS_WITH_HTTP_PROXY - struct lws_rewrite *rw; -#endif -#ifdef LWS_LATENCY - unsigned long action_start; - unsigned long latency_start; -#endif - lws_sock_file_fd_type desc; /* .filefd / .sockfd */ -#if defined(LWS_WITH_STATS) - uint64_t active_writable_req_us; -#endif - /* ints */ - int position_in_fds_table; - uint32_t rxflow_len; - uint32_t rxflow_pos; - unsigned int trunc_alloc_len; /* size of malloc */ - unsigned int trunc_offset; /* where we are in terms of spilling */ - unsigned int trunc_len; /* how much is buffered */ -#ifndef LWS_NO_CLIENT - int chunk_remaining; -#endif - unsigned int cache_secs; - - unsigned int hdr_parsing_completed:1; - unsigned int http2_substream:1; - unsigned int upgraded_to_http2:1; - unsigned int seen_nonpseudoheader:1; - unsigned int listener:1; - unsigned int user_space_externally_allocated:1; - unsigned int socket_is_permanently_unusable:1; - unsigned int rxflow_change_to:2; - unsigned int more_rx_waiting:1; /* has to live here since ah may stick to end */ - unsigned int conn_stat_done:1; - unsigned int cache_reuse:1; - unsigned int cache_revalidate:1; - unsigned int cache_intermediaries:1; - unsigned int favoured_pollin:1; - unsigned int sending_chunked:1; - unsigned int already_did_cce:1; - unsigned int told_user_closed:1; - unsigned int waiting_to_send_close_frame:1; - unsigned int ipv6:1; - unsigned int parent_carries_io:1; - unsigned int parent_pending_cb_on_writable:1; - unsigned int cgi_stdout_zero_length:1; - unsigned int seen_zero_length_recv:1; - unsigned int rxflow_will_be_applied:1; - -#if defined(LWS_WITH_ESP8266) - unsigned int pending_send_completion:3; - unsigned int close_is_pending_send_completion:1; -#endif -#ifdef LWS_WITH_ACCESS_LOG - unsigned int access_log_pending:1; -#endif -#ifndef LWS_NO_CLIENT - unsigned int do_ws:1; /* whether we are doing http or ws flow */ - unsigned int chunked:1; /* if the clientside connection is chunked */ - unsigned int client_rx_avail:1; - unsigned int client_http_body_pending:1; -#endif -#ifdef LWS_WITH_HTTP_PROXY - unsigned int perform_rewrite:1; -#endif -#ifndef LWS_NO_EXTENSIONS - unsigned int extension_data_pending:1; -#endif -#ifdef LWS_OPENSSL_SUPPORT - unsigned int use_ssl:4; -#endif -#ifdef _WIN32 - unsigned int sock_send_blocking:1; -#endif -#ifdef LWS_OPENSSL_SUPPORT - unsigned int redirect_to_https:1; -#endif - - /* volatile to make sure code is aware other thread can change */ - volatile unsigned int handling_pollout:1; - volatile unsigned int leave_pollout_active:1; - -#ifndef LWS_NO_CLIENT - unsigned short c_port; -#endif - - /* chars */ -#ifndef LWS_NO_EXTENSIONS - unsigned char count_act_ext; -#endif - uint8_t ietf_spec_revision; - char mode; /* enum connection_mode */ - char state; /* enum lws_connection_states */ - char state_pre_close; - char lws_rx_parse_state; /* enum lws_rx_parse_state */ - char rx_frame_type; /* enum lws_write_protocol */ - char pending_timeout; /* enum pending_timeout */ - char tsi; /* thread service index we belong to */ - char protocol_interpret_idx; - char redirects; - uint8_t rxflow_bitmap; -#ifdef LWS_WITH_CGI - char cgi_channel; /* which of stdin/out/err */ - char hdr_state; -#endif -#ifndef LWS_NO_CLIENT - char chunk_parser; /* enum lws_chunk_parser */ -#endif -#if defined(LWS_WITH_CGI) || !defined(LWS_NO_CLIENT) - char reason_bf; /* internal writeable callback reason bitfield */ -#endif -}; - -#define lws_is_flowcontrolled(w) (!!(wsi->rxflow_bitmap)) - -LWS_EXTERN int log_level; - -LWS_EXTERN int -lws_socket_bind(struct lws_vhost *vhost, lws_sockfd_type sockfd, int port, - const char *iface); - -#if defined(LWS_WITH_IPV6) -LWS_EXTERN unsigned long -lws_get_addr_scope(const char *ipaddr); -#endif - -LWS_EXTERN void -lws_close_free_wsi(struct lws *wsi, enum lws_close_status); - -LWS_EXTERN void -lws_free_wsi(struct lws *wsi); - -LWS_EXTERN int -remove_wsi_socket_from_fds(struct lws *wsi); -LWS_EXTERN int -lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len); - -#ifndef LWS_LATENCY -static inline void -lws_latency(struct lws_context *context, struct lws *wsi, const char *action, - int ret, int completion) { - do { - (void)context; (void)wsi; (void)action; (void)ret; - (void)completion; - } while (0); -} -static inline void -lws_latency_pre(struct lws_context *context, struct lws *wsi) { - do { (void)context; (void)wsi; } while (0); -} -#else -#define lws_latency_pre(_context, _wsi) lws_latency(_context, _wsi, NULL, 0, 0) -extern void -lws_latency(struct lws_context *context, struct lws *wsi, const char *action, - int ret, int completion); -#endif - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_client_rx_sm(struct lws *wsi, unsigned char c); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_parse(struct lws *wsi, unsigned char c); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_parse_urldecode(struct lws *wsi, uint8_t *_c); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_http_action(struct lws *wsi); - -LWS_EXTERN int -lws_b64_selftest(void); - -LWS_EXTERN int -lws_service_flag_pending(struct lws_context *context, int tsi); - -#if defined(_WIN32) || defined(LWS_WITH_ESP8266) -LWS_EXTERN struct lws * -wsi_from_fd(const struct lws_context *context, lws_sockfd_type fd); - -LWS_EXTERN int -insert_wsi(struct lws_context *context, struct lws *wsi); - -LWS_EXTERN int -delete_from_fd(struct lws_context *context, lws_sockfd_type fd); -#else -#define wsi_from_fd(A,B) A->lws_lookup[B] -#define insert_wsi(A,B) assert(A->lws_lookup[B->desc.sockfd] == 0); A->lws_lookup[B->desc.sockfd]=B -#define delete_from_fd(A,B) A->lws_lookup[B]=0 -#endif - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -insert_wsi_socket_into_fds(struct lws_context *context, struct lws *wsi); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len); - - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_service_timeout_check(struct lws *wsi, unsigned int sec); - -LWS_EXTERN void -lws_remove_from_timeout_list(struct lws *wsi); - -LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT -lws_client_connect_2(struct lws *wsi); - -LWS_VISIBLE struct lws * LWS_WARN_UNUSED_RESULT -lws_client_reset(struct lws **wsi, int ssl, const char *address, int port, - const char *path, const char *host); - -LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT -lws_create_new_server_wsi(struct lws_vhost *vhost); - -LWS_EXTERN char * LWS_WARN_UNUSED_RESULT -lws_generate_client_handshake(struct lws *wsi, char *pkt); - -LWS_EXTERN int -lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd); - -LWS_EXTERN struct lws * -lws_client_connect_via_info2(struct lws *wsi); - -LWS_EXTERN int -_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah); - -/* - * EXTENSIONS - */ - -#ifndef LWS_NO_EXTENSIONS -LWS_VISIBLE void -lws_context_init_extensions(struct lws_context_creation_info *info, - struct lws_context *context); -LWS_EXTERN int -lws_any_extension_handled(struct lws *wsi, enum lws_extension_callback_reasons r, - void *v, size_t len); - -LWS_EXTERN int -lws_ext_cb_active(struct lws *wsi, int reason, void *buf, int len); -LWS_EXTERN int -lws_ext_cb_all_exts(struct lws_context *context, struct lws *wsi, int reason, - void *arg, int len); - -#else -#define lws_any_extension_handled(_a, _b, _c, _d) (0) -#define lws_ext_cb_active(_a, _b, _c, _d) (0) -#define lws_ext_cb_all_exts(_a, _b, _c, _d, _e) (0) -#define lws_issue_raw_ext_access lws_issue_raw -#define lws_context_init_extensions(_a, _b) -#endif - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_client_interpret_server_handshake(struct lws *wsi); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_rx_sm(struct lws *wsi, unsigned char c); - -LWS_EXTERN int -lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf, size_t *len); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_issue_raw_ext_access(struct lws *wsi, unsigned char *buf, size_t len); - -LWS_EXTERN void -lws_union_transition(struct lws *wsi, enum connection_mode mode); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -user_callback_handle_rxflow(lws_callback_function, struct lws *wsi, - enum lws_callback_reasons reason, void *user, - void *in, size_t len); -#ifdef LWS_WITH_HTTP2 -struct lws * lws_h2_get_nth_child(struct lws *wsi, int n); -LWS_EXTERN void lws_h2_init(struct lws *wsi); -LWS_EXTERN int -lws_h2_settings(struct lws *nwsi, struct http2_settings *settings, - unsigned char *buf, int len); -LWS_EXTERN int -lws_h2_parser(struct lws *wsi, unsigned char c); -LWS_EXTERN int lws_h2_do_pps_send(struct lws *wsi); -LWS_EXTERN int lws_h2_frame_write(struct lws *wsi, int type, int flags, - unsigned int sid, unsigned int len, - unsigned char *buf); -LWS_EXTERN struct lws * -lws_h2_wsi_from_id(struct lws *wsi, unsigned int sid); -LWS_EXTERN int lws_hpack_interpret(struct lws *wsi, - unsigned char c); -LWS_EXTERN int -lws_add_http2_header_by_name(struct lws *wsi, - const unsigned char *name, - const unsigned char *value, int length, - unsigned char **p, unsigned char *end); -LWS_EXTERN int -lws_add_http2_header_by_token(struct lws *wsi, - enum lws_token_indexes token, - const unsigned char *value, int length, - unsigned char **p, unsigned char *end); -LWS_EXTERN int -lws_add_http2_header_status(struct lws *wsi, - unsigned int code, unsigned char **p, - unsigned char *end); -LWS_EXTERN int -lws_h2_configure_if_upgraded(struct lws *wsi); -LWS_EXTERN void -lws_hpack_destroy_dynamic_header(struct lws *wsi); -LWS_EXTERN int -lws_hpack_dynamic_size(struct lws *wsi, int size); -LWS_EXTERN int -lws_h2_goaway(struct lws *wsi, uint32_t err, const char *reason); -LWS_EXTERN int -lws_h2_tx_cr_get(struct lws *wsi); -LWS_EXTERN void -lws_h2_tx_cr_consume(struct lws *wsi, int consumed); -LWS_EXTERN int -lws_hdr_extant(struct lws *wsi, enum lws_token_indexes h); -LWS_EXTERN void -lws_pps_schedule(struct lws *wsi, struct lws_h2_protocol_send *pss); - -LWS_EXTERN const struct http2_settings lws_h2_defaults; -#else -#define lws_h2_configure_if_upgraded(x) -#endif - -LWS_EXTERN int -lws_plat_set_socket_options(struct lws_vhost *vhost, lws_sockfd_type fd); - -LWS_EXTERN int -lws_plat_check_connection_error(struct lws *wsi); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_header_table_attach(struct lws *wsi, int autoservice); - -LWS_EXTERN int -lws_header_table_detach(struct lws *wsi, int autoservice); - -LWS_EXTERN void -lws_header_table_reset(struct lws *wsi, int autoservice); -void -_lws_header_table_reset(struct allocated_headers *ah); - -void -lws_header_table_force_to_detachable_state(struct lws *wsi); -int -lws_header_table_is_in_detachable_state(struct lws *wsi); - -LWS_EXTERN char * LWS_WARN_UNUSED_RESULT -lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ensure_user_space(struct lws *wsi); - -LWS_EXTERN int -lws_change_pollfd(struct lws *wsi, int _and, int _or); - -#ifndef LWS_NO_SERVER -int lws_context_init_server(struct lws_context_creation_info *info, - struct lws_vhost *vhost); -LWS_EXTERN struct lws_vhost * -lws_select_vhost(struct lws_context *context, int port, const char *servername); -LWS_EXTERN int -handshake_0405(struct lws_context *context, struct lws *wsi); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len); -LWS_EXTERN void -lws_server_get_canonical_hostname(struct lws_context *context, - struct lws_context_creation_info *info); -#else -#define lws_context_init_server(_a, _b) (0) -#define lws_interpret_incoming_packet(_a, _b, _c) (0) -#define lws_server_get_canonical_hostname(_a, _b) -#endif - -#ifndef LWS_NO_DAEMONIZE -LWS_EXTERN int get_daemonize_pid(); -#else -#define get_daemonize_pid() (0) -#endif - -#if !defined(LWS_WITH_ESP8266) -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -interface_to_sa(struct lws_vhost *vh, const char *ifname, - struct sockaddr_in *addr, size_t addrlen); -#endif -LWS_EXTERN void lwsl_emit_stderr(int level, const char *line); - -enum lws_ssl_capable_status { - LWS_SSL_CAPABLE_ERROR = -1, - LWS_SSL_CAPABLE_MORE_SERVICE = -2, -}; - -#ifndef LWS_OPENSSL_SUPPORT -#define LWS_SSL_ENABLED(context) (0) -#define lws_context_init_server_ssl(_a, _b) (0) -#define lws_ssl_destroy(_a) -#define lws_context_init_http2_ssl(_a) -#define lws_ssl_capable_read lws_ssl_capable_read_no_ssl -#define lws_ssl_capable_write lws_ssl_capable_write_no_ssl -#define lws_ssl_pending lws_ssl_pending_no_ssl -#define lws_server_socket_service_ssl(_b, _c) (0) -#define lws_ssl_close(_a) (0) -#define lws_ssl_context_destroy(_a) -#define lws_ssl_SSL_CTX_destroy(_a) -#define lws_ssl_remove_wsi_from_buffered_list(_a) -#define lws_context_init_ssl_library(_a) -#define lws_ssl_anybody_has_buffered_read_tsi(_a, _b) (0) -#else -#define LWS_SSL_ENABLED(context) (context->use_ssl) -LWS_EXTERN int openssl_websocket_private_data_index; -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_pending(struct lws *wsi); -LWS_EXTERN int -lws_context_init_ssl_library(struct lws_context_creation_info *info); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_server_socket_service_ssl(struct lws *new_wsi, lws_sockfd_type accept_fd); -LWS_EXTERN int -lws_ssl_close(struct lws *wsi); -LWS_EXTERN void -lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost); -LWS_EXTERN void -lws_ssl_context_destroy(struct lws_context *context); -LWS_VISIBLE void -lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi); -LWS_EXTERN int -lws_ssl_client_bio_create(struct lws *wsi); -LWS_EXTERN int -lws_ssl_client_connect1(struct lws *wsi); -LWS_EXTERN int -lws_ssl_client_connect2(struct lws *wsi); -LWS_EXTERN void -lws_ssl_elaborate_error(void); -LWS_EXTERN int -lws_ssl_anybody_has_buffered_read_tsi(struct lws_context *context, int tsi); -#ifndef LWS_NO_SERVER -LWS_EXTERN int -lws_context_init_server_ssl(struct lws_context_creation_info *info, - struct lws_vhost *vhost); -#else -#define lws_context_init_server_ssl(_a, _b) (0) -#endif -LWS_EXTERN void -lws_ssl_destroy(struct lws_vhost *vhost); -/* HTTP2-related */ - -#ifdef LWS_WITH_HTTP2 -LWS_EXTERN void -lws_context_init_http2_ssl(struct lws_vhost *vhost); -#else -#define lws_context_init_http2_ssl(_a) -#endif -#endif - -#if LWS_MAX_SMP > 1 -static LWS_INLINE void -lws_pt_mutex_init(struct lws_context_per_thread *pt) -{ - pthread_mutex_init(&pt->lock, NULL); -} - -static LWS_INLINE void -lws_pt_mutex_destroy(struct lws_context_per_thread *pt) -{ - pthread_mutex_destroy(&pt->lock); -} - -static LWS_INLINE void -lws_pt_lock(struct lws_context_per_thread *pt) -{ - if (!pt->lock_depth++) - pthread_mutex_lock(&pt->lock); -} - -static LWS_INLINE void -lws_pt_unlock(struct lws_context_per_thread *pt) -{ - if (!(--pt->lock_depth)) - pthread_mutex_unlock(&pt->lock); -} -static LWS_INLINE void -lws_context_lock(struct lws_context *context) -{ - if (!context->lock_depth++) - pthread_mutex_lock(&context->lock); -} - -static LWS_INLINE void -lws_context_unlock(struct lws_context *context) -{ - if (!(--context->lock_depth)) - pthread_mutex_unlock(&context->lock); -} - -#else -#define lws_pt_mutex_init(_a) (void)(_a) -#define lws_pt_mutex_destroy(_a) (void)(_a) -#define lws_pt_lock(_a) (void)(_a) -#define lws_pt_unlock(_a) (void)(_a) -#define lws_context_lock(_a) (void)(_a) -#define lws_context_unlock(_a) (void)(_a) -#endif - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_ssl_pending_no_ssl(struct lws *wsi); - -#ifdef LWS_WITH_HTTP_PROXY -struct lws_rewrite { - hubbub_parser *parser; - hubbub_parser_optparams params; - const char *from, *to; - int from_len, to_len; - unsigned char *p, *end; - struct lws *wsi; -}; -static LWS_INLINE int hstrcmp(hubbub_string *s, const char *p, int len) -{ - if (s->len != len) - return 1; - - return strncmp((const char *)s->ptr, p, len); -} -typedef hubbub_error (*hubbub_callback_t)(const hubbub_token *token, void *pw); -LWS_EXTERN struct lws_rewrite * -lws_rewrite_create(struct lws *wsi, hubbub_callback_t cb, const char *from, const char *to); -LWS_EXTERN void -lws_rewrite_destroy(struct lws_rewrite *r); -LWS_EXTERN int -lws_rewrite_parse(struct lws_rewrite *r, const unsigned char *in, int in_len); -#endif - -#ifndef LWS_NO_CLIENT -LWS_EXTERN int lws_client_socket_service(struct lws_context *context, - struct lws *wsi, - struct lws_pollfd *pollfd); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_http_transaction_completed_client(struct lws *wsi); -#ifdef LWS_OPENSSL_SUPPORT -LWS_EXTERN int -lws_context_init_client_ssl(struct lws_context_creation_info *info, - struct lws_vhost *vhost); - -LWS_EXTERN void -lws_ssl_info_callback(const SSL *ssl, int where, int ret); - -#else - #define lws_context_init_client_ssl(_a, _b) (0) -#endif -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len); -LWS_EXTERN void -lws_decode_ssl_error(void); -#else -#define lws_context_init_client_ssl(_a, _b) (0) -#define lws_handshake_client(_a, _b, _c) (0) -#endif - -LWS_EXTERN int -_lws_rx_flow_control(struct lws *wsi); - -LWS_EXTERN int -_lws_change_pollfd(struct lws *wsi, int _and, int _or, struct lws_pollargs *pa); - -#ifndef LWS_NO_SERVER -LWS_EXTERN int -lws_server_socket_service(struct lws_context *context, struct lws *wsi, - struct lws_pollfd *pollfd); -LWS_EXTERN int -lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len); -#else -#define lws_server_socket_service(_a, _b, _c) (0) -#define lws_handshake_server(_a, _b, _c) (0) -#endif - -#ifdef LWS_WITH_ACCESS_LOG -LWS_EXTERN int -lws_access_log(struct lws *wsi); -LWS_EXTERN void -lws_prepare_access_log_info(struct lws *wsi, char *uri_ptr, int meth); -#else -#define lws_access_log(_a) -#endif - -LWS_EXTERN int -lws_cgi_kill_terminated(struct lws_context_per_thread *pt); - -LWS_EXTERN void -lws_cgi_remove_and_kill(struct lws *wsi); - -int -lws_protocol_init(struct lws_context *context); - -int -lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p); - -const struct lws_http_mount * -lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len); - -/* - * custom allocator - */ -LWS_EXTERN void * -lws_realloc(void *ptr, size_t size, const char *reason); - -LWS_EXTERN void * LWS_WARN_UNUSED_RESULT -lws_zalloc(size_t size, const char *reason); - -#ifdef LWS_PLAT_OPTEE -void *lws_malloc(size_t size, const char *reason); -void lws_free(void *p); -#define lws_free_set_NULL(P) do { lws_free(P); (P) = NULL; } while(0) -#else -#define lws_malloc(S, R) lws_realloc(NULL, S, R) -#define lws_free(P) lws_realloc(P, 0, "lws_free") -#define lws_free_set_NULL(P) do { lws_realloc(P, 0, "free"); (P) = NULL; } while(0) -#endif - -const struct lws_plat_file_ops * -lws_vfs_select_fops(const struct lws_plat_file_ops *fops, const char *vfs_path, - const char **vpath); - -/* lws_plat_ */ -LWS_EXTERN void -lws_plat_delete_socket_from_fds(struct lws_context *context, - struct lws *wsi, int m); -LWS_EXTERN void -lws_plat_insert_socket_into_fds(struct lws_context *context, - struct lws *wsi); -LWS_EXTERN void -lws_plat_service_periodic(struct lws_context *context); - -LWS_EXTERN int -lws_plat_change_pollfd(struct lws_context *context, struct lws *wsi, - struct lws_pollfd *pfd); -LWS_EXTERN void -lws_add_wsi_to_draining_ext_list(struct lws *wsi); -LWS_EXTERN void -lws_remove_wsi_from_draining_ext_list(struct lws *wsi); -LWS_EXTERN int -lws_plat_context_early_init(void); -LWS_EXTERN void -lws_plat_context_early_destroy(struct lws_context *context); -LWS_EXTERN void -lws_plat_context_late_destroy(struct lws_context *context); -LWS_EXTERN int -lws_poll_listen_fd(struct lws_pollfd *fd); -LWS_EXTERN int -lws_plat_service(struct lws_context *context, int timeout_ms); -LWS_EXTERN LWS_VISIBLE int -_lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi); -LWS_EXTERN int -lws_plat_init(struct lws_context *context, - struct lws_context_creation_info *info); -LWS_EXTERN void -lws_plat_drop_app_privileges(struct lws_context_creation_info *info); -LWS_EXTERN unsigned long long -time_in_microseconds(void); -LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT -lws_plat_inet_ntop(int af, const void *src, char *dst, int cnt); -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_plat_inet_pton(int af, const char *src, void *dst); - -LWS_EXTERN int LWS_WARN_UNUSED_RESULT -lws_check_utf8(unsigned char *state, unsigned char *buf, size_t len); -LWS_EXTERN int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount); -LWS_EXTERN int alloc_pem_to_der_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount); - -LWS_EXTERN void -lws_same_vh_protocol_remove(struct lws *wsi); -LWS_EXTERN void -lws_same_vh_protocol_insert(struct lws *wsi, int n); - -#if defined(LWS_WITH_STATS) -void -lws_stats_atomic_bump(struct lws_context * context, - struct lws_context_per_thread *pt, int index, uint64_t bump); -void -lws_stats_atomic_max(struct lws_context * context, - struct lws_context_per_thread *pt, int index, uint64_t val); -#else -static inline uint64_t lws_stats_atomic_bump(struct lws_context * context, - struct lws_context_per_thread *pt, int index, uint64_t bump) { - (void)context; (void)pt; (void)index; (void)bump; return 0; } -static inline uint64_t lws_stats_atomic_max(struct lws_context * context, - struct lws_context_per_thread *pt, int index, uint64_t val) { - (void)context; (void)pt; (void)index; (void)val; return 0; } -#endif - -/* socks */ -void socks_generate_msg(struct lws *wsi, enum socks_msg_type type, - ssize_t *msg_len); - -#if defined(LWS_WITH_PEER_LIMITS) -void -lws_peer_track_wsi_close(struct lws_context *context, struct lws_peer *peer); -int -lws_peer_confirm_ah_attach_ok(struct lws_context *context, struct lws_peer *peer); -void -lws_peer_track_ah_detach(struct lws_context *context, struct lws_peer *peer); -void -lws_peer_cull_peer_wait_list(struct lws_context *context); -struct lws_peer * -lws_get_or_create_peer(struct lws_vhost *vhost, lws_sockfd_type sockfd); -void -lws_peer_add_wsi(struct lws_context *context, struct lws_peer *peer, - struct lws *wsi); -#endif - -#ifdef __cplusplus -}; -#endif diff --git a/thirdparty/lws/server/parsers.c b/thirdparty/lws/server/parsers.c deleted file mode 100644 index fb345ab04c..0000000000 --- a/thirdparty/lws/server/parsers.c +++ /dev/null @@ -1,1783 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -const unsigned char lextable[] = { - #include "lextable.h" -}; - -#define FAIL_CHAR 0x08 - -int LWS_WARN_UNUSED_RESULT -lextable_decode(int pos, char c) -{ - if (c >= 'A' && c <= 'Z') - c += 'a' - 'A'; - - while (1) { - if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */ - if ((lextable[pos] & 0x7f) != c) - return -1; - /* fall thru */ - pos++; - if (lextable[pos] == FAIL_CHAR) - return -1; - return pos; - } - - if (lextable[pos] == FAIL_CHAR) - return -1; - - /* b7 = 0, end or 3-byte */ - if (lextable[pos] < FAIL_CHAR) /* terminal marker */ - return pos; - - if (lextable[pos] == c) /* goto */ - return pos + (lextable[pos + 1]) + - (lextable[pos + 2] << 8); - /* fall thru goto */ - pos += 3; - /* continue */ - } -} - -static struct allocated_headers * -_lws_create_ah(struct lws_context_per_thread *pt, ah_data_idx_t data_size) -{ - struct allocated_headers *ah = lws_zalloc(sizeof(*ah), "ah struct"); - - if (!ah) - return NULL; - - ah->data = lws_malloc(data_size, "ah data"); - if (!ah->data) { - lws_free(ah); - - return NULL; - } - ah->next = pt->ah_list; - pt->ah_list = ah; - ah->data_length = data_size; - pt->ah_pool_length++; - - lwsl_info("%s: created ah %p (size %d): pool length %d\n", __func__, - ah, (int)data_size, pt->ah_pool_length); - - return ah; -} - -int -_lws_destroy_ah(struct lws_context_per_thread *pt, struct allocated_headers *ah) -{ - lws_start_foreach_llp(struct allocated_headers **, a, pt->ah_list) { - if ((*a) == ah) { - *a = ah->next; - pt->ah_pool_length--; - lwsl_info("%s: freed ah %p : pool length %d\n", - __func__, ah, pt->ah_pool_length); - if (ah->data) - lws_free(ah->data); - lws_free(ah); - - return 0; - } - } lws_end_foreach_llp(a, next); - - return 1; -} - -void -_lws_header_table_reset(struct allocated_headers *ah) -{ - /* init the ah to reflect no headers or data have appeared yet */ - memset(ah->frag_index, 0, sizeof(ah->frag_index)); - memset(ah->frags, 0, sizeof(ah->frags)); - ah->nfrag = 0; - ah->pos = 0; - ah->http_response = 0; -} - -// doesn't scrub the ah rxbuffer by default, parent must do if needed - -void -lws_header_table_reset(struct lws *wsi, int autoservice) -{ - struct allocated_headers *ah = wsi->u.hdr.ah; - struct lws_context_per_thread *pt; - struct lws_pollfd *pfd; - - /* if we have the idea we're resetting 'our' ah, must be bound to one */ - assert(ah); - /* ah also concurs with ownership */ - assert(ah->wsi == wsi); - - _lws_header_table_reset(ah); - - wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; - wsi->u.hdr.lextable_pos = 0; - - /* since we will restart the ah, our new headers are not completed */ - wsi->hdr_parsing_completed = 0; - - /* while we hold the ah, keep a timeout on the wsi */ - lws_set_timeout(wsi, PENDING_TIMEOUT_HOLDING_AH, - wsi->vhost->timeout_secs_ah_idle); - - time(&ah->assigned); - - /* - * if we inherited pending rx (from socket adoption deferred - * processing), apply and free it. - */ - if (wsi->u.hdr.preamble_rx) { - memcpy(ah->rx, wsi->u.hdr.preamble_rx, - wsi->u.hdr.preamble_rx_len); - ah->rxlen = wsi->u.hdr.preamble_rx_len; - lws_free_set_NULL(wsi->u.hdr.preamble_rx); - - if (autoservice) { - lwsl_debug("%s: service on readbuf ah\n", __func__); - - pt = &wsi->context->pt[(int)wsi->tsi]; - /* - * Unlike a normal connect, we have the headers already - * (or the first part of them anyway) - */ - pfd = &pt->fds[wsi->position_in_fds_table]; - pfd->revents |= LWS_POLLIN; - lwsl_err("%s: calling service\n", __func__); - lws_service_fd_tsi(wsi->context, pfd, wsi->tsi); - } - } -} - -static void -_lws_header_ensure_we_are_on_waiting_list(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - struct lws_pollargs pa; - struct lws **pwsi = &pt->ah_wait_list; - - while (*pwsi) { - if (*pwsi == wsi) - return; - pwsi = &(*pwsi)->u.hdr.ah_wait_list; - } - - lwsl_info("%s: wsi: %p\n", __func__, wsi); - wsi->u.hdr.ah_wait_list = pt->ah_wait_list; - pt->ah_wait_list = wsi; - pt->ah_wait_list_length++; - - /* we cannot accept input then */ - - _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa); -} - -static int -__lws_remove_from_ah_waiting_list(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - struct lws **pwsi =&pt->ah_wait_list; - - while (*pwsi) { - if (*pwsi == wsi) { - lwsl_info("%s: wsi %p\n", __func__, wsi); - /* point prev guy to our next */ - *pwsi = wsi->u.hdr.ah_wait_list; - /* we shouldn't point anywhere now */ - wsi->u.hdr.ah_wait_list = NULL; - pt->ah_wait_list_length--; - - return 1; - } - pwsi = &(*pwsi)->u.hdr.ah_wait_list; - } - - return 0; -} - -int LWS_WARN_UNUSED_RESULT -lws_header_table_attach(struct lws *wsi, int autoservice) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - struct lws_pollargs pa; - int n; - - lwsl_info("%s: wsi %p: ah %p (tsi %d, count = %d) in\n", __func__, - (void *)wsi, (void *)wsi->u.hdr.ah, wsi->tsi, - pt->ah_count_in_use); - - /* if we are already bound to one, just clear it down */ - if (wsi->u.hdr.ah) { - lwsl_info("%s: cleardown\n", __func__); - goto reset; - } - - lws_pt_lock(pt); - - n = pt->ah_count_in_use == context->max_http_header_pool; -#if defined(LWS_WITH_PEER_LIMITS) - if (!n) { - n = lws_peer_confirm_ah_attach_ok(context, wsi->peer); - if (n) - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); - } -#endif - if (n) { - /* - * Pool is either all busy, or we don't want to give this - * particular guy an ah right now... - * - * Make sure we are on the waiting list, and return that we - * weren't able to provide the ah - */ - _lws_header_ensure_we_are_on_waiting_list(wsi); - - goto bail; - } - - __lws_remove_from_ah_waiting_list(wsi); - - wsi->u.hdr.ah = _lws_create_ah(pt, context->max_http_header_data); - if (!wsi->u.hdr.ah) { /* we could not create an ah */ - _lws_header_ensure_we_are_on_waiting_list(wsi); - - goto bail; - } - - wsi->u.hdr.ah->in_use = 1; - wsi->u.hdr.ah->wsi = wsi; /* mark our owner */ - pt->ah_count_in_use++; - -#if defined(LWS_WITH_PEER_LIMITS) - if (wsi->peer) - wsi->peer->count_ah++; -#endif - - _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); - - lwsl_info("%s: did attach wsi %p: ah %p: count %d (on exit)\n", __func__, - (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use); - - lws_pt_unlock(pt); - -reset: - - /* and reset the rx state */ - wsi->u.hdr.ah->rxpos = 0; - wsi->u.hdr.ah->rxlen = 0; - - lws_header_table_reset(wsi, autoservice); - -#ifndef LWS_NO_CLIENT - if (wsi->state == LWSS_CLIENT_UNCONNECTED) - if (!lws_client_connect_via_info2(wsi)) - /* our client connect has failed, the wsi - * has been closed - */ - return -1; -#endif - - return 0; - -bail: - lws_pt_unlock(pt); - - return 1; -} - -void -lws_header_table_force_to_detachable_state(struct lws *wsi) -{ - if (wsi->u.hdr.ah) { - wsi->u.hdr.ah->rxpos = -1; - wsi->u.hdr.ah->rxlen = -1; - wsi->hdr_parsing_completed = 1; - } -} - -int -lws_header_table_is_in_detachable_state(struct lws *wsi) -{ - struct allocated_headers *ah = wsi->u.hdr.ah; - - return ah && ah->rxpos == ah->rxlen && wsi->hdr_parsing_completed; -} - -int lws_header_table_detach(struct lws *wsi, int autoservice) -{ - struct lws_context *context = wsi->context; - struct allocated_headers *ah = wsi->u.hdr.ah; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - struct lws_pollargs pa; - struct lws **pwsi, **pwsi_eligible; - time_t now; - - lws_pt_lock(pt); - __lws_remove_from_ah_waiting_list(wsi); - lws_pt_unlock(pt); - - if (!ah) - return 0; - - lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, - (void *)wsi, (void *)ah, wsi->tsi, - pt->ah_count_in_use); - - if (wsi->u.hdr.preamble_rx) - lws_free_set_NULL(wsi->u.hdr.preamble_rx); - - /* may not be detached while he still has unprocessed rx */ - if (!lws_header_table_is_in_detachable_state(wsi)) { - lwsl_err("%s: %p: CANNOT DETACH rxpos:%d, rxlen:%d, " - "wsi->hdr_parsing_completed = %d\n", __func__, wsi, - ah->rxpos, ah->rxlen, wsi->hdr_parsing_completed); - return 0; - } - - lws_pt_lock(pt); - - /* we did have an ah attached */ - time(&now); - if (ah->assigned && now - ah->assigned > 3) { - /* - * we're detaching the ah, but it was held an - * unreasonably long time - */ - lwsl_debug("%s: wsi %p: ah held %ds, " - "ah.rxpos %d, ah.rxlen %d, mode/state %d %d," - "wsi->more_rx_waiting %d\n", __func__, wsi, - (int)(now - ah->assigned), - ah->rxpos, ah->rxlen, wsi->mode, wsi->state, - wsi->more_rx_waiting); - } - - ah->assigned = 0; - - /* if we think we're detaching one, there should be one in use */ - assert(pt->ah_count_in_use > 0); - /* and this specific one should have been in use */ - assert(ah->in_use); - wsi->u.hdr.ah = NULL; - ah->wsi = NULL; /* no owner */ -#if defined(LWS_WITH_PEER_LIMITS) - lws_peer_track_ah_detach(context, wsi->peer); -#endif - - pwsi = &pt->ah_wait_list; - - /* oh there is nobody on the waiting list... leave the ah unattached */ - if (!*pwsi) - goto nobody_usable_waiting; - - /* - * at least one wsi on the same tsi is waiting, give it to oldest guy - * who is allowed to take it (if any) - */ - lwsl_info("pt wait list %p\n", *pwsi); - wsi = NULL; - pwsi_eligible = NULL; - - while (*pwsi) { -#if defined(LWS_WITH_PEER_LIMITS) - /* are we willing to give this guy an ah? */ - if (!lws_peer_confirm_ah_attach_ok(context, (*pwsi)->peer)) -#endif - { - wsi = *pwsi; - pwsi_eligible = pwsi; - } -#if defined(LWS_WITH_PEER_LIMITS) - else - if (!(*pwsi)->u.hdr.ah_wait_list) - lws_stats_atomic_bump(context, pt, - LWSSTATS_C_PEER_LIMIT_AH_DENIED, 1); -#endif - pwsi = &(*pwsi)->u.hdr.ah_wait_list; - } - - if (!wsi) /* everybody waiting already has too many ah... */ - goto nobody_usable_waiting; - - lwsl_info("%s: last eligible wsi in wait list %p\n", __func__, wsi); - - wsi->u.hdr.ah = ah; - ah->wsi = wsi; /* new owner */ - - /* and reset the rx state */ - ah->rxpos = 0; - ah->rxlen = 0; - lws_header_table_reset(wsi, autoservice); -#if defined(LWS_WITH_PEER_LIMITS) - if (wsi->peer) - wsi->peer->count_ah++; -#endif - - /* clients acquire the ah and then insert themselves in fds table... */ - if (wsi->position_in_fds_table != -1) { - lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi); - - /* he has been stuck waiting for an ah, but now his wait is - * over, let him progress */ - - _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa); - } - - /* point prev guy to next guy in list instead */ - *pwsi_eligible = wsi->u.hdr.ah_wait_list; - /* the guy who got one is out of the list */ - wsi->u.hdr.ah_wait_list = NULL; - pt->ah_wait_list_length--; - -#ifndef LWS_NO_CLIENT - if (wsi->state == LWSS_CLIENT_UNCONNECTED) { - lws_pt_unlock(pt); - - if (!lws_client_connect_via_info2(wsi)) { - /* our client connect has failed, the wsi - * has been closed - */ - - return -1; - } - return 0; - } -#endif - - assert(!!pt->ah_wait_list_length == !!(lws_intptr_t)pt->ah_wait_list); -bail: - lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__, - (void *)wsi, (void *)ah, pt->tid, pt->ah_count_in_use); - - lws_pt_unlock(pt); - - return 0; - -nobody_usable_waiting: - lwsl_info("%s: nobody usable waiting\n", __func__); - _lws_destroy_ah(pt, ah); - pt->ah_count_in_use--; - - goto bail; -} - -LWS_VISIBLE int -lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx) -{ - int n; - - if (!wsi->u.hdr.ah) - return 0; - - n = wsi->u.hdr.ah->frag_index[h]; - if (!n) - return 0; - do { - if (!frag_idx) - return wsi->u.hdr.ah->frags[n].len; - n = wsi->u.hdr.ah->frags[n].nfrag; - } while (frag_idx-- && n); - - return 0; -} - -LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h) -{ - int n; - int len = 0; - - if (!wsi->u.hdr.ah) - return 0; - - n = wsi->u.hdr.ah->frag_index[h]; - if (!n) - return 0; - do { - len += wsi->u.hdr.ah->frags[n].len; - n = wsi->u.hdr.ah->frags[n].nfrag; - } while (n); - - return len; -} - -LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len, - enum lws_token_indexes h, int frag_idx) -{ - int n = 0; - int f; - - if (!wsi->u.hdr.ah) - return -1; - - f = wsi->u.hdr.ah->frag_index[h]; - - if (!f) - return -1; - - while (n < frag_idx) { - f = wsi->u.hdr.ah->frags[f].nfrag; - if (!f) - return -1; - n++; - } - - if (wsi->u.hdr.ah->frags[f].len >= len) - return -1; - - memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset, - wsi->u.hdr.ah->frags[f].len); - dst[wsi->u.hdr.ah->frags[f].len] = '\0'; - - return wsi->u.hdr.ah->frags[f].len; -} - -LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len, - enum lws_token_indexes h) -{ - int toklen = lws_hdr_total_length(wsi, h); - int n; - - if (toklen >= len) - return -1; - - if (!wsi->u.hdr.ah) - return -1; - - n = wsi->u.hdr.ah->frag_index[h]; - if (!n) - return 0; - - do { - if (wsi->u.hdr.ah->frags[n].len >= len) - return -1; - strncpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset], - wsi->u.hdr.ah->frags[n].len); - dst += wsi->u.hdr.ah->frags[n].len; - len -= wsi->u.hdr.ah->frags[n].len; - n = wsi->u.hdr.ah->frags[n].nfrag; - } while (n); - *dst = '\0'; - - return toklen; -} - -char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h) -{ - int n; - - n = wsi->u.hdr.ah->frag_index[h]; - if (!n) - return NULL; - - return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset; -} - -int LWS_WARN_UNUSED_RESULT -lws_pos_in_bounds(struct lws *wsi) -{ - if (wsi->u.hdr.ah->pos < - (unsigned int)wsi->context->max_http_header_data) - return 0; - - if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) { - lwsl_err("Ran out of header data space\n"); - return 1; - } - - /* - * with these tests everywhere, it should never be able to exceed - * the limit, only meet it - */ - lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos, - wsi->context->max_http_header_data); - assert(0); - - return 1; -} - -int LWS_WARN_UNUSED_RESULT -lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s) -{ - wsi->u.hdr.ah->nfrag++; - if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) { - lwsl_warn("More hdr frags than we can deal with, dropping\n"); - return -1; - } - - wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag; - - wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos; - wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0; - wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0; - - do { - if (lws_pos_in_bounds(wsi)) - return -1; - - wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s; - if (*s) - wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++; - } while (*s++); - - return 0; -} - -signed char char_to_hex(const char c) -{ - if (c >= '0' && c <= '9') - return c - '0'; - - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - - if (c >= 'A' && c <= 'F') - return c - 'A' + 10; - - return -1; -} - -static int LWS_WARN_UNUSED_RESULT -issue_char(struct lws *wsi, unsigned char c) -{ - unsigned short frag_len; - - if (lws_pos_in_bounds(wsi)) - return -1; - - frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len; - /* - * If we haven't hit the token limit, just copy the character into - * the header - */ - if (frag_len < wsi->u.hdr.current_token_limit) { - wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c; - if (c) - wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++; - return 0; - } - - /* Insert a null character when we *hit* the limit: */ - if (frag_len == wsi->u.hdr.current_token_limit) { - if (lws_pos_in_bounds(wsi)) - return -1; - - wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0'; - lwsl_warn("header %i exceeds limit %d\n", - wsi->u.hdr.parser_state, - wsi->u.hdr.current_token_limit); - } - - return 1; -} - -int -lws_parse_urldecode(struct lws *wsi, uint8_t *_c) -{ - struct allocated_headers *ah = wsi->u.hdr.ah; - unsigned int enc = 0; - uint8_t c = *_c; - - /* - * PRIORITY 1 - * special URI processing... convert %xx - */ - switch (wsi->u.hdr.ues) { - case URIES_IDLE: - if (c == '%') { - wsi->u.hdr.ues = URIES_SEEN_PERCENT; - goto swallow; - } - break; - case URIES_SEEN_PERCENT: - if (char_to_hex(c) < 0) - /* illegal post-% char */ - goto forbid; - - wsi->u.hdr.esc_stash = c; - wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1; - goto swallow; - - case URIES_SEEN_PERCENT_H1: - if (char_to_hex(c) < 0) - /* illegal post-% char */ - goto forbid; - - *_c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) | - char_to_hex(c); - c = *_c; - enc = 1; - wsi->u.hdr.ues = URIES_IDLE; - break; - } - - /* - * PRIORITY 2 - * special URI processing... - * convert /.. or /... or /../ etc to / - * convert /./ to / - * convert // or /// etc to / - * leave /.dir or whatever alone - */ - - switch (wsi->u.hdr.ups) { - case URIPS_IDLE: - if (!c) - return -1; - /* genuine delimiter */ - if ((c == '&' || c == ';') && !enc) { - if (issue_char(wsi, c) < 0) - return -1; - /* swallow the terminator */ - ah->frags[ah->nfrag].len--; - /* link to next fragment */ - ah->frags[ah->nfrag].nfrag = ah->nfrag + 1; - ah->nfrag++; - if (ah->nfrag >= ARRAY_SIZE(ah->frags)) - goto excessive; - /* start next fragment after the & */ - wsi->u.hdr.post_literal_equal = 0; - ah->frags[ah->nfrag].offset = ah->pos; - ah->frags[ah->nfrag].len = 0; - ah->frags[ah->nfrag].nfrag = 0; - goto swallow; - } - /* uriencoded = in the name part, disallow */ - if (c == '=' && enc && - ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] && - !wsi->u.hdr.post_literal_equal) { - c = '_'; - *_c =c; - } - - /* after the real =, we don't care how many = */ - if (c == '=' && !enc) - wsi->u.hdr.post_literal_equal = 1; - - /* + to space */ - if (c == '+' && !enc) { - c = ' '; - *_c = c; - } - /* issue the first / always */ - if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) - wsi->u.hdr.ups = URIPS_SEEN_SLASH; - break; - case URIPS_SEEN_SLASH: - /* swallow subsequent slashes */ - if (c == '/') - goto swallow; - /* track and swallow the first . after / */ - if (c == '.') { - wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT; - goto swallow; - } - wsi->u.hdr.ups = URIPS_IDLE; - break; - case URIPS_SEEN_SLASH_DOT: - /* swallow second . */ - if (c == '.') { - wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT; - goto swallow; - } - /* change /./ to / */ - if (c == '/') { - wsi->u.hdr.ups = URIPS_SEEN_SLASH; - goto swallow; - } - /* it was like /.dir ... regurgitate the . */ - wsi->u.hdr.ups = URIPS_IDLE; - if (issue_char(wsi, '.') < 0) - return -1; - break; - - case URIPS_SEEN_SLASH_DOT_DOT: - - /* /../ or /..[End of URI] --> backup to last / */ - if (c == '/' || c == '?') { - /* - * back up one dir level if possible - * safe against header fragmentation because - * the method URI can only be in 1 fragment - */ - if (ah->frags[ah->nfrag].len > 2) { - ah->pos--; - ah->frags[ah->nfrag].len--; - do { - ah->pos--; - ah->frags[ah->nfrag].len--; - } while (ah->frags[ah->nfrag].len > 1 && - ah->data[ah->pos] != '/'); - } - wsi->u.hdr.ups = URIPS_SEEN_SLASH; - if (ah->frags[ah->nfrag].len > 1) - break; - goto swallow; - } - - /* /..[^/] ... regurgitate and allow */ - - if (issue_char(wsi, '.') < 0) - return -1; - if (issue_char(wsi, '.') < 0) - return -1; - wsi->u.hdr.ups = URIPS_IDLE; - break; - } - - if (c == '?' && !enc && - !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */ - if (wsi->u.hdr.ues != URIES_IDLE) - goto forbid; - - /* seal off uri header */ - if (issue_char(wsi, '\0') < 0) - return -1; - - /* move to using WSI_TOKEN_HTTP_URI_ARGS */ - ah->nfrag++; - if (ah->nfrag >= ARRAY_SIZE(ah->frags)) - goto excessive; - ah->frags[ah->nfrag].offset = ah->pos; - ah->frags[ah->nfrag].len = 0; - ah->frags[ah->nfrag].nfrag = 0; - - wsi->u.hdr.post_literal_equal = 0; - ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag; - wsi->u.hdr.ups = URIPS_IDLE; - goto swallow; - } - - return LPUR_CONTINUE; - -swallow: - return LPUR_SWALLOW; - -forbid: - return LPUR_FORBID; - -excessive: - return LPUR_EXCESSIVE; -} - -static const unsigned char methods[] = { - WSI_TOKEN_GET_URI, - WSI_TOKEN_POST_URI, - WSI_TOKEN_OPTIONS_URI, - WSI_TOKEN_PUT_URI, - WSI_TOKEN_PATCH_URI, - WSI_TOKEN_DELETE_URI, - WSI_TOKEN_CONNECT, - WSI_TOKEN_HEAD_URI, -}; - -int LWS_WARN_UNUSED_RESULT -lws_parse(struct lws *wsi, unsigned char c) -{ - struct allocated_headers *ah = wsi->u.hdr.ah; - struct lws_context *context = wsi->context; - unsigned int n, m; - int r; - - assert(wsi->u.hdr.ah); - - switch (wsi->u.hdr.parser_state) { - default: - - lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c); - - /* collect into malloc'd buffers */ - /* optional initial space swallow */ - if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len && - c == ' ') - break; - - for (m = 0; m < ARRAY_SIZE(methods); m++) - if (wsi->u.hdr.parser_state == methods[m]) - break; - if (m == ARRAY_SIZE(methods)) - /* it was not any of the methods */ - goto check_eol; - - /* special URI processing... end at space */ - - if (c == ' ') { - /* enforce starting with / */ - if (!ah->frags[ah->nfrag].len) - if (issue_char(wsi, '/') < 0) - return -1; - - if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) { - /* - * back up one dir level if possible - * safe against header fragmentation because - * the method URI can only be in 1 fragment - */ - if (ah->frags[ah->nfrag].len > 2) { - ah->pos--; - ah->frags[ah->nfrag].len--; - do { - ah->pos--; - ah->frags[ah->nfrag].len--; - } while (ah->frags[ah->nfrag].len > 1 && - ah->data[ah->pos] != '/'); - } - } - - /* begin parsing HTTP version: */ - if (issue_char(wsi, '\0') < 0) - return -1; - wsi->u.hdr.parser_state = WSI_TOKEN_HTTP; - goto start_fragment; - } - - r = lws_parse_urldecode(wsi, &c); - switch (r) { - case LPUR_CONTINUE: - break; - case LPUR_SWALLOW: - goto swallow; - case LPUR_FORBID: - goto forbid; - case LPUR_EXCESSIVE: - goto excessive; - default: - return -1; - } -check_eol: - /* bail at EOL */ - if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE && - c == '\x0d') { - if (wsi->u.hdr.ues != URIES_IDLE) - goto forbid; - - c = '\0'; - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR; - lwsl_parser("*\n"); - } - - n = issue_char(wsi, c); - if ((int)n < 0) - return -1; - if (n > 0) - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; - -swallow: - /* per-protocol end of headers management */ - - if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE) - goto set_parsing_complete; - break; - - /* collecting and checking a name part */ - case WSI_TOKEN_NAME_PART: - lwsl_parser("WSI_TOKEN_NAME_PART '%c' 0x%02X (mode=%d) wsi->u.hdr.lextable_pos=%d\n", c, c, wsi->mode, wsi->u.hdr.lextable_pos); - - wsi->u.hdr.lextable_pos = - lextable_decode(wsi->u.hdr.lextable_pos, c); - /* - * Server needs to look out for unknown methods... - */ - if (wsi->u.hdr.lextable_pos < 0 && - (wsi->mode == LWSCM_HTTP_SERVING)) { - /* this is not a header we know about */ - for (m = 0; m < ARRAY_SIZE(methods); m++) - if (ah->frag_index[methods[m]]) { - /* - * already had the method, no idea what - * this crap from the client is, ignore - */ - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; - break; - } - /* - * hm it's an unknown http method from a client in fact, - * it cannot be valid http - */ - if (m == ARRAY_SIZE(methods)) { - /* - * are we set up to accept raw in these cases? - */ - if (lws_check_opt(wsi->vhost->options, - LWS_SERVER_OPTION_FALLBACK_TO_RAW)) - return 2; /* transition to raw */ - - lwsl_info("Unknown method - dropping\n"); - goto forbid; - } - break; - } - /* - * ...otherwise for a client, let him ignore unknown headers - * coming from the server - */ - if (wsi->u.hdr.lextable_pos < 0) { - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; - break; - } - - if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) { - /* terminal state */ - - n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) | - lextable[wsi->u.hdr.lextable_pos + 1]; - - lwsl_parser("known hdr %d\n", n); - for (m = 0; m < ARRAY_SIZE(methods); m++) - if (n == methods[m] && - ah->frag_index[methods[m]]) { - lwsl_warn("Duplicated method\n"); - return -1; - } - - /* - * WSORIGIN is protocol equiv to ORIGIN, - * JWebSocket likes to send it, map to ORIGIN - */ - if (n == WSI_TOKEN_SWORIGIN) - n = WSI_TOKEN_ORIGIN; - - wsi->u.hdr.parser_state = (enum lws_token_indexes) - (WSI_TOKEN_GET_URI + n); - - if (context->token_limits) - wsi->u.hdr.current_token_limit = - context->token_limits->token_limit[ - wsi->u.hdr.parser_state]; - else - wsi->u.hdr.current_token_limit = - wsi->context->max_http_header_data; - - if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE) - goto set_parsing_complete; - - goto start_fragment; - } - break; - -start_fragment: - ah->nfrag++; -excessive: - if (ah->nfrag == ARRAY_SIZE(ah->frags)) { - lwsl_warn("More hdr frags than we can deal with\n"); - return -1; - } - - ah->frags[ah->nfrag].offset = ah->pos; - ah->frags[ah->nfrag].len = 0; - ah->frags[ah->nfrag].nfrag = 0; - ah->frags[ah->nfrag].flags = 2; - - n = ah->frag_index[wsi->u.hdr.parser_state]; - if (!n) { /* first fragment */ - ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag; - ah->hdr_token_idx = wsi->u.hdr.parser_state; - break; - } - /* continuation */ - while (ah->frags[n].nfrag) - n = ah->frags[n].nfrag; - ah->frags[n].nfrag = ah->nfrag; - - if (issue_char(wsi, ' ') < 0) - return -1; - break; - - /* skipping arg part of a name we didn't recognize */ - case WSI_TOKEN_SKIPPING: - lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c); - - if (c == '\x0d') - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR; - break; - - case WSI_TOKEN_SKIPPING_SAW_CR: - lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c); - if (wsi->u.hdr.ues != URIES_IDLE) - goto forbid; - if (c == '\x0a') { - wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART; - wsi->u.hdr.lextable_pos = 0; - } else - wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING; - break; - /* we're done, ignore anything else */ - - case WSI_PARSING_COMPLETE: - lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c); - break; - } - - return 0; - -set_parsing_complete: - if (wsi->u.hdr.ues != URIES_IDLE) - goto forbid; - if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) { - if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION)) - wsi->ietf_spec_revision = - atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION)); - - lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision); - } - wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE; - wsi->hdr_parsing_completed = 1; - - return 0; - -forbid: - lwsl_notice(" forbidding on uri sanitation\n"); - lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL); - - return -1; -} - -LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi) -{ - return wsi->u.ws.frame_is_binary; -} - -void -lws_add_wsi_to_draining_ext_list(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - - if (wsi->u.ws.rx_draining_ext) - return; - - lwsl_ext("%s: RX EXT DRAINING: Adding to list\n", __func__); - - wsi->u.ws.rx_draining_ext = 1; - wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list; - pt->rx_draining_ext_list = wsi; -} - -void -lws_remove_wsi_from_draining_ext_list(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - struct lws **w = &pt->rx_draining_ext_list; - - if (!wsi->u.ws.rx_draining_ext) - return; - - lwsl_ext("%s: RX EXT DRAINING: Removing from list\n", __func__); - - wsi->u.ws.rx_draining_ext = 0; - - /* remove us from context draining ext list */ - while (*w) { - if (*w == wsi) { - /* if us, point it instead to who we were pointing to */ - *w = wsi->u.ws.rx_draining_ext_list; - break; - } - w = &((*w)->u.ws.rx_draining_ext_list); - } - wsi->u.ws.rx_draining_ext_list = NULL; -} - -/* - * client-parser.c: lws_client_rx_sm() needs to be roughly kept in - * sync with changes here, esp related to ext draining - */ - -int -lws_rx_sm(struct lws *wsi, unsigned char c) -{ - int callback_action = LWS_CALLBACK_RECEIVE; - int ret = 0, n, rx_draining_ext = 0; - struct lws_tokens eff_buf; - - eff_buf.token = NULL; - eff_buf.token_len = 0; - if (wsi->socket_is_permanently_unusable) - return -1; - - switch (wsi->lws_rx_parse_state) { - case LWS_RXPS_NEW: - if (wsi->u.ws.rx_draining_ext) { - eff_buf.token = NULL; - eff_buf.token_len = 0; - lws_remove_wsi_from_draining_ext_list(wsi); - rx_draining_ext = 1; - lwsl_debug("%s: doing draining flow\n", __func__); - - goto drain_extension; - } - switch (wsi->ietf_spec_revision) { - case 13: - /* - * no prepended frame key any more - */ - wsi->u.ws.all_zero_nonce = 1; - goto handle_first; - - default: - lwsl_warn("lws_rx_sm: unknown spec version %d\n", - wsi->ietf_spec_revision); - break; - } - break; - case LWS_RXPS_04_mask_1: - wsi->u.ws.mask[1] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2; - break; - case LWS_RXPS_04_mask_2: - wsi->u.ws.mask[2] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3; - break; - case LWS_RXPS_04_mask_3: - wsi->u.ws.mask[3] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - - /* - * start from the zero'th byte in the XOR key buffer since - * this is the start of a frame with a new key - */ - - wsi->u.ws.mask_idx = 0; - - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1; - break; - - /* - * 04 logical framing from the spec (all this is masked when incoming - * and has to be unmasked) - * - * We ignore the possibility of extension data because we don't - * negotiate any extensions at the moment. - * - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-------+-+-------------+-------------------------------+ - * |F|R|R|R| opcode|R| Payload len | Extended payload length | - * |I|S|S|S| (4) |S| (7) | (16/63) | - * |N|V|V|V| |V| | (if payload len==126/127) | - * | |1|2|3| |4| | | - * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + - * | Extended payload length continued, if payload len == 127 | - * + - - - - - - - - - - - - - - - +-------------------------------+ - * | | Extension data | - * +-------------------------------+ - - - - - - - - - - - - - - - + - * : : - * +---------------------------------------------------------------+ - * : Application data : - * +---------------------------------------------------------------+ - * - * We pass payload through to userland as soon as we get it, ignoring - * FIN. It's up to userland to buffer it up if it wants to see a - * whole unfragmented block of the original size (which may be up to - * 2^63 long!) - */ - - case LWS_RXPS_04_FRAME_HDR_1: -handle_first: - - wsi->u.ws.opcode = c & 0xf; - wsi->u.ws.rsv = c & 0x70; - wsi->u.ws.final = !!((c >> 7) & 1); - - switch (wsi->u.ws.opcode) { - case LWSWSOPC_TEXT_FRAME: - case LWSWSOPC_BINARY_FRAME: - wsi->u.ws.rsv_first_msg = (c & 0x70); - wsi->u.ws.frame_is_binary = - wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME; - wsi->u.ws.first_fragment = 1; - break; - case 3: - case 4: - case 5: - case 6: - case 7: - case 0xb: - case 0xc: - case 0xd: - case 0xe: - case 0xf: - lwsl_info("illegal opcode\n"); - return -1; - } - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN: - - wsi->u.ws.this_frame_masked = !!(c & 0x80); - - switch (c & 0x7f) { - case 126: - /* control frames are not allowed to have big lengths */ - if (wsi->u.ws.opcode & 8) - goto illegal_ctl_length; - - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2; - break; - case 127: - /* control frames are not allowed to have big lengths */ - if (wsi->u.ws.opcode & 8) - goto illegal_ctl_length; - - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8; - break; - default: - wsi->u.ws.rx_packet_length = c & 0x7f; - if (wsi->u.ws.this_frame_masked) - wsi->lws_rx_parse_state = - LWS_RXPS_07_COLLECT_FRAME_KEY_1; - else - if (wsi->u.ws.rx_packet_length) - wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; - else { - wsi->lws_rx_parse_state = LWS_RXPS_NEW; - goto spill; - } - break; - } - break; - - case LWS_RXPS_04_FRAME_HDR_LEN16_2: - wsi->u.ws.rx_packet_length = c << 8; - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN16_1: - wsi->u.ws.rx_packet_length |= c; - if (wsi->u.ws.this_frame_masked) - wsi->lws_rx_parse_state = - LWS_RXPS_07_COLLECT_FRAME_KEY_1; - else - wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_8: - if (c & 0x80) { - lwsl_warn("b63 of length must be zero\n"); - /* kill the connection */ - return -1; - } -#if defined __LP64__ - wsi->u.ws.rx_packet_length = ((size_t)c) << 56; -#else - wsi->u.ws.rx_packet_length = 0; -#endif - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_7: -#if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 48; -#endif - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_6: -#if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 40; -#endif - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_5: -#if defined __LP64__ - wsi->u.ws.rx_packet_length |= ((size_t)c) << 32; -#endif - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_4: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 24; - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_3: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 16; - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_2: - wsi->u.ws.rx_packet_length |= ((size_t)c) << 8; - wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1; - break; - - case LWS_RXPS_04_FRAME_HDR_LEN64_1: - wsi->u.ws.rx_packet_length |= ((size_t)c); - if (wsi->u.ws.this_frame_masked) - wsi->lws_rx_parse_state = - LWS_RXPS_07_COLLECT_FRAME_KEY_1; - else - wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; - break; - - case LWS_RXPS_07_COLLECT_FRAME_KEY_1: - wsi->u.ws.mask[0] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2; - break; - - case LWS_RXPS_07_COLLECT_FRAME_KEY_2: - wsi->u.ws.mask[1] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3; - break; - - case LWS_RXPS_07_COLLECT_FRAME_KEY_3: - wsi->u.ws.mask[2] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4; - break; - - case LWS_RXPS_07_COLLECT_FRAME_KEY_4: - wsi->u.ws.mask[3] = c; - if (c) - wsi->u.ws.all_zero_nonce = 0; - wsi->lws_rx_parse_state = - LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED; - wsi->u.ws.mask_idx = 0; - if (wsi->u.ws.rx_packet_length == 0) { - wsi->lws_rx_parse_state = LWS_RXPS_NEW; - goto spill; - } - break; - - - case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED: - assert(wsi->u.ws.rx_ubuf); - - if (wsi->u.ws.rx_draining_ext) - goto drain_extension; - - if (wsi->u.ws.rx_ubuf_head + LWS_PRE >= - wsi->u.ws.rx_ubuf_alloc) { - lwsl_err("Attempted overflow \n"); - return -1; - } - if (wsi->u.ws.all_zero_nonce) - wsi->u.ws.rx_ubuf[LWS_PRE + - (wsi->u.ws.rx_ubuf_head++)] = c; - else - wsi->u.ws.rx_ubuf[LWS_PRE + - (wsi->u.ws.rx_ubuf_head++)] = - c ^ wsi->u.ws.mask[ - (wsi->u.ws.mask_idx++) & 3]; - - if (--wsi->u.ws.rx_packet_length == 0) { - /* spill because we have the whole frame */ - wsi->lws_rx_parse_state = LWS_RXPS_NEW; - goto spill; - } - - /* - * if there's no protocol max frame size given, we are - * supposed to default to context->pt_serv_buf_size - */ - if (!wsi->protocol->rx_buffer_size && - wsi->u.ws.rx_ubuf_head != wsi->context->pt_serv_buf_size) - break; - - if (wsi->protocol->rx_buffer_size && - wsi->u.ws.rx_ubuf_head != wsi->protocol->rx_buffer_size) - break; - - /* spill because we filled our rx buffer */ -spill: - /* - * is this frame a control packet we should take care of at this - * layer? If so service it and hide it from the user callback - */ - - lwsl_parser("spill on %s\n", wsi->protocol->name); - - switch (wsi->u.ws.opcode) { - case LWSWSOPC_CLOSE: - - /* is this an acknowledgement of our close? */ - if (wsi->state == LWSS_AWAITING_CLOSE_ACK) { - /* - * fine he has told us he is closing too, let's - * finish our close - */ - lwsl_parser("seen client close ack\n"); - return -1; - } - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY) - /* if he sends us 2 CLOSE, kill him */ - return -1; - - if (lws_partial_buffered(wsi)) { - /* - * if we're in the middle of something, - * we can't do a normal close response and - * have to just close our end. - */ - wsi->socket_is_permanently_unusable = 1; - lwsl_parser("Closing on peer close due to Pending tx\n"); - return -1; - } - - if (user_callback_handle_rxflow( - wsi->protocol->callback, wsi, - LWS_CALLBACK_WS_PEER_INITIATED_CLOSE, - wsi->user_space, - &wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head)) - return -1; - - lwsl_parser("server sees client close packet\n"); - wsi->state = LWSS_RETURNED_CLOSE_ALREADY; - /* deal with the close packet contents as a PONG */ - wsi->u.ws.payload_is_close = 1; - goto process_as_ping; - - case LWSWSOPC_PING: - lwsl_info("received %d byte ping, sending pong\n", - wsi->u.ws.rx_ubuf_head); - - if (wsi->u.ws.ping_pending_flag) { - /* - * there is already a pending ping payload - * we should just log and drop - */ - lwsl_parser("DROP PING since one pending\n"); - goto ping_drop; - } -process_as_ping: - /* control packets can only be < 128 bytes long */ - if (wsi->u.ws.rx_ubuf_head > 128 - 3) { - lwsl_parser("DROP PING payload too large\n"); - goto ping_drop; - } - - /* stash the pong payload */ - memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE, - &wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head); - - wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head; - wsi->u.ws.ping_pending_flag = 1; - - /* get it sent as soon as possible */ - lws_callback_on_writable(wsi); -ping_drop: - wsi->u.ws.rx_ubuf_head = 0; - return 0; - - case LWSWSOPC_PONG: - lwsl_info("received pong\n"); - lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE], - wsi->u.ws.rx_ubuf_head); - - if (wsi->pending_timeout == PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) { - lwsl_info("received expected PONG on wsi %p\n", wsi); - lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); - } - - /* issue it */ - callback_action = LWS_CALLBACK_RECEIVE_PONG; - break; - - case LWSWSOPC_TEXT_FRAME: - case LWSWSOPC_BINARY_FRAME: - case LWSWSOPC_CONTINUATION: - break; - - default: - lwsl_parser("passing opc %x up to exts\n", - wsi->u.ws.opcode); - /* - * It's something special we can't understand here. - * Pass the payload up to the extension's parsing - * state machine. - */ - - eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE]; - eff_buf.token_len = wsi->u.ws.rx_ubuf_head; - - if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX, - &eff_buf, 0) <= 0) - /* not handle or fail */ - lwsl_ext("ext opc opcode 0x%x unknown\n", - wsi->u.ws.opcode); - - wsi->u.ws.rx_ubuf_head = 0; - return 0; - } - - /* - * No it's real payload, pass it up to the user callback. - * It's nicely buffered with the pre-padding taken care of - * so it can be sent straight out again using lws_write - */ - - eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE]; - eff_buf.token_len = wsi->u.ws.rx_ubuf_head; - - if (wsi->u.ws.opcode == LWSWSOPC_PONG && !eff_buf.token_len) - goto already_done; - -drain_extension: - lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len); - - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY || - wsi->state == LWSS_AWAITING_CLOSE_ACK) - goto already_done; - - n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0); - /* - * eff_buf may be pointing somewhere completely different now, - * it's the output - */ - wsi->u.ws.first_fragment = 0; - if (n < 0) { - /* - * we may rely on this to get RX, just drop connection - */ - wsi->socket_is_permanently_unusable = 1; - return -1; - } - - if (rx_draining_ext && eff_buf.token_len == 0) - goto already_done; - - if (n && eff_buf.token_len) - /* extension had more... main loop will come back */ - lws_add_wsi_to_draining_ext_list(wsi); - else - lws_remove_wsi_from_draining_ext_list(wsi); - - if (eff_buf.token_len > 0 || - callback_action == LWS_CALLBACK_RECEIVE_PONG) { - eff_buf.token[eff_buf.token_len] = '\0'; - - if (wsi->protocol->callback) { - - if (callback_action == LWS_CALLBACK_RECEIVE_PONG) - lwsl_info("Doing pong callback\n"); - - ret = user_callback_handle_rxflow( - wsi->protocol->callback, - wsi, - (enum lws_callback_reasons)callback_action, - wsi->user_space, - eff_buf.token, - eff_buf.token_len); - } - else - lwsl_err("No callback on payload spill!\n"); - } - -already_done: - wsi->u.ws.rx_ubuf_head = 0; - break; - } - - return ret; - -illegal_ctl_length: - - lwsl_warn("Control frame with xtended length is illegal\n"); - /* kill the connection */ - return -1; -} - -LWS_VISIBLE size_t -lws_remaining_packet_payload(struct lws *wsi) -{ - return wsi->u.ws.rx_packet_length; -} - -/* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much - * to expect in that state and can deal with it in bulk more efficiently. - */ - -int -lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf, - size_t *len) -{ - unsigned char *buffer = *buf, mask[4]; - int buffer_size, n; - unsigned int avail; - char *rx_ubuf; - - if (wsi->protocol->rx_buffer_size) - buffer_size = wsi->protocol->rx_buffer_size; - else - buffer_size = wsi->context->pt_serv_buf_size; - avail = buffer_size - wsi->u.ws.rx_ubuf_head; - - /* do not consume more than we should */ - if (avail > wsi->u.ws.rx_packet_length) - avail = wsi->u.ws.rx_packet_length; - - /* do not consume more than what is in the buffer */ - if (avail > *len) - avail = *len; - - /* we want to leave 1 byte for the parser to handle properly */ - if (avail <= 1) - return 0; - - avail--; - rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head; - if (wsi->u.ws.all_zero_nonce) - memcpy(rx_ubuf, buffer, avail); - else { - - for (n = 0; n < 4; n++) - mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3]; - - /* deal with 4-byte chunks using unwrapped loop */ - n = avail >> 2; - while (n--) { - *(rx_ubuf++) = *(buffer++) ^ mask[0]; - *(rx_ubuf++) = *(buffer++) ^ mask[1]; - *(rx_ubuf++) = *(buffer++) ^ mask[2]; - *(rx_ubuf++) = *(buffer++) ^ mask[3]; - } - /* and the remaining bytes bytewise */ - for (n = 0; n < (int)(avail & 3); n++) - *(rx_ubuf++) = *(buffer++) ^ mask[n]; - - wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3; - } - - (*buf) += avail; - wsi->u.ws.rx_ubuf_head += avail; - wsi->u.ws.rx_packet_length -= avail; - *len -= avail; - - return avail; -} diff --git a/thirdparty/lws/server/ranges.c b/thirdparty/lws/server/ranges.c deleted file mode 100644 index bc1578d733..0000000000 --- a/thirdparty/lws/server/ranges.c +++ /dev/null @@ -1,214 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * RFC7233 ranges parser - * - * Copyright (C) 2016 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -/* - * RFC7233 examples - * - * o The first 500 bytes (byte offsets 0-499, inclusive): - * - * bytes=0-499 - * - * o The second 500 bytes (byte offsets 500-999, inclusive): - * - * bytes=500-999 - * - * o The final 500 bytes (byte offsets 9500-9999, inclusive): - * - * bytes=-500 - * - * Or: - * - * bytes=9500- - * - * o The first and last bytes only (bytes 0 and 9999): - * - * bytes=0-0,-1 - * - * o Other valid (but not canonical) specifications of the second 500 - * bytes (byte offsets 500-999, inclusive): - * - * bytes=500-600,601-999 - * bytes=500-700,601-999 - */ - -/* - * returns 1 if the range struct represents a usable range - * if no ranges header, you get one of these for the whole - * file. Otherwise you get one for each valid range in the - * header. - * - * returns 0 if no further valid range forthcoming; rp->state - * may be LWSRS_SYNTAX or LWSRS_COMPLETED - */ - -int -lws_ranges_next(struct lws_range_parsing *rp) -{ - static const char * const beq = "bytes="; - char c; - - while (1) { - - c = rp->buf[rp->pos]; - - switch (rp->state) { - case LWSRS_SYNTAX: - case LWSRS_COMPLETED: - return 0; - - case LWSRS_NO_ACTIVE_RANGE: - rp->state = LWSRS_COMPLETED; - return 0; - - case LWSRS_BYTES_EQ: // looking for "bytes=" - if (c != beq[rp->pos]) { - rp->state = LWSRS_SYNTAX; - return -1; - } - if (rp->pos == 5) - rp->state = LWSRS_FIRST; - break; - - case LWSRS_FIRST: - rp->start = 0; - rp->end = 0; - rp->start_valid = 0; - rp->end_valid = 0; - - rp->state = LWSRS_STARTING; - - // fallthru - - case LWSRS_STARTING: - if (c == '-') { - rp->state = LWSRS_ENDING; - break; - } - - if (!(c >= '0' && c <= '9')) { - rp->state = LWSRS_SYNTAX; - return 0; - } - rp->start = (rp->start * 10) + (c - '0'); - rp->start_valid = 1; - break; - - case LWSRS_ENDING: - if (c == ',' || c == '\0') { - rp->state = LWSRS_FIRST; - if (c == ',') - rp->pos++; - - /* - * By the end of this, start and end are - * always valid if the range still is - */ - - if (!rp->start_valid) { /* eg, -500 */ - if (rp->end > rp->extent) - rp->end = rp->extent; - - rp->start = rp->extent - rp->end; - rp->end = rp->extent - 1; - } else - if (!rp->end_valid) - rp->end = rp->extent - 1; - - rp->did_try = 1; - - /* end must be >= start or ignore it */ - if (rp->end < rp->start) { - if (c == ',') - break; - rp->state = LWSRS_COMPLETED; - return 0; - } - - return 1; /* issue range */ - } - - if (!(c >= '0' && c <= '9')) { - rp->state = LWSRS_SYNTAX; - return 0; - } - rp->end = (rp->end * 10) + (c - '0'); - rp->end_valid = 1; - break; - } - - rp->pos++; - } -} - -void -lws_ranges_reset(struct lws_range_parsing *rp) -{ - rp->pos = 0; - rp->ctr = 0; - rp->start = 0; - rp->end = 0; - rp->start_valid = 0; - rp->end_valid = 0; - rp->state = LWSRS_BYTES_EQ; -} - -/* - * returns count of valid ranges - */ -int -lws_ranges_init(struct lws *wsi, struct lws_range_parsing *rp, - unsigned long long extent) -{ - rp->agg = 0; - rp->send_ctr = 0; - rp->inside = 0; - rp->count_ranges = 0; - rp->did_try = 0; - lws_ranges_reset(rp); - rp->state = LWSRS_COMPLETED; - - rp->extent = extent; - - if (lws_hdr_copy(wsi, (char *)rp->buf, sizeof(rp->buf), - WSI_TOKEN_HTTP_RANGE) <= 0) - return 0; - - rp->state = LWSRS_BYTES_EQ; - - while (lws_ranges_next(rp)) { - rp->count_ranges++; - rp->agg += rp->end - rp->start + 1; - } - - lwsl_debug("%s: count %d\n", __func__, rp->count_ranges); - lws_ranges_reset(rp); - - if (rp->did_try && !rp->count_ranges) - return -1; /* "not satisfiable */ - - lws_ranges_next(rp); - - return rp->count_ranges; -} diff --git a/thirdparty/lws/server/server-handshake.c b/thirdparty/lws/server/server-handshake.c deleted file mode 100644 index 3d319c35d6..0000000000 --- a/thirdparty/lws/server/server-handshake.c +++ /dev/null @@ -1,360 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -#define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); } - -#ifndef LWS_NO_EXTENSIONS -static int -lws_extension_server_handshake(struct lws *wsi, char **p, int budget) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - char ext_name[64], *args, *end = (*p) + budget - 1; - const struct lws_ext_options *opts, *po; - const struct lws_extension *ext; - struct lws_ext_option_arg oa; - int n, m, more = 1; - int ext_count = 0; - char ignore; - char *c; - - /* - * Figure out which extensions the client has that we want to - * enable on this connection, and give him back the list - */ - if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) - return 0; - - /* - * break down the list of client extensions - * and go through them - */ - - if (lws_hdr_copy(wsi, (char *)pt->serv_buf, context->pt_serv_buf_size, - WSI_TOKEN_EXTENSIONS) < 0) - return 1; - - c = (char *)pt->serv_buf; - lwsl_parser("WSI_TOKEN_EXTENSIONS = '%s'\n", c); - wsi->count_act_ext = 0; - ignore = 0; - n = 0; - args = NULL; - - /* - * We may get a simple request - * - * Sec-WebSocket-Extensions: permessage-deflate - * - * or an elaborated one with requested options - * - * Sec-WebSocket-Extensions: permessage-deflate; \ - * server_no_context_takeover; \ - * client_no_context_takeover - */ - - while (more) { - - if (*c && (*c != ',' && *c != '\t')) { - if (*c == ';') { - ignore = 1; - args = c + 1; - } - if (ignore || *c == ' ') { - c++; - continue; - } - ext_name[n] = *c++; - if (n < sizeof(ext_name) - 1) - n++; - continue; - } - ext_name[n] = '\0'; - - ignore = 0; - if (!*c) - more = 0; - else { - c++; - if (!n) - continue; - } - - while (args && *args && *args == ' ') - args++; - - /* check a client's extension against our support */ - - ext = wsi->vhost->extensions; - - while (ext && ext->callback) { - - if (strcmp(ext_name, ext->name)) { - ext++; - continue; - } - - /* - * oh, we do support this one he asked for... but let's - * confirm he only gave it once - */ - for (m = 0; m < wsi->count_act_ext; m++) - if (wsi->active_extensions[m] == ext) { - lwsl_info("extension mentioned twice\n"); - return 1; /* shenanigans */ - } - - /* - * ask user code if it's OK to apply it on this - * particular connection + protocol - */ - m = (wsi->protocol->callback)(wsi, - LWS_CALLBACK_CONFIRM_EXTENSION_OKAY, - wsi->user_space, ext_name, 0); - - /* - * zero return from callback means go ahead and allow - * the extension, it's what we get if the callback is - * unhandled - */ - if (m) { - ext++; - continue; - } - - /* apply it */ - - ext_count++; - - /* instantiate the extension on this conn */ - - wsi->active_extensions[wsi->count_act_ext] = ext; - - /* allow him to construct his context */ - - if (ext->callback(lws_get_context(wsi), ext, wsi, - LWS_EXT_CB_CONSTRUCT, - (void *)&wsi->act_ext_user[ - wsi->count_act_ext], - (void *)&opts, 0)) { - lwsl_info("ext %s failed construction\n", - ext_name); - ext_count--; - ext++; - - continue; - } - - if (ext_count > 1) - *(*p)++ = ','; - else - LWS_CPYAPP(*p, - "\x0d\x0aSec-WebSocket-Extensions: "); - *p += lws_snprintf(*p, (end - *p), "%s", ext_name); - - /* - * go through the options trying to apply the - * recognized ones - */ - - lwsl_debug("ext args %s", args); - - while (args && *args && *args != ',') { - while (*args == ' ') - args++; - po = opts; - while (po->name) { - lwsl_debug("'%s' '%s'\n", po->name, args); - /* only support arg-less options... */ - if (po->type == EXTARG_NONE && - !strncmp(args, po->name, - strlen(po->name))) { - oa.option_name = NULL; - oa.option_index = po - opts; - oa.start = NULL; - lwsl_debug("setting %s\n", po->name); - if (!ext->callback( - lws_get_context(wsi), ext, wsi, - LWS_EXT_CB_OPTION_SET, - wsi->act_ext_user[ - wsi->count_act_ext], - &oa, (end - *p))) { - - *p += lws_snprintf(*p, (end - *p), "; %s", po->name); - lwsl_debug("adding option %s\n", po->name); - } - } - po++; - } - while (*args && *args != ',' && *args != ';') - args++; - } - - wsi->count_act_ext++; - lwsl_parser("count_act_ext <- %d\n", - wsi->count_act_ext); - - ext++; - } - - n = 0; - args = NULL; - } - - return 0; -} -#endif -int -handshake_0405(struct lws_context *context, struct lws *wsi) -{ - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - struct lws_process_html_args args; - unsigned char hash[20]; - int n, accept_len; - char *response; - char *p; - - if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST) || - !lws_hdr_total_length(wsi, WSI_TOKEN_KEY)) { - lwsl_parser("handshake_04 missing pieces\n"); - /* completed header processing, but missing some bits */ - goto bail; - } - - if (lws_hdr_total_length(wsi, WSI_TOKEN_KEY) >= MAX_WEBSOCKET_04_KEY_LEN) { - lwsl_warn("Client key too long %d\n", MAX_WEBSOCKET_04_KEY_LEN); - goto bail; - } - - /* - * since key length is restricted above (currently 128), cannot - * overflow - */ - n = sprintf((char *)pt->serv_buf, - "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", - lws_hdr_simple_ptr(wsi, WSI_TOKEN_KEY)); - - lws_SHA1(pt->serv_buf, n, hash); - - accept_len = lws_b64_encode_string((char *)hash, 20, - (char *)pt->serv_buf, context->pt_serv_buf_size); - if (accept_len < 0) { - lwsl_warn("Base64 encoded hash too long\n"); - goto bail; - } - - /* allocate the per-connection user memory (if any) */ - if (lws_ensure_user_space(wsi)) - goto bail; - - /* create the response packet */ - - /* make a buffer big enough for everything */ - - response = (char *)pt->serv_buf + MAX_WEBSOCKET_04_KEY_LEN + LWS_PRE; - p = response; - LWS_CPYAPP(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a" - "Upgrade: WebSocket\x0d\x0a" - "Connection: Upgrade\x0d\x0a" - "Sec-WebSocket-Accept: "); - strcpy(p, (char *)pt->serv_buf); - p += accept_len; - - /* we can only return the protocol header if: - * - one came in, and ... */ - if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) && - /* - it is not an empty string */ - wsi->protocol->name && - wsi->protocol->name[0]) { - LWS_CPYAPP(p, "\x0d\x0aSec-WebSocket-Protocol: "); - p += lws_snprintf(p, 128, "%s", wsi->protocol->name); - } - -#ifndef LWS_NO_EXTENSIONS - /* - * Figure out which extensions the client has that we want to - * enable on this connection, and give him back the list. - * - * Give him a limited write bugdet - */ - if (lws_extension_server_handshake(wsi, &p, 192)) - goto bail; -#endif - LWS_CPYAPP(p, "\x0d\x0a"); - - args.p = p; - args.max_len = ((char *)pt->serv_buf + context->pt_serv_buf_size) - p; - if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, - LWS_CALLBACK_ADD_HEADERS, - wsi->user_space, &args, 0)) - goto bail; - - p = args.p; - - /* end of response packet */ - - LWS_CPYAPP(p, "\x0d\x0a"); - - if (!lws_any_extension_handled(wsi, LWS_EXT_CB_HANDSHAKE_REPLY_TX, - response, p - response)) { - - /* okay send the handshake response accepting the connection */ - - lwsl_parser("issuing resp pkt %d len\n", (int)(p - response)); -#if defined(DEBUG) && ! defined(LWS_WITH_ESP8266) - fwrite(response, 1, p - response, stderr); -#endif - n = lws_write(wsi, (unsigned char *)response, - p - response, LWS_WRITE_HTTP_HEADERS); - if (n != (p - response)) { - lwsl_debug("handshake_0405: ERROR writing to socket\n"); - goto bail; - } - - } - - /* alright clean up and set ourselves into established state */ - - wsi->state = LWSS_ESTABLISHED; - wsi->lws_rx_parse_state = LWS_RXPS_NEW; - - { - const char * uri_ptr = - lws_hdr_simple_ptr(wsi, WSI_TOKEN_GET_URI); - int uri_len = lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI); - const struct lws_http_mount *hit = - lws_find_mount(wsi, uri_ptr, uri_len); - if (hit && hit->cgienv && - wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_PMO, - wsi->user_space, (void *)hit->cgienv, 0)) - return 1; - } - - return 0; - - -bail: - /* caller will free up his parsing allocations */ - return -1; -} - diff --git a/thirdparty/lws/server/ssl-server.c b/thirdparty/lws/server/ssl-server.c deleted file mode 100644 index c4362824bf..0000000000 --- a/thirdparty/lws/server/ssl-server.c +++ /dev/null @@ -1,477 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -extern int openssl_websocket_private_data_index, - openssl_SSL_CTX_private_data_index; - -extern void -lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info); - -#if !defined(LWS_WITH_MBEDTLS) -static int -OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) -{ - SSL *ssl; - int n; - struct lws *wsi; - - ssl = X509_STORE_CTX_get_ex_data(x509_ctx, - SSL_get_ex_data_X509_STORE_CTX_idx()); - - /* - * !!! nasty openssl requires the index to come as a library-scope - * static - */ - wsi = SSL_get_ex_data(ssl, openssl_websocket_private_data_index); - - n = wsi->vhost->protocols[0].callback(wsi, - LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION, - x509_ctx, ssl, preverify_ok); - - /* convert return code from 0 = OK to 1 = OK */ - return !n; -} -#endif - -static int -lws_context_ssl_init_ecdh(struct lws_vhost *vhost) -{ -#ifdef LWS_SSL_SERVER_WITH_ECDH_CERT - EC_KEY *EC_key = NULL; - EVP_PKEY *pkey; - int KeyType; - X509 *x; - - if (!lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_SSL_ECDH)) - return 0; - - lwsl_notice(" Using ECDH certificate support\n"); - - /* Get X509 certificate from ssl context */ - x = sk_X509_value(vhost->ssl_ctx->extra_certs, 0); - if (!x) { - lwsl_err("%s: x is NULL\n", __func__); - return 1; - } - /* Get the public key from certificate */ - pkey = X509_get_pubkey(x); - if (!pkey) { - lwsl_err("%s: pkey is NULL\n", __func__); - - return 1; - } - /* Get the key type */ - KeyType = EVP_PKEY_type(pkey->type); - - if (EVP_PKEY_EC != KeyType) { - lwsl_notice("Key type is not EC\n"); - return 0; - } - /* Get the key */ - EC_key = EVP_PKEY_get1_EC_KEY(pkey); - /* Set ECDH parameter */ - if (!EC_key) { - lwsl_err("%s: ECDH key is NULL \n", __func__); - return 1; - } - SSL_CTX_set_tmp_ecdh(vhost->ssl_ctx, EC_key); - EC_KEY_free(EC_key); -#endif - return 0; -} - -static int -lws_context_ssl_init_ecdh_curve(struct lws_context_creation_info *info, - struct lws_vhost *vhost) -{ -#if defined(LWS_HAVE_OPENSSL_ECDH_H) && !defined(LWS_WITH_MBEDTLS) - EC_KEY *ecdh; - int ecdh_nid; - const char *ecdh_curve = "prime256v1"; - - if (info->ecdh_curve) - ecdh_curve = info->ecdh_curve; - - ecdh_nid = OBJ_sn2nid(ecdh_curve); - if (NID_undef == ecdh_nid) { - lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve); - return 1; - } - - ecdh = EC_KEY_new_by_curve_name(ecdh_nid); - if (NULL == ecdh) { - lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve); - return 1; - } - SSL_CTX_set_tmp_ecdh(vhost->ssl_ctx, ecdh); - EC_KEY_free(ecdh); - - SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_SINGLE_ECDH_USE); - - lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve); -#else -#if !defined(LWS_WITH_MBEDTLS) - lwsl_notice(" OpenSSL doesn't support ECDH\n"); -#endif -#endif - return 0; -} - -#if !defined(LWS_WITH_MBEDTLS) && defined(SSL_TLSEXT_ERR_NOACK) && !defined(OPENSSL_NO_TLSEXT) -static int -lws_ssl_server_name_cb(SSL *ssl, int *ad, void *arg) -{ - struct lws_context *context = (struct lws_context *)arg; - struct lws_vhost *vhost, *vh; - const char *servername; - - if (!ssl) - return SSL_TLSEXT_ERR_NOACK; - - /* - * We can only get ssl accepted connections by using a vhost's ssl_ctx - * find out which listening one took us and only match vhosts on the - * same port. - */ - vh = context->vhost_list; - while (vh) { - if (!vh->being_destroyed && ssl && vh->ssl_ctx == SSL_get_SSL_CTX(ssl)) - break; - vh = vh->vhost_next; - } - - if (!vh) { - assert(vh); /* can't match the incoming vh? */ - return SSL_TLSEXT_ERR_OK; - } - - servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); - if (!servername) { - /* the client doesn't know what hostname it wants */ - lwsl_info("SNI: Unknown ServerName: %s\n", servername); - - return SSL_TLSEXT_ERR_OK; - } - - vhost = lws_select_vhost(context, vh->listen_port, servername); - if (!vhost) { - lwsl_info("SNI: none: %s:%d\n", servername, vh->listen_port); - - return SSL_TLSEXT_ERR_OK; - } - - lwsl_info("SNI: Found: %s:%d\n", servername, vh->listen_port); - - /* select the ssl ctx from the selected vhost for this conn */ - SSL_set_SSL_CTX(ssl, vhost->ssl_ctx); - - return SSL_TLSEXT_ERR_OK; -} -#endif - -LWS_VISIBLE int -lws_context_init_server_ssl(struct lws_context_creation_info *info, - struct lws_vhost *vhost) -{ - struct lws_context *context = vhost->context; - struct lws wsi; - unsigned long error; - int n; - - if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) { - vhost->use_ssl = 0; - return 0; - } - - /* - * If he is giving a cert filepath, take it as a sign he wants to use - * it on this vhost. User code can leave the cert filepath NULL and - * set the LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX option itself, in - * which case he's expected to set up the cert himself at - * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which - * provides the vhost SSL_CTX * in the user parameter. - */ - if (info->ssl_cert_filepath) - info->options |= LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX; - - if (info->port != CONTEXT_PORT_NO_LISTEN) { - - vhost->use_ssl = lws_check_opt(info->options, - LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX); - - if (vhost->use_ssl && info->ssl_cipher_list) - lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list); - - if (vhost->use_ssl) - lwsl_notice(" Using SSL mode\n"); - else - lwsl_notice(" Using non-SSL mode\n"); - } - - /* - * give him a fake wsi with context + vhost set, so he can use - * lws_get_context() in the callback - */ - memset(&wsi, 0, sizeof(wsi)); - wsi.vhost = vhost; - wsi.context = context; - - (void)n; - (void)error; - - /* - * Firefox insists on SSLv23 not SSLv3 - * Konq disables SSLv2 by default now, SSLv23 works - * - * SSLv23_server_method() is the openssl method for "allow all TLS - * versions", compared to e.g. TLSv1_2_server_method() which only allows - * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options() - */ -#if !defined(LWS_WITH_MBEDTLS) - { - SSL_METHOD *method; - - method = (SSL_METHOD *)SSLv23_server_method(); - if (!method) { - error = ERR_get_error(); - lwsl_err("problem creating ssl method %lu: %s\n", - error, ERR_error_string(error, - (char *)context->pt[0].serv_buf)); - return 1; - } - vhost->ssl_ctx = SSL_CTX_new(method); /* create context */ - if (!vhost->ssl_ctx) { - error = ERR_get_error(); - lwsl_err("problem creating ssl context %lu: %s\n", - error, ERR_error_string(error, - (char *)context->pt[0].serv_buf)); - return 1; - } - } -#else - { - const SSL_METHOD *method = TLSv1_2_server_method(); - - vhost->ssl_ctx = SSL_CTX_new(method); /* create context */ - if (!vhost->ssl_ctx) { - lwsl_err("problem creating ssl context\n"); - return 1; - } - - } -#endif -#if !defined(LWS_WITH_MBEDTLS) - - /* associate the lws context with the SSL_CTX */ - - SSL_CTX_set_ex_data(vhost->ssl_ctx, - openssl_SSL_CTX_private_data_index, (char *)vhost->context); - /* Disable SSLv2 and SSLv3 */ - SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); -#ifdef SSL_OP_NO_COMPRESSION - SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_NO_COMPRESSION); -#endif - SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_SINGLE_DH_USE); - SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); - - if (info->ssl_cipher_list) - SSL_CTX_set_cipher_list(vhost->ssl_ctx, - info->ssl_cipher_list); -#endif - - /* as a server, are we requiring clients to identify themselves? */ - - if (lws_check_opt(info->options, - LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT)) { - int verify_options = SSL_VERIFY_PEER; - - if (!lws_check_opt(info->options, - LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED)) - verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; - -#if !defined(LWS_WITH_MBEDTLS) - SSL_CTX_set_session_id_context(vhost->ssl_ctx, - (unsigned char *)context, sizeof(void *)); - - /* absolutely require the client cert */ - - SSL_CTX_set_verify(vhost->ssl_ctx, - verify_options, OpenSSL_verify_callback); -#endif - } - -#if !defined(LWS_WITH_MBEDTLS) && !defined(OPENSSL_NO_TLSEXT) - SSL_CTX_set_tlsext_servername_callback(vhost->ssl_ctx, - lws_ssl_server_name_cb); - SSL_CTX_set_tlsext_servername_arg(vhost->ssl_ctx, context); -#endif - - /* - * give user code a chance to load certs into the server - * allowing it to verify incoming client certs - */ -#if !defined(LWS_WITH_MBEDTLS) - if (info->ssl_ca_filepath && - !SSL_CTX_load_verify_locations(vhost->ssl_ctx, - info->ssl_ca_filepath, NULL)) { - lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n", __func__); - } -#endif - if (vhost->use_ssl) { - if (lws_context_ssl_init_ecdh_curve(info, vhost)) - return -1; - - vhost->protocols[0].callback(&wsi, - LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, - vhost->ssl_ctx, NULL, 0); - } - - if (lws_check_opt(info->options, LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT)) - /* Normally SSL listener rejects non-ssl, optionally allow */ - vhost->allow_non_ssl_on_ssl_port = 1; - - if (info->ssl_options_set) - SSL_CTX_set_options(vhost->ssl_ctx, info->ssl_options_set); - -/* SSL_clear_options introduced in 0.9.8m */ -#if !defined(LWS_WITH_MBEDTLS) -#if (OPENSSL_VERSION_NUMBER >= 0x009080df) && !defined(USE_WOLFSSL) - if (info->ssl_options_clear) - SSL_CTX_clear_options(vhost->ssl_ctx, info->ssl_options_clear); -#endif -#endif - - lwsl_info(" SSL options 0x%lX\n", SSL_CTX_get_options(vhost->ssl_ctx)); - - if (vhost->use_ssl && info->ssl_cert_filepath) { - /* - * The user code can choose to either pass the cert and - * key filepaths using the info members like this, or it can - * leave them NULL; force the vhost SSL_CTX init using the info - * options flag LWS_SERVER_OPTION_CREATE_VHOST_SSL_CTX; and - * set up the cert himself using the user callback - * LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS, which - * happened just above and has the vhost SSL_CTX * in the user - * parameter. - */ -#if !defined(LWS_WITH_MBEDTLS) - /* set the local certificate from CertFile */ - n = SSL_CTX_use_certificate_chain_file(vhost->ssl_ctx, - info->ssl_cert_filepath); - if (n != 1) { - error = ERR_get_error(); - lwsl_err("problem getting cert '%s' %lu: %s\n", - info->ssl_cert_filepath, - error, - ERR_error_string(error, - (char *)context->pt[0].serv_buf)); - return 1; - } - lws_ssl_bind_passphrase(vhost->ssl_ctx, info); -#else - uint8_t *p; - lws_filepos_t flen; - int err; - - if (alloc_pem_to_der_file(vhost->context, info->ssl_cert_filepath, &p, - &flen)) { - lwsl_err("couldn't find cert file %s\n", - info->ssl_cert_filepath); - - return 1; - } - err = SSL_CTX_use_certificate_ASN1(vhost->ssl_ctx, flen, p); - if (!err) { - lwsl_err("Problem loading cert\n"); - return 1; - } -#if !defined(LWS_WITH_ESP32) - free(p); - p = NULL; -#endif - - if (info->ssl_private_key_filepath) { - if (alloc_pem_to_der_file(vhost->context, - info->ssl_private_key_filepath, &p, &flen)) { - lwsl_err("couldn't find cert file %s\n", - info->ssl_cert_filepath); - - return 1; - } - err = SSL_CTX_use_PrivateKey_ASN1(0, vhost->ssl_ctx, p, flen); - if (!err) { - lwsl_err("Problem loading key\n"); - - return 1; - } - } - -#if !defined(LWS_WITH_ESP32) - free(p); - p = NULL; -#endif -#endif - if (info->ssl_private_key_filepath != NULL) { -#if !defined(LWS_WITH_MBEDTLS) - /* set the private key from KeyFile */ - if (SSL_CTX_use_PrivateKey_file(vhost->ssl_ctx, - info->ssl_private_key_filepath, - SSL_FILETYPE_PEM) != 1) { - error = ERR_get_error(); - lwsl_err("ssl problem getting key '%s' %lu: %s\n", - info->ssl_private_key_filepath, error, - ERR_error_string(error, - (char *)context->pt[0].serv_buf)); - return 1; - } -#endif - } else - if (vhost->protocols[0].callback(&wsi, - LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY, - vhost->ssl_ctx, NULL, 0)) { - lwsl_err("ssl private key not set\n"); - - return 1; - } -#if !defined(LWS_WITH_MBEDTLS) - /* verify private key */ - if (!SSL_CTX_check_private_key(vhost->ssl_ctx)) { - lwsl_err("Private SSL key doesn't match cert\n"); - return 1; - } -#endif - } - if (vhost->use_ssl) { - if (lws_context_ssl_init_ecdh(vhost)) - return 1; - - /* - * SSL is happy and has a cert it's content with - * If we're supporting HTTP2, initialize that - */ - lws_context_init_http2_ssl(vhost); - } - - return 0; -} - diff --git a/thirdparty/lws/service.c b/thirdparty/lws/service.c deleted file mode 100644 index 8cf455e2c9..0000000000 --- a/thirdparty/lws/service.c +++ /dev/null @@ -1,1714 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" - -static int -lws_calllback_as_writeable(struct lws *wsi) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - int n; - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1); -#if defined(LWS_WITH_STATS) - if (wsi->active_writable_req_us) { - uint64_t ul = time_in_microseconds() - - wsi->active_writable_req_us; - - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_MS_WRITABLE_DELAY, ul); - lws_stats_atomic_max(wsi->context, pt, - LWSSTATS_MS_WORST_WRITABLE_DELAY, ul); - wsi->active_writable_req_us = 0; - } -#endif - - switch (wsi->mode) { - case LWSCM_RAW: - n = LWS_CALLBACK_RAW_WRITEABLE; - break; - case LWSCM_RAW_FILEDESC: - n = LWS_CALLBACK_RAW_WRITEABLE_FILE; - break; - case LWSCM_WS_CLIENT: - n = LWS_CALLBACK_CLIENT_WRITEABLE; - break; - case LWSCM_WSCL_ISSUE_HTTP_BODY: - n = LWS_CALLBACK_CLIENT_HTTP_WRITEABLE; - break; - case LWSCM_WS_SERVING: - n = LWS_CALLBACK_SERVER_WRITEABLE; - break; - default: - n = LWS_CALLBACK_HTTP_WRITEABLE; - break; - } - - return user_callback_handle_rxflow(wsi->protocol->callback, - wsi, (enum lws_callback_reasons) n, - wsi->user_space, NULL, 0); -} - -LWS_VISIBLE int -lws_handle_POLLOUT_event(struct lws *wsi, struct lws_pollfd *pollfd) -{ - int write_type = LWS_WRITE_PONG; - struct lws_tokens eff_buf; -#ifdef LWS_WITH_HTTP2 - struct lws **wsi2, *wsi2a; -#endif - int ret, m, n; - - wsi->leave_pollout_active = 0; - wsi->handling_pollout = 1; - /* - * if another thread wants POLLOUT on us, from here on while - * handling_pollout is set, he will only set leave_pollout_active. - * If we are going to disable POLLOUT, we will check that first. - */ - - /* - * user callback is lowest priority to get these notifications - * actually, since other pending things cannot be disordered - */ - - /* Priority 1: pending truncated sends are incomplete ws fragments - * If anything else sent first the protocol would be - * corrupted. - */ - if (wsi->trunc_len) { - //lwsl_notice("%s: completing partial\n", __func__); - if (lws_issue_raw(wsi, wsi->trunc_alloc + wsi->trunc_offset, - wsi->trunc_len) < 0) { - lwsl_info("%s signalling to close\n", __func__); - goto bail_die; - } - /* leave POLLOUT active either way */ - goto bail_ok; - } else - if (wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) { - wsi->socket_is_permanently_unusable = 1; - goto bail_die; /* retry closing now */ - } - - if (wsi->mode == LWSCM_WSCL_ISSUE_HTTP_BODY) - goto user_service; - -#ifdef LWS_WITH_HTTP2 - /* - * Priority 2: protocol packets - */ - if (wsi->upgraded_to_http2 && wsi->u.h2.h2n->pps) { - lwsl_info("servicing pps\n"); - if (lws_h2_do_pps_send(wsi)) { - wsi->socket_is_permanently_unusable = 1; - goto bail_die; - } - if (wsi->u.h2.h2n->pps) - goto bail_ok; - - /* we can resume whatever we were doing */ - lws_rx_flow_control(wsi, LWS_RXFLOW_REASON_APPLIES_ENABLE | - LWS_RXFLOW_REASON_H2_PPS_PENDING); - - goto bail_ok; /* leave POLLOUT active */ - } -#endif - -#ifdef LWS_WITH_CGI - if (wsi->cgi) { - /* also one shot */ - if (pollfd) - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_info("failed at set pollfd\n"); - return 1; - } - goto user_service_go_again; - } -#endif - - /* Priority 3: pending control packets (pong or close) - * - * 3a: close notification packet requested from close api - */ - - if (wsi->state == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION) { - lwsl_debug("sending close packet\n"); - wsi->waiting_to_send_close_frame = 0; - n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE], - wsi->u.ws.close_in_ping_buffer_len, - LWS_WRITE_CLOSE); - if (n >= 0) { - wsi->state = LWSS_AWAITING_CLOSE_ACK; - lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK, 1); - lwsl_debug("sent close indication, awaiting ack\n"); - - goto bail_ok; - } - - goto bail_die; - } - - /* else, the send failed and we should just hang up */ - - if ((wsi->state == LWSS_ESTABLISHED && - wsi->u.ws.ping_pending_flag) || - (wsi->state == LWSS_RETURNED_CLOSE_ALREADY && - wsi->u.ws.payload_is_close)) { - - if (wsi->u.ws.payload_is_close) - write_type = LWS_WRITE_CLOSE; - - n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE], - wsi->u.ws.ping_payload_len, write_type); - if (n < 0) - goto bail_die; - - /* well he is sent, mark him done */ - wsi->u.ws.ping_pending_flag = 0; - if (wsi->u.ws.payload_is_close) - /* oh... a close frame was it... then we are done */ - goto bail_die; - - /* otherwise for PING, leave POLLOUT active either way */ - goto bail_ok; - } - - if (wsi->state == LWSS_ESTABLISHED && - !wsi->socket_is_permanently_unusable && - wsi->u.ws.send_check_ping) { - - lwsl_info("issuing ping on wsi %p\n", wsi); - wsi->u.ws.send_check_ping = 0; - n = lws_write(wsi, &wsi->u.ws.ping_payload_buf[LWS_PRE], - 0, LWS_WRITE_PING); - if (n < 0) - goto bail_die; - - /* - * we apparently were able to send the PING in a reasonable time - * now reset the clock on our peer to be able to send the - * PONG in a reasonable time. - */ - - lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG, - wsi->context->timeout_secs); - - goto bail_ok; - } - - /* Priority 4: if we are closing, not allowed to send more data frags - * which means user callback or tx ext flush banned now - */ - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY) - goto user_service; - - /* Priority 5: Tx path extension with more to send - * - * These are handled as new fragments each time around - * So while we must block new writeable callback to enforce - * payload ordering, but since they are always complete - * fragments control packets can interleave OK. - */ - if (wsi->state == LWSS_ESTABLISHED && wsi->u.ws.tx_draining_ext) { - lwsl_ext("SERVICING TX EXT DRAINING\n"); - if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0) - goto bail_die; - /* leave POLLOUT active */ - goto bail_ok; - } - - /* Priority 6: user can get the callback - */ - m = lws_ext_cb_active(wsi, LWS_EXT_CB_IS_WRITEABLE, NULL, 0); - if (m) - goto bail_die; -#ifndef LWS_NO_EXTENSIONS - if (!wsi->extension_data_pending) - goto user_service; -#endif - /* - * check in on the active extensions, see if they - * had pending stuff to spill... they need to get the - * first look-in otherwise sequence will be disordered - * - * NULL, zero-length eff_buf means just spill pending - */ - - ret = 1; - if (wsi->mode == LWSCM_RAW || wsi->mode == LWSCM_RAW_FILEDESC) - ret = 0; - - while (ret == 1) { - - /* default to nobody has more to spill */ - - ret = 0; - eff_buf.token = NULL; - eff_buf.token_len = 0; - - /* give every extension a chance to spill */ - - m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND, - &eff_buf, 0); - if (m < 0) { - lwsl_err("ext reports fatal error\n"); - goto bail_die; - } - if (m) - /* - * at least one extension told us he has more - * to spill, so we will go around again after - */ - ret = 1; - - /* assuming they gave us something to send, send it */ - - if (eff_buf.token_len) { - n = lws_issue_raw(wsi, (unsigned char *)eff_buf.token, - eff_buf.token_len); - if (n < 0) { - lwsl_info("closing from POLLOUT spill\n"); - goto bail_die; - } - /* - * Keep amount spilled small to minimize chance of this - */ - if (n != eff_buf.token_len) { - lwsl_err("Unable to spill ext %d vs %d\n", - eff_buf.token_len, n); - goto bail_die; - } - } else - continue; - - /* no extension has more to spill */ - - if (!ret) - continue; - - /* - * There's more to spill from an extension, but we just sent - * something... did that leave the pipe choked? - */ - - if (!lws_send_pipe_choked(wsi)) - /* no we could add more */ - continue; - - lwsl_info("choked in POLLOUT service\n"); - - /* - * Yes, he's choked. Leave the POLLOUT masked on so we will - * come back here when he is unchoked. Don't call the user - * callback to enforce ordering of spilling, he'll get called - * when we come back here and there's nothing more to spill. - */ - - goto bail_ok; - } -#ifndef LWS_NO_EXTENSIONS - wsi->extension_data_pending = 0; -#endif -user_service: - /* one shot */ - - if (wsi->parent_carries_io) { - wsi->handling_pollout = 0; - wsi->leave_pollout_active = 0; - - return lws_calllback_as_writeable(wsi); - } - - if (pollfd) { - int eff = wsi->leave_pollout_active; - - if (!eff) - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_info("failed at set pollfd\n"); - goto bail_die; - } - - wsi->handling_pollout = 0; - - /* cannot get leave_pollout_active set after the above */ - if (!eff && wsi->leave_pollout_active) - /* got set inbetween sampling eff and clearing - * handling_pollout, force POLLOUT on */ - lws_calllback_as_writeable(wsi); - - wsi->leave_pollout_active = 0; - } - - if (wsi->mode != LWSCM_WSCL_ISSUE_HTTP_BODY && - !wsi->hdr_parsing_completed) - goto bail_ok; - - -#ifdef LWS_WITH_CGI -user_service_go_again: -#endif - -#ifdef LWS_WITH_HTTP2 - /* - * we are the 'network wsi' for potentially many muxed child wsi with - * no network connection of their own, who have to use us for all their - * network actions. So we use a round-robin scheme to share out the - * POLLOUT notifications to our children. - * - * But because any child could exhaust the socket's ability to take - * writes, we can only let one child get notified each time. - * - * In addition children may be closed / deleted / added between POLLOUT - * notifications, so we can't hold pointers - */ - - if (wsi->mode != LWSCM_HTTP2_SERVING) { - lwsl_info("%s: non http2\n", __func__); - goto notify; - } - - wsi->u.h2.requested_POLLOUT = 0; - if (!wsi->u.h2.initialized) { - lwsl_info("pollout on uninitialized http2 conn\n"); - goto bail_ok; - } - -// if (SSL_want_read(wsi->ssl) || SSL_want_write(wsi->ssl)) { -// lws_callback_on_writable(wsi); -// goto bail_ok; -// } - - lwsl_info("%s: %p: children waiting for POLLOUT service:\n", __func__, wsi); - wsi2a = wsi->u.h2.child_list; - while (wsi2a) { - if (wsi2a->u.h2.requested_POLLOUT) - lwsl_debug(" * %p\n", wsi2a); - else - lwsl_debug(" %p\n", wsi2a); - - wsi2a = wsi2a->u.h2.sibling_list; - } - - wsi2 = &wsi->u.h2.child_list; - if (!*wsi2) - goto bail_ok; - - do { - struct lws *w, **wa; - - wa = &(*wsi2)->u.h2.sibling_list; - if (!(*wsi2)->u.h2.requested_POLLOUT) { - lwsl_debug(" child %p doesn't want POLLOUT\n", *wsi2); - goto next_child; - } - - /* - * we're going to do writable callback for this child. - * move him to be the last child - */ - - lwsl_debug("servicing child %p\n", *wsi2); - - w = *wsi2; - while (w) { - if (!w->u.h2.sibling_list) { /* w is the current last */ - lwsl_debug("w=%p, *wsi2 = %p\n", w, *wsi2); - if (w == *wsi2) /* we are already last */ - break; - w->u.h2.sibling_list = *wsi2; /* last points to us as new last */ - *wsi2 = (*wsi2)->u.h2.sibling_list; /* guy pointing to us until now points to our old next */ - w->u.h2.sibling_list->u.h2.sibling_list = NULL; /* we point to nothing because we are last */ - w = w->u.h2.sibling_list; /* w becomes us */ - break; - } - w = w->u.h2.sibling_list; - } - - w->u.h2.requested_POLLOUT = 0; - lwsl_info("%s: child %p (state %d)\n", __func__, (*wsi2), (*wsi2)->state); - - if (w->u.h2.pending_status_body) { - w->u.h2.send_END_STREAM = 1; - n = lws_write(w, - (uint8_t *)w->u.h2.pending_status_body + LWS_PRE, - strlen(w->u.h2.pending_status_body + LWS_PRE), - LWS_WRITE_HTTP_FINAL); - lws_free_set_NULL(w->u.h2.pending_status_body); - lws_close_free_wsi(w, LWS_CLOSE_STATUS_NOSTATUS); - wa = &wsi->u.h2.child_list; - goto next_child; - } - - if (w->state == LWSS_HTTP_ISSUING_FILE) { - - w->leave_pollout_active = 0; - - /* >0 == completion, <0 == error - * - * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when - * it's done. That's the case even if we just completed the - * send, so wait for that. - */ - n = lws_serve_http_file_fragment(w); - lwsl_debug("lws_serve_http_file_fragment says %d\n", n); - - /* - * We will often hear about out having sent the final - * DATA here... if so close the actual wsi - */ - if (n < 0 || w->u.h2.send_END_STREAM) { - lwsl_debug("Closing POLLOUT child %p\n", w); - lws_close_free_wsi(w, LWS_CLOSE_STATUS_NOSTATUS); - wa = &wsi->u.h2.child_list; - goto next_child; - } - if (n > 0) - if (lws_http_transaction_completed(w)) - goto bail_die; - if (!n) { - lws_callback_on_writable(w); - (w)->u.h2.requested_POLLOUT = 1; - } - - goto next_child; - } - - if (lws_calllback_as_writeable(w) || w->u.h2.send_END_STREAM) { - lwsl_debug("Closing POLLOUT child\n"); - lws_close_free_wsi(w, LWS_CLOSE_STATUS_NOSTATUS); - wa = &wsi->u.h2.child_list; - } - -next_child: - wsi2 = wa; - } while (wsi2 && *wsi2 && !lws_send_pipe_choked(wsi)); - - lwsl_info("%s: %p: children waiting for POLLOUT service: %p\n", __func__, wsi, wsi->u.h2.child_list); - wsi2a = wsi->u.h2.child_list; - while (wsi2a) { - if (wsi2a->u.h2.requested_POLLOUT) - lwsl_debug(" * %p\n", wsi2a); - else - lwsl_debug(" %p\n", wsi2a); - - wsi2a = wsi2a->u.h2.sibling_list; - } - - - wsi2a = wsi->u.h2.child_list; - while (wsi2a) { - if (wsi2a->u.h2.requested_POLLOUT) { - lws_change_pollfd(wsi, 0, LWS_POLLOUT); - break; - } - wsi2a = wsi2a->u.h2.sibling_list; - } - - goto bail_ok; - - -notify: -#endif - wsi->leave_pollout_active = 0; - - n = lws_calllback_as_writeable(wsi); - wsi->handling_pollout = 0; - - if (wsi->leave_pollout_active) - lws_change_pollfd(wsi, 0, LWS_POLLOUT); - - return n; - - /* - * since these don't disable the POLLOUT, they are always doing the - * right thing for leave_pollout_active whether it was set or not. - */ - -bail_ok: - wsi->handling_pollout = 0; - wsi->leave_pollout_active = 0; - - return 0; - -bail_die: - wsi->handling_pollout = 0; - wsi->leave_pollout_active = 0; - - return -1; -} - -int -lws_service_timeout_check(struct lws *wsi, unsigned int sec) -{ - struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; - int n = 0; - - (void)n; - - /* - * if extensions want in on it (eg, we are a mux parent) - * give them a chance to service child timeouts - */ - if (lws_ext_cb_active(wsi, LWS_EXT_CB_1HZ, NULL, sec) < 0) - return 0; - - if (!wsi->pending_timeout) - return 0; - - /* - * if we went beyond the allowed time, kill the - * connection - */ - if ((time_t)sec > wsi->pending_timeout_limit) { - - if (wsi->desc.sockfd != LWS_SOCK_INVALID && - wsi->position_in_fds_table >= 0) - n = pt->fds[wsi->position_in_fds_table].events; - - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_TIMEOUTS, 1); - - /* no need to log normal idle keepalive timeout */ - if (wsi->pending_timeout != PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE) - lwsl_info("wsi %p: TIMEDOUT WAITING on %d " - "(did hdr %d, ah %p, wl %d, pfd " - "events %d) %llu vs %llu\n", - (void *)wsi, wsi->pending_timeout, - wsi->hdr_parsing_completed, wsi->u.hdr.ah, - pt->ah_wait_list_length, n, - (unsigned long long)sec, - (unsigned long long)wsi->pending_timeout_limit); - - /* - * Since he failed a timeout, he already had a chance to do - * something and was unable to... that includes situations like - * half closed connections. So process this "failed timeout" - * close as a violent death and don't try to do protocol - * cleanup like flush partials. - */ - wsi->socket_is_permanently_unusable = 1; - if (wsi->mode == LWSCM_WSCL_WAITING_SSL) - wsi->vhost->protocols[0].callback(wsi, - LWS_CALLBACK_CLIENT_CONNECTION_ERROR, - wsi->user_space, - (void *)"Timed out waiting SSL", 21); - - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - - return 1; - } - - return 0; -} - -int lws_rxflow_cache(struct lws *wsi, unsigned char *buf, int n, int len) -{ -#if defined(LWS_WITH_HTTP2) - if (wsi->upgraded_to_http2) { - struct lws_h2_netconn *h2n = wsi->u.h2.h2n; - - assert(h2n->rx_scratch); - buf += n; - len -= n; - assert ((char *)buf >= (char *)h2n->rx_scratch && - (char *)&buf[len] <= (char *)&h2n->rx_scratch[LWS_H2_RX_SCRATCH_SIZE]); - - h2n->rx_scratch_pos = ((char *)buf - (char *)h2n->rx_scratch); - h2n->rx_scratch_len = len; - - lwsl_info("%s: %p: pausing h2 rx_scratch\n", __func__, wsi); - - return 0; - } -#endif - /* his RX is flowcontrolled, don't send remaining now */ - if (wsi->rxflow_buffer) { - if (buf >= wsi->rxflow_buffer && - &buf[len - 1] < &wsi->rxflow_buffer[wsi->rxflow_len]) { - /* rxflow while we were spilling prev rxflow */ - lwsl_info("%s: staying in rxflow buf\n", __func__); - return 1; - } else { - lwsl_err("%s: conflicting rxflow buf, " - "current %p len %d, new %p len %d\n", __func__, - wsi->rxflow_buffer, wsi->rxflow_len, buf, len); - assert(0); - return 1; - } - } - - /* a new rxflow, buffer it and warn caller */ - lwsl_info("%s: new rxflow input buffer len %d\n", __func__, len - n); - wsi->rxflow_buffer = lws_malloc(len - n, "rxflow buf"); - if (!wsi->rxflow_buffer) - return -1; - - wsi->rxflow_len = len - n; - wsi->rxflow_pos = 0; - memcpy(wsi->rxflow_buffer, buf + n, len - n); - - return 0; -} - -/* this is used by the platform service code to stop us waiting for network - * activity in poll() when we have something that already needs service - */ - -LWS_VISIBLE LWS_EXTERN int -lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi) -{ - struct lws_context_per_thread *pt = &context->pt[tsi]; - struct allocated_headers *ah; - - /* Figure out if we really want to wait in poll() - * We only need to wait if really nothing already to do and we have - * to wait for something from network - */ - - /* 1) if we know we are draining rx ext, do not wait in poll */ - if (pt->rx_draining_ext_list) - return 0; - -#ifdef LWS_OPENSSL_SUPPORT - /* 2) if we know we have non-network pending data, do not wait in poll */ - if (lws_ssl_anybody_has_buffered_read_tsi(context, tsi)) { - lwsl_info("ssl buffered read\n"); - return 0; - } -#endif - - /* 3) if any ah has pending rx, do not wait in poll */ - ah = pt->ah_list; - while (ah) { - if (ah->rxpos != ah->rxlen) { - if (!ah->wsi) { - assert(0); - } - return 0; - } - ah = ah->next; - } - - return timeout_ms; -} - -/* - * guys that need POLLIN service again without waiting for network action - * can force POLLIN here if not flowcontrolled, so they will get service. - * - * Return nonzero if anybody got their POLLIN faked - */ -int -lws_service_flag_pending(struct lws_context *context, int tsi) -{ - struct lws_context_per_thread *pt = &context->pt[tsi]; - struct allocated_headers *ah; -#ifdef LWS_OPENSSL_SUPPORT - struct lws *wsi_next; -#endif - struct lws *wsi; - int forced = 0; - - /* POLLIN faking */ - - /* - * 1) For all guys with already-available ext data to drain, if they are - * not flowcontrolled, fake their POLLIN status - */ - wsi = pt->rx_draining_ext_list; - while (wsi) { - pt->fds[wsi->position_in_fds_table].revents |= - pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; - if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) { - forced = 1; - break; - } - wsi = wsi->u.ws.rx_draining_ext_list; - } - -#ifdef LWS_OPENSSL_SUPPORT - /* - * 2) For all guys with buffered SSL read data already saved up, if they - * are not flowcontrolled, fake their POLLIN status so they'll get - * service to use up the buffered incoming data, even though their - * network socket may have nothing - */ - wsi = pt->pending_read_list; - while (wsi) { - wsi_next = wsi->pending_read_list_next; - pt->fds[wsi->position_in_fds_table].revents |= - pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; - if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) { - forced = 1; - /* - * he's going to get serviced now, take him off the - * list of guys with buffered SSL. If he still has some - * at the end of the service, he'll get put back on the - * list then. - */ - lws_ssl_remove_wsi_from_buffered_list(wsi); - } - - wsi = wsi_next; - } -#endif - /* - * 3) For any wsi who have an ah with pending RX who did not - * complete their current headers, and are not flowcontrolled, - * fake their POLLIN status so they will be able to drain the - * rx buffered in the ah - */ - ah = pt->ah_list; - while (ah) { - if (ah->rxpos != ah->rxlen && !ah->wsi->hdr_parsing_completed) { - pt->fds[ah->wsi->position_in_fds_table].revents |= - pt->fds[ah->wsi->position_in_fds_table].events & - LWS_POLLIN; - if (pt->fds[ah->wsi->position_in_fds_table].revents & - LWS_POLLIN) { - forced = 1; - break; - } - } - ah = ah->next; - } - - return forced; -} - -#ifndef LWS_NO_CLIENT - -LWS_VISIBLE int -lws_http_client_read(struct lws *wsi, char **buf, int *len) -{ - int rlen, n; - - rlen = lws_ssl_capable_read(wsi, (unsigned char *)*buf, *len); - *len = 0; - - /* allow the source to signal he has data again next time */ - lws_change_pollfd(wsi, 0, LWS_POLLIN); - - if (rlen == LWS_SSL_CAPABLE_ERROR) { - lwsl_notice("%s: SSL capable error\n", __func__); - return -1; - } - - if (rlen == 0) - return -1; - - if (rlen < 0) - return 0; - - *len = rlen; - wsi->client_rx_avail = 0; - - /* - * server may insist on transfer-encoding: chunked, - * so http client must deal with it - */ -spin_chunks: - while (wsi->chunked && (wsi->chunk_parser != ELCP_CONTENT) && *len) { - switch (wsi->chunk_parser) { - case ELCP_HEX: - if ((*buf)[0] == '\x0d') { - wsi->chunk_parser = ELCP_CR; - break; - } - n = char_to_hex((*buf)[0]); - if (n < 0) { - lwsl_debug("chunking failure\n"); - return -1; - } - wsi->chunk_remaining <<= 4; - wsi->chunk_remaining |= n; - break; - case ELCP_CR: - if ((*buf)[0] != '\x0a') { - lwsl_debug("chunking failure\n"); - return -1; - } - wsi->chunk_parser = ELCP_CONTENT; - lwsl_info("chunk %d\n", wsi->chunk_remaining); - if (wsi->chunk_remaining) - break; - lwsl_info("final chunk\n"); - goto completed; - - case ELCP_CONTENT: - break; - - case ELCP_POST_CR: - if ((*buf)[0] != '\x0d') { - lwsl_debug("chunking failure\n"); - - return -1; - } - - wsi->chunk_parser = ELCP_POST_LF; - break; - - case ELCP_POST_LF: - if ((*buf)[0] != '\x0a') - return -1; - - wsi->chunk_parser = ELCP_HEX; - wsi->chunk_remaining = 0; - break; - } - (*buf)++; - (*len)--; - } - - if (wsi->chunked && !wsi->chunk_remaining) - return 0; - - if (wsi->u.http.rx_content_remain && - wsi->u.http.rx_content_remain < *len) - n = (int)wsi->u.http.rx_content_remain; - else - n = *len; - - if (wsi->chunked && wsi->chunk_remaining && - wsi->chunk_remaining < n) - n = wsi->chunk_remaining; - -#ifdef LWS_WITH_HTTP_PROXY - /* hubbub */ - if (wsi->perform_rewrite) - lws_rewrite_parse(wsi->rw, (unsigned char *)*buf, n); - else -#endif - if (user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ, - wsi->user_space, *buf, n)) { - lwsl_debug("%s: LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ returned -1\n", __func__); - - return -1; - } - - if (wsi->chunked && wsi->chunk_remaining) { - (*buf) += n; - wsi->chunk_remaining -= n; - *len -= n; - } - - if (wsi->chunked && !wsi->chunk_remaining) - wsi->chunk_parser = ELCP_POST_CR; - - if (wsi->chunked && *len) - goto spin_chunks; - - if (wsi->chunked) - return 0; - - /* if we know the content length, decrement the content remaining */ - if (wsi->u.http.rx_content_length > 0) - wsi->u.http.rx_content_remain -= n; - - if (wsi->u.http.rx_content_remain || !wsi->u.http.rx_content_length) - return 0; - -completed: - if (user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_COMPLETED_CLIENT_HTTP, - wsi->user_space, NULL, 0)) { - lwsl_debug("Completed call returned -1\n"); - return -1; - } - - if (lws_http_transaction_completed_client(wsi)) { - lwsl_notice("%s: transaction completed says -1\n", __func__); - return -1; - } - - return 0; -} -#endif - -static int -lws_is_ws_with_ext(struct lws *wsi) -{ -#if defined(LWS_NO_EXTENSIONS) - return 0; -#else - return wsi->state == LWSS_ESTABLISHED && - !!wsi->count_act_ext; -#endif -} - -LWS_VISIBLE int -lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd, int tsi) -{ - struct lws_context_per_thread *pt = &context->pt[tsi]; - lws_sockfd_type our_fd = 0, tmp_fd; - struct allocated_headers *ah; - struct lws_tokens eff_buf; - unsigned int pending = 0; - struct lws *wsi, *wsi1; - char draining_flow = 0; - int timed_out = 0; - time_t now; - int n = 0, m; - int more; - - if (!context->protocol_init_done) - lws_protocol_init(context); - - time(&now); - - /* - * handle case that system time was uninitialized when lws started - * at boot, and got initialized a little later - */ - if (context->time_up < 1464083026 && now > 1464083026) - context->time_up = now; - - /* TODO: if using libev, we should probably use timeout watchers... */ - if (context->last_timeout_check_s != now) { - context->last_timeout_check_s = now; - -#if defined(LWS_WITH_STATS) - if (!tsi && now - context->last_dump > 10) { - lws_stats_log_dump(context); - context->last_dump = now; - } -#endif - - lws_plat_service_periodic(context); - - lws_check_deferred_free(context, 0); - -#if defined(LWS_WITH_PEER_LIMITS) - lws_peer_cull_peer_wait_list(context); -#endif - - /* retire unused deprecated context */ -#if !defined(LWS_PLAT_OPTEE) && !defined(LWS_WITH_ESP32) -#if LWS_POSIX && !defined(_WIN32) - if (context->deprecated && !context->count_wsi_allocated) { - lwsl_notice("%s: ending deprecated context\n", __func__); - kill(getpid(), SIGINT); - return 0; - } -#endif -#endif - /* global timeout check once per second */ - - if (pollfd) - our_fd = pollfd->fd; - - /* - * Phase 1: check every wsi on the timeout check list - */ - - wsi = context->pt[tsi].timeout_list; - while (wsi) { - /* we have to take copies, because he may be deleted */ - wsi1 = wsi->timeout_list; - tmp_fd = wsi->desc.sockfd; - if (lws_service_timeout_check(wsi, (unsigned int)now)) { - /* he did time out... */ - if (tmp_fd == our_fd) - /* it was the guy we came to service! */ - timed_out = 1; - /* he's gone, no need to mark as handled */ - } - wsi = wsi1; - } - - /* - * Phase 2: double-check active ah timeouts independent of wsi - * timeout status - */ - - ah = pt->ah_list; - while (ah) { - int len; - char buf[256]; - const unsigned char *c; - - if (!ah->in_use || !ah->wsi || !ah->assigned || - (ah->wsi->vhost && now - ah->assigned < - ah->wsi->vhost->timeout_secs_ah_idle + 60)) { - ah = ah->next; - continue; - } - - /* - * a single ah session somehow got held for - * an unreasonable amount of time. - * - * Dump info on the connection... - */ - wsi = ah->wsi; - buf[0] = '\0'; - lws_get_peer_simple(wsi, buf, sizeof(buf)); - lwsl_notice("ah excessive hold: wsi %p\n" - " peer address: %s\n" - " ah rxpos %u, rxlen %u, pos %u\n", - wsi, buf, ah->rxpos, ah->rxlen, - ah->pos); - buf[0] = '\0'; - m = 0; - do { - c = lws_token_to_string(m); - if (!c) - break; - if (!(*c)) - break; - - len = lws_hdr_total_length(wsi, m); - if (!len || len > sizeof(buf) - 1) { - m++; - continue; - } - - if (lws_hdr_copy(wsi, buf, - sizeof buf, m) > 0) { - buf[sizeof(buf) - 1] = '\0'; - - lwsl_notice(" %s = %s\n", - (const char *)c, buf); - } - m++; - } while (1); - - /* explicitly detach the ah */ - - lws_header_table_force_to_detachable_state(wsi); - lws_header_table_detach(wsi, 0); - - /* ... and then drop the connection */ - - if (wsi->desc.sockfd == our_fd) - /* it was the guy we came to service! */ - timed_out = 1; - - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - - ah = pt->ah_list; - } - -#ifdef LWS_WITH_CGI - /* - * Phase 3: handle cgi timeouts - */ - lws_cgi_kill_terminated(pt); -#endif -#if 0 - { - char s[300], *p = s; - - for (n = 0; n < context->count_threads; n++) - p += sprintf(p, " %7lu (%5d), ", - context->pt[n].count_conns, - context->pt[n].fds_count); - - lwsl_notice("load: %s\n", s); - } -#endif - } - - /* - * at intervals, check for ws connections needing ping-pong checks - */ - - if (context->ws_ping_pong_interval && - context->last_ws_ping_pong_check_s < now + 10) { - struct lws_vhost *vh = context->vhost_list; - context->last_ws_ping_pong_check_s = now; - - while (vh) { - for (n = 0; n < vh->count_protocols; n++) { - wsi = vh->same_vh_protocol_list[n]; - - while (wsi) { - if (wsi->state == LWSS_ESTABLISHED && - !wsi->socket_is_permanently_unusable && - !wsi->u.ws.send_check_ping && - wsi->u.ws.time_next_ping_check && - wsi->u.ws.time_next_ping_check < now) { - - lwsl_info("requesting ping-pong on wsi %p\n", wsi); - wsi->u.ws.send_check_ping = 1; - lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING, - context->timeout_secs); - lws_callback_on_writable(wsi); - wsi->u.ws.time_next_ping_check = now + - wsi->context->ws_ping_pong_interval; - } - wsi = wsi->same_vh_protocol_next; - } - } - vh = vh->vhost_next; - } - } - - - /* the socket we came to service timed out, nothing to do */ - if (timed_out) - return 0; - - /* just here for timeout management? */ - if (!pollfd) - return 0; - - /* no, here to service a socket descriptor */ - wsi = wsi_from_fd(context, pollfd->fd); - if (!wsi) - /* not lws connection ... leave revents alone and return */ - return 0; - - /* - * so that caller can tell we handled, past here we need to - * zero down pollfd->revents after handling - */ - -#if LWS_POSIX - /* handle session socket closed */ - - if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) && - (pollfd->revents & LWS_POLLHUP)) { - wsi->socket_is_permanently_unusable = 1; - lwsl_debug("Session Socket %p (fd=%d) dead\n", - (void *)wsi, pollfd->fd); - - goto close_and_handled; - } - -#ifdef _WIN32 - if (pollfd->revents & LWS_POLLOUT) - wsi->sock_send_blocking = FALSE; -#endif - -#endif - - if ((!(pollfd->revents & pollfd->events & LWS_POLLIN)) && - (pollfd->revents & LWS_POLLHUP)) { - lwsl_debug("pollhup\n"); - wsi->socket_is_permanently_unusable = 1; - goto close_and_handled; - } - -#ifdef LWS_OPENSSL_SUPPORT - if ((wsi->state == LWSS_SHUTDOWN) && lws_is_ssl(wsi) && wsi->ssl) { - n = SSL_shutdown(wsi->ssl); - lwsl_debug("SSL_shutdown=%d for fd %d\n", n, wsi->desc.sockfd); - switch (n) { - case 1: - n = shutdown(wsi->desc.sockfd, SHUT_WR); - goto close_and_handled; - - case 0: - lws_change_pollfd(wsi, 0, LWS_POLLIN); - n = 0; - goto handled; - - default: - n = SSL_get_error(wsi->ssl, n); - if (n != SSL_ERROR_SYSCALL && n != SSL_ERROR_SSL) { - if (SSL_want_read(wsi->ssl)) { - lwsl_debug("(wants read)\n"); - lws_change_pollfd(wsi, 0, LWS_POLLIN); - n = 0; - goto handled; - } - if (SSL_want_write(wsi->ssl)) { - lwsl_debug("(wants write)\n"); - lws_change_pollfd(wsi, 0, LWS_POLLOUT); - n = 0; - goto handled; - } - } - - /* actual error occurred, just close the connection */ - n = shutdown(wsi->desc.sockfd, SHUT_WR); - goto close_and_handled; - } - } -#endif - - /* okay, what we came here to do... */ - - switch (wsi->mode) { - case LWSCM_HTTP_SERVING: - case LWSCM_HTTP_CLIENT: - case LWSCM_HTTP_SERVING_ACCEPTED: - case LWSCM_SERVER_LISTENER: - case LWSCM_SSL_ACK_PENDING: - case LWSCM_SSL_ACK_PENDING_RAW: - if (wsi->state == LWSS_CLIENT_HTTP_ESTABLISHED) - goto handled; - -#ifdef LWS_WITH_CGI - if (wsi->cgi && (pollfd->revents & LWS_POLLOUT)) { - n = lws_handle_POLLOUT_event(wsi, pollfd); - if (n) - goto close_and_handled; - goto handled; - } -#endif - /* fallthru */ - case LWSCM_RAW: - n = lws_server_socket_service(context, wsi, pollfd); - if (n) /* closed by above */ - return 1; - goto handled; - - case LWSCM_RAW_FILEDESC: - - if (pollfd->revents & LWS_POLLOUT) { - n = lws_calllback_as_writeable(wsi); - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_info("failed at set pollfd\n"); - return 1; - } - if (n) - goto close_and_handled; - } - n = LWS_CALLBACK_RAW_RX; - if (wsi->mode == LWSCM_RAW_FILEDESC) - n = LWS_CALLBACK_RAW_RX_FILE; - - if (pollfd->revents & LWS_POLLIN) { - if (user_callback_handle_rxflow( - wsi->protocol->callback, - wsi, n, - wsi->user_space, NULL, 0)) { - lwsl_debug("raw rx callback closed it\n"); - goto close_and_handled; - } - } - - if (pollfd->revents & LWS_POLLHUP) - goto close_and_handled; - n = 0; - goto handled; - - case LWSCM_WS_SERVING: - case LWSCM_WS_CLIENT: - case LWSCM_HTTP2_SERVING: - case LWSCM_HTTP_CLIENT_ACCEPTED: - - /* 1: something requested a callback when it was OK to write */ - - if ((pollfd->revents & LWS_POLLOUT) && - ((wsi->state == LWSS_ESTABLISHED || - wsi->state == LWSS_HTTP2_ESTABLISHED || - wsi->state == LWSS_HTTP2_ESTABLISHED_PRE_SETTINGS || - wsi->state == LWSS_RETURNED_CLOSE_ALREADY || - wsi->state == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION || - wsi->state == LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE)) && - lws_handle_POLLOUT_event(wsi, pollfd)) { - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY) - wsi->state = LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE; - lwsl_info("lws_service_fd: closing\n"); - goto close_and_handled; - } - - if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY || - wsi->state == LWSS_WAITING_TO_SEND_CLOSE_NOTIFICATION || - wsi->state == LWSS_AWAITING_CLOSE_ACK) { - /* - * we stopped caring about anything except control - * packets. Force flow control off, defeat tx - * draining. - */ - lws_rx_flow_control(wsi, 1); - wsi->u.ws.tx_draining_ext = 0; - } - - if (wsi->u.ws.tx_draining_ext) - /* we cannot deal with new RX until the TX ext - * path has been drained. It's because new - * rx will, eg, crap on the wsi rx buf that - * may be needed to retain state. - * - * TX ext drain path MUST go through event loop - * to avoid blocking. - */ - break; - - if (lws_is_flowcontrolled(wsi)) - /* We cannot deal with any kind of new RX - * because we are RX-flowcontrolled. - */ - break; - -#if defined(LWS_WITH_HTTP2) - if (wsi->http2_substream || wsi->upgraded_to_http2) { - wsi1 = lws_get_network_wsi(wsi); - if (wsi1 && wsi1->trunc_len) - /* We cannot deal with any kind of new RX - * because we are dealing with a partial send - * (new RX may trigger new http_action() that - * expect to be able to send) - */ - break; - } -#endif - - /* 2: RX Extension needs to be drained - */ - - if (wsi->state == LWSS_ESTABLISHED && - wsi->u.ws.rx_draining_ext) { - - lwsl_ext("%s: RX EXT DRAINING: Service\n", __func__); -#ifndef LWS_NO_CLIENT - if (wsi->mode == LWSCM_WS_CLIENT) { - n = lws_client_rx_sm(wsi, 0); - if (n < 0) - /* we closed wsi */ - n = 0; - } else -#endif - n = lws_rx_sm(wsi, 0); - - goto handled; - } - - if (wsi->u.ws.rx_draining_ext) - /* - * We have RX EXT content to drain, but can't do it - * right now. That means we cannot do anything lower - * priority either. - */ - break; - - /* 3: RX Flowcontrol buffer / h2 rx scratch needs to be drained - */ - - if (wsi->rxflow_buffer) { - lwsl_info("draining rxflow (len %d)\n", - wsi->rxflow_len - wsi->rxflow_pos); - assert(wsi->rxflow_pos < wsi->rxflow_len); - /* well, drain it */ - eff_buf.token = (char *)wsi->rxflow_buffer + - wsi->rxflow_pos; - eff_buf.token_len = wsi->rxflow_len - wsi->rxflow_pos; - draining_flow = 1; - goto drain; - } - -#if defined(LWS_WITH_HTTP2) - if (wsi->upgraded_to_http2) { - struct lws_h2_netconn *h2n = wsi->u.h2.h2n; - - if (h2n->rx_scratch_len) { - lwsl_info("%s: %p: resuming h2 rx_scratch pos = %d len = %d\n", - __func__, wsi, h2n->rx_scratch_pos, h2n->rx_scratch_len); - eff_buf.token = (char *)h2n->rx_scratch + - h2n->rx_scratch_pos; - eff_buf.token_len = h2n->rx_scratch_len; - - h2n->rx_scratch_len = 0; - goto drain; - } - } -#endif - - /* 4: any incoming (or ah-stashed incoming rx) data ready? - * notice if rx flow going off raced poll(), rx flow wins - */ - - if (!(pollfd->revents & pollfd->events & LWS_POLLIN)) - break; -read: - if (lws_is_flowcontrolled(wsi)) { - lwsl_info("%s: %p should be rxflow (bm 0x%x)..\n", - __func__, wsi, wsi->rxflow_bitmap); - break; - } - - /* all the union members start with hdr, so even in ws mode - * we can deal with the ah via u.hdr - */ - if (wsi->u.hdr.ah) { - lwsl_info("%s: %p: inherited ah rx\n", __func__, wsi); - eff_buf.token_len = wsi->u.hdr.ah->rxlen - - wsi->u.hdr.ah->rxpos; - eff_buf.token = (char *)wsi->u.hdr.ah->rx + - wsi->u.hdr.ah->rxpos; - } else { - if (wsi->mode != LWSCM_HTTP_CLIENT_ACCEPTED) { - /* - * extension may not consume everything (eg, pmd may be constrained - * as to what it can output...) has to go in per-wsi rx buf area. - * Otherwise in large temp serv_buf area. - */ - -#if defined(LWS_WITH_HTTP2) - if (wsi->upgraded_to_http2) { - if (!wsi->u.h2.h2n->rx_scratch) { - wsi->u.h2.h2n->rx_scratch = lws_malloc(LWS_H2_RX_SCRATCH_SIZE, "h2 rx scratch"); - if (!wsi->u.h2.h2n->rx_scratch) - goto close_and_handled; - } - eff_buf.token = wsi->u.h2.h2n->rx_scratch; - eff_buf.token_len = LWS_H2_RX_SCRATCH_SIZE; - } else -#endif - { - eff_buf.token = (char *)pt->serv_buf; - if (lws_is_ws_with_ext(wsi)) { - eff_buf.token_len = wsi->u.ws.rx_ubuf_alloc; - } else { - eff_buf.token_len = context->pt_serv_buf_size; - } - - if ((unsigned int)eff_buf.token_len > context->pt_serv_buf_size) - eff_buf.token_len = context->pt_serv_buf_size; - } - - if ((int)pending > eff_buf.token_len) - pending = eff_buf.token_len; - - eff_buf.token_len = lws_ssl_capable_read(wsi, - (unsigned char *)eff_buf.token, pending ? pending : - eff_buf.token_len); - switch (eff_buf.token_len) { - case 0: - lwsl_info("%s: zero length read\n", __func__); - goto close_and_handled; - case LWS_SSL_CAPABLE_MORE_SERVICE: - lwsl_info("SSL Capable more service\n"); - n = 0; - goto handled; - case LWS_SSL_CAPABLE_ERROR: - lwsl_info("Closing when error\n"); - goto close_and_handled; - } - // lwsl_notice("Actual RX %d\n", eff_buf.token_len); - } - } - -drain: -#ifndef LWS_NO_CLIENT - if (wsi->mode == LWSCM_HTTP_CLIENT_ACCEPTED && - !wsi->told_user_closed) { - - /* - * In SSL mode we get POLLIN notification about - * encrypted data in. - * - * But that is not necessarily related to decrypted - * data out becoming available; in may need to perform - * other in or out before that happens. - * - * simply mark ourselves as having readable data - * and turn off our POLLIN - */ - wsi->client_rx_avail = 1; - lws_change_pollfd(wsi, LWS_POLLIN, 0); - - /* let user code know, he'll usually ask for writeable - * callback and drain / re-enable it there - */ - if (user_callback_handle_rxflow( - wsi->protocol->callback, - wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP, - wsi->user_space, NULL, 0)) { - lwsl_info("RECEIVE_CLIENT_HTTP closed it\n"); - goto close_and_handled; - } - - n = 0; - goto handled; - } -#endif - /* - * give any active extensions a chance to munge the buffer - * before parse. We pass in a pointer to an lws_tokens struct - * prepared with the default buffer and content length that's in - * there. Rather than rewrite the default buffer, extensions - * that expect to grow the buffer can adapt .token to - * point to their own per-connection buffer in the extension - * user allocation. By default with no extensions or no - * extension callback handling, just the normal input buffer is - * used then so it is efficient. - */ - do { - more = 0; - - m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_RX_PREPARSE, - &eff_buf, 0); - if (m < 0) - goto close_and_handled; - if (m) - more = 1; - - /* service incoming data */ - - if (eff_buf.token_len) { - /* - * if draining from rxflow buffer, not - * critical to track what was used since at the - * use it bumps wsi->rxflow_pos. If we come - * around again it will pick up from where it - * left off. - */ - n = lws_read(wsi, (unsigned char *)eff_buf.token, - eff_buf.token_len); - if (n < 0) { - /* we closed wsi */ - n = 0; - goto handled; - } - } - - eff_buf.token = NULL; - eff_buf.token_len = 0; - } while (more); - - if (wsi->u.hdr.ah) { - lwsl_debug("%s: %p: detaching\n", __func__, wsi); - lws_header_table_force_to_detachable_state(wsi); - /* we can run the normal ah detach flow despite - * being in ws union mode, since all union members - * start with hdr */ - lws_header_table_detach(wsi, 0); - } - - pending = lws_ssl_pending(wsi); - if (pending) { - if (lws_is_ws_with_ext(wsi)) - pending = pending > wsi->u.ws.rx_ubuf_alloc ? - wsi->u.ws.rx_ubuf_alloc : pending; - else - pending = pending > context->pt_serv_buf_size ? - context->pt_serv_buf_size : pending; - goto read; - } - - if (draining_flow && wsi->rxflow_buffer && - wsi->rxflow_pos == wsi->rxflow_len) { - lwsl_info("%s: %p flow buf: drained\n", __func__, wsi); - lws_free_set_NULL(wsi->rxflow_buffer); - /* having drained the rxflow buffer, can rearm POLLIN */ -#ifdef LWS_NO_SERVER - n = -#endif - _lws_rx_flow_control(wsi); - /* n ignored, needed for NO_SERVER case */ - } - - break; -#ifdef LWS_WITH_CGI - case LWSCM_CGI: /* we exist to handle a cgi's stdin/out/err data... - * do the callback on our master wsi - */ - { - struct lws_cgi_args args; - - if (wsi->cgi_channel >= LWS_STDOUT && - !(pollfd->revents & pollfd->events & LWS_POLLIN)) - break; - if (wsi->cgi_channel == LWS_STDIN && - !(pollfd->revents & pollfd->events & LWS_POLLOUT)) - break; - - if (wsi->cgi_channel == LWS_STDIN) - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_info("failed at set pollfd\n"); - return 1; - } - - args.ch = wsi->cgi_channel; - args.stdwsi = &wsi->parent->cgi->stdwsi[0]; - args.hdr_state = wsi->hdr_state; - - lwsl_debug("CGI LWS_STDOUT %p mode %d state %d\n", - wsi->parent, wsi->parent->mode, - wsi->parent->state); - - if (user_callback_handle_rxflow( - wsi->parent->protocol->callback, - wsi->parent, LWS_CALLBACK_CGI, - wsi->parent->user_space, - (void *)&args, 0)) - return 1; - - break; - } -#endif - /* - * something went wrong with parsing the handshake, and - * we ended up back in the event loop without completing it - */ - case LWSCM_PRE_WS_SERVING_ACCEPT: - wsi->socket_is_permanently_unusable = 1; - goto close_and_handled; - - default: -#ifdef LWS_NO_CLIENT - break; -#else - if ((pollfd->revents & LWS_POLLOUT) && - lws_handle_POLLOUT_event(wsi, pollfd)) { - lwsl_debug("POLLOUT event closed it\n"); - goto close_and_handled; - } - - n = lws_client_socket_service(context, wsi, pollfd); - if (n) - return 1; - goto handled; -#endif - } - - n = 0; - goto handled; - -close_and_handled: - lwsl_debug("%p: Close and handled\n", wsi); - lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS); - /* - * pollfd may point to something else after the close - * due to pollfd swapping scheme on delete on some platforms - * we can't clear revents now because it'd be the wrong guy's revents - */ - return 1; - -handled: - pollfd->revents = 0; - return n; -} - -LWS_VISIBLE int -lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd) -{ - return lws_service_fd_tsi(context, pollfd, 0); -} - -LWS_VISIBLE int -lws_service(struct lws_context *context, int timeout_ms) -{ - return lws_plat_service(context, timeout_ms); -} - -LWS_VISIBLE int -lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi) -{ - return _lws_plat_service_tsi(context, timeout_ms, tsi); -} - diff --git a/thirdparty/lws/ssl.c b/thirdparty/lws/ssl.c deleted file mode 100644 index 4ff3088ab3..0000000000 --- a/thirdparty/lws/ssl.c +++ /dev/null @@ -1,973 +0,0 @@ -/* - * libwebsockets - small server side websockets and web server implementation - * - * Copyright (C) 2010-2017 Andy Green <andy@warmcat.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation: - * version 2.1 of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301 USA - */ - -#include "private-libwebsockets.h" -#include <errno.h> - -int lws_alloc_vfs_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount) -{ - lws_filepos_t len; - lws_fop_flags_t flags = LWS_O_RDONLY; - lws_fop_fd_t fops_fd = lws_vfs_file_open( - lws_get_fops(context), filename, &flags); - int ret = 1; - - if (!fops_fd) - return 1; - - len = lws_vfs_get_length(fops_fd); - - *buf = lws_malloc((size_t)len, "lws_alloc_vfs_file"); - if (!*buf) - goto bail; - - if (lws_vfs_file_read(fops_fd, amount, *buf, len)) - goto bail; - - ret = 0; -bail: - lws_vfs_file_close(&fops_fd); - - return ret; -} - -#if defined(LWS_WITH_MBEDTLS) -#if defined(LWS_WITH_ESP32) -int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount) -{ - nvs_handle nvh; - size_t s; - int n = 0; - - ESP_ERROR_CHECK(nvs_open("lws-station", NVS_READWRITE, &nvh)); - if (nvs_get_blob(nvh, filename, NULL, &s) != ESP_OK) { - n = 1; - goto bail; - } - *buf = lws_malloc(s, "alloc_file"); - if (!*buf) { - n = 2; - goto bail; - } - if (nvs_get_blob(nvh, filename, (char *)*buf, &s) != ESP_OK) { - lws_free(*buf); - n = 1; - goto bail; - } - - *amount = s; - -bail: - nvs_close(nvh); - - return n; -} -#else -int alloc_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount) -{ - FILE *f; - size_t s; - int n = 0; - - f = fopen(filename, "rb"); - if (f == NULL) { - n = 1; - goto bail; - } - - if (fseek(f, 0, SEEK_END) != 0) { - n = 1; - goto bail; - } - - s = ftell(f); - if (s == -1) { - n = 1; - goto bail; - } - - if (fseek(f, 0, SEEK_SET) != 0) { - n = 1; - goto bail; - } - - *buf = lws_malloc(s, "alloc_file"); - if (!*buf) { - n = 2; - goto bail; - } - - if (fread(*buf, s, 1, f) != 1) { - lws_free(*buf); - n = 1; - goto bail; - } - - *amount = s; - -bail: - if (f) - fclose(f); - - return n; - -} -#endif -int alloc_pem_to_der_file(struct lws_context *context, const char *filename, uint8_t **buf, - lws_filepos_t *amount) -{ - uint8_t *pem, *p, *q, *end; - lws_filepos_t len; - int n; - - n = alloc_file(context, filename, &pem, &len); - if (n) - return n; - - /* trim the first line */ - - p = pem; - end = p + len; - if (strncmp((char *)p, "-----", 5)) - goto bail; - p += 5; - while (p < end && *p != '\n' && *p != '-') - p++; - - if (*p != '-') - goto bail; - - while (p < end && *p != '\n') - p++; - - if (p >= end) - goto bail; - - p++; - - /* trim the last line */ - - q = end - 2; - - while (q > pem && *q != '\n') - q--; - - if (*q != '\n') - goto bail; - - *q = '\0'; - - *amount = lws_b64_decode_string((char *)p, (char *)pem, len); - *buf = pem; - - return 0; - -bail: - lws_free(pem); - - return 4; -} -#endif - -int openssl_websocket_private_data_index, - openssl_SSL_CTX_private_data_index; - -int lws_ssl_get_error(struct lws *wsi, int n) -{ - int m; - - if (!wsi->ssl) - return 99; - - m = SSL_get_error(wsi->ssl, n); - lwsl_debug("%s: %p %d -> %d\n", __func__, wsi->ssl, n, m); - - return m; -} - -/* Copies a string describing the code returned by lws_ssl_get_error(), - * which may also contain system error information in the case of SSL_ERROR_SYSCALL, - * into buf up to len. - * Returns a pointer to buf. - * - * Note: the lws_ssl_get_error() code is *not* an error code that can be passed - * to ERR_error_string(), - * - * ret is the return value originally passed to lws_ssl_get_error(), needed to disambiguate - * SYS_ERROR_SYSCALL. - * - * See man page for SSL_get_error(). - * - * Not thread safe, uses strerror() - */ -char* lws_ssl_get_error_string(int status, int ret, char *buf, size_t len) { - switch (status) { - case SSL_ERROR_NONE: return strncpy(buf, "SSL_ERROR_NONE", len); - case SSL_ERROR_ZERO_RETURN: return strncpy(buf, "SSL_ERROR_ZERO_RETURN", len); - case SSL_ERROR_WANT_READ: return strncpy(buf, "SSL_ERROR_WANT_READ", len); - case SSL_ERROR_WANT_WRITE: return strncpy(buf, "SSL_ERROR_WANT_WRITE", len); - case SSL_ERROR_WANT_CONNECT: return strncpy(buf, "SSL_ERROR_WANT_CONNECT", len); - case SSL_ERROR_WANT_ACCEPT: return strncpy(buf, "SSL_ERROR_WANT_ACCEPT", len); - case SSL_ERROR_WANT_X509_LOOKUP: return strncpy(buf, "SSL_ERROR_WANT_X509_LOOKUP", len); - case SSL_ERROR_SYSCALL: - switch (ret) { - case 0: - lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: EOF"); - return buf; - case -1: -#ifndef LWS_PLAT_OPTEE - lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: %s", strerror(errno)); -#else - lws_snprintf(buf, len, "SSL_ERROR_SYSCALL: %d", errno); -#endif - return buf; - default: - return strncpy(buf, "SSL_ERROR_SYSCALL", len); - } - case SSL_ERROR_SSL: return "SSL_ERROR_SSL"; - default: return "SSL_ERROR_UNKNOWN"; - } -} - -void -lws_ssl_elaborate_error(void) -{ -#if defined(LWS_WITH_MBEDTLS) -#else - char buf[256]; - u_long err; - - while ((err = ERR_get_error()) != 0) { - ERR_error_string_n(err, buf, sizeof(buf)); - lwsl_info("*** %s\n", buf); - } -#endif -} - -#if !defined(LWS_WITH_MBEDTLS) - -static int -lws_context_init_ssl_pem_passwd_cb(char * buf, int size, int rwflag, void *userdata) -{ - struct lws_context_creation_info * info = - (struct lws_context_creation_info *)userdata; - - strncpy(buf, info->ssl_private_key_password, size); - buf[size - 1] = '\0'; - - return strlen(buf); -} - -void -lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info) -{ - if (!info->ssl_private_key_password) - return; - /* - * password provided, set ssl callback and user data - * for checking password which will be trigered during - * SSL_CTX_use_PrivateKey_file function - */ - SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *)info); - SSL_CTX_set_default_passwd_cb(ssl_ctx, lws_context_init_ssl_pem_passwd_cb); -} -#endif - -int -lws_context_init_ssl_library(struct lws_context_creation_info *info) -{ -#ifdef USE_WOLFSSL -#ifdef USE_OLD_CYASSL - lwsl_info(" Compiled with CyaSSL support\n"); -#else - lwsl_info(" Compiled with wolfSSL support\n"); -#endif -#else -#if defined(LWS_WITH_BORINGSSL) - lwsl_info(" Compiled with BoringSSL support\n"); -#else -#if defined(LWS_WITH_MBEDTLS) - lwsl_info(" Compiled with MbedTLS support\n"); -#else - lwsl_info(" Compiled with OpenSSL support\n"); -#endif -#endif -#endif - if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) { - lwsl_info(" SSL disabled: no LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT\n"); - return 0; - } - - /* basic openssl init */ - - lwsl_info("Doing SSL library init\n"); - -#if !defined(LWS_WITH_MBEDTLS) - SSL_library_init(); - OpenSSL_add_all_algorithms(); - SSL_load_error_strings(); - - openssl_websocket_private_data_index = - SSL_get_ex_new_index(0, "lws", NULL, NULL, NULL); - - openssl_SSL_CTX_private_data_index = SSL_CTX_get_ex_new_index(0, - NULL, NULL, NULL, NULL); -#endif - - return 0; -} - -LWS_VISIBLE void -lws_ssl_destroy(struct lws_vhost *vhost) -{ - if (!lws_check_opt(vhost->context->options, - LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) - return; - - if (vhost->ssl_ctx) - SSL_CTX_free(vhost->ssl_ctx); - if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx) - SSL_CTX_free(vhost->ssl_client_ctx); - -#if defined(LWS_WITH_MBEDTLS) - if (vhost->x509_client_CA) - X509_free(vhost->x509_client_CA); -#else -// after 1.1.0 no need -#if (OPENSSL_VERSION_NUMBER < 0x10100000) -// <= 1.0.1f = old api, 1.0.1g+ = new api -#if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL) - ERR_remove_state(0); -#else -#if OPENSSL_VERSION_NUMBER >= 0x1010005f && \ - !defined(LIBRESSL_VERSION_NUMBER) && \ - !defined(OPENSSL_IS_BORINGSSL) - ERR_remove_thread_state(); -#else - ERR_remove_thread_state(NULL); -#endif -#endif - // after 1.1.0 no need -#if (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000) - SSL_COMP_free_compression_methods(); -#endif - ERR_free_strings(); - EVP_cleanup(); - CRYPTO_cleanup_all_ex_data(); -#endif -#endif -} - -int -lws_ssl_anybody_has_buffered_read_tsi(struct lws_context *context, int tsi) -{ - struct lws_context_per_thread *pt = &context->pt[tsi]; - struct lws *wsi, *wsi_next; - - wsi = pt->pending_read_list; - while (wsi) { - wsi_next = wsi->pending_read_list_next; - pt->fds[wsi->position_in_fds_table].revents |= - pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN; - if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN) - return 1; - - wsi = wsi_next; - } - - return 0; -} - -LWS_VISIBLE void -lws_ssl_remove_wsi_from_buffered_list(struct lws *wsi) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - - if (!wsi->pending_read_list_prev && - !wsi->pending_read_list_next && - pt->pending_read_list != wsi) - /* we are not on the list */ - return; - - /* point previous guy's next to our next */ - if (!wsi->pending_read_list_prev) - pt->pending_read_list = wsi->pending_read_list_next; - else - wsi->pending_read_list_prev->pending_read_list_next = - wsi->pending_read_list_next; - - /* point next guy's previous to our previous */ - if (wsi->pending_read_list_next) - wsi->pending_read_list_next->pending_read_list_prev = - wsi->pending_read_list_prev; - - wsi->pending_read_list_prev = NULL; - wsi->pending_read_list_next = NULL; -} - -LWS_VISIBLE int -lws_ssl_capable_read(struct lws *wsi, unsigned char *buf, int len) -{ - struct lws_context *context = wsi->context; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - int n = 0, m; - - if (!wsi->ssl) - return lws_ssl_capable_read_no_ssl(wsi, buf, len); - - lws_stats_atomic_bump(context, pt, LWSSTATS_C_API_READ, 1); - - errno = 0; - n = SSL_read(wsi->ssl, buf, len); -#if defined(LWS_WITH_ESP32) - if (!n && errno == ENOTCONN) { - lwsl_debug("%p: SSL_read ENOTCONN\n", wsi); - return LWS_SSL_CAPABLE_ERROR; - } -#endif -#if defined(LWS_WITH_STATS) - if (!wsi->seen_rx) { - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_SSL_RX_DELAY, - time_in_microseconds() - wsi->accept_start_us); - lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_SSL_CONNS_HAD_RX, 1); - wsi->seen_rx = 1; - } -#endif - - - lwsl_debug("%p: SSL_read says %d\n", wsi, n); - /* manpage: returning 0 means connection shut down */ - if (!n || (n == -1 && errno == ENOTCONN)) { - wsi->socket_is_permanently_unusable = 1; - - return LWS_SSL_CAPABLE_ERROR; - } - - if (n < 0) { - m = lws_ssl_get_error(wsi, n); - lwsl_debug("%p: ssl err %d errno %d\n", wsi, m, errno); - if (m == SSL_ERROR_ZERO_RETURN || - m == SSL_ERROR_SYSCALL) - return LWS_SSL_CAPABLE_ERROR; - - if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->ssl)) { - lwsl_debug("%s: WANT_READ\n", __func__); - lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi); - return LWS_SSL_CAPABLE_MORE_SERVICE; - } - if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->ssl)) { - lwsl_debug("%s: WANT_WRITE\n", __func__); - lwsl_debug("%p: LWS_SSL_CAPABLE_MORE_SERVICE\n", wsi); - return LWS_SSL_CAPABLE_MORE_SERVICE; - } - wsi->socket_is_permanently_unusable = 1; - - return LWS_SSL_CAPABLE_ERROR; - } - - lws_stats_atomic_bump(context, pt, LWSSTATS_B_READ, n); - - if (wsi->vhost) - wsi->vhost->conn_stats.rx += n; - - lws_restart_ws_ping_pong_timer(wsi); - - /* - * if it was our buffer that limited what we read, - * check if SSL has additional data pending inside SSL buffers. - * - * Because these won't signal at the network layer with POLLIN - * and if we don't realize, this data will sit there forever - */ - if (n != len) - goto bail; - if (!wsi->ssl) - goto bail; - - if (!SSL_pending(wsi->ssl)) - goto bail; - - if (wsi->pending_read_list_next) - return n; - if (wsi->pending_read_list_prev) - return n; - if (pt->pending_read_list == wsi) - return n; - - /* add us to the linked list of guys with pending ssl */ - if (pt->pending_read_list) - pt->pending_read_list->pending_read_list_prev = wsi; - - wsi->pending_read_list_next = pt->pending_read_list; - wsi->pending_read_list_prev = NULL; - pt->pending_read_list = wsi; - - return n; -bail: - lws_ssl_remove_wsi_from_buffered_list(wsi); - - return n; -} - -LWS_VISIBLE int -lws_ssl_pending(struct lws *wsi) -{ - if (!wsi->ssl) - return 0; - - return SSL_pending(wsi->ssl); -} - -LWS_VISIBLE int -lws_ssl_capable_write(struct lws *wsi, unsigned char *buf, int len) -{ - int n, m; - - if (!wsi->ssl) - return lws_ssl_capable_write_no_ssl(wsi, buf, len); - - n = SSL_write(wsi->ssl, buf, len); - if (n > 0) - return n; - - m = lws_ssl_get_error(wsi, n); - if (m != SSL_ERROR_SYSCALL) { - - if (SSL_want_read(wsi->ssl)) { - lwsl_notice("%s: want read\n", __func__); - - return LWS_SSL_CAPABLE_MORE_SERVICE; - } - - if (SSL_want_write(wsi->ssl)) { - lws_set_blocking_send(wsi); - - lwsl_notice("%s: want write\n", __func__); - - return LWS_SSL_CAPABLE_MORE_SERVICE; - } - } - - lwsl_debug("%s failed: %s\n",__func__, ERR_error_string(m, NULL)); - lws_ssl_elaborate_error(); - - wsi->socket_is_permanently_unusable = 1; - - return LWS_SSL_CAPABLE_ERROR; -} - -static int -lws_gate_accepts(struct lws_context *context, int on) -{ - struct lws_vhost *v = context->vhost_list; - - lwsl_info("gating accepts %d\n", on); - context->ssl_gate_accepts = !on; -#if defined(LWS_WITH_STATS) - context->updated = 1; -#endif - - while (v) { - if (v->use_ssl && v->lserv_wsi) /* gate ability to accept incoming connections */ - if (lws_change_pollfd(v->lserv_wsi, (LWS_POLLIN) * !on, - (LWS_POLLIN) * on)) - lwsl_info("Unable to set accept POLLIN %d\n", on); - - v = v->vhost_next; - } - - return 0; -} - -void -lws_ssl_info_callback(const SSL *ssl, int where, int ret) -{ - struct lws *wsi; - struct lws_context *context; - struct lws_ssl_info si; - - context = (struct lws_context *)SSL_CTX_get_ex_data( - SSL_get_SSL_CTX(ssl), - openssl_SSL_CTX_private_data_index); - if (!context) - return; - wsi = wsi_from_fd(context, SSL_get_fd(ssl)); - if (!wsi) - return; - - if (!(where & wsi->vhost->ssl_info_event_mask)) - return; - - si.where = where; - si.ret = ret; - - if (user_callback_handle_rxflow(wsi->protocol->callback, - wsi, LWS_CALLBACK_SSL_INFO, - wsi->user_space, &si, 0)) - lws_set_timeout(wsi, PENDING_TIMEOUT_KILLED_BY_SSL_INFO, -1); -} - - -LWS_VISIBLE int -lws_ssl_close(struct lws *wsi) -{ - lws_sockfd_type n; - - if (!wsi->ssl) - return 0; /* not handled */ - -#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK) - /* kill ssl callbacks, becausse we will remove the fd from the - * table linking it to the wsi - */ - if (wsi->vhost->ssl_info_event_mask) - SSL_set_info_callback(wsi->ssl, NULL); -#endif - - n = SSL_get_fd(wsi->ssl); - if (!wsi->socket_is_permanently_unusable) - SSL_shutdown(wsi->ssl); - compatible_close(n); - SSL_free(wsi->ssl); - wsi->ssl = NULL; - - if (wsi->context->simultaneous_ssl_restriction && - wsi->context->simultaneous_ssl-- == - wsi->context->simultaneous_ssl_restriction) - /* we made space and can do an accept */ - lws_gate_accepts(wsi->context, 1); -#if defined(LWS_WITH_STATS) - wsi->context->updated = 1; -#endif - - return 1; /* handled */ -} - -/* leave all wsi close processing to the caller */ - -LWS_VISIBLE int -lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd) -{ - struct lws_context *context = wsi->context; - struct lws_vhost *vh; - struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; - int n, m; -#if !defined(USE_WOLFSSL) && !defined(LWS_WITH_MBEDTLS) - BIO *bio; -#endif - char buf[256]; - - (void)buf; - - if (!LWS_SSL_ENABLED(wsi->vhost)) - return 0; - - switch (wsi->mode) { - case LWSCM_SSL_INIT: - case LWSCM_SSL_INIT_RAW: - if (wsi->ssl) - lwsl_err("%s: leaking ssl\n", __func__); - if (accept_fd == LWS_SOCK_INVALID) - assert(0); - if (context->simultaneous_ssl_restriction && - context->simultaneous_ssl >= context->simultaneous_ssl_restriction) { - lwsl_notice("unable to deal with SSL connection\n"); - return 1; - } - errno = 0; - wsi->ssl = SSL_new(wsi->vhost->ssl_ctx); - if (wsi->ssl == NULL) { - lwsl_err("SSL_new failed: %d (errno %d)\n", - lws_ssl_get_error(wsi, 0), errno); - - lws_ssl_elaborate_error(); - if (accept_fd != LWS_SOCK_INVALID) - compatible_close(accept_fd); - goto fail; - } -#if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK) - if (wsi->vhost->ssl_info_event_mask) - SSL_set_info_callback(wsi->ssl, lws_ssl_info_callback); -#endif - if (context->simultaneous_ssl_restriction && - ++context->simultaneous_ssl == context->simultaneous_ssl_restriction) - /* that was the last allowed SSL connection */ - lws_gate_accepts(context, 0); -#if defined(LWS_WITH_STATS) - context->updated = 1; -#endif - -#if !defined(LWS_WITH_MBEDTLS) - SSL_set_ex_data(wsi->ssl, - openssl_websocket_private_data_index, wsi); -#endif - SSL_set_fd(wsi->ssl, accept_fd); - -#ifdef USE_WOLFSSL -#ifdef USE_OLD_CYASSL - CyaSSL_set_using_nonblock(wsi->ssl, 1); -#else - wolfSSL_set_using_nonblock(wsi->ssl, 1); -#endif -#else -#if defined(LWS_WITH_MBEDTLS) - lws_plat_set_socket_options(wsi->vhost, accept_fd); -#else - SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); - bio = SSL_get_rbio(wsi->ssl); - if (bio) - BIO_set_nbio(bio, 1); /* nonblocking */ - else - lwsl_notice("NULL rbio\n"); - bio = SSL_get_wbio(wsi->ssl); - if (bio) - BIO_set_nbio(bio, 1); /* nonblocking */ - else - lwsl_notice("NULL rbio\n"); -#endif -#endif - - /* - * we are not accepted yet, but we need to enter ourselves - * as a live connection. That way we can retry when more - * pieces come if we're not sorted yet - */ - - if (wsi->mode == LWSCM_SSL_INIT) - wsi->mode = LWSCM_SSL_ACK_PENDING; - else - wsi->mode = LWSCM_SSL_ACK_PENDING_RAW; - - if (insert_wsi_socket_into_fds(context, wsi)) { - lwsl_err("%s: failed to insert into fds\n", __func__); - goto fail; - } - - lws_set_timeout(wsi, PENDING_TIMEOUT_SSL_ACCEPT, - context->timeout_secs); - - lwsl_debug("inserted SSL accept into fds, trying SSL_accept\n"); - - /* fallthru */ - - case LWSCM_SSL_ACK_PENDING: - case LWSCM_SSL_ACK_PENDING_RAW: - if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) { - lwsl_err("%s: lws_change_pollfd failed\n", __func__); - goto fail; - } - - lws_latency_pre(context, wsi); - - if (wsi->vhost->allow_non_ssl_on_ssl_port) { - - n = recv(wsi->desc.sockfd, (char *)pt->serv_buf, - context->pt_serv_buf_size, MSG_PEEK); - - /* - * optionally allow non-SSL connect on SSL listening socket - * This is disabled by default, if enabled it goes around any - * SSL-level access control (eg, client-side certs) so leave - * it disabled unless you know it's not a problem for you - */ - - if (n >= 1 && pt->serv_buf[0] >= ' ') { - /* - * TLS content-type for Handshake is 0x16, and - * for ChangeCipherSpec Record, it's 0x14 - * - * A non-ssl session will start with the HTTP - * method in ASCII. If we see it's not a legit - * SSL handshake kill the SSL for this - * connection and try to handle as a HTTP - * connection upgrade directly. - */ - wsi->use_ssl = 0; - - SSL_shutdown(wsi->ssl); - SSL_free(wsi->ssl); - wsi->ssl = NULL; - if (lws_check_opt(context->options, - LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS)) - wsi->redirect_to_https = 1; - goto accepted; - } - if (!n) /* - * connection is gone, or nothing to read - * if it's gone, we will timeout on - * PENDING_TIMEOUT_SSL_ACCEPT - */ - break; - if (n < 0 && (LWS_ERRNO == LWS_EAGAIN || - LWS_ERRNO == LWS_EWOULDBLOCK)) { - /* - * well, we get no way to know ssl or not - * so go around again waiting for something - * to come and give us a hint, or timeout the - * connection. - */ - m = SSL_ERROR_WANT_READ; - goto go_again; - } - } - - /* normal SSL connection processing path */ - -#if defined(LWS_WITH_STATS) - if (!wsi->accept_start_us) - wsi->accept_start_us = time_in_microseconds(); -#endif - errno = 0; - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_SSL_CONNECTIONS_ACCEPT_SPIN, 1); - n = SSL_accept(wsi->ssl); - lws_latency(context, wsi, - "SSL_accept LWSCM_SSL_ACK_PENDING\n", n, n == 1); - lwsl_info("SSL_accept says %d\n", n); - if (n == 1) - goto accepted; - - m = lws_ssl_get_error(wsi, n); - -#if defined(LWS_WITH_MBEDTLS) - if (m == SSL_ERROR_SYSCALL && errno == 11) - m = SSL_ERROR_WANT_READ; -#endif - if (m == SSL_ERROR_SYSCALL || m == SSL_ERROR_SSL) - goto failed; - -go_again: - if (m == SSL_ERROR_WANT_READ || SSL_want_read(wsi->ssl)) { - if (lws_change_pollfd(wsi, 0, LWS_POLLIN)) { - lwsl_info("%s: WANT_READ change_pollfd failed\n", __func__); - goto fail; - } - - lwsl_info("SSL_ERROR_WANT_READ\n"); - break; - } - if (m == SSL_ERROR_WANT_WRITE || SSL_want_write(wsi->ssl)) { - lwsl_debug("%s: WANT_WRITE\n", __func__); - - if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) { - lwsl_info("%s: WANT_WRITE change_pollfd failed\n", __func__); - goto fail; - } - - break; - } -failed: - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_SSL_CONNECTIONS_FAILED, 1); - wsi->socket_is_permanently_unusable = 1; - lwsl_info("SSL_accept failed socket %u: %s\n", wsi->desc.sockfd, - lws_ssl_get_error_string(m, n, buf, sizeof(buf))); - lws_ssl_elaborate_error(); - goto fail; - -accepted: - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_C_SSL_CONNECTIONS_ACCEPTED, 1); -#if defined(LWS_WITH_STATS) - lws_stats_atomic_bump(wsi->context, pt, - LWSSTATS_MS_SSL_CONNECTIONS_ACCEPTED_DELAY, - time_in_microseconds() - wsi->accept_start_us); - wsi->accept_start_us = time_in_microseconds(); -#endif - - /* adapt our vhost to match the SNI SSL_CTX that was chosen */ - vh = context->vhost_list; - while (vh) { - if (!vh->being_destroyed && wsi->ssl && - vh->ssl_ctx == SSL_get_SSL_CTX(wsi->ssl)) { - lwsl_info("setting wsi to vh %s\n", vh->name); - wsi->vhost = vh; - break; - } - vh = vh->vhost_next; - } - - /* OK, we are accepted... give him some time to negotiate */ - lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER, - context->timeout_secs); - - if (wsi->mode == LWSCM_SSL_ACK_PENDING_RAW) - wsi->mode = LWSCM_RAW; - else - wsi->mode = LWSCM_HTTP_SERVING; -#if defined(LWS_WITH_HTTP2) - if (lws_h2_configure_if_upgraded(wsi)) - goto fail; -#endif - lwsl_debug("accepted new SSL conn\n"); - break; - } - - return 0; - -fail: - return 1; -} - -void -lws_ssl_SSL_CTX_destroy(struct lws_vhost *vhost) -{ - if (vhost->ssl_ctx) - SSL_CTX_free(vhost->ssl_ctx); - - if (!vhost->user_supplied_ssl_ctx && vhost->ssl_client_ctx) - SSL_CTX_free(vhost->ssl_client_ctx); -} - -void -lws_ssl_context_destroy(struct lws_context *context) -{ - -#if !defined(LWS_WITH_MBEDTLS) - -// after 1.1.0 no need -#if (OPENSSL_VERSION_NUMBER < 0x10100000) -// <= 1.0.1f = old api, 1.0.1g+ = new api -#if (OPENSSL_VERSION_NUMBER <= 0x1000106f) || defined(USE_WOLFSSL) - ERR_remove_state(0); -#else -#if OPENSSL_VERSION_NUMBER >= 0x1010005f && \ - !defined(LIBRESSL_VERSION_NUMBER) && \ - !defined(OPENSSL_IS_BORINGSSL) - ERR_remove_thread_state(); -#else - ERR_remove_thread_state(NULL); -#endif -#endif - // after 1.1.0 no need -#if (OPENSSL_VERSION_NUMBER >= 0x10002000) && (OPENSSL_VERSION_NUMBER <= 0x10100000) - SSL_COMP_free_compression_methods(); -#endif - ERR_free_strings(); - EVP_cleanup(); - CRYPTO_cleanup_all_ex_data(); -#endif -#endif -} diff --git a/thirdparty/mbedtls/LICENSE b/thirdparty/mbedtls/LICENSE new file mode 100644 index 0000000000..546a8e631f --- /dev/null +++ b/thirdparty/mbedtls/LICENSE @@ -0,0 +1,2 @@ +Unless specifically indicated otherwise in a file, files are licensed +under the Apache 2.0 license, as can be found in: apache-2.0.txt diff --git a/thirdparty/mbedtls/apache-2.0.txt b/thirdparty/mbedtls/apache-2.0.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/thirdparty/mbedtls/apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/thirdparty/miniupnpc/LICENSE b/thirdparty/miniupnpc/LICENSE new file mode 100644 index 0000000000..0816733704 --- /dev/null +++ b/thirdparty/miniupnpc/LICENSE @@ -0,0 +1,27 @@ +MiniUPnPc +Copyright (c) 2005-2016, Thomas BERNARD +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + diff --git a/thirdparty/miniupnpc/codelength.h b/thirdparty/miniupnpc/codelength.h new file mode 100644 index 0000000000..ea0b005ffe --- /dev/null +++ b/thirdparty/miniupnpc/codelength.h @@ -0,0 +1,54 @@ +/* $Id: codelength.h,v 1.3 2011/07/30 13:10:05 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas BERNARD + * copyright (c) 2005-2015 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENCE file. */ +#ifndef CODELENGTH_H_INCLUDED +#define CODELENGTH_H_INCLUDED + +/* Encode length by using 7bit per Byte : + * Most significant bit of each byte specifies that the + * following byte is part of the code */ + +/* n : unsigned + * p : unsigned char * + */ +#define DECODELENGTH(n, p) n = 0; \ + do { n = (n << 7) | (*p & 0x7f); } \ + while((*(p++)&0x80) && (n<(1<<25))); + +/* n : unsigned + * READ : function/macro to read one byte (unsigned char) + */ +#define DECODELENGTH_READ(n, READ) \ + n = 0; \ + do { \ + unsigned char c; \ + READ(c); \ + n = (n << 7) | (c & 0x07f); \ + if(!(c&0x80)) break; \ + } while(n<(1<<25)); + +/* n : unsigned + * p : unsigned char * + * p_limit : unsigned char * + */ +#define DECODELENGTH_CHECKLIMIT(n, p, p_limit) \ + n = 0; \ + do { \ + if((p) >= (p_limit)) break; \ + n = (n << 7) | (*(p) & 0x7f); \ + } while((*((p)++)&0x80) && (n<(1<<25))); + + +/* n : unsigned + * p : unsigned char * + */ +#define CODELENGTH(n, p) if(n>=268435456) *(p++) = (n >> 28) | 0x80; \ + if(n>=2097152) *(p++) = (n >> 21) | 0x80; \ + if(n>=16384) *(p++) = (n >> 14) | 0x80; \ + if(n>=128) *(p++) = (n >> 7) | 0x80; \ + *(p++) = n & 0x7f; + +#endif /* CODELENGTH_H_INCLUDED */ diff --git a/thirdparty/miniupnpc/connecthostport.c b/thirdparty/miniupnpc/connecthostport.c new file mode 100644 index 0000000000..ea6e4e5943 --- /dev/null +++ b/thirdparty/miniupnpc/connecthostport.c @@ -0,0 +1,264 @@ +/* $Id: connecthostport.c,v 1.15 2015/10/09 16:26:19 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2010-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +/* use getaddrinfo() or gethostbyname() + * uncomment the following line in order to use gethostbyname() */ +#ifdef NO_GETADDRINFO +#define USE_GETHOSTBYNAME +#endif + +#include <string.h> +#include <stdio.h> +#ifdef _WIN32 +#include <winsock2.h> +#include <ws2tcpip.h> +#include <io.h> +#define MAXHOSTNAMELEN 64 +#define snprintf _snprintf +#define herror +#define socklen_t int +#else /* #ifdef _WIN32 */ +#include <unistd.h> +#include <sys/types.h> +#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT +#include <sys/time.h> +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ +#include <sys/param.h> +#include <sys/select.h> +#include <errno.h> +#define closesocket close +#include <netdb.h> +#include <netinet/in.h> +/* defining MINIUPNPC_IGNORE_EINTR enable the ignore of interruptions + * during the connect() call */ +#define MINIUPNPC_IGNORE_EINTR +#include <sys/socket.h> +#include <sys/select.h> +#endif /* #else _WIN32 */ + +/* definition of PRINT_SOCKET_ERROR */ +#ifdef _WIN32 +#define PRINT_SOCKET_ERROR(x) fprintf(stderr, "Socket error: %s, %d\n", x, WSAGetLastError()); +#else +#define PRINT_SOCKET_ERROR(x) perror(x) +#endif + +#if defined(__amigaos__) || defined(__amigaos4__) +#define herror(A) printf("%s\n", A) +#endif + +#include "connecthostport.h" + +#ifndef MAXHOSTNAMELEN +#define MAXHOSTNAMELEN 64 +#endif + +/* connecthostport() + * return a socket connected (TCP) to the host and port + * or -1 in case of error */ +SOCKET connecthostport(const char * host, unsigned short port, + unsigned int scope_id) +{ + SOCKET s; + int n; +#ifdef USE_GETHOSTBYNAME + struct sockaddr_in dest; + struct hostent *hp; +#else /* #ifdef USE_GETHOSTBYNAME */ + char tmp_host[MAXHOSTNAMELEN+1]; + char port_str[8]; + struct addrinfo *ai, *p; + struct addrinfo hints; +#endif /* #ifdef USE_GETHOSTBYNAME */ +#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT + struct timeval timeout; +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ + +#ifdef USE_GETHOSTBYNAME + hp = gethostbyname(host); + if(hp == NULL) + { + herror(host); + return INVALID_SOCKET; + } + memcpy(&dest.sin_addr, hp->h_addr, sizeof(dest.sin_addr)); + memset(dest.sin_zero, 0, sizeof(dest.sin_zero)); + s = socket(PF_INET, SOCK_STREAM, 0); + if(ISINVALID(s)) + { + PRINT_SOCKET_ERROR("socket"); + return INVALID_SOCKET; + } +#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT + /* setting a 3 seconds timeout for the connect() call */ + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt SO_RCVTIMEO"); + } + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt SO_SNDTIMEO"); + } +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ + dest.sin_family = AF_INET; + dest.sin_port = htons(port); + n = connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr_in)); +#ifdef MINIUPNPC_IGNORE_EINTR + /* EINTR The system call was interrupted by a signal that was caught + * EINPROGRESS The socket is nonblocking and the connection cannot + * be completed immediately. */ + while(n < 0 && (errno == EINTR || errno == EINPROGRESS)) + { + socklen_t len; + fd_set wset; + int err; + FD_ZERO(&wset); + FD_SET(s, &wset); + if((n = select(s + 1, NULL, &wset, NULL, NULL)) == -1 && errno == EINTR) + continue; + /*len = 0;*/ + /*n = getpeername(s, NULL, &len);*/ + len = sizeof(err); + if(getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len) < 0) { + PRINT_SOCKET_ERROR("getsockopt"); + closesocket(s); + return INVALID_SOCKET; + } + if(err != 0) { + errno = err; + n = -1; + } + } +#endif /* #ifdef MINIUPNPC_IGNORE_EINTR */ + if(n<0) + { + PRINT_SOCKET_ERROR("connect"); + closesocket(s); + return INVALID_SOCKET; + } +#else /* #ifdef USE_GETHOSTBYNAME */ + /* use getaddrinfo() instead of gethostbyname() */ + memset(&hints, 0, sizeof(hints)); + /* hints.ai_flags = AI_ADDRCONFIG; */ +#ifdef AI_NUMERICSERV + hints.ai_flags = AI_NUMERICSERV; +#endif + hints.ai_socktype = SOCK_STREAM; + hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */ + /* hints.ai_protocol = IPPROTO_TCP; */ + snprintf(port_str, sizeof(port_str), "%hu", port); + if(host[0] == '[') + { + /* literal ip v6 address */ + int i, j; + for(i = 0, j = 1; host[j] && (host[j] != ']') && i < MAXHOSTNAMELEN; i++, j++) + { + tmp_host[i] = host[j]; + if(0 == memcmp(host+j, "%25", 3)) /* %25 is just url encoding for '%' */ + j+=2; /* skip "25" */ + } + tmp_host[i] = '\0'; + } + else + { + strncpy(tmp_host, host, MAXHOSTNAMELEN); + } + tmp_host[MAXHOSTNAMELEN] = '\0'; + n = getaddrinfo(tmp_host, port_str, &hints, &ai); + if(n != 0) + { +#ifdef _WIN32 + fprintf(stderr, "getaddrinfo() error : %d\n", n); +#else + fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n)); +#endif + return INVALID_SOCKET; + } + s = -1; + for(p = ai; p; p = p->ai_next) + { + s = socket(p->ai_family, p->ai_socktype, p->ai_protocol); + if(ISINVALID(s)) + continue; + if(p->ai_addr->sa_family == AF_INET6 && scope_id > 0) { + struct sockaddr_in6 * addr6 = (struct sockaddr_in6 *)p->ai_addr; + addr6->sin6_scope_id = scope_id; + } +#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT + /* setting a 3 seconds timeout for the connect() call */ + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt"); + } + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt"); + } +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ + n = connect(s, p->ai_addr, p->ai_addrlen); +#ifdef MINIUPNPC_IGNORE_EINTR + /* EINTR The system call was interrupted by a signal that was caught + * EINPROGRESS The socket is nonblocking and the connection cannot + * be completed immediately. */ + while(n < 0 && (errno == EINTR || errno == EINPROGRESS)) + { + socklen_t len; + fd_set wset; + int err; + FD_ZERO(&wset); + FD_SET(s, &wset); + if((n = select(s + 1, NULL, &wset, NULL, NULL)) == -1 && errno == EINTR) + continue; + /*len = 0;*/ + /*n = getpeername(s, NULL, &len);*/ + len = sizeof(err); + if(getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len) < 0) { + PRINT_SOCKET_ERROR("getsockopt"); + closesocket(s); + freeaddrinfo(ai); + return INVALID_SOCKET; + } + if(err != 0) { + errno = err; + n = -1; + } + } +#endif /* #ifdef MINIUPNPC_IGNORE_EINTR */ + if(n < 0) + { + closesocket(s); + continue; + } + else + { + break; + } + } + freeaddrinfo(ai); + if(ISINVALID(s)) + { + PRINT_SOCKET_ERROR("socket"); + return INVALID_SOCKET; + } + if(n < 0) + { + PRINT_SOCKET_ERROR("connect"); + return INVALID_SOCKET; + } +#endif /* #ifdef USE_GETHOSTBYNAME */ + return s; +} + diff --git a/thirdparty/miniupnpc/connecthostport.h b/thirdparty/miniupnpc/connecthostport.h new file mode 100644 index 0000000000..701816b5b6 --- /dev/null +++ b/thirdparty/miniupnpc/connecthostport.h @@ -0,0 +1,20 @@ +/* $Id: connecthostport.h,v 1.2 2012/06/23 22:32:33 nanard Exp $ */ +/* Project: miniupnp + * http://miniupnp.free.fr/ + * Author: Thomas Bernard + * Copyright (c) 2010-2018 Thomas Bernard + * This software is subjects to the conditions detailed + * in the LICENCE file provided within this distribution */ +#ifndef CONNECTHOSTPORT_H_INCLUDED +#define CONNECTHOSTPORT_H_INCLUDED + +#include "miniupnpc_socketdef.h" + +/* connecthostport() + * return a socket connected (TCP) to the host and port + * or INVALID_SOCKET in case of error */ +SOCKET connecthostport(const char * host, unsigned short port, + unsigned int scope_id); + +#endif + diff --git a/thirdparty/miniupnpc/igd_desc_parse.c b/thirdparty/miniupnpc/igd_desc_parse.c new file mode 100644 index 0000000000..d2999ad011 --- /dev/null +++ b/thirdparty/miniupnpc/igd_desc_parse.c @@ -0,0 +1,123 @@ +/* $Id: igd_desc_parse.c,v 1.17 2015/09/15 13:30:04 nanard Exp $ */ +/* Project : miniupnp + * http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005-2015 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +#include "igd_desc_parse.h" +#include <stdio.h> +#include <string.h> + +/* Start element handler : + * update nesting level counter and copy element name */ +void IGDstartelt(void * d, const char * name, int l) +{ + struct IGDdatas * datas = (struct IGDdatas *)d; + if(l >= MINIUPNPC_URL_MAXSIZE) + l = MINIUPNPC_URL_MAXSIZE-1; + memcpy(datas->cureltname, name, l); + datas->cureltname[l] = '\0'; + datas->level++; + if( (l==7) && !memcmp(name, "service", l) ) { + datas->tmp.controlurl[0] = '\0'; + datas->tmp.eventsuburl[0] = '\0'; + datas->tmp.scpdurl[0] = '\0'; + datas->tmp.servicetype[0] = '\0'; + } +} + +#define COMPARE(str, cstr) (0==memcmp(str, cstr, sizeof(cstr) - 1)) + +/* End element handler : + * update nesting level counter and update parser state if + * service element is parsed */ +void IGDendelt(void * d, const char * name, int l) +{ + struct IGDdatas * datas = (struct IGDdatas *)d; + datas->level--; + /*printf("endelt %2d %.*s\n", datas->level, l, name);*/ + if( (l==7) && !memcmp(name, "service", l) ) + { + if(COMPARE(datas->tmp.servicetype, + "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:")) { + memcpy(&datas->CIF, &datas->tmp, sizeof(struct IGDdatas_service)); + } else if(COMPARE(datas->tmp.servicetype, + "urn:schemas-upnp-org:service:WANIPv6FirewallControl:")) { + memcpy(&datas->IPv6FC, &datas->tmp, sizeof(struct IGDdatas_service)); + } else if(COMPARE(datas->tmp.servicetype, + "urn:schemas-upnp-org:service:WANIPConnection:") + || COMPARE(datas->tmp.servicetype, + "urn:schemas-upnp-org:service:WANPPPConnection:") ) { + if(datas->first.servicetype[0] == '\0') { + memcpy(&datas->first, &datas->tmp, sizeof(struct IGDdatas_service)); + } else { + memcpy(&datas->second, &datas->tmp, sizeof(struct IGDdatas_service)); + } + } + } +} + +/* Data handler : + * copy data depending on the current element name and state */ +void IGDdata(void * d, const char * data, int l) +{ + struct IGDdatas * datas = (struct IGDdatas *)d; + char * dstmember = 0; + /*printf("%2d %s : %.*s\n", + datas->level, datas->cureltname, l, data); */ + if( !strcmp(datas->cureltname, "URLBase") ) + dstmember = datas->urlbase; + else if( !strcmp(datas->cureltname, "presentationURL") ) + dstmember = datas->presentationurl; + else if( !strcmp(datas->cureltname, "serviceType") ) + dstmember = datas->tmp.servicetype; + else if( !strcmp(datas->cureltname, "controlURL") ) + dstmember = datas->tmp.controlurl; + else if( !strcmp(datas->cureltname, "eventSubURL") ) + dstmember = datas->tmp.eventsuburl; + else if( !strcmp(datas->cureltname, "SCPDURL") ) + dstmember = datas->tmp.scpdurl; +/* else if( !strcmp(datas->cureltname, "deviceType") ) + dstmember = datas->devicetype_tmp;*/ + if(dstmember) + { + if(l>=MINIUPNPC_URL_MAXSIZE) + l = MINIUPNPC_URL_MAXSIZE-1; + memcpy(dstmember, data, l); + dstmember[l] = '\0'; + } +} + +#ifdef DEBUG +void printIGD(struct IGDdatas * d) +{ + printf("urlbase = '%s'\n", d->urlbase); + printf("WAN Device (Common interface config) :\n"); + /*printf(" deviceType = '%s'\n", d->CIF.devicetype);*/ + printf(" serviceType = '%s'\n", d->CIF.servicetype); + printf(" controlURL = '%s'\n", d->CIF.controlurl); + printf(" eventSubURL = '%s'\n", d->CIF.eventsuburl); + printf(" SCPDURL = '%s'\n", d->CIF.scpdurl); + printf("primary WAN Connection Device (IP or PPP Connection):\n"); + /*printf(" deviceType = '%s'\n", d->first.devicetype);*/ + printf(" servicetype = '%s'\n", d->first.servicetype); + printf(" controlURL = '%s'\n", d->first.controlurl); + printf(" eventSubURL = '%s'\n", d->first.eventsuburl); + printf(" SCPDURL = '%s'\n", d->first.scpdurl); + printf("secondary WAN Connection Device (IP or PPP Connection):\n"); + /*printf(" deviceType = '%s'\n", d->second.devicetype);*/ + printf(" servicetype = '%s'\n", d->second.servicetype); + printf(" controlURL = '%s'\n", d->second.controlurl); + printf(" eventSubURL = '%s'\n", d->second.eventsuburl); + printf(" SCPDURL = '%s'\n", d->second.scpdurl); + printf("WAN IPv6 Firewall Control :\n"); + /*printf(" deviceType = '%s'\n", d->IPv6FC.devicetype);*/ + printf(" servicetype = '%s'\n", d->IPv6FC.servicetype); + printf(" controlURL = '%s'\n", d->IPv6FC.controlurl); + printf(" eventSubURL = '%s'\n", d->IPv6FC.eventsuburl); + printf(" SCPDURL = '%s'\n", d->IPv6FC.scpdurl); +} +#endif /* DEBUG */ + diff --git a/thirdparty/miniupnpc/igd_desc_parse.h b/thirdparty/miniupnpc/igd_desc_parse.h new file mode 100644 index 0000000000..0de546b697 --- /dev/null +++ b/thirdparty/miniupnpc/igd_desc_parse.h @@ -0,0 +1,49 @@ +/* $Id: igd_desc_parse.h,v 1.12 2014/11/17 17:19:13 nanard Exp $ */ +/* Project : miniupnp + * http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005-2014 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#ifndef IGD_DESC_PARSE_H_INCLUDED +#define IGD_DESC_PARSE_H_INCLUDED + +/* Structure to store the result of the parsing of UPnP + * descriptions of Internet Gateway Devices */ +#define MINIUPNPC_URL_MAXSIZE (128) +struct IGDdatas_service { + char controlurl[MINIUPNPC_URL_MAXSIZE]; + char eventsuburl[MINIUPNPC_URL_MAXSIZE]; + char scpdurl[MINIUPNPC_URL_MAXSIZE]; + char servicetype[MINIUPNPC_URL_MAXSIZE]; + /*char devicetype[MINIUPNPC_URL_MAXSIZE];*/ +}; + +struct IGDdatas { + char cureltname[MINIUPNPC_URL_MAXSIZE]; + char urlbase[MINIUPNPC_URL_MAXSIZE]; + char presentationurl[MINIUPNPC_URL_MAXSIZE]; + int level; + /*int state;*/ + /* "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */ + struct IGDdatas_service CIF; + /* "urn:schemas-upnp-org:service:WANIPConnection:1" + * "urn:schemas-upnp-org:service:WANPPPConnection:1" */ + struct IGDdatas_service first; + /* if both WANIPConnection and WANPPPConnection are present */ + struct IGDdatas_service second; + /* "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1" */ + struct IGDdatas_service IPv6FC; + /* tmp */ + struct IGDdatas_service tmp; +}; + +void IGDstartelt(void *, const char *, int); +void IGDendelt(void *, const char *, int); +void IGDdata(void *, const char *, int); +#ifdef DEBUG +void printIGD(struct IGDdatas *); +#endif /* DEBUG */ + +#endif /* IGD_DESC_PARSE_H_INCLUDED */ diff --git a/thirdparty/miniupnpc/listdevices.c b/thirdparty/miniupnpc/listdevices.c new file mode 100644 index 0000000000..bd9ba57efc --- /dev/null +++ b/thirdparty/miniupnpc/listdevices.c @@ -0,0 +1,197 @@ +/* $Id: listdevices.c,v 1.6 2015/07/23 20:40:08 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2013-2015 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#ifdef _WIN32 +#include <winsock2.h> +#endif /* _WIN32 */ +#include "miniupnpc.h" + +struct upnp_dev_list { + struct upnp_dev_list * next; + char * descURL; + struct UPNPDev * * array; + size_t count; + size_t allocated_count; +}; + +#define ADD_DEVICE_COUNT_STEP 16 + +void add_device(struct upnp_dev_list * * list_head, struct UPNPDev * dev) +{ + struct upnp_dev_list * elt; + size_t i; + + if(dev == NULL) + return; + for(elt = *list_head; elt != NULL; elt = elt->next) { + if(strcmp(elt->descURL, dev->descURL) == 0) { + for(i = 0; i < elt->count; i++) { + if (strcmp(elt->array[i]->st, dev->st) == 0 && strcmp(elt->array[i]->usn, dev->usn) == 0) { + return; /* already found */ + } + } + if(elt->count >= elt->allocated_count) { + struct UPNPDev * * tmp; + elt->allocated_count += ADD_DEVICE_COUNT_STEP; + tmp = realloc(elt->array, elt->allocated_count * sizeof(struct UPNPDev *)); + if(tmp == NULL) { + fprintf(stderr, "Failed to realloc(%p, %lu)\n", elt->array, (unsigned long)(elt->allocated_count * sizeof(struct UPNPDev *))); + return; + } + elt->array = tmp; + } + elt->array[elt->count++] = dev; + return; + } + } + elt = malloc(sizeof(struct upnp_dev_list)); + if(elt == NULL) { + fprintf(stderr, "Failed to malloc(%lu)\n", (unsigned long)sizeof(struct upnp_dev_list)); + return; + } + elt->next = *list_head; + elt->descURL = strdup(dev->descURL); + if(elt->descURL == NULL) { + fprintf(stderr, "Failed to strdup(%s)\n", dev->descURL); + free(elt); + return; + } + elt->allocated_count = ADD_DEVICE_COUNT_STEP; + elt->array = malloc(ADD_DEVICE_COUNT_STEP * sizeof(struct UPNPDev *)); + if(elt->array == NULL) { + fprintf(stderr, "Failed to malloc(%lu)\n", (unsigned long)(ADD_DEVICE_COUNT_STEP * sizeof(struct UPNPDev *))); + free(elt->descURL); + free(elt); + return; + } + elt->array[0] = dev; + elt->count = 1; + *list_head = elt; +} + +void free_device(struct upnp_dev_list * elt) +{ + free(elt->descURL); + free(elt->array); + free(elt); +} + +int main(int argc, char * * argv) +{ + const char * searched_device = NULL; + const char * * searched_devices = NULL; + const char * multicastif = 0; + const char * minissdpdpath = 0; + int ipv6 = 0; + unsigned char ttl = 2; + int error = 0; + struct UPNPDev * devlist = 0; + struct UPNPDev * dev; + struct upnp_dev_list * sorted_list = NULL; + struct upnp_dev_list * dev_array; + int i; + +#ifdef _WIN32 + WSADATA wsaData; + int nResult = WSAStartup(MAKEWORD(2,2), &wsaData); + if(nResult != NO_ERROR) + { + fprintf(stderr, "WSAStartup() failed.\n"); + return -1; + } +#endif + + for(i = 1; i < argc; i++) { + if(strcmp(argv[i], "-6") == 0) + ipv6 = 1; + else if(strcmp(argv[i], "-d") == 0) { + if(++i >= argc) { + fprintf(stderr, "%s option needs one argument\n", "-d"); + return 1; + } + searched_device = argv[i]; + } else if(strcmp(argv[i], "-t") == 0) { + if(++i >= argc) { + fprintf(stderr, "%s option needs one argument\n", "-t"); + return 1; + } + ttl = (unsigned char)atoi(argv[i]); + } else if(strcmp(argv[i], "-l") == 0) { + if(++i >= argc) { + fprintf(stderr, "-l option needs at least one argument\n"); + return 1; + } + searched_devices = (const char * *)(argv + i); + break; + } else if(strcmp(argv[i], "-m") == 0) { + if(++i >= argc) { + fprintf(stderr, "-m option needs one argument\n"); + return 1; + } + multicastif = argv[i]; + } else { + printf("usage : %s [options] [-l <device1> <device2> ...]\n", argv[0]); + printf("options :\n"); + printf(" -6 : use IPv6\n"); + printf(" -m address/ifname : network interface to use for multicast\n"); + printf(" -d <device string> : search only for this type of device\n"); + printf(" -l <device1> <device2> ... : search only for theses types of device\n"); + printf(" -t ttl : set multicast TTL. Default value is 2.\n"); + printf(" -h : this help\n"); + return 1; + } + } + + if(searched_device) { + printf("searching UPnP device type %s\n", searched_device); + devlist = upnpDiscoverDevice(searched_device, + 2000, multicastif, minissdpdpath, + 0/*localport*/, ipv6, ttl, &error); + } else if(searched_devices) { + printf("searching UPnP device types :\n"); + for(i = 0; searched_devices[i]; i++) + printf("\t%s\n", searched_devices[i]); + devlist = upnpDiscoverDevices(searched_devices, + 2000, multicastif, minissdpdpath, + 0/*localport*/, ipv6, ttl, &error, 1); + } else { + printf("searching all UPnP devices\n"); + devlist = upnpDiscoverAll(2000, multicastif, minissdpdpath, + 0/*localport*/, ipv6, ttl, &error); + } + if(devlist) { + for(dev = devlist, i = 1; dev != NULL; dev = dev->pNext, i++) { + printf("%3d: %-48s\n", i, dev->st); + printf(" %s\n", dev->descURL); + printf(" %s\n", dev->usn); + add_device(&sorted_list, dev); + } + putchar('\n'); + for (dev_array = sorted_list; dev_array != NULL ; dev_array = dev_array->next) { + printf("%s :\n", dev_array->descURL); + for(i = 0; (unsigned)i < dev_array->count; i++) { + printf("%2d: %s\n", i+1, dev_array->array[i]->st); + printf(" %s\n", dev_array->array[i]->usn); + } + putchar('\n'); + } + freeUPNPDevlist(devlist); + while(sorted_list != NULL) { + dev_array = sorted_list; + sorted_list = sorted_list->next; + free_device(dev_array); + } + } else { + printf("no device found.\n"); + } + + return 0; +} + diff --git a/thirdparty/miniupnpc/minisoap.c b/thirdparty/miniupnpc/minisoap.c new file mode 100644 index 0000000000..520c9302e8 --- /dev/null +++ b/thirdparty/miniupnpc/minisoap.c @@ -0,0 +1,124 @@ +/* $Id: minisoap.c,v 1.25 2017/04/21 10:03:24 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * + * Minimal SOAP implementation for UPnP protocol. + */ +#include <stdio.h> +#include <string.h> +#ifdef _WIN32 +#include <io.h> +#include <winsock2.h> +#define snprintf _snprintf +#else +#include <unistd.h> +#include <sys/types.h> +#include <sys/socket.h> +#endif +#include "minisoap.h" +#include "miniupnpcstrings.h" + +/* only for malloc */ +#include <stdlib.h> + +#ifdef _WIN32 +#define PRINT_SOCKET_ERROR(x) fprintf(stderr, "Socket error: %s, %d\n", x, WSAGetLastError()); +#else +#define PRINT_SOCKET_ERROR(x) perror(x) +#endif + +/* httpWrite sends the headers and the body to the socket + * and returns the number of bytes sent */ +static int +httpWrite(SOCKET fd, const char * body, int bodysize, + const char * headers, int headerssize) +{ + int n = 0; + /*n = write(fd, headers, headerssize);*/ + /*if(bodysize>0) + n += write(fd, body, bodysize);*/ + /* Note : my old linksys router only took into account + * soap request that are sent into only one packet */ + char * p; + /* TODO: AVOID MALLOC, we could use writev() for that */ + p = malloc(headerssize+bodysize); + if(!p) + return -1; + memcpy(p, headers, headerssize); + memcpy(p+headerssize, body, bodysize); + /*n = write(fd, p, headerssize+bodysize);*/ + n = send(fd, p, headerssize+bodysize, 0); + if(n<0) { + PRINT_SOCKET_ERROR("send"); + } + /* disable send on the socket */ + /* draytek routers don't seem to like that... */ +#if 0 +#ifdef _WIN32 + if(shutdown(fd, SD_SEND)<0) { +#else + if(shutdown(fd, SHUT_WR)<0) { /*SD_SEND*/ +#endif + PRINT_SOCKET_ERROR("shutdown"); + } +#endif + free(p); + return n; +} + +/* self explanatory */ +int soapPostSubmit(SOCKET fd, + const char * url, + const char * host, + unsigned short port, + const char * action, + const char * body, + const char * httpversion) +{ + int bodysize; + char headerbuf[512]; + int headerssize; + char portstr[8]; + bodysize = (int)strlen(body); + /* We are not using keep-alive HTTP connections. + * HTTP/1.1 needs the header Connection: close to do that. + * This is the default with HTTP/1.0 + * Using HTTP/1.1 means we need to support chunked transfer-encoding : + * When using HTTP/1.1, the router "BiPAC 7404VNOX" always use chunked + * transfer encoding. */ + /* Connection: Close is normally there only in HTTP/1.1 but who knows */ + portstr[0] = '\0'; + if(port != 80) + snprintf(portstr, sizeof(portstr), ":%hu", port); + headerssize = snprintf(headerbuf, sizeof(headerbuf), + "POST %s HTTP/%s\r\n" + "Host: %s%s\r\n" + "User-Agent: " OS_STRING ", " UPNP_VERSION_STRING ", MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n" + "Content-Length: %d\r\n" + "Content-Type: text/xml\r\n" + "SOAPAction: \"%s\"\r\n" + "Connection: Close\r\n" + "Cache-Control: no-cache\r\n" /* ??? */ + "Pragma: no-cache\r\n" + "\r\n", + url, httpversion, host, portstr, bodysize, action); + if ((unsigned int)headerssize >= sizeof(headerbuf)) + return -1; +#ifdef DEBUG + /*printf("SOAP request : headersize=%d bodysize=%d\n", + headerssize, bodysize); + */ + printf("SOAP request : POST %s HTTP/%s - Host: %s%s\n", + url, httpversion, host, portstr); + printf("SOAPAction: \"%s\" - Content-Length: %d\n", action, bodysize); + printf("Headers :\n%s", headerbuf); + printf("Body :\n%s\n", body); +#endif + return httpWrite(fd, body, bodysize, headerbuf, headerssize); +} + + diff --git a/thirdparty/miniupnpc/minisoap.h b/thirdparty/miniupnpc/minisoap.h new file mode 100644 index 0000000000..d6a45d03ba --- /dev/null +++ b/thirdparty/miniupnpc/minisoap.h @@ -0,0 +1,17 @@ +/* $Id: minisoap.h,v 1.4 2010/04/12 20:39:41 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ +#ifndef MINISOAP_H_INCLUDED +#define MINISOAP_H_INCLUDED + +#include "miniupnpc_socketdef.h" + +/*int httpWrite(int, const char *, int, const char *);*/ +int soapPostSubmit(SOCKET, const char *, const char *, unsigned short, + const char *, const char *, const char *); + +#endif + diff --git a/thirdparty/miniupnpc/minissdpc.c b/thirdparty/miniupnpc/minissdpc.c new file mode 100644 index 0000000000..d76b242ad0 --- /dev/null +++ b/thirdparty/miniupnpc/minissdpc.c @@ -0,0 +1,888 @@ +/* $Id: minissdpc.c,v 1.32 2016/10/07 09:04:36 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project : miniupnp + * Web : http://miniupnp.free.fr/ + * Author : Thomas BERNARD + * copyright (c) 2005-2018 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENCE file. */ +/*#include <syslog.h>*/ +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <sys/types.h> +#if defined (__NetBSD__) +#include <net/if.h> +#endif +#if defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__) +#ifdef _WIN32 +#include <winsock2.h> +#include <ws2tcpip.h> +#include <io.h> +#include <iphlpapi.h> +#define snprintf _snprintf +#if !defined(_MSC_VER) +#include <stdint.h> +#else /* !defined(_MSC_VER) */ +typedef unsigned short uint16_t; +#endif /* !defined(_MSC_VER) */ +#ifndef strncasecmp +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define strncasecmp _memicmp +#else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#define strncasecmp memicmp +#endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#endif /* #ifndef strncasecmp */ +#endif /* _WIN32 */ +#if defined(__amigaos__) || defined(__amigaos4__) +#include <sys/socket.h> +#endif /* defined(__amigaos__) || defined(__amigaos4__) */ +#if defined(__amigaos__) +#define uint16_t unsigned short +#endif /* defined(__amigaos__) */ +/* Hack */ +#define UNIX_PATH_LEN 108 +struct sockaddr_un { + uint16_t sun_family; + char sun_path[UNIX_PATH_LEN]; +}; +#else /* defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__) */ +#include <strings.h> +#include <unistd.h> +#include <sys/socket.h> +#include <sys/param.h> +#include <sys/time.h> +#include <sys/un.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <net/if.h> +#define closesocket close +#endif + +#include "miniupnpc_socketdef.h" + +#if !defined(__DragonFly__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) && !defined(__sun) && !defined(__GNU__) && !defined(__FreeBSD_kernel__) +#define HAS_IP_MREQN +#endif + +#if !defined(HAS_IP_MREQN) && !defined(_WIN32) +#include <sys/ioctl.h> +#if defined(__sun) +#include <sys/sockio.h> +#endif +#endif + +#if defined(HAS_IP_MREQN) && defined(NEED_STRUCT_IP_MREQN) +/* Several versions of glibc don't define this structure, + * define it here and compile with CFLAGS NEED_STRUCT_IP_MREQN */ +struct ip_mreqn +{ + struct in_addr imr_multiaddr; /* IP multicast address of group */ + struct in_addr imr_address; /* local IP address of interface */ + int imr_ifindex; /* Interface index */ +}; +#endif + +#if defined(__amigaos__) || defined(__amigaos4__) +/* Amiga OS specific stuff */ +#define TIMEVAL struct timeval +#endif + +#include "minissdpc.h" +#include "miniupnpc.h" +#include "receivedata.h" + +#if !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__)) + +#include "codelength.h" + +struct UPNPDev * +getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath, int * error) +{ + struct UPNPDev * devlist = NULL; + int s; + int res; + + s = connectToMiniSSDPD(socketpath); + if (s < 0) { + if (error) + *error = s; + return NULL; + } + res = requestDevicesFromMiniSSDPD(s, devtype); + if (res < 0) { + if (error) + *error = res; + } else { + devlist = receiveDevicesFromMiniSSDPD(s, error); + } + disconnectFromMiniSSDPD(s); + return devlist; +} + +/* macros used to read from unix socket */ +#define READ_BYTE_BUFFER(c) \ + if((int)bufferindex >= n) { \ + n = read(s, buffer, sizeof(buffer)); \ + if(n<=0) break; \ + bufferindex = 0; \ + } \ + c = buffer[bufferindex++]; + +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif /* MIN */ + +#define READ_COPY_BUFFER(dst, len) \ + for(l = len, p = (unsigned char *)dst; l > 0; ) { \ + unsigned int lcopy; \ + if((int)bufferindex >= n) { \ + n = read(s, buffer, sizeof(buffer)); \ + if(n<=0) break; \ + bufferindex = 0; \ + } \ + lcopy = MIN(l, (n - bufferindex)); \ + memcpy(p, buffer + bufferindex, lcopy); \ + l -= lcopy; \ + p += lcopy; \ + bufferindex += lcopy; \ + } + +#define READ_DISCARD_BUFFER(len) \ + for(l = len; l > 0; ) { \ + unsigned int lcopy; \ + if(bufferindex >= n) { \ + n = read(s, buffer, sizeof(buffer)); \ + if(n<=0) break; \ + bufferindex = 0; \ + } \ + lcopy = MIN(l, (n - bufferindex)); \ + l -= lcopy; \ + bufferindex += lcopy; \ + } + +int +connectToMiniSSDPD(const char * socketpath) +{ + int s; + struct sockaddr_un addr; +#if defined(MINIUPNPC_SET_SOCKET_TIMEOUT) && !defined(__sun) + struct timeval timeout; +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ + + s = socket(AF_UNIX, SOCK_STREAM, 0); + if(s < 0) + { + /*syslog(LOG_ERR, "socket(unix): %m");*/ + perror("socket(unix)"); + return MINISSDPC_SOCKET_ERROR; + } +#if defined(MINIUPNPC_SET_SOCKET_TIMEOUT) && !defined(__sun) + /* setting a 3 seconds timeout */ + /* not supported for AF_UNIX sockets under Solaris */ + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + perror("setsockopt SO_RCVTIMEO unix"); + } + timeout.tv_sec = 3; + timeout.tv_usec = 0; + if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0) + { + perror("setsockopt SO_SNDTIMEO unix"); + } +#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */ + if(!socketpath) + socketpath = "/var/run/minissdpd.sock"; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, socketpath, sizeof(addr.sun_path)); + /* TODO : check if we need to handle the EINTR */ + if(connect(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0) + { + /*syslog(LOG_WARNING, "connect(\"%s\"): %m", socketpath);*/ + close(s); + return MINISSDPC_SOCKET_ERROR; + } + return s; +} + +int +disconnectFromMiniSSDPD(int s) +{ + if (close(s) < 0) + return MINISSDPC_SOCKET_ERROR; + return MINISSDPC_SUCCESS; +} + +int +requestDevicesFromMiniSSDPD(int s, const char * devtype) +{ + unsigned char buffer[256]; + unsigned char * p; + unsigned int stsize, l; + + stsize = strlen(devtype); + if(stsize == 8 && 0 == memcmp(devtype, "ssdp:all", 8)) + { + buffer[0] = 3; /* request type 3 : everything */ + } + else + { + buffer[0] = 1; /* request type 1 : request devices/services by type */ + } + p = buffer + 1; + l = stsize; CODELENGTH(l, p); + if(p + stsize > buffer + sizeof(buffer)) + { + /* devtype is too long ! */ +#ifdef DEBUG + fprintf(stderr, "devtype is too long ! stsize=%u sizeof(buffer)=%u\n", + stsize, (unsigned)sizeof(buffer)); +#endif /* DEBUG */ + return MINISSDPC_INVALID_INPUT; + } + memcpy(p, devtype, stsize); + p += stsize; + if(write(s, buffer, p - buffer) < 0) + { + /*syslog(LOG_ERR, "write(): %m");*/ + perror("minissdpc.c: write()"); + return MINISSDPC_SOCKET_ERROR; + } + return MINISSDPC_SUCCESS; +} + +struct UPNPDev * +receiveDevicesFromMiniSSDPD(int s, int * error) +{ + struct UPNPDev * tmp; + struct UPNPDev * devlist = NULL; + unsigned char buffer[256]; + ssize_t n; + unsigned char * p; + unsigned char * url; + unsigned char * st; + unsigned int bufferindex; + unsigned int i, ndev; + unsigned int urlsize, stsize, usnsize, l; + + n = read(s, buffer, sizeof(buffer)); + if(n<=0) + { + perror("minissdpc.c: read()"); + if (error) + *error = MINISSDPC_SOCKET_ERROR; + return NULL; + } + ndev = buffer[0]; + bufferindex = 1; + for(i = 0; i < ndev; i++) + { + DECODELENGTH_READ(urlsize, READ_BYTE_BUFFER); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + return devlist; + } +#ifdef DEBUG + printf(" urlsize=%u", urlsize); +#endif /* DEBUG */ + url = malloc(urlsize); + if(url == NULL) { + if (error) + *error = MINISSDPC_MEMORY_ERROR; + return devlist; + } + READ_COPY_BUFFER(url, urlsize); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + goto free_url_and_return; + } + DECODELENGTH_READ(stsize, READ_BYTE_BUFFER); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + goto free_url_and_return; + } +#ifdef DEBUG + printf(" stsize=%u", stsize); +#endif /* DEBUG */ + st = malloc(stsize); + if (st == NULL) { + if (error) + *error = MINISSDPC_MEMORY_ERROR; + goto free_url_and_return; + } + READ_COPY_BUFFER(st, stsize); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + goto free_url_and_st_and_return; + } + DECODELENGTH_READ(usnsize, READ_BYTE_BUFFER); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + goto free_url_and_st_and_return; + } +#ifdef DEBUG + printf(" usnsize=%u\n", usnsize); +#endif /* DEBUG */ + tmp = (struct UPNPDev *)malloc(sizeof(struct UPNPDev)+urlsize+stsize+usnsize); + if(tmp == NULL) { + if (error) + *error = MINISSDPC_MEMORY_ERROR; + goto free_url_and_st_and_return; + } + tmp->pNext = devlist; + tmp->descURL = tmp->buffer; + tmp->st = tmp->buffer + 1 + urlsize; + memcpy(tmp->buffer, url, urlsize); + tmp->buffer[urlsize] = '\0'; + memcpy(tmp->st, st, stsize); + tmp->buffer[urlsize+1+stsize] = '\0'; + free(url); + free(st); + url = NULL; + st = NULL; + tmp->usn = tmp->buffer + 1 + urlsize + 1 + stsize; + READ_COPY_BUFFER(tmp->usn, usnsize); + if(n<=0) { + if (error) + *error = MINISSDPC_INVALID_SERVER_REPLY; + goto free_tmp_and_return; + } + tmp->buffer[urlsize+1+stsize+1+usnsize] = '\0'; + tmp->scope_id = 0; /* default value. scope_id is not available with MiniSSDPd */ + devlist = tmp; + } + if (error) + *error = MINISSDPC_SUCCESS; + return devlist; + +free_url_and_st_and_return: + free(st); +free_url_and_return: + free(url); + return devlist; + +free_tmp_and_return: + free(tmp); + return devlist; +} + +#endif /* !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__)) */ + +/* parseMSEARCHReply() + * the last 4 arguments are filled during the parsing : + * - location/locationsize : "location:" field of the SSDP reply packet + * - st/stsize : "st:" field of the SSDP reply packet. + * The strings are NOT null terminated */ +static void +parseMSEARCHReply(const char * reply, int size, + const char * * location, int * locationsize, + const char * * st, int * stsize, + const char * * usn, int * usnsize) +{ + int a, b, i; + i = 0; + a = i; /* start of the line */ + b = 0; /* end of the "header" (position of the colon) */ + while(i<size) + { + switch(reply[i]) + { + case ':': + if(b==0) + { + b = i; /* end of the "header" */ + /*for(j=a; j<b; j++) + { + putchar(reply[j]); + } + */ + } + break; + case '\x0a': + case '\x0d': + if(b!=0) + { + /*for(j=b+1; j<i; j++) + { + putchar(reply[j]); + } + putchar('\n');*/ + /* skip the colon and white spaces */ + do { b++; } while(reply[b]==' '); + if(0==strncasecmp(reply+a, "location", 8)) + { + *location = reply+b; + *locationsize = i-b; + } + else if(0==strncasecmp(reply+a, "st", 2)) + { + *st = reply+b; + *stsize = i-b; + } + else if(0==strncasecmp(reply+a, "usn", 3)) + { + *usn = reply+b; + *usnsize = i-b; + } + b = 0; + } + a = i+1; + break; + default: + break; + } + i++; + } +} + +/* port upnp discover : SSDP protocol */ +#define SSDP_PORT 1900 +#define XSTR(s) STR(s) +#define STR(s) #s +#define UPNP_MCAST_ADDR "239.255.255.250" +/* for IPv6 */ +#define UPNP_MCAST_LL_ADDR "FF02::C" /* link-local */ +#define UPNP_MCAST_SL_ADDR "FF05::C" /* site-local */ + +/* direct discovery if minissdpd responses are not sufficient */ +/* ssdpDiscoverDevices() : + * return a chained list of all devices found or NULL if + * no devices was found. + * It is up to the caller to free the chained list + * delay is in millisecond (poll). + * UDA v1.1 says : + * The TTL for the IP packet SHOULD default to 2 and + * SHOULD be configurable. */ +struct UPNPDev * +ssdpDiscoverDevices(const char * const deviceTypes[], + int delay, const char * multicastif, + int localport, + int ipv6, unsigned char ttl, + int * error, + int searchalltypes) +{ + struct UPNPDev * tmp; + struct UPNPDev * devlist = 0; + unsigned int scope_id = 0; + int opt = 1; + static const char MSearchMsgFmt[] = + "M-SEARCH * HTTP/1.1\r\n" + "HOST: %s:" XSTR(SSDP_PORT) "\r\n" + "ST: %s\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: %u\r\n" + "\r\n"; + int deviceIndex; + char bufr[1536]; /* reception and emission buffer */ + SOCKET sudp; + int n; + struct sockaddr_storage sockudp_r; + unsigned int mx; +#ifdef NO_GETADDRINFO + struct sockaddr_storage sockudp_w; +#else + int rv; + struct addrinfo hints, *servinfo, *p; +#endif +#ifdef _WIN32 + MIB_IPFORWARDROW ip_forward; + unsigned long _ttl = (unsigned long)ttl; +#endif + int linklocal = 1; + int sentok; + + if(error) + *error = MINISSDPC_UNKNOWN_ERROR; + + if(localport==UPNP_LOCAL_PORT_SAME) + localport = SSDP_PORT; + +#ifdef _WIN32 + sudp = socket(ipv6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP); +#else + sudp = socket(ipv6 ? PF_INET6 : PF_INET, SOCK_DGRAM, 0); +#endif + if(ISINVALID(sudp)) + { + if(error) + *error = MINISSDPC_SOCKET_ERROR; + PRINT_SOCKET_ERROR("socket"); + return NULL; + } + /* reception */ + memset(&sockudp_r, 0, sizeof(struct sockaddr_storage)); + if(ipv6) { + struct sockaddr_in6 * p = (struct sockaddr_in6 *)&sockudp_r; + p->sin6_family = AF_INET6; + if(localport > 0 && localport < 65536) + p->sin6_port = htons((unsigned short)localport); + p->sin6_addr = in6addr_any; /* in6addr_any is not available with MinGW32 3.4.2 */ + } else { + struct sockaddr_in * p = (struct sockaddr_in *)&sockudp_r; + p->sin_family = AF_INET; + if(localport > 0 && localport < 65536) + p->sin_port = htons((unsigned short)localport); + p->sin_addr.s_addr = INADDR_ANY; + } +#ifdef _WIN32 +/* This code could help us to use the right Network interface for + * SSDP multicast traffic */ +/* Get IP associated with the index given in the ip_forward struct + * in order to give this ip to setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF) */ + if(!ipv6 + && (GetBestRoute(inet_addr("223.255.255.255"), 0, &ip_forward) == NO_ERROR)) { + DWORD dwRetVal = 0; + PMIB_IPADDRTABLE pIPAddrTable; + DWORD dwSize = 0; +#ifdef DEBUG + IN_ADDR IPAddr; +#endif + int i; +#ifdef DEBUG + printf("ifIndex=%lu nextHop=%lx \n", ip_forward.dwForwardIfIndex, ip_forward.dwForwardNextHop); +#endif + pIPAddrTable = (MIB_IPADDRTABLE *) malloc(sizeof (MIB_IPADDRTABLE)); + if(pIPAddrTable) { + if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) { + free(pIPAddrTable); + pIPAddrTable = (MIB_IPADDRTABLE *) malloc(dwSize); + } + } + if(pIPAddrTable) { + dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 ); + if (dwRetVal == NO_ERROR) { +#ifdef DEBUG + printf("\tNum Entries: %ld\n", pIPAddrTable->dwNumEntries); +#endif + for (i=0; i < (int) pIPAddrTable->dwNumEntries; i++) { +#ifdef DEBUG + printf("\n\tInterface Index[%d]:\t%ld\n", i, pIPAddrTable->table[i].dwIndex); + IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr; + printf("\tIP Address[%d]: \t%s\n", i, inet_ntoa(IPAddr) ); + IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask; + printf("\tSubnet Mask[%d]: \t%s\n", i, inet_ntoa(IPAddr) ); + IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwBCastAddr; + printf("\tBroadCast[%d]: \t%s (%ld)\n", i, inet_ntoa(IPAddr), pIPAddrTable->table[i].dwBCastAddr); + printf("\tReassembly size[%d]:\t%ld\n", i, pIPAddrTable->table[i].dwReasmSize); + printf("\tType and State[%d]:", i); + printf("\n"); +#endif + if (pIPAddrTable->table[i].dwIndex == ip_forward.dwForwardIfIndex) { + /* Set the address of this interface to be used */ + struct in_addr mc_if; + memset(&mc_if, 0, sizeof(mc_if)); + mc_if.s_addr = pIPAddrTable->table[i].dwAddr; + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&mc_if, sizeof(mc_if)) < 0) { + PRINT_SOCKET_ERROR("setsockopt"); + } + ((struct sockaddr_in *)&sockudp_r)->sin_addr.s_addr = pIPAddrTable->table[i].dwAddr; +#ifndef DEBUG + break; +#endif + } + } + } + free(pIPAddrTable); + pIPAddrTable = NULL; + } + } +#endif /* _WIN32 */ + +#ifdef _WIN32 + if (setsockopt(sudp, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof (opt)) < 0) +#else + if (setsockopt(sudp, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt)) < 0) +#endif + { + if(error) + *error = MINISSDPC_SOCKET_ERROR; + PRINT_SOCKET_ERROR("setsockopt(SO_REUSEADDR,...)"); + return NULL; + } + + if(ipv6) { +#ifdef _WIN32 + DWORD mcastHops = ttl; + if(setsockopt(sudp, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char *)&mcastHops, sizeof(mcastHops)) < 0) +#else /* _WIN32 */ + int mcastHops = ttl; + if(setsockopt(sudp, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastHops, sizeof(mcastHops)) < 0) +#endif /* _WIN32 */ + { + PRINT_SOCKET_ERROR("setsockopt(IPV6_MULTICAST_HOPS,...)"); + } + } else { +#ifdef _WIN32 + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&_ttl, sizeof(_ttl)) < 0) +#else /* _WIN32 */ + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) < 0) +#endif /* _WIN32 */ + { + /* not a fatal error */ + PRINT_SOCKET_ERROR("setsockopt(IP_MULTICAST_TTL,...)"); + } + } + + if(multicastif) + { + if(ipv6) { +#if !defined(_WIN32) + /* according to MSDN, if_nametoindex() is supported since + * MS Windows Vista and MS Windows Server 2008. + * http://msdn.microsoft.com/en-us/library/bb408409%28v=vs.85%29.aspx */ + unsigned int ifindex = if_nametoindex(multicastif); /* eth0, etc. */ + if(setsockopt(sudp, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifindex, sizeof(ifindex)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt IPV6_MULTICAST_IF"); + } +#else +#ifdef DEBUG + printf("Setting of multicast interface not supported in IPv6 under Windows.\n"); +#endif +#endif + } else { + struct in_addr mc_if; + mc_if.s_addr = inet_addr(multicastif); /* ex: 192.168.x.x */ + if(mc_if.s_addr != INADDR_NONE) + { + ((struct sockaddr_in *)&sockudp_r)->sin_addr.s_addr = mc_if.s_addr; + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&mc_if, sizeof(mc_if)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt IP_MULTICAST_IF"); + } + } else { +#ifdef HAS_IP_MREQN + /* was not an ip address, try with an interface name */ + struct ip_mreqn reqn; /* only defined with -D_BSD_SOURCE or -D_GNU_SOURCE */ + memset(&reqn, 0, sizeof(struct ip_mreqn)); + reqn.imr_ifindex = if_nametoindex(multicastif); + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&reqn, sizeof(reqn)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt IP_MULTICAST_IF"); + } +#elif !defined(_WIN32) + struct ifreq ifr; + int ifrlen = sizeof(ifr); + strncpy(ifr.ifr_name, multicastif, IFNAMSIZ); + ifr.ifr_name[IFNAMSIZ-1] = '\0'; + if(ioctl(sudp, SIOCGIFADDR, &ifr, &ifrlen) < 0) + { + PRINT_SOCKET_ERROR("ioctl(...SIOCGIFADDR...)"); + } + mc_if.s_addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr; + if(setsockopt(sudp, IPPROTO_IP, IP_MULTICAST_IF, (const char *)&mc_if, sizeof(mc_if)) < 0) + { + PRINT_SOCKET_ERROR("setsockopt IP_MULTICAST_IF"); + } +#else /* _WIN32 */ +#ifdef DEBUG + printf("Setting of multicast interface not supported with interface name.\n"); +#endif +#endif /* #ifdef HAS_IP_MREQN / !defined(_WIN32) */ + } + } + } + + /* Before sending the packed, we first "bind" in order to be able + * to receive the response */ + if (bind(sudp, (const struct sockaddr *)&sockudp_r, + ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) != 0) + { + if(error) + *error = MINISSDPC_SOCKET_ERROR; + PRINT_SOCKET_ERROR("bind"); + closesocket(sudp); + return NULL; + } + + if(error) + *error = MINISSDPC_SUCCESS; + /* Calculating maximum response time in seconds */ + mx = ((unsigned int)delay) / 1000u; + if(mx == 0) { + mx = 1; + delay = 1000; + } + /* receiving SSDP response packet */ + for(deviceIndex = 0; deviceTypes[deviceIndex]; deviceIndex++) { + sentok = 0; + /* sending the SSDP M-SEARCH packet */ + n = snprintf(bufr, sizeof(bufr), + MSearchMsgFmt, + ipv6 ? + (linklocal ? "[" UPNP_MCAST_LL_ADDR "]" : "[" UPNP_MCAST_SL_ADDR "]") + : UPNP_MCAST_ADDR, + deviceTypes[deviceIndex], mx); + if ((unsigned int)n >= sizeof(bufr)) { + if(error) + *error = MINISSDPC_MEMORY_ERROR; + goto error; + } +#ifdef DEBUG + /*printf("Sending %s", bufr);*/ + printf("Sending M-SEARCH request to %s with ST: %s\n", + ipv6 ? + (linklocal ? "[" UPNP_MCAST_LL_ADDR "]" : "[" UPNP_MCAST_SL_ADDR "]") + : UPNP_MCAST_ADDR, + deviceTypes[deviceIndex]); +#endif +#ifdef NO_GETADDRINFO + /* the following code is not using getaddrinfo */ + /* emission */ + memset(&sockudp_w, 0, sizeof(struct sockaddr_storage)); + if(ipv6) { + struct sockaddr_in6 * p = (struct sockaddr_in6 *)&sockudp_w; + p->sin6_family = AF_INET6; + p->sin6_port = htons(SSDP_PORT); + inet_pton(AF_INET6, + linklocal ? UPNP_MCAST_LL_ADDR : UPNP_MCAST_SL_ADDR, + &(p->sin6_addr)); + } else { + struct sockaddr_in * p = (struct sockaddr_in *)&sockudp_w; + p->sin_family = AF_INET; + p->sin_port = htons(SSDP_PORT); + p->sin_addr.s_addr = inet_addr(UPNP_MCAST_ADDR); + } + n = sendto(sudp, bufr, n, 0, &sockudp_w, + ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)); + if (n < 0) { + if(error) + *error = MINISSDPC_SOCKET_ERROR; + PRINT_SOCKET_ERROR("sendto"); + } else { + sentok = 1; + } +#else /* #ifdef NO_GETADDRINFO */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; /* AF_INET6 or AF_INET */ + hints.ai_socktype = SOCK_DGRAM; + /*hints.ai_flags = */ + if ((rv = getaddrinfo(ipv6 + ? (linklocal ? UPNP_MCAST_LL_ADDR : UPNP_MCAST_SL_ADDR) + : UPNP_MCAST_ADDR, + XSTR(SSDP_PORT), &hints, &servinfo)) != 0) { + if(error) + *error = MINISSDPC_SOCKET_ERROR; +#ifdef _WIN32 + fprintf(stderr, "getaddrinfo() failed: %d\n", rv); +#else + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); +#endif + break; + } + for(p = servinfo; p; p = p->ai_next) { + n = sendto(sudp, bufr, n, 0, p->ai_addr, p->ai_addrlen); + if (n < 0) { +#ifdef DEBUG + char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV]; + if (getnameinfo(p->ai_addr, p->ai_addrlen, hbuf, sizeof(hbuf), sbuf, + sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV) == 0) { + fprintf(stderr, "host:%s port:%s\n", hbuf, sbuf); + } +#endif + PRINT_SOCKET_ERROR("sendto"); + continue; + } else { + sentok = 1; + } + } + freeaddrinfo(servinfo); + if(!sentok) { + if(error) + *error = MINISSDPC_SOCKET_ERROR; + } +#endif /* #ifdef NO_GETADDRINFO */ + /* Waiting for SSDP REPLY packet to M-SEARCH + * if searchalltypes is set, enter the loop only + * when the last deviceType is reached */ + if((sentok && !searchalltypes) || !deviceTypes[deviceIndex + 1]) do { + n = receivedata(sudp, bufr, sizeof(bufr), delay, &scope_id); + if (n < 0) { + /* error */ + if(error) + *error = MINISSDPC_SOCKET_ERROR; + goto error; + } else if (n == 0) { + /* no data or Time Out */ +#ifdef DEBUG + printf("NODATA or TIMEOUT\n"); +#endif /* DEBUG */ + if (devlist && !searchalltypes) { + /* found some devices, stop now*/ + if(error) + *error = MINISSDPC_SUCCESS; + goto error; + } + } else { + const char * descURL=NULL; + int urlsize=0; + const char * st=NULL; + int stsize=0; + const char * usn=NULL; + int usnsize=0; + parseMSEARCHReply(bufr, n, &descURL, &urlsize, &st, &stsize, &usn, &usnsize); + if(st&&descURL) { +#ifdef DEBUG + printf("M-SEARCH Reply:\n ST: %.*s\n USN: %.*s\n Location: %.*s\n", + stsize, st, usnsize, (usn?usn:""), urlsize, descURL); +#endif /* DEBUG */ + for(tmp=devlist; tmp; tmp = tmp->pNext) { + if(memcmp(tmp->descURL, descURL, urlsize) == 0 && + tmp->descURL[urlsize] == '\0' && + memcmp(tmp->st, st, stsize) == 0 && + tmp->st[stsize] == '\0' && + (usnsize == 0 || memcmp(tmp->usn, usn, usnsize) == 0) && + tmp->usn[usnsize] == '\0') + break; + } + /* at the exit of the loop above, tmp is null if + * no duplicate device was found */ + if(tmp) + continue; + tmp = (struct UPNPDev *)malloc(sizeof(struct UPNPDev)+urlsize+stsize+usnsize); + if(!tmp) { + /* memory allocation error */ + if(error) + *error = MINISSDPC_MEMORY_ERROR; + goto error; + } + tmp->pNext = devlist; + tmp->descURL = tmp->buffer; + tmp->st = tmp->buffer + 1 + urlsize; + tmp->usn = tmp->st + 1 + stsize; + memcpy(tmp->buffer, descURL, urlsize); + tmp->buffer[urlsize] = '\0'; + memcpy(tmp->st, st, stsize); + tmp->buffer[urlsize+1+stsize] = '\0'; + if(usn != NULL) + memcpy(tmp->usn, usn, usnsize); + tmp->buffer[urlsize+1+stsize+1+usnsize] = '\0'; + tmp->scope_id = scope_id; + devlist = tmp; + } + } + } while(n > 0); + if(ipv6) { + /* switch linklocal flag */ + if(linklocal) { + linklocal = 0; + --deviceIndex; + } else { + linklocal = 1; + } + } + } +error: + closesocket(sudp); + return devlist; +} + diff --git a/thirdparty/miniupnpc/minissdpc.h b/thirdparty/miniupnpc/minissdpc.h new file mode 100644 index 0000000000..167d897cb6 --- /dev/null +++ b/thirdparty/miniupnpc/minissdpc.h @@ -0,0 +1,58 @@ +/* $Id: minissdpc.h,v 1.6 2015/09/18 12:45:16 nanard Exp $ */ +/* Project: miniupnp + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * Author: Thomas Bernard + * Copyright (c) 2005-2015 Thomas Bernard + * This software is subjects to the conditions detailed + * in the LICENCE file provided within this distribution */ +#ifndef MINISSDPC_H_INCLUDED +#define MINISSDPC_H_INCLUDED + +#include "miniupnpc_declspec.h" +#include "upnpdev.h" + +/* error codes : */ +#define MINISSDPC_SUCCESS (0) +#define MINISSDPC_UNKNOWN_ERROR (-1) +#define MINISSDPC_SOCKET_ERROR (-101) +#define MINISSDPC_MEMORY_ERROR (-102) +#define MINISSDPC_INVALID_INPUT (-103) +#define MINISSDPC_INVALID_SERVER_REPLY (-104) + +#ifdef __cplusplus +extern "C" { +#endif + +#if !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__)) + +MINIUPNP_LIBSPEC struct UPNPDev * +getDevicesFromMiniSSDPD(const char * devtype, const char * socketpath, int * error); + +MINIUPNP_LIBSPEC int +connectToMiniSSDPD(const char * socketpath); + +MINIUPNP_LIBSPEC int +disconnectFromMiniSSDPD(int fd); + +MINIUPNP_LIBSPEC int +requestDevicesFromMiniSSDPD(int fd, const char * devtype); + +MINIUPNP_LIBSPEC struct UPNPDev * +receiveDevicesFromMiniSSDPD(int fd, int * error); + +#endif /* !(defined(_WIN32) || defined(__amigaos__) || defined(__amigaos4__)) */ + +MINIUPNP_LIBSPEC struct UPNPDev * +ssdpDiscoverDevices(const char * const deviceTypes[], + int delay, const char * multicastif, + int localport, + int ipv6, unsigned char ttl, + int * error, + int searchalltypes); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/thirdparty/miniupnpc/miniupnpc.c b/thirdparty/miniupnpc/miniupnpc.c new file mode 100644 index 0000000000..5d93ef9933 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc.c @@ -0,0 +1,727 @@ +/* $Id: miniupnpc.c,v 1.149 2016/02/09 09:50:46 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project : miniupnp + * Web : http://miniupnp.free.fr/ + * Author : Thomas BERNARD + * copyright (c) 2005-2018 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENSE file. */ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#ifdef _WIN32 +/* Win32 Specific includes and defines */ +#include <winsock2.h> +#include <ws2tcpip.h> +#include <io.h> +#include <iphlpapi.h> +#define snprintf _snprintf +#define strdup _strdup +#ifndef strncasecmp +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define strncasecmp _memicmp +#else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#define strncasecmp memicmp +#endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#endif /* #ifndef strncasecmp */ +#define MAXHOSTNAMELEN 64 +#else /* #ifdef _WIN32 */ +/* Standard POSIX includes */ +#include <unistd.h> +#if defined(__amigaos__) && !defined(__amigaos4__) +/* Amiga OS 3 specific stuff */ +#define socklen_t int +#else +#include <sys/select.h> +#endif +#include <sys/socket.h> +#include <sys/types.h> +#include <sys/param.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <net/if.h> +#if !defined(__amigaos__) && !defined(__amigaos4__) +#include <poll.h> +#endif +#include <strings.h> +#include <errno.h> +#define closesocket close +#endif /* #else _WIN32 */ +#ifdef __GNU__ +#define MAXHOSTNAMELEN 64 +#endif + + +#include "miniupnpc.h" +#include "minissdpc.h" +#include "miniwget.h" +#include "miniwget_private.h" +#include "minisoap.h" +#include "minixml.h" +#include "upnpcommands.h" +#include "connecthostport.h" + +/* compare the beginning of a string with a constant string */ +#define COMPARE(str, cstr) (0==memcmp(str, cstr, sizeof(cstr) - 1)) + +#ifndef MAXHOSTNAMELEN +#define MAXHOSTNAMELEN 64 +#endif + +#define SOAPPREFIX "s" +#define SERVICEPREFIX "u" +#define SERVICEPREFIX2 'u' + +/* check if an ip address is a private (LAN) address + * see https://tools.ietf.org/html/rfc1918 */ +static int is_rfc1918addr(const char * addr) +{ + /* 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) */ + if(COMPARE(addr, "192.168.")) + return 1; + /* 10.0.0.0 - 10.255.255.255 (10/8 prefix) */ + if(COMPARE(addr, "10.")) + return 1; + /* 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) */ + if(COMPARE(addr, "172.")) { + int i = atoi(addr + 4); + if((16 <= i) && (i <= 31)) + return 1; + } + return 0; +} + +/* root description parsing */ +MINIUPNP_LIBSPEC void parserootdesc(const char * buffer, int bufsize, struct IGDdatas * data) +{ + struct xmlparser parser; + /* xmlparser object */ + parser.xmlstart = buffer; + parser.xmlsize = bufsize; + parser.data = data; + parser.starteltfunc = IGDstartelt; + parser.endeltfunc = IGDendelt; + parser.datafunc = IGDdata; + parser.attfunc = 0; + parsexml(&parser); +#ifdef DEBUG + printIGD(data); +#endif +} + +/* simpleUPnPcommand2 : + * not so simple ! + * return values : + * pointer - OK + * NULL - error */ +static char * +simpleUPnPcommand2(SOCKET s, const char * url, const char * service, + const char * action, struct UPNParg * args, + int * bufsize, const char * httpversion) +{ + char hostname[MAXHOSTNAMELEN+1]; + unsigned short port = 0; + char * path; + char soapact[128]; + char soapbody[2048]; + int soapbodylen; + char * buf; + int n; + int status_code; + + *bufsize = 0; + snprintf(soapact, sizeof(soapact), "%s#%s", service, action); + if(args==NULL) + { + soapbodylen = snprintf(soapbody, sizeof(soapbody), + "<?xml version=\"1.0\"?>\r\n" + "<" SOAPPREFIX ":Envelope " + "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" " + SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<" SOAPPREFIX ":Body>" + "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">" + "</" SERVICEPREFIX ":%s>" + "</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>" + "\r\n", action, service, action); + if ((unsigned int)soapbodylen >= sizeof(soapbody)) + return NULL; + } + else + { + char * p; + const char * pe, * pv; + const char * const pend = soapbody + sizeof(soapbody); + soapbodylen = snprintf(soapbody, sizeof(soapbody), + "<?xml version=\"1.0\"?>\r\n" + "<" SOAPPREFIX ":Envelope " + "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" " + SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<" SOAPPREFIX ":Body>" + "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">", + action, service); + if ((unsigned int)soapbodylen >= sizeof(soapbody)) + return NULL; + p = soapbody + soapbodylen; + while(args->elt) + { + if(p >= pend) /* check for space to write next byte */ + return NULL; + *(p++) = '<'; + + pe = args->elt; + while(p < pend && *pe) + *(p++) = *(pe++); + + if(p >= pend) /* check for space to write next byte */ + return NULL; + *(p++) = '>'; + + if((pv = args->val)) + { + while(p < pend && *pv) + *(p++) = *(pv++); + } + + if((p+2) > pend) /* check for space to write next 2 bytes */ + return NULL; + *(p++) = '<'; + *(p++) = '/'; + + pe = args->elt; + while(p < pend && *pe) + *(p++) = *(pe++); + + if(p >= pend) /* check for space to write next byte */ + return NULL; + *(p++) = '>'; + + args++; + } + if((p+4) > pend) /* check for space to write next 4 bytes */ + return NULL; + *(p++) = '<'; + *(p++) = '/'; + *(p++) = SERVICEPREFIX2; + *(p++) = ':'; + + pe = action; + while(p < pend && *pe) + *(p++) = *(pe++); + + strncpy(p, "></" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>\r\n", + pend - p); + if(soapbody[sizeof(soapbody)-1]) /* strncpy pads buffer with 0s, so if it doesn't end in 0, could not fit full string */ + return NULL; + } + if(!parseURL(url, hostname, &port, &path, NULL)) return NULL; + if(ISINVALID(s)) { + s = connecthostport(hostname, port, 0); + if(ISINVALID(s)) { + /* failed to connect */ + return NULL; + } + } + + n = soapPostSubmit(s, path, hostname, port, soapact, soapbody, httpversion); + if(n<=0) { +#ifdef DEBUG + printf("Error sending SOAP request\n"); +#endif + closesocket(s); + return NULL; + } + + buf = getHTTPResponse(s, bufsize, &status_code); +#ifdef DEBUG + if(*bufsize > 0 && buf) + { + printf("HTTP %d SOAP Response :\n%.*s\n", status_code, *bufsize, buf); + } + else + { + printf("HTTP %d, empty SOAP response. size=%d\n", status_code, *bufsize); + } +#endif + closesocket(s); + return buf; +} + +/* simpleUPnPcommand : + * not so simple ! + * return values : + * pointer - OK + * NULL - error */ +char * +simpleUPnPcommand(int s, const char * url, const char * service, + const char * action, struct UPNParg * args, + int * bufsize) +{ + char * buf; + +#if 1 + buf = simpleUPnPcommand2((SOCKET)s, url, service, action, args, bufsize, "1.1"); +#else + buf = simpleUPnPcommand2((SOCKET)s, url, service, action, args, bufsize, "1.0"); + if (!buf || *bufsize == 0) + { +#if DEBUG + printf("Error or no result from SOAP request; retrying with HTTP/1.1\n"); +#endif + buf = simpleUPnPcommand2((SOCKET)s, url, service, action, args, bufsize, "1.1"); + } +#endif + return buf; +} + +/* upnpDiscoverDevices() : + * return a chained list of all devices found or NULL if + * no devices was found. + * It is up to the caller to free the chained list + * delay is in millisecond (poll). + * UDA v1.1 says : + * The TTL for the IP packet SHOULD default to 2 and + * SHOULD be configurable. */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevices(const char * const deviceTypes[], + int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error, + int searchalltypes) +{ + struct UPNPDev * tmp; + struct UPNPDev * devlist = 0; +#if !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) + int deviceIndex; +#endif /* !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) */ + + if(error) + *error = UPNPDISCOVER_UNKNOWN_ERROR; +#if !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) + /* first try to get infos from minissdpd ! */ + if(!minissdpdsock) + minissdpdsock = "/var/run/minissdpd.sock"; + if(minissdpdsock[0] != '\0') { + for(deviceIndex = 0; deviceTypes[deviceIndex]; deviceIndex++) { + struct UPNPDev * minissdpd_devlist; + int only_rootdevice = 1; + minissdpd_devlist = getDevicesFromMiniSSDPD(deviceTypes[deviceIndex], + minissdpdsock, 0); + if(minissdpd_devlist) { +#ifdef DEBUG + printf("returned by MiniSSDPD: %s\t%s\n", + minissdpd_devlist->st, minissdpd_devlist->descURL); +#endif /* DEBUG */ + if(!strstr(minissdpd_devlist->st, "rootdevice")) + only_rootdevice = 0; + for(tmp = minissdpd_devlist; tmp->pNext != NULL; tmp = tmp->pNext) { +#ifdef DEBUG + printf("returned by MiniSSDPD: %s\t%s\n", + tmp->pNext->st, tmp->pNext->descURL); +#endif /* DEBUG */ + if(!strstr(tmp->st, "rootdevice")) + only_rootdevice = 0; + } + tmp->pNext = devlist; + devlist = minissdpd_devlist; + if(!searchalltypes && !only_rootdevice) + break; + } + } + } + for(tmp = devlist; tmp != NULL; tmp = tmp->pNext) { + /* We return what we have found if it was not only a rootdevice */ + if(!strstr(tmp->st, "rootdevice")) { + if(error) + *error = UPNPDISCOVER_SUCCESS; + return devlist; + } + } +#endif /* !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) */ + + /* direct discovery if minissdpd responses are not sufficient */ + { + struct UPNPDev * discovered_devlist; + discovered_devlist = ssdpDiscoverDevices(deviceTypes, delay, multicastif, localport, + ipv6, ttl, error, searchalltypes); + if(devlist == NULL) + devlist = discovered_devlist; + else { + for(tmp = devlist; tmp->pNext != NULL; tmp = tmp->pNext); + tmp->pNext = discovered_devlist; + } + } + return devlist; +} + +/* upnpDiscover() Discover IGD device */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscover(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error) +{ + static const char * const deviceList[] = { +#if 0 + "urn:schemas-upnp-org:device:InternetGatewayDevice:2", + "urn:schemas-upnp-org:service:WANIPConnection:2", +#endif + "urn:schemas-upnp-org:device:InternetGatewayDevice:1", + "urn:schemas-upnp-org:service:WANIPConnection:1", + "urn:schemas-upnp-org:service:WANPPPConnection:1", + "upnp:rootdevice", + /*"ssdp:all",*/ + 0 + }; + return upnpDiscoverDevices(deviceList, + delay, multicastif, minissdpdsock, localport, + ipv6, ttl, error, 0); +} + +/* upnpDiscoverAll() Discover all UPnP devices */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverAll(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error) +{ + static const char * const deviceList[] = { + /*"upnp:rootdevice",*/ + "ssdp:all", + 0 + }; + return upnpDiscoverDevices(deviceList, + delay, multicastif, minissdpdsock, localport, + ipv6, ttl, error, 0); +} + +/* upnpDiscoverDevice() Discover a specific device */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevice(const char * device, int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error) +{ + const char * const deviceList[] = { + device, + 0 + }; + return upnpDiscoverDevices(deviceList, + delay, multicastif, minissdpdsock, localport, + ipv6, ttl, error, 0); +} + +static char * +build_absolute_url(const char * baseurl, const char * descURL, + const char * url, unsigned int scope_id) +{ + int l, n; + char * s; + const char * base; + char * p; +#if defined(IF_NAMESIZE) && !defined(_WIN32) + char ifname[IF_NAMESIZE]; +#else /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + char scope_str[8]; +#endif /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + + if( (url[0] == 'h') + &&(url[1] == 't') + &&(url[2] == 't') + &&(url[3] == 'p') + &&(url[4] == ':') + &&(url[5] == '/') + &&(url[6] == '/')) + return strdup(url); + base = (baseurl[0] == '\0') ? descURL : baseurl; + n = strlen(base); + if(n > 7) { + p = strchr(base + 7, '/'); + if(p) + n = p - base; + } + l = n + strlen(url) + 1; + if(url[0] != '/') + l++; + if(scope_id != 0) { +#if defined(IF_NAMESIZE) && !defined(_WIN32) + if(if_indextoname(scope_id, ifname)) { + l += 3 + strlen(ifname); /* 3 == strlen(%25) */ + } +#else /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + /* under windows, scope is numerical */ + l += 3 + snprintf(scope_str, sizeof(scope_str), "%u", scope_id); +#endif /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + } + s = malloc(l); + if(s == NULL) return NULL; + memcpy(s, base, n); + if(scope_id != 0) { + s[n] = '\0'; + if(0 == memcmp(s, "http://[fe80:", 13)) { + /* this is a linklocal IPv6 address */ + p = strchr(s, ']'); + if(p) { + /* insert %25<scope> into URL */ +#if defined(IF_NAMESIZE) && !defined(_WIN32) + memmove(p + 3 + strlen(ifname), p, strlen(p) + 1); + memcpy(p, "%25", 3); + memcpy(p + 3, ifname, strlen(ifname)); + n += 3 + strlen(ifname); +#else /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + memmove(p + 3 + strlen(scope_str), p, strlen(p) + 1); + memcpy(p, "%25", 3); + memcpy(p + 3, scope_str, strlen(scope_str)); + n += 3 + strlen(scope_str); +#endif /* defined(IF_NAMESIZE) && !defined(_WIN32) */ + } + } + } + if(url[0] != '/') + s[n++] = '/'; + memcpy(s + n, url, l - n); + return s; +} + +/* Prepare the Urls for usage... + */ +MINIUPNP_LIBSPEC void +GetUPNPUrls(struct UPNPUrls * urls, struct IGDdatas * data, + const char * descURL, unsigned int scope_id) +{ + /* strdup descURL */ + urls->rootdescURL = strdup(descURL); + + /* get description of WANIPConnection */ + urls->ipcondescURL = build_absolute_url(data->urlbase, descURL, + data->first.scpdurl, scope_id); + urls->controlURL = build_absolute_url(data->urlbase, descURL, + data->first.controlurl, scope_id); + urls->controlURL_CIF = build_absolute_url(data->urlbase, descURL, + data->CIF.controlurl, scope_id); + urls->controlURL_6FC = build_absolute_url(data->urlbase, descURL, + data->IPv6FC.controlurl, scope_id); + +#ifdef DEBUG + printf("urls->ipcondescURL='%s'\n", urls->ipcondescURL); + printf("urls->controlURL='%s'\n", urls->controlURL); + printf("urls->controlURL_CIF='%s'\n", urls->controlURL_CIF); + printf("urls->controlURL_6FC='%s'\n", urls->controlURL_6FC); +#endif +} + +MINIUPNP_LIBSPEC void +FreeUPNPUrls(struct UPNPUrls * urls) +{ + if(!urls) + return; + free(urls->controlURL); + urls->controlURL = 0; + free(urls->ipcondescURL); + urls->ipcondescURL = 0; + free(urls->controlURL_CIF); + urls->controlURL_CIF = 0; + free(urls->controlURL_6FC); + urls->controlURL_6FC = 0; + free(urls->rootdescURL); + urls->rootdescURL = 0; +} + +int +UPNPIGD_IsConnected(struct UPNPUrls * urls, struct IGDdatas * data) +{ + char status[64]; + unsigned int uptime; + status[0] = '\0'; + UPNP_GetStatusInfo(urls->controlURL, data->first.servicetype, + status, &uptime, NULL); + if(0 == strcmp("Connected", status)) + return 1; + else if(0 == strcmp("Up", status)) /* Also accept "Up" */ + return 1; + else + return 0; +} + + +/* UPNP_GetValidIGD() : + * return values : + * -1 = Internal error + * 0 = NO IGD found + * 1 = A valid connected IGD has been found + * 2 = A valid IGD has been found but it reported as + * not connected + * 3 = an UPnP device has been found but was not recognized as an IGD + * + * In any positive non zero return case, the urls and data structures + * passed as parameters are set. Don't forget to call FreeUPNPUrls(urls) to + * free allocated memory. + */ +MINIUPNP_LIBSPEC int +UPNP_GetValidIGD(struct UPNPDev * devlist, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen) +{ + struct xml_desc { + char * xml; + int size; + int is_igd; + } * desc = NULL; + struct UPNPDev * dev; + int ndev = 0; + int i; + int state = -1; /* state 1 : IGD connected. State 2 : IGD. State 3 : anything */ + int n_igd = 0; + char extIpAddr[16]; + char myLanAddr[40]; + int status_code = -1; + + if(!devlist) + { +#ifdef DEBUG + printf("Empty devlist\n"); +#endif + return 0; + } + /* counting total number of devices in the list */ + for(dev = devlist; dev; dev = dev->pNext) + ndev++; + if(ndev > 0) + { + desc = calloc(ndev, sizeof(struct xml_desc)); + if(!desc) + return -1; /* memory allocation error */ + } + /* Step 1 : downloading descriptions and testing type */ + for(dev = devlist, i = 0; dev; dev = dev->pNext, i++) + { + /* we should choose an internet gateway device. + * with st == urn:schemas-upnp-org:device:InternetGatewayDevice:1 */ + desc[i].xml = miniwget_getaddr(dev->descURL, &(desc[i].size), + myLanAddr, sizeof(myLanAddr), + dev->scope_id, &status_code); +#ifdef DEBUG + if(!desc[i].xml) + { + printf("error getting XML description %s\n", dev->descURL); + } +#endif + if(desc[i].xml) + { + memset(data, 0, sizeof(struct IGDdatas)); + memset(urls, 0, sizeof(struct UPNPUrls)); + parserootdesc(desc[i].xml, desc[i].size, data); + if(COMPARE(data->CIF.servicetype, + "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:")) + { + desc[i].is_igd = 1; + n_igd++; + if(lanaddr) + strncpy(lanaddr, myLanAddr, lanaddrlen); + } + } + } + /* iterate the list to find a device depending on state */ + for(state = 1; state <= 3; state++) + { + for(dev = devlist, i = 0; dev; dev = dev->pNext, i++) + { + if(desc[i].xml) + { + memset(data, 0, sizeof(struct IGDdatas)); + memset(urls, 0, sizeof(struct UPNPUrls)); + parserootdesc(desc[i].xml, desc[i].size, data); + if(desc[i].is_igd || state >= 3 ) + { + int is_connected; + + GetUPNPUrls(urls, data, dev->descURL, dev->scope_id); + + /* in state 2 and 3 we don't test if device is connected ! */ + if(state >= 2) + goto free_and_return; + is_connected = UPNPIGD_IsConnected(urls, data); +#ifdef DEBUG + printf("UPNPIGD_IsConnected(%s) = %d\n", + urls->controlURL, is_connected); +#endif + /* checks that status is connected AND there is a external IP address assigned */ + if(is_connected && + (UPNP_GetExternalIPAddress(urls->controlURL, data->first.servicetype, extIpAddr) == 0)) { + if(!is_rfc1918addr(extIpAddr) && (extIpAddr[0] != '\0') + && (0 != strcmp(extIpAddr, "0.0.0.0"))) + goto free_and_return; + } + FreeUPNPUrls(urls); + if(data->second.servicetype[0] != '\0') { +#ifdef DEBUG + printf("We tried %s, now we try %s !\n", + data->first.servicetype, data->second.servicetype); +#endif + /* swaping WANPPPConnection and WANIPConnection ! */ + memcpy(&data->tmp, &data->first, sizeof(struct IGDdatas_service)); + memcpy(&data->first, &data->second, sizeof(struct IGDdatas_service)); + memcpy(&data->second, &data->tmp, sizeof(struct IGDdatas_service)); + GetUPNPUrls(urls, data, dev->descURL, dev->scope_id); + is_connected = UPNPIGD_IsConnected(urls, data); +#ifdef DEBUG + printf("UPNPIGD_IsConnected(%s) = %d\n", + urls->controlURL, is_connected); +#endif + if(is_connected && + (UPNP_GetExternalIPAddress(urls->controlURL, data->first.servicetype, extIpAddr) == 0)) { + if(!is_rfc1918addr(extIpAddr) && (extIpAddr[0] != '\0') + && (0 != strcmp(extIpAddr, "0.0.0.0"))) + goto free_and_return; + } + FreeUPNPUrls(urls); + } + } + memset(data, 0, sizeof(struct IGDdatas)); + } + } + } + state = 0; +free_and_return: + if(desc) { + for(i = 0; i < ndev; i++) { + if(desc[i].xml) { + free(desc[i].xml); + } + } + free(desc); + } + return state; +} + +/* UPNP_GetIGDFromUrl() + * Used when skipping the discovery process. + * return value : + * 0 - Not ok + * 1 - OK */ +int +UPNP_GetIGDFromUrl(const char * rootdescurl, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen) +{ + char * descXML; + int descXMLsize = 0; + + descXML = miniwget_getaddr(rootdescurl, &descXMLsize, + lanaddr, lanaddrlen, 0, NULL); + if(descXML) { + memset(data, 0, sizeof(struct IGDdatas)); + memset(urls, 0, sizeof(struct UPNPUrls)); + parserootdesc(descXML, descXMLsize, data); + free(descXML); + descXML = NULL; + GetUPNPUrls(urls, data, rootdescurl, 0); + return 1; + } else { + return 0; + } +} + diff --git a/thirdparty/miniupnpc/miniupnpc.def b/thirdparty/miniupnpc/miniupnpc.def new file mode 100644 index 0000000000..60e0bbe423 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc.def @@ -0,0 +1,45 @@ +LIBRARY +; miniupnpc library + miniupnpc + +EXPORTS +; miniupnpc + upnpDiscover + freeUPNPDevlist + parserootdesc + UPNP_GetValidIGD + UPNP_GetIGDFromUrl + GetUPNPUrls + FreeUPNPUrls +; miniwget + miniwget + miniwget_getaddr +; upnpcommands + UPNP_GetTotalBytesSent + UPNP_GetTotalBytesReceived + UPNP_GetTotalPacketsSent + UPNP_GetTotalPacketsReceived + UPNP_GetStatusInfo + UPNP_GetConnectionTypeInfo + UPNP_GetExternalIPAddress + UPNP_GetLinkLayerMaxBitRates + UPNP_AddPortMapping + UPNP_AddAnyPortMapping + UPNP_DeletePortMapping + UPNP_DeletePortMappingRange + UPNP_GetPortMappingNumberOfEntries + UPNP_GetSpecificPortMappingEntry + UPNP_GetGenericPortMappingEntry + UPNP_GetListOfPortMappings + UPNP_AddPinhole + UPNP_CheckPinholeWorking + UPNP_UpdatePinhole + UPNP_GetPinholePackets + UPNP_DeletePinhole + UPNP_GetFirewallStatus + UPNP_GetOutboundPinholeTimeout +; upnperrors + strupnperror +; portlistingparse + ParsePortListing + FreePortListing diff --git a/thirdparty/miniupnpc/miniupnpc.h b/thirdparty/miniupnpc/miniupnpc.h new file mode 100644 index 0000000000..8ddc282bd1 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc.h @@ -0,0 +1,153 @@ +/* $Id: miniupnpc.h,v 1.53 2018/05/07 11:05:16 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project: miniupnp + * http://miniupnp.free.fr/ + * Author: Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subjects to the conditions detailed + * in the LICENCE file provided within this distribution */ +#ifndef MINIUPNPC_H_INCLUDED +#define MINIUPNPC_H_INCLUDED + +#include "miniupnpc_declspec.h" +#include "igd_desc_parse.h" +#include "upnpdev.h" + +/* error codes : */ +#define UPNPDISCOVER_SUCCESS (0) +#define UPNPDISCOVER_UNKNOWN_ERROR (-1) +#define UPNPDISCOVER_SOCKET_ERROR (-101) +#define UPNPDISCOVER_MEMORY_ERROR (-102) + +/* versions : */ +#define MINIUPNPC_VERSION "2.1" +#define MINIUPNPC_API_VERSION 17 + +/* Source port: + Using "1" as an alias for 1900 for backwards compatibility + (presuming one would have used that for the "sameport" parameter) */ +#define UPNP_LOCAL_PORT_ANY 0 +#define UPNP_LOCAL_PORT_SAME 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structures definitions : */ +struct UPNParg { const char * elt; const char * val; }; + +char * +simpleUPnPcommand(int, const char *, const char *, + const char *, struct UPNParg *, + int *); + +/* upnpDiscover() + * discover UPnP devices on the network. + * The discovered devices are returned as a chained list. + * It is up to the caller to free the list with freeUPNPDevlist(). + * delay (in millisecond) is the maximum time for waiting any device + * response. + * If available, device list will be obtained from MiniSSDPd. + * Default path for minissdpd socket will be used if minissdpdsock argument + * is NULL. + * If multicastif is not NULL, it will be used instead of the default + * multicast interface for sending SSDP discover packets. + * If localport is set to UPNP_LOCAL_PORT_SAME(1) SSDP packets will be sent + * from the source port 1900 (same as destination port), if set to + * UPNP_LOCAL_PORT_ANY(0) system assign a source port, any other value will + * be attempted as the source port. + * "searchalltypes" parameter is useful when searching several types, + * if 0, the discovery will stop with the first type returning results. + * TTL should default to 2. */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscover(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverAll(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevice(const char * device, int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevices(const char * const deviceTypes[], + int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error, + int searchalltypes); + +/* parserootdesc() : + * parse root XML description of a UPnP device and fill the IGDdatas + * structure. */ +MINIUPNP_LIBSPEC void parserootdesc(const char *, int, struct IGDdatas *); + +/* structure used to get fast access to urls + * controlURL: controlURL of the WANIPConnection + * ipcondescURL: url of the description of the WANIPConnection + * controlURL_CIF: controlURL of the WANCommonInterfaceConfig + * controlURL_6FC: controlURL of the WANIPv6FirewallControl + */ +struct UPNPUrls { + char * controlURL; + char * ipcondescURL; + char * controlURL_CIF; + char * controlURL_6FC; + char * rootdescURL; +}; + +/* UPNP_GetValidIGD() : + * return values : + * 0 = NO IGD found + * 1 = A valid connected IGD has been found + * 2 = A valid IGD has been found but it reported as + * not connected + * 3 = an UPnP device has been found but was not recognized as an IGD + * + * In any non zero return case, the urls and data structures + * passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to + * free allocated memory. + */ +MINIUPNP_LIBSPEC int +UPNP_GetValidIGD(struct UPNPDev * devlist, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen); + +/* UPNP_GetIGDFromUrl() + * Used when skipping the discovery process. + * When succeding, urls, data, and lanaddr arguments are set. + * return value : + * 0 - Not ok + * 1 - OK */ +MINIUPNP_LIBSPEC int +UPNP_GetIGDFromUrl(const char * rootdescurl, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen); + +MINIUPNP_LIBSPEC void +GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *, + const char *, unsigned int); + +MINIUPNP_LIBSPEC void +FreeUPNPUrls(struct UPNPUrls *); + +/* return 0 or 1 */ +MINIUPNP_LIBSPEC int UPNPIGD_IsConnected(struct UPNPUrls *, struct IGDdatas *); + + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/thirdparty/miniupnpc/miniupnpc/miniupnpc.h b/thirdparty/miniupnpc/miniupnpc/miniupnpc.h new file mode 100644 index 0000000000..8ddc282bd1 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc/miniupnpc.h @@ -0,0 +1,153 @@ +/* $Id: miniupnpc.h,v 1.53 2018/05/07 11:05:16 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project: miniupnp + * http://miniupnp.free.fr/ + * Author: Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subjects to the conditions detailed + * in the LICENCE file provided within this distribution */ +#ifndef MINIUPNPC_H_INCLUDED +#define MINIUPNPC_H_INCLUDED + +#include "miniupnpc_declspec.h" +#include "igd_desc_parse.h" +#include "upnpdev.h" + +/* error codes : */ +#define UPNPDISCOVER_SUCCESS (0) +#define UPNPDISCOVER_UNKNOWN_ERROR (-1) +#define UPNPDISCOVER_SOCKET_ERROR (-101) +#define UPNPDISCOVER_MEMORY_ERROR (-102) + +/* versions : */ +#define MINIUPNPC_VERSION "2.1" +#define MINIUPNPC_API_VERSION 17 + +/* Source port: + Using "1" as an alias for 1900 for backwards compatibility + (presuming one would have used that for the "sameport" parameter) */ +#define UPNP_LOCAL_PORT_ANY 0 +#define UPNP_LOCAL_PORT_SAME 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structures definitions : */ +struct UPNParg { const char * elt; const char * val; }; + +char * +simpleUPnPcommand(int, const char *, const char *, + const char *, struct UPNParg *, + int *); + +/* upnpDiscover() + * discover UPnP devices on the network. + * The discovered devices are returned as a chained list. + * It is up to the caller to free the list with freeUPNPDevlist(). + * delay (in millisecond) is the maximum time for waiting any device + * response. + * If available, device list will be obtained from MiniSSDPd. + * Default path for minissdpd socket will be used if minissdpdsock argument + * is NULL. + * If multicastif is not NULL, it will be used instead of the default + * multicast interface for sending SSDP discover packets. + * If localport is set to UPNP_LOCAL_PORT_SAME(1) SSDP packets will be sent + * from the source port 1900 (same as destination port), if set to + * UPNP_LOCAL_PORT_ANY(0) system assign a source port, any other value will + * be attempted as the source port. + * "searchalltypes" parameter is useful when searching several types, + * if 0, the discovery will stop with the first type returning results. + * TTL should default to 2. */ +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscover(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverAll(int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevice(const char * device, int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error); + +MINIUPNP_LIBSPEC struct UPNPDev * +upnpDiscoverDevices(const char * const deviceTypes[], + int delay, const char * multicastif, + const char * minissdpdsock, int localport, + int ipv6, unsigned char ttl, + int * error, + int searchalltypes); + +/* parserootdesc() : + * parse root XML description of a UPnP device and fill the IGDdatas + * structure. */ +MINIUPNP_LIBSPEC void parserootdesc(const char *, int, struct IGDdatas *); + +/* structure used to get fast access to urls + * controlURL: controlURL of the WANIPConnection + * ipcondescURL: url of the description of the WANIPConnection + * controlURL_CIF: controlURL of the WANCommonInterfaceConfig + * controlURL_6FC: controlURL of the WANIPv6FirewallControl + */ +struct UPNPUrls { + char * controlURL; + char * ipcondescURL; + char * controlURL_CIF; + char * controlURL_6FC; + char * rootdescURL; +}; + +/* UPNP_GetValidIGD() : + * return values : + * 0 = NO IGD found + * 1 = A valid connected IGD has been found + * 2 = A valid IGD has been found but it reported as + * not connected + * 3 = an UPnP device has been found but was not recognized as an IGD + * + * In any non zero return case, the urls and data structures + * passed as parameters are set. Donc forget to call FreeUPNPUrls(urls) to + * free allocated memory. + */ +MINIUPNP_LIBSPEC int +UPNP_GetValidIGD(struct UPNPDev * devlist, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen); + +/* UPNP_GetIGDFromUrl() + * Used when skipping the discovery process. + * When succeding, urls, data, and lanaddr arguments are set. + * return value : + * 0 - Not ok + * 1 - OK */ +MINIUPNP_LIBSPEC int +UPNP_GetIGDFromUrl(const char * rootdescurl, + struct UPNPUrls * urls, + struct IGDdatas * data, + char * lanaddr, int lanaddrlen); + +MINIUPNP_LIBSPEC void +GetUPNPUrls(struct UPNPUrls *, struct IGDdatas *, + const char *, unsigned int); + +MINIUPNP_LIBSPEC void +FreeUPNPUrls(struct UPNPUrls *); + +/* return 0 or 1 */ +MINIUPNP_LIBSPEC int UPNPIGD_IsConnected(struct UPNPUrls *, struct IGDdatas *); + + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/thirdparty/miniupnpc/miniupnpc/miniwget.h b/thirdparty/miniupnpc/miniupnpc/miniwget.h new file mode 100644 index 0000000000..f5572c2544 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc/miniwget.h @@ -0,0 +1,27 @@ +/* $Id: miniwget.h,v 1.12 2016/01/24 17:24:36 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2016 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#ifndef MINIWGET_H_INCLUDED +#define MINIWGET_H_INCLUDED + +#include "miniupnpc_declspec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +MINIUPNP_LIBSPEC void * miniwget(const char *, int *, unsigned int, int *); + +MINIUPNP_LIBSPEC void * miniwget_getaddr(const char *, int *, char *, int, unsigned int, int *); + +int parseURL(const char *, char *, unsigned short *, char * *, unsigned int *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/miniupnpc/miniupnpc/upnpcommands.h b/thirdparty/miniupnpc/miniupnpc/upnpcommands.h new file mode 100644 index 0000000000..0c6d501666 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc/upnpcommands.h @@ -0,0 +1,348 @@ +/* $Id: upnpcommands.h,v 1.32 2018/03/13 23:34:47 nanard Exp $ */ +/* Miniupnp project : http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided within this distribution */ +#ifndef UPNPCOMMANDS_H_INCLUDED +#define UPNPCOMMANDS_H_INCLUDED + +#include "miniupnpc_declspec.h" +#include "miniupnpctypes.h" + +/* MiniUPnPc return codes : */ +#define UPNPCOMMAND_SUCCESS (0) +#define UPNPCOMMAND_UNKNOWN_ERROR (-1) +#define UPNPCOMMAND_INVALID_ARGS (-2) +#define UPNPCOMMAND_HTTP_ERROR (-3) +#define UPNPCOMMAND_INVALID_RESPONSE (-4) +#define UPNPCOMMAND_MEM_ALLOC_ERROR (-5) + +#ifdef __cplusplus +extern "C" { +#endif + +struct PortMappingParserData; + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesSent(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesReceived(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsSent(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsReceived(const char * controlURL, + const char * servicetype); + +/* UPNP_GetStatusInfo() + * status and lastconnerror are 64 byte buffers + * Return values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error code */ +MINIUPNP_LIBSPEC int +UPNP_GetStatusInfo(const char * controlURL, + const char * servicetype, + char * status, + unsigned int * uptime, + char * lastconnerror); + +/* UPNP_GetConnectionTypeInfo() + * argument connectionType is a 64 character buffer + * Return Values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error code */ +MINIUPNP_LIBSPEC int +UPNP_GetConnectionTypeInfo(const char * controlURL, + const char * servicetype, + char * connectionType); + +/* UPNP_GetExternalIPAddress() call the corresponding UPNP method. + * if the third arg is not null the value is copied to it. + * at least 16 bytes must be available + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR Either an UPnP error code or an unknown error. + * + * possible UPnP Errors : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. */ +MINIUPNP_LIBSPEC int +UPNP_GetExternalIPAddress(const char * controlURL, + const char * servicetype, + char * extIpAdd); + +/* UPNP_GetLinkLayerMaxBitRates() + * call WANCommonInterfaceConfig:1#GetCommonLinkProperties + * + * return values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. */ +MINIUPNP_LIBSPEC int +UPNP_GetLinkLayerMaxBitRates(const char* controlURL, + const char* servicetype, + unsigned int * bitrateDown, + unsigned int * bitrateUp); + +/* UPNP_AddPortMapping() + * if desc is NULL, it will be defaulted to "libminiupnpc" + * remoteHost is usually NULL because IGD don't support it. + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR. Either an UPnP error code or an unknown error. + * + * List of possible UPnP errors for AddPortMapping : + * errorCode errorDescription (short) - Description (long) + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization and + * the sender was not authorized. + * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be + * wild-carded + * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded + * 718 ConflictInMappingEntry - The port mapping entry specified conflicts + * with a mapping assigned previously to another client + * 724 SamePortValuesRequired - Internal and External port values + * must be the same + * 725 OnlyPermanentLeasesSupported - The NAT implementation only supports + * permanent lease times on port mappings + * 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard + * and cannot be a specific IP address or DNS name + * 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and + * cannot be a specific port value + * 728 NoPortMapsAvailable - There are not enough free ports available to + * complete port mapping. + * 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed + * due to conflict with other mechanisms. + * 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded + */ +MINIUPNP_LIBSPEC int +UPNP_AddPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration); + +/* UPNP_AddAnyPortMapping() + * if desc is NULL, it will be defaulted to "libminiupnpc" + * remoteHost is usually NULL because IGD don't support it. + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR. Either an UPnP error code or an unknown error. + * + * List of possible UPnP errors for AddPortMapping : + * errorCode errorDescription (short) - Description (long) + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization and + * the sender was not authorized. + * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be + * wild-carded + * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded + * 728 NoPortMapsAvailable - There are not enough free ports available to + * complete port mapping. + * 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed + * due to conflict with other mechanisms. + * 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded + */ +MINIUPNP_LIBSPEC int +UPNP_AddAnyPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration, + char * reservedPort); + +/* UPNP_DeletePortMapping() + * Use same argument values as what was used for AddPortMapping(). + * remoteHost is usually NULL because IGD don't support it. + * Return Values : + * 0 : SUCCESS + * NON ZERO : error. Either an UPnP error code or an undefined error. + * + * List of possible UPnP errors for DeletePortMapping : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 714 NoSuchEntryInArray - The specified value does not exist in the array */ +MINIUPNP_LIBSPEC int +UPNP_DeletePortMapping(const char * controlURL, const char * servicetype, + const char * extPort, const char * proto, + const char * remoteHost); + +/* UPNP_DeletePortRangeMapping() + * Use same argument values as what was used for AddPortMapping(). + * remoteHost is usually NULL because IGD don't support it. + * Return Values : + * 0 : SUCCESS + * NON ZERO : error. Either an UPnP error code or an undefined error. + * + * List of possible UPnP errors for DeletePortMapping : + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 730 PortMappingNotFound - This error message is returned if no port + * mapping is found in the specified range. + * 733 InconsistentParameters - NewStartPort and NewEndPort values are not consistent. */ +MINIUPNP_LIBSPEC int +UPNP_DeletePortMappingRange(const char * controlURL, const char * servicetype, + const char * extPortStart, const char * extPortEnd, + const char * proto, + const char * manage); + +/* UPNP_GetPortMappingNumberOfEntries() + * not supported by all routers */ +MINIUPNP_LIBSPEC int +UPNP_GetPortMappingNumberOfEntries(const char* controlURL, + const char* servicetype, + unsigned int * num); + +/* UPNP_GetSpecificPortMappingEntry() + * retrieves an existing port mapping + * params : + * in extPort + * in proto + * in remoteHost + * out intClient (16 bytes) + * out intPort (6 bytes) + * out desc (80 bytes) + * out enabled (4 bytes) + * out leaseDuration (16 bytes) + * + * return value : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. + * + * List of possible UPnP errors for _GetSpecificPortMappingEntry : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 714 NoSuchEntryInArray - The specified value does not exist in the array. + */ +MINIUPNP_LIBSPEC int +UPNP_GetSpecificPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * extPort, + const char * proto, + const char * remoteHost, + char * intClient, + char * intPort, + char * desc, + char * enabled, + char * leaseDuration); + +/* UPNP_GetGenericPortMappingEntry() + * params : + * in index + * out extPort (6 bytes) + * out intClient (16 bytes) + * out intPort (6 bytes) + * out protocol (4 bytes) + * out desc (80 bytes) + * out enabled (4 bytes) + * out rHost (64 bytes) + * out duration (16 bytes) + * + * return value : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. + * + * Possible UPNP Error codes : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds + */ +MINIUPNP_LIBSPEC int +UPNP_GetGenericPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * index, + char * extPort, + char * intClient, + char * intPort, + char * protocol, + char * desc, + char * enabled, + char * rHost, + char * duration); + +/* UPNP_GetListOfPortMappings() Available in IGD v2 + * + * + * Possible UPNP Error codes : + * 606 Action not Authorized + * 730 PortMappingNotFound - no port mapping is found in the specified range. + * 733 InconsistantParameters - NewStartPort and NewEndPort values are not + * consistent. + */ +MINIUPNP_LIBSPEC int +UPNP_GetListOfPortMappings(const char * controlURL, + const char * servicetype, + const char * startPort, + const char * endPort, + const char * protocol, + const char * numberOfPorts, + struct PortMappingParserData * data); + +/* IGD:2, functions for service WANIPv6FirewallControl:1 */ +MINIUPNP_LIBSPEC int +UPNP_GetFirewallStatus(const char * controlURL, + const char * servicetype, + int * firewallEnabled, + int * inboundPinholeAllowed); + +MINIUPNP_LIBSPEC int +UPNP_GetOutboundPinholeTimeout(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + int * opTimeout); + +MINIUPNP_LIBSPEC int +UPNP_AddPinhole(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + const char * leaseTime, + char * uniqueID); + +MINIUPNP_LIBSPEC int +UPNP_UpdatePinhole(const char * controlURL, const char * servicetype, + const char * uniqueID, + const char * leaseTime); + +MINIUPNP_LIBSPEC int +UPNP_DeletePinhole(const char * controlURL, const char * servicetype, const char * uniqueID); + +MINIUPNP_LIBSPEC int +UPNP_CheckPinholeWorking(const char * controlURL, const char * servicetype, + const char * uniqueID, int * isWorking); + +MINIUPNP_LIBSPEC int +UPNP_GetPinholePackets(const char * controlURL, const char * servicetype, + const char * uniqueID, int * packets); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/thirdparty/miniupnpc/miniupnpc_declspec.h b/thirdparty/miniupnpc/miniupnpc_declspec.h new file mode 100644 index 0000000000..40adb922ec --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc_declspec.h @@ -0,0 +1,21 @@ +#ifndef MINIUPNPC_DECLSPEC_H_INCLUDED +#define MINIUPNPC_DECLSPEC_H_INCLUDED + +#if defined(_WIN32) && !defined(MINIUPNP_STATICLIB) + /* for windows dll */ + #ifdef MINIUPNP_EXPORTS + #define MINIUPNP_LIBSPEC __declspec(dllexport) + #else + #define MINIUPNP_LIBSPEC __declspec(dllimport) + #endif +#else + #if defined(__GNUC__) && __GNUC__ >= 4 + /* fix dynlib for OS X 10.9.2 and Apple LLVM version 5.0 */ + #define MINIUPNP_LIBSPEC __attribute__ ((visibility ("default"))) + #else + #define MINIUPNP_LIBSPEC + #endif +#endif + +#endif /* MINIUPNPC_DECLSPEC_H_INCLUDED */ + diff --git a/thirdparty/miniupnpc/miniupnpc_socketdef.h b/thirdparty/miniupnpc/miniupnpc_socketdef.h new file mode 100644 index 0000000000..965d9151b9 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpc_socketdef.h @@ -0,0 +1,37 @@ +/* $Id: miniupnpc_socketdef.h,v 1.1 2018/03/13 23:44:10 nanard Exp $ */ +/* Miniupnp project : http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/ + * Author : Thomas Bernard + * Copyright (c) 2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided within this distribution */ +#ifndef MINIUPNPC_SOCKETDEF_H_INCLUDED +#define MINIUPNPC_SOCKETDEF_H_INCLUDED + +#ifdef _MSC_VER + +#define ISINVALID(s) (INVALID_SOCKET==(s)) + +#else + +#ifndef SOCKET +#define SOCKET int +#endif +#ifndef SSIZE_T +#define SSIZE_T ssize_t +#endif +#ifndef INVALID_SOCKET +#define INVALID_SOCKET (-1) +#endif +#ifndef ISINVALID +#define ISINVALID(s) ((s)<0) +#endif + +#endif + +#ifdef _WIN32 +#define PRINT_SOCKET_ERROR(x) fprintf(stderr, "Socket error: %s, %d\n", x, WSAGetLastError()); +#else +#define PRINT_SOCKET_ERROR(x) perror(x) +#endif + +#endif /* MINIUPNPC_SOCKETDEF_H_INCLUDED */ diff --git a/thirdparty/miniupnpc/miniupnpcmodule.c b/thirdparty/miniupnpc/miniupnpcmodule.c new file mode 100644 index 0000000000..8657a0e002 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpcmodule.c @@ -0,0 +1,703 @@ +/* $Id: miniupnpcmodule.c,v 1.24 2014/06/10 09:48:11 nanard Exp $*/ +/* Project : miniupnp + * Author : Thomas BERNARD + * website : https://miniupnp.tuxfamily.org/ + * copyright (c) 2007-2018 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENCE file. */ +#include <Python.h> +#define MINIUPNP_STATICLIB +#include "structmember.h" +#include "miniupnpc.h" +#include "upnpcommands.h" +#include "upnperrors.h" + +#ifdef _WIN32 +#include <winsock2.h> +#endif + +/* for compatibility with Python < 2.4 */ +#ifndef Py_RETURN_NONE +#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None +#endif + +#ifndef Py_RETURN_TRUE +#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True +#endif + +#ifndef Py_RETURN_FALSE +#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False +#endif + +/* for compatibility with Python < 3.0 */ +#ifndef PyVarObject_HEAD_INIT +#define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, +#endif + +#ifndef Py_TYPE +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#endif + +typedef struct { + PyObject_HEAD + /* Type-specific fields go here. */ + struct UPNPDev * devlist; + struct UPNPUrls urls; + struct IGDdatas data; + unsigned int discoverdelay; /* value passed to upnpDiscover() */ + unsigned int localport; /* value passed to upnpDiscover() */ + char lanaddr[40]; /* our ip address on the LAN */ + char * multicastif; + char * minissdpdsocket; +} UPnPObject; + +static PyMemberDef UPnP_members[] = { + {"lanaddr", T_STRING_INPLACE, offsetof(UPnPObject, lanaddr), + READONLY, "ip address on the LAN" + }, + {"discoverdelay", T_UINT, offsetof(UPnPObject, discoverdelay), + 0/*READWRITE*/, "value in ms used to wait for SSDP responses" + }, + {"localport", T_UINT, offsetof(UPnPObject, localport), + 0/*READWRITE*/, + "If localport is set to UPNP_LOCAL_PORT_SAME(1) " + "SSDP packets will be sent from the source port " + "1900 (same as destination port), if set to " + "UPNP_LOCAL_PORT_ANY(0) system assign a source " + "port, any other value will be attempted as the " + "source port" + }, + /* T_STRING is allways readonly :( */ + {"multicastif", T_STRING, offsetof(UPnPObject, multicastif), + 0, "IP of the network interface to be used for multicast operations" + }, + {"minissdpdsocket", T_STRING, offsetof(UPnPObject, minissdpdsocket), + 0, "path of the MiniSSDPd unix socket" + }, + {NULL} +}; + + +static int UPnP_init(UPnPObject *self, PyObject *args, PyObject *kwds) +{ + char* multicastif = NULL; + char* minissdpdsocket = NULL; + static char *kwlist[] = { + "multicastif", "minissdpdsocket", "discoverdelay", + "localport", NULL + }; + + if(!PyArg_ParseTupleAndKeywords(args, kwds, "|zzII", kwlist, + &multicastif, + &minissdpdsocket, + &self->discoverdelay, + &self->localport)) + return -1; + + if(self->localport>1 && + (self->localport>65534||self->localport<1024)) { + PyErr_SetString(PyExc_Exception, "Invalid localport value"); + return -1; + } + if(multicastif) + self->multicastif = strdup(multicastif); + if(minissdpdsocket) + self->minissdpdsocket = strdup(minissdpdsocket); + + return 0; +} + +static void +UPnPObject_dealloc(UPnPObject *self) +{ + freeUPNPDevlist(self->devlist); + FreeUPNPUrls(&self->urls); + free(self->multicastif); + free(self->minissdpdsocket); + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static PyObject * +UPnP_discover(UPnPObject *self) +{ + struct UPNPDev * dev; + int i; + PyObject *res = NULL; + if(self->devlist) + { + freeUPNPDevlist(self->devlist); + self->devlist = 0; + } + Py_BEGIN_ALLOW_THREADS + self->devlist = upnpDiscover((int)self->discoverdelay/*timeout in ms*/, + self->multicastif, + self->minissdpdsocket, + (int)self->localport, + 0/*ip v6*/, + 2/* TTL */, + 0/*error */); + Py_END_ALLOW_THREADS + /* Py_RETURN_NONE ??? */ + for(dev = self->devlist, i = 0; dev; dev = dev->pNext) + i++; + res = Py_BuildValue("i", i); + return res; +} + +static PyObject * +UPnP_selectigd(UPnPObject *self) +{ + int r; +Py_BEGIN_ALLOW_THREADS + r = UPNP_GetValidIGD(self->devlist, &self->urls, &self->data, + self->lanaddr, sizeof(self->lanaddr)); +Py_END_ALLOW_THREADS + if(r) + { + return Py_BuildValue("s", self->urls.controlURL); + } + else + { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, "No UPnP device discovered"); + return NULL; + } +} + +static PyObject * +UPnP_totalbytesent(UPnPObject *self) +{ + UNSIGNED_INTEGER i; +Py_BEGIN_ALLOW_THREADS + i = UPNP_GetTotalBytesSent(self->urls.controlURL_CIF, + self->data.CIF.servicetype); +Py_END_ALLOW_THREADS +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("I", i); +#else + return Py_BuildValue("i", (int)i); +#endif +} + +static PyObject * +UPnP_totalbytereceived(UPnPObject *self) +{ + UNSIGNED_INTEGER i; +Py_BEGIN_ALLOW_THREADS + i = UPNP_GetTotalBytesReceived(self->urls.controlURL_CIF, + self->data.CIF.servicetype); +Py_END_ALLOW_THREADS +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("I", i); +#else + return Py_BuildValue("i", (int)i); +#endif +} + +static PyObject * +UPnP_totalpacketsent(UPnPObject *self) +{ + UNSIGNED_INTEGER i; +Py_BEGIN_ALLOW_THREADS + i = UPNP_GetTotalPacketsSent(self->urls.controlURL_CIF, + self->data.CIF.servicetype); +Py_END_ALLOW_THREADS +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("I", i); +#else + return Py_BuildValue("i", (int)i); +#endif +} + +static PyObject * +UPnP_totalpacketreceived(UPnPObject *self) +{ + UNSIGNED_INTEGER i; +Py_BEGIN_ALLOW_THREADS + i = UPNP_GetTotalPacketsReceived(self->urls.controlURL_CIF, + self->data.CIF.servicetype); +Py_END_ALLOW_THREADS +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("I", i); +#else + return Py_BuildValue("i", (int)i); +#endif +} + +static PyObject * +UPnP_statusinfo(UPnPObject *self) +{ + char status[64]; + char lastconnerror[64]; + unsigned int uptime = 0; + int r; + status[0] = '\0'; + lastconnerror[0] = '\0'; +Py_BEGIN_ALLOW_THREADS + r = UPNP_GetStatusInfo(self->urls.controlURL, self->data.first.servicetype, + status, &uptime, lastconnerror); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("(s,I,s)", status, uptime, lastconnerror); +#else + return Py_BuildValue("(s,i,s)", status, (int)uptime, lastconnerror); +#endif + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +static PyObject * +UPnP_connectiontype(UPnPObject *self) +{ + char connectionType[64]; + int r; + connectionType[0] = '\0'; +Py_BEGIN_ALLOW_THREADS + r = UPNP_GetConnectionTypeInfo(self->urls.controlURL, + self->data.first.servicetype, + connectionType); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { + return Py_BuildValue("s", connectionType); + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +static PyObject * +UPnP_externalipaddress(UPnPObject *self) +{ + char externalIPAddress[40]; + int r; + externalIPAddress[0] = '\0'; +Py_BEGIN_ALLOW_THREADS + r = UPNP_GetExternalIPAddress(self->urls.controlURL, + self->data.first.servicetype, + externalIPAddress); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { + return Py_BuildValue("s", externalIPAddress); + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +/* AddPortMapping(externalPort, protocol, internalHost, internalPort, desc, + * remoteHost) + * protocol is 'UDP' or 'TCP' */ +static PyObject * +UPnP_addportmapping(UPnPObject *self, PyObject *args) +{ + char extPort[6]; + unsigned short ePort; + char inPort[6]; + unsigned short iPort; + const char * proto; + const char * host; + const char * desc; + const char * remoteHost; + const char * leaseDuration = "0"; + int r; + if (!PyArg_ParseTuple(args, "HssHzz", &ePort, &proto, + &host, &iPort, &desc, &remoteHost)) + return NULL; +Py_BEGIN_ALLOW_THREADS + sprintf(extPort, "%hu", ePort); + sprintf(inPort, "%hu", iPort); + r = UPNP_AddPortMapping(self->urls.controlURL, self->data.first.servicetype, + extPort, inPort, host, desc, proto, + remoteHost, leaseDuration); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) + { + Py_RETURN_TRUE; + } + else + { + // TODO: RAISE an Exception. See upnpcommands.h for errors codes. + // upnperrors.c + //Py_RETURN_FALSE; + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +/* AddAnyPortMapping(externalPort, protocol, internalHost, internalPort, desc, + * remoteHost) + * protocol is 'UDP' or 'TCP' */ +static PyObject * +UPnP_addanyportmapping(UPnPObject *self, PyObject *args) +{ + char extPort[6]; + unsigned short ePort; + char inPort[6]; + unsigned short iPort; + char reservedPort[6]; + const char * proto; + const char * host; + const char * desc; + const char * remoteHost; + const char * leaseDuration = "0"; + int r; + if (!PyArg_ParseTuple(args, "HssHzz", &ePort, &proto, &host, &iPort, &desc, &remoteHost)) + return NULL; +Py_BEGIN_ALLOW_THREADS + sprintf(extPort, "%hu", ePort); + sprintf(inPort, "%hu", iPort); + r = UPNP_AddAnyPortMapping(self->urls.controlURL, self->data.first.servicetype, + extPort, inPort, host, desc, proto, + remoteHost, leaseDuration, reservedPort); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { + return Py_BuildValue("i", atoi(reservedPort)); + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + + +/* DeletePortMapping(extPort, proto, removeHost='') + * proto = 'UDP', 'TCP' */ +static PyObject * +UPnP_deleteportmapping(UPnPObject *self, PyObject *args) +{ + char extPort[6]; + unsigned short ePort; + const char * proto; + const char * remoteHost = ""; + int r; + if(!PyArg_ParseTuple(args, "Hs|z", &ePort, &proto, &remoteHost)) + return NULL; +Py_BEGIN_ALLOW_THREADS + sprintf(extPort, "%hu", ePort); + r = UPNP_DeletePortMapping(self->urls.controlURL, self->data.first.servicetype, + extPort, proto, remoteHost); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { + Py_RETURN_TRUE; + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +/* DeletePortMappingRange(extPort, proto, removeHost='') + * proto = 'UDP', 'TCP' */ +static PyObject * +UPnP_deleteportmappingrange(UPnPObject *self, PyObject *args) +{ + char extPortStart[6]; + unsigned short ePortStart; + char extPortEnd[6]; + unsigned short ePortEnd; + const char * proto; + unsigned char manage; + char manageStr[6]; + int r; + if(!PyArg_ParseTuple(args, "HHsb", &ePortStart, &ePortEnd, &proto, &manage)) + return NULL; +Py_BEGIN_ALLOW_THREADS + sprintf(extPortStart, "%hu", ePortStart); + sprintf(extPortEnd, "%hu", ePortEnd); + sprintf(manageStr, "%hu", (unsigned short)manage); + r = UPNP_DeletePortMappingRange(self->urls.controlURL, self->data.first.servicetype, + extPortStart, extPortEnd, proto, manageStr); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { + Py_RETURN_TRUE; + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +static PyObject * +UPnP_getportmappingnumberofentries(UPnPObject *self) +{ + unsigned int n = 0; + int r; +Py_BEGIN_ALLOW_THREADS + r = UPNP_GetPortMappingNumberOfEntries(self->urls.controlURL, + self->data.first.servicetype, + &n); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) { +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("I", n); +#else + return Py_BuildValue("i", (int)n); +#endif + } else { + /* TODO: have our own exception type ! */ + PyErr_SetString(PyExc_Exception, strupnperror(r)); + return NULL; + } +} + +/* GetSpecificPortMapping(ePort, proto, remoteHost='') + * proto = 'UDP' or 'TCP' */ +static PyObject * +UPnP_getspecificportmapping(UPnPObject *self, PyObject *args) +{ + char extPort[6]; + unsigned short ePort; + const char * proto; + const char * remoteHost = ""; + char intClient[40]; + char intPort[6]; + unsigned short iPort; + char desc[80]; + char enabled[4]; + char leaseDuration[16]; + if(!PyArg_ParseTuple(args, "Hs|z", &ePort, &proto, &remoteHost)) + return NULL; + extPort[0] = '\0'; intClient[0] = '\0'; intPort[0] = '\0'; + desc[0] = '\0'; enabled[0] = '\0'; leaseDuration[0] = '\0'; +Py_BEGIN_ALLOW_THREADS + sprintf(extPort, "%hu", ePort); + UPNP_GetSpecificPortMappingEntry(self->urls.controlURL, + self->data.first.servicetype, + extPort, proto, remoteHost, + intClient, intPort, + desc, enabled, leaseDuration); +Py_END_ALLOW_THREADS + if(intClient[0]) + { + iPort = (unsigned short)atoi(intPort); + return Py_BuildValue("(s,H,s,O,i)", + intClient, iPort, desc, + PyBool_FromLong(atoi(enabled)), + atoi(leaseDuration)); + } + else + { + Py_RETURN_NONE; + } +} + +/* GetGenericPortMapping(index) */ +static PyObject * +UPnP_getgenericportmapping(UPnPObject *self, PyObject *args) +{ + int i, r; + char index[8]; + char intClient[40]; + char intPort[6]; + unsigned short iPort; + char extPort[6]; + unsigned short ePort; + char protocol[4]; + char desc[80]; + char enabled[6]; + char rHost[64]; + char duration[16]; /* lease duration */ + unsigned int dur; + if(!PyArg_ParseTuple(args, "i", &i)) + return NULL; +Py_BEGIN_ALLOW_THREADS + snprintf(index, sizeof(index), "%d", i); + rHost[0] = '\0'; enabled[0] = '\0'; + duration[0] = '\0'; desc[0] = '\0'; + extPort[0] = '\0'; intPort[0] = '\0'; intClient[0] = '\0'; + r = UPNP_GetGenericPortMappingEntry(self->urls.controlURL, + self->data.first.servicetype, + index, + extPort, intClient, intPort, + protocol, desc, enabled, rHost, + duration); +Py_END_ALLOW_THREADS + if(r==UPNPCOMMAND_SUCCESS) + { + ePort = (unsigned short)atoi(extPort); + iPort = (unsigned short)atoi(intPort); + dur = (unsigned int)strtoul(duration, 0, 0); +#if (PY_MAJOR_VERSION >= 3) || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION > 3) + return Py_BuildValue("(H,s,(s,H),s,s,s,I)", + ePort, protocol, intClient, iPort, + desc, enabled, rHost, dur); +#else + return Py_BuildValue("(i,s,(s,i),s,s,s,i)", + (int)ePort, protocol, intClient, (int)iPort, + desc, enabled, rHost, (int)dur); +#endif + } + else + { + Py_RETURN_NONE; + } +} + +/* miniupnpc.UPnP object Method Table */ +static PyMethodDef UPnP_methods[] = { + {"discover", (PyCFunction)UPnP_discover, METH_NOARGS, + "discover UPnP IGD devices on the network" + }, + {"selectigd", (PyCFunction)UPnP_selectigd, METH_NOARGS, + "select a valid UPnP IGD among discovered devices" + }, + {"totalbytesent", (PyCFunction)UPnP_totalbytesent, METH_NOARGS, + "return the total number of bytes sent by UPnP IGD" + }, + {"totalbytereceived", (PyCFunction)UPnP_totalbytereceived, METH_NOARGS, + "return the total number of bytes received by UPnP IGD" + }, + {"totalpacketsent", (PyCFunction)UPnP_totalpacketsent, METH_NOARGS, + "return the total number of packets sent by UPnP IGD" + }, + {"totalpacketreceived", (PyCFunction)UPnP_totalpacketreceived, METH_NOARGS, + "return the total number of packets received by UPnP IGD" + }, + {"statusinfo", (PyCFunction)UPnP_statusinfo, METH_NOARGS, + "return status and uptime" + }, + {"connectiontype", (PyCFunction)UPnP_connectiontype, METH_NOARGS, + "return IGD WAN connection type" + }, + {"externalipaddress", (PyCFunction)UPnP_externalipaddress, METH_NOARGS, + "return external IP address" + }, + {"addportmapping", (PyCFunction)UPnP_addportmapping, METH_VARARGS, + "add a port mapping" + }, + {"addanyportmapping", (PyCFunction)UPnP_addanyportmapping, METH_VARARGS, + "add a port mapping, IGD to select alternative if necessary" + }, + {"deleteportmapping", (PyCFunction)UPnP_deleteportmapping, METH_VARARGS, + "delete a port mapping" + }, + {"deleteportmappingrange", (PyCFunction)UPnP_deleteportmappingrange, METH_VARARGS, + "delete a range of port mappings" + }, + {"getportmappingnumberofentries", (PyCFunction)UPnP_getportmappingnumberofentries, METH_NOARGS, + "-- non standard --" + }, + {"getspecificportmapping", (PyCFunction)UPnP_getspecificportmapping, METH_VARARGS, + "get details about a specific port mapping entry" + }, + {"getgenericportmapping", (PyCFunction)UPnP_getgenericportmapping, METH_VARARGS, + "get all details about the port mapping at index" + }, + {NULL} /* Sentinel */ +}; + +static PyTypeObject UPnPType = { + PyVarObject_HEAD_INIT(NULL, + 0) /*ob_size*/ + "miniupnpc.UPnP", /*tp_name*/ + sizeof(UPnPObject), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)UPnPObject_dealloc,/*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + "UPnP objects", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + UPnP_methods, /* tp_methods */ + UPnP_members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)UPnP_init, /* tp_init */ + 0, /* tp_alloc */ +#ifndef _WIN32 + PyType_GenericNew,/*UPnP_new,*/ /* tp_new */ +#else + 0, +#endif +}; + +/* module methods */ +static PyMethodDef miniupnpc_methods[] = { + {NULL} /* Sentinel */ +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "miniupnpc", /* m_name */ + "miniupnpc module.", /* m_doc */ + -1, /* m_size */ + miniupnpc_methods, /* m_methods */ + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL, /* m_free */ +}; +#endif + +#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ +#define PyMODINIT_FUNC void +#endif + +PyMODINIT_FUNC +#if PY_MAJOR_VERSION >= 3 +PyInit_miniupnpc(void) +#else +initminiupnpc(void) +#endif +{ + PyObject* m; + +#ifdef _WIN32 + /* initialize Winsock. */ + WSADATA wsaData; + int nResult = WSAStartup(MAKEWORD(2,2), &wsaData); + + UPnPType.tp_new = PyType_GenericNew; +#endif + if (PyType_Ready(&UPnPType) < 0) +#if PY_MAJOR_VERSION >= 3 + return 0; +#else + return; +#endif + +#if PY_MAJOR_VERSION >= 3 + m = PyModule_Create(&moduledef); +#else + m = Py_InitModule3("miniupnpc", miniupnpc_methods, + "miniupnpc module."); +#endif + + Py_INCREF(&UPnPType); + PyModule_AddObject(m, "UPnP", (PyObject *)&UPnPType); + +#if PY_MAJOR_VERSION >= 3 + return m; +#endif +} + diff --git a/thirdparty/miniupnpc/miniupnpcstrings.h b/thirdparty/miniupnpc/miniupnpcstrings.h new file mode 100644 index 0000000000..1d5c5882fd --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpcstrings.h @@ -0,0 +1,17 @@ +#ifndef MINIUPNPCSTRINGS_H_INCLUDED +#define MINIUPNPCSTRINGS_H_INCLUDED + +#include <version.h> + +#define OS_STRING VERSION_NAME "/1.0" +#define MINIUPNPC_VERSION_STRING "2.1" + +#if 0 +/* according to "UPnP Device Architecture 1.0" */ +#define UPNP_VERSION_STRING "UPnP/1.0" +#else +/* according to "UPnP Device Architecture 1.1" */ +#define UPNP_VERSION_STRING "UPnP/1.1" +#endif + +#endif diff --git a/thirdparty/miniupnpc/miniupnpctypes.h b/thirdparty/miniupnpc/miniupnpctypes.h new file mode 100644 index 0000000000..307ce39699 --- /dev/null +++ b/thirdparty/miniupnpc/miniupnpctypes.h @@ -0,0 +1,19 @@ +/* $Id: miniupnpctypes.h,v 1.1 2011/02/15 11:10:40 nanard Exp $ */ +/* Miniupnp project : http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org + * Author : Thomas Bernard + * Copyright (c) 2011 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided within this distribution */ +#ifndef MINIUPNPCTYPES_H_INCLUDED +#define MINIUPNPCTYPES_H_INCLUDED + +#if (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L) +#define UNSIGNED_INTEGER unsigned long long +#define STRTOUI strtoull +#else +#define UNSIGNED_INTEGER unsigned int +#define STRTOUI strtoul +#endif + +#endif + diff --git a/thirdparty/miniupnpc/miniwget.c b/thirdparty/miniupnpc/miniwget.c new file mode 100644 index 0000000000..a46ba76022 --- /dev/null +++ b/thirdparty/miniupnpc/miniwget.c @@ -0,0 +1,662 @@ +/* $Id: miniwget.c,v 1.78 2018/03/13 23:22:18 nanard Exp $ */ +/* Project : miniupnp + * Website : http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> +#ifdef _WIN32 +#include <winsock2.h> +#include <ws2tcpip.h> +#include <io.h> +#define MAXHOSTNAMELEN 64 +#define snprintf _snprintf +#define socklen_t int +#ifndef strncasecmp +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#define strncasecmp _memicmp +#else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#define strncasecmp memicmp +#endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */ +#endif /* #ifndef strncasecmp */ +#else /* #ifdef _WIN32 */ +#include <unistd.h> +#include <sys/param.h> +#if defined(__amigaos__) && !defined(__amigaos4__) +#define socklen_t int +#else /* #if defined(__amigaos__) && !defined(__amigaos4__) */ +#include <sys/select.h> +#endif /* #else defined(__amigaos__) && !defined(__amigaos4__) */ +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <net/if.h> +#include <netdb.h> +#define closesocket close +#include <strings.h> +#endif /* #else _WIN32 */ +#ifdef __GNU__ +#define MAXHOSTNAMELEN 64 +#endif /* __GNU__ */ + +#ifndef MIN +#define MIN(x,y) (((x)<(y))?(x):(y)) +#endif /* MIN */ + + +#include "miniupnpcstrings.h" +#include "miniwget.h" +#include "connecthostport.h" +#include "receivedata.h" + +#ifndef MAXHOSTNAMELEN +#define MAXHOSTNAMELEN 64 +#endif + +/* + * Read a HTTP response from a socket. + * Process Content-Length and Transfer-encoding headers. + * return a pointer to the content buffer, which length is saved + * to the length parameter. + */ +void * +getHTTPResponse(SOCKET s, int * size, int * status_code) +{ + char buf[2048]; + int n; + int endofheaders = 0; + int chunked = 0; + int content_length = -1; + unsigned int chunksize = 0; + unsigned int bytestocopy = 0; + /* buffers : */ + char * header_buf; + unsigned int header_buf_len = 2048; + unsigned int header_buf_used = 0; + char * content_buf; + unsigned int content_buf_len = 2048; + unsigned int content_buf_used = 0; + char chunksize_buf[32]; + unsigned int chunksize_buf_index; +#ifdef DEBUG + char * reason_phrase = NULL; + int reason_phrase_len = 0; +#endif + + if(status_code) *status_code = -1; + header_buf = malloc(header_buf_len); + if(header_buf == NULL) + { +#ifdef DEBUG + fprintf(stderr, "%s: Memory allocation error\n", "getHTTPResponse"); +#endif /* DEBUG */ + *size = -1; + return NULL; + } + content_buf = malloc(content_buf_len); + if(content_buf == NULL) + { + free(header_buf); +#ifdef DEBUG + fprintf(stderr, "%s: Memory allocation error\n", "getHTTPResponse"); +#endif /* DEBUG */ + *size = -1; + return NULL; + } + chunksize_buf[0] = '\0'; + chunksize_buf_index = 0; + + while((n = receivedata(s, buf, sizeof(buf), 5000, NULL)) > 0) + { + if(endofheaders == 0) + { + int i; + int linestart=0; + int colon=0; + int valuestart=0; + if(header_buf_used + n > header_buf_len) { + char * tmp = realloc(header_buf, header_buf_used + n); + if(tmp == NULL) { + /* memory allocation error */ + free(header_buf); + free(content_buf); + *size = -1; + return NULL; + } + header_buf = tmp; + header_buf_len = header_buf_used + n; + } + memcpy(header_buf + header_buf_used, buf, n); + header_buf_used += n; + /* search for CR LF CR LF (end of headers) + * recognize also LF LF */ + i = 0; + while(i < ((int)header_buf_used-1) && (endofheaders == 0)) { + if(header_buf[i] == '\r') { + i++; + if(header_buf[i] == '\n') { + i++; + if(i < (int)header_buf_used && header_buf[i] == '\r') { + i++; + if(i < (int)header_buf_used && header_buf[i] == '\n') { + endofheaders = i+1; + } + } + } + } else if(header_buf[i] == '\n') { + i++; + if(header_buf[i] == '\n') { + endofheaders = i+1; + } + } + i++; + } + if(endofheaders == 0) + continue; + /* parse header lines */ + for(i = 0; i < endofheaders - 1; i++) { + if(linestart > 0 && colon <= linestart && header_buf[i]==':') + { + colon = i; + while(i < (endofheaders-1) + && (header_buf[i+1] == ' ' || header_buf[i+1] == '\t')) + i++; + valuestart = i + 1; + } + /* detecting end of line */ + else if(header_buf[i]=='\r' || header_buf[i]=='\n') + { + if(linestart == 0 && status_code) + { + /* Status line + * HTTP-Version SP Status-Code SP Reason-Phrase CRLF */ + int sp; + for(sp = 0; sp < i; sp++) + if(header_buf[sp] == ' ') + { + if(*status_code < 0) + *status_code = atoi(header_buf + sp + 1); + else + { +#ifdef DEBUG + reason_phrase = header_buf + sp + 1; + reason_phrase_len = i - sp - 1; +#endif + break; + } + } +#ifdef DEBUG + printf("HTTP status code = %d, Reason phrase = %.*s\n", + *status_code, reason_phrase_len, reason_phrase); +#endif + } + else if(colon > linestart && valuestart > colon) + { +#ifdef DEBUG + printf("header='%.*s', value='%.*s'\n", + colon-linestart, header_buf+linestart, + i-valuestart, header_buf+valuestart); +#endif + if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart)) + { + content_length = atoi(header_buf+valuestart); +#ifdef DEBUG + printf("Content-Length: %d\n", content_length); +#endif + } + else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart) + && 0==strncasecmp(header_buf+valuestart, "chunked", 7)) + { +#ifdef DEBUG + printf("chunked transfer-encoding!\n"); +#endif + chunked = 1; + } + } + while((i < (int)header_buf_used) && (header_buf[i]=='\r' || header_buf[i] == '\n')) + i++; + linestart = i; + colon = linestart; + valuestart = 0; + } + } + /* copy the remaining of the received data back to buf */ + n = header_buf_used - endofheaders; + memcpy(buf, header_buf + endofheaders, n); + /* if(headers) */ + } + /* if we get there, endofheaders != 0. + * In the other case, there was a continue above */ + /* content */ + if(chunked) + { + int i = 0; + while(i < n) + { + if(chunksize == 0) + { + /* reading chunk size */ + if(chunksize_buf_index == 0) { + /* skipping any leading CR LF */ + if(i<n && buf[i] == '\r') i++; + if(i<n && buf[i] == '\n') i++; + } + while(i<n && isxdigit(buf[i]) + && chunksize_buf_index < (sizeof(chunksize_buf)-1)) + { + chunksize_buf[chunksize_buf_index++] = buf[i]; + chunksize_buf[chunksize_buf_index] = '\0'; + i++; + } + while(i<n && buf[i] != '\r' && buf[i] != '\n') + i++; /* discarding chunk-extension */ + if(i<n && buf[i] == '\r') i++; + if(i<n && buf[i] == '\n') { + unsigned int j; + for(j = 0; j < chunksize_buf_index; j++) { + if(chunksize_buf[j] >= '0' + && chunksize_buf[j] <= '9') + chunksize = (chunksize << 4) + (chunksize_buf[j] - '0'); + else + chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10); + } + chunksize_buf[0] = '\0'; + chunksize_buf_index = 0; + i++; + } else { + /* not finished to get chunksize */ + continue; + } +#ifdef DEBUG + printf("chunksize = %u (%x)\n", chunksize, chunksize); +#endif + if(chunksize == 0) + { +#ifdef DEBUG + printf("end of HTTP content - %d %d\n", i, n); + /*printf("'%.*s'\n", n-i, buf+i);*/ +#endif + goto end_of_stream; + } + } + /* it is guaranteed that (n >= i) */ + bytestocopy = (chunksize < (unsigned int)(n - i))?chunksize:(unsigned int)(n - i); + if((content_buf_used + bytestocopy) > content_buf_len) + { + char * tmp; + if((content_length >= 0) && ((unsigned int)content_length >= (content_buf_used + bytestocopy))) { + content_buf_len = content_length; + } else { + content_buf_len = content_buf_used + bytestocopy; + } + tmp = realloc(content_buf, content_buf_len); + if(tmp == NULL) { + /* memory allocation error */ + free(content_buf); + free(header_buf); + *size = -1; + return NULL; + } + content_buf = tmp; + } + memcpy(content_buf + content_buf_used, buf + i, bytestocopy); + content_buf_used += bytestocopy; + i += bytestocopy; + chunksize -= bytestocopy; + } + } + else + { + /* not chunked */ + if(content_length > 0 + && (content_buf_used + n) > (unsigned int)content_length) { + /* skipping additional bytes */ + n = content_length - content_buf_used; + } + if(content_buf_used + n > content_buf_len) + { + char * tmp; + if(content_length >= 0 + && (unsigned int)content_length >= (content_buf_used + n)) { + content_buf_len = content_length; + } else { + content_buf_len = content_buf_used + n; + } + tmp = realloc(content_buf, content_buf_len); + if(tmp == NULL) { + /* memory allocation error */ + free(content_buf); + free(header_buf); + *size = -1; + return NULL; + } + content_buf = tmp; + } + memcpy(content_buf + content_buf_used, buf, n); + content_buf_used += n; + } + /* use the Content-Length header value if available */ + if(content_length > 0 && content_buf_used >= (unsigned int)content_length) + { +#ifdef DEBUG + printf("End of HTTP content\n"); +#endif + break; + } + } +end_of_stream: + free(header_buf); header_buf = NULL; + *size = content_buf_used; + if(content_buf_used == 0) + { + free(content_buf); + content_buf = NULL; + } + return content_buf; +} + +/* miniwget3() : + * do all the work. + * Return NULL if something failed. */ +static void * +miniwget3(const char * host, + unsigned short port, const char * path, + int * size, char * addr_str, int addr_str_len, + const char * httpversion, unsigned int scope_id, + int * status_code) +{ + char buf[2048]; + SOCKET s; + int n; + int len; + int sent; + void * content; + + *size = 0; + s = connecthostport(host, port, scope_id); + if(ISINVALID(s)) + return NULL; + + /* get address for caller ! */ + if(addr_str) + { + struct sockaddr_storage saddr; + socklen_t saddrlen; + + saddrlen = sizeof(saddr); + if(getsockname(s, (struct sockaddr *)&saddr, &saddrlen) < 0) + { + perror("getsockname"); + } + else + { +#if defined(__amigaos__) && !defined(__amigaos4__) + /* using INT WINAPI WSAAddressToStringA(LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFOA, LPSTR, LPDWORD); + * But his function make a string with the port : nn.nn.nn.nn:port */ +/* if(WSAAddressToStringA((SOCKADDR *)&saddr, sizeof(saddr), + NULL, addr_str, (DWORD *)&addr_str_len)) + { + printf("WSAAddressToStringA() failed : %d\n", WSAGetLastError()); + }*/ + /* the following code is only compatible with ip v4 addresses */ + strncpy(addr_str, inet_ntoa(((struct sockaddr_in *)&saddr)->sin_addr), addr_str_len); +#else +#if 0 + if(saddr.sa_family == AF_INET6) { + inet_ntop(AF_INET6, + &(((struct sockaddr_in6 *)&saddr)->sin6_addr), + addr_str, addr_str_len); + } else { + inet_ntop(AF_INET, + &(((struct sockaddr_in *)&saddr)->sin_addr), + addr_str, addr_str_len); + } +#endif + /* getnameinfo return ip v6 address with the scope identifier + * such as : 2a01:e35:8b2b:7330::%4281128194 */ + n = getnameinfo((const struct sockaddr *)&saddr, saddrlen, + addr_str, addr_str_len, + NULL, 0, + NI_NUMERICHOST | NI_NUMERICSERV); + if(n != 0) { +#ifdef _WIN32 + fprintf(stderr, "getnameinfo() failed : %d\n", n); +#else + fprintf(stderr, "getnameinfo() failed : %s\n", gai_strerror(n)); +#endif + } +#endif + } +#ifdef DEBUG + printf("address miniwget : %s\n", addr_str); +#endif + } + + len = snprintf(buf, sizeof(buf), + "GET %s HTTP/%s\r\n" + "Host: %s:%d\r\n" + "Connection: Close\r\n" + "User-Agent: " OS_STRING ", " UPNP_VERSION_STRING ", MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n" + + "\r\n", + path, httpversion, host, port); + if ((unsigned int)len >= sizeof(buf)) + { + closesocket(s); + return NULL; + } + sent = 0; + /* sending the HTTP request */ + while(sent < len) + { + n = send(s, buf+sent, len-sent, 0); + if(n < 0) + { + perror("send"); + closesocket(s); + return NULL; + } + else + { + sent += n; + } + } + content = getHTTPResponse(s, size, status_code); + closesocket(s); + return content; +} + +/* miniwget2() : + * Call miniwget3(); retry with HTTP/1.1 if 1.0 fails. */ +static void * +miniwget2(const char * host, + unsigned short port, const char * path, + int * size, char * addr_str, int addr_str_len, + unsigned int scope_id, int * status_code) +{ + char * respbuffer; + +#if 1 + respbuffer = miniwget3(host, port, path, size, + addr_str, addr_str_len, "1.1", + scope_id, status_code); +#else + respbuffer = miniwget3(host, port, path, size, + addr_str, addr_str_len, "1.0", + scope_id, status_code); + if (*size == 0) + { +#ifdef DEBUG + printf("Retrying with HTTP/1.1\n"); +#endif + free(respbuffer); + respbuffer = miniwget3(host, port, path, size, + addr_str, addr_str_len, "1.1", + scope_id, status_code); + } +#endif + return respbuffer; +} + + + + +/* parseURL() + * arguments : + * url : source string not modified + * hostname : hostname destination string (size of MAXHOSTNAMELEN+1) + * port : port (destination) + * path : pointer to the path part of the URL + * + * Return values : + * 0 - Failure + * 1 - Success */ +int +parseURL(const char * url, + char * hostname, unsigned short * port, + char * * path, unsigned int * scope_id) +{ + char * p1, *p2, *p3; + if(!url) + return 0; + p1 = strstr(url, "://"); + if(!p1) + return 0; + p1 += 3; + if( (url[0]!='h') || (url[1]!='t') + ||(url[2]!='t') || (url[3]!='p')) + return 0; + memset(hostname, 0, MAXHOSTNAMELEN + 1); + if(*p1 == '[') + { + /* IP v6 : http://[2a00:1450:8002::6a]/path/abc */ + char * scope; + scope = strchr(p1, '%'); + p2 = strchr(p1, ']'); + if(p2 && scope && scope < p2 && scope_id) { + /* parse scope */ +#ifdef IF_NAMESIZE + char tmp[IF_NAMESIZE]; + int l; + scope++; + /* "%25" is just '%' in URL encoding */ + if(scope[0] == '2' && scope[1] == '5') + scope += 2; /* skip "25" */ + l = p2 - scope; + if(l >= IF_NAMESIZE) + l = IF_NAMESIZE - 1; + memcpy(tmp, scope, l); + tmp[l] = '\0'; + *scope_id = if_nametoindex(tmp); + if(*scope_id == 0) { + *scope_id = (unsigned int)strtoul(tmp, NULL, 10); + } +#else + /* under windows, scope is numerical */ + char tmp[8]; + int l; + scope++; + /* "%25" is just '%' in URL encoding */ + if(scope[0] == '2' && scope[1] == '5') + scope += 2; /* skip "25" */ + l = p2 - scope; + if(l >= sizeof(tmp)) + l = sizeof(tmp) - 1; + memcpy(tmp, scope, l); + tmp[l] = '\0'; + *scope_id = (unsigned int)strtoul(tmp, NULL, 10); +#endif + } + p3 = strchr(p1, '/'); + if(p2 && p3) + { + p2++; + strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1))); + if(*p2 == ':') + { + *port = 0; + p2++; + while( (*p2 >= '0') && (*p2 <= '9')) + { + *port *= 10; + *port += (unsigned short)(*p2 - '0'); + p2++; + } + } + else + { + *port = 80; + } + *path = p3; + return 1; + } + } + p2 = strchr(p1, ':'); + p3 = strchr(p1, '/'); + if(!p3) + return 0; + if(!p2 || (p2>p3)) + { + strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p3-p1))); + *port = 80; + } + else + { + strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1))); + *port = 0; + p2++; + while( (*p2 >= '0') && (*p2 <= '9')) + { + *port *= 10; + *port += (unsigned short)(*p2 - '0'); + p2++; + } + } + *path = p3; + return 1; +} + +void * +miniwget(const char * url, int * size, + unsigned int scope_id, int * status_code) +{ + unsigned short port; + char * path; + /* protocol://host:port/chemin */ + char hostname[MAXHOSTNAMELEN+1]; + *size = 0; + if(!parseURL(url, hostname, &port, &path, &scope_id)) + return NULL; +#ifdef DEBUG + printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n", + hostname, port, path, scope_id); +#endif + return miniwget2(hostname, port, path, size, 0, 0, scope_id, status_code); +} + +void * +miniwget_getaddr(const char * url, int * size, + char * addr, int addrlen, unsigned int scope_id, + int * status_code) +{ + unsigned short port; + char * path; + /* protocol://host:port/path */ + char hostname[MAXHOSTNAMELEN+1]; + *size = 0; + if(addr) + addr[0] = '\0'; + if(!parseURL(url, hostname, &port, &path, &scope_id)) + return NULL; +#ifdef DEBUG + printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n", + hostname, port, path, scope_id); +#endif + return miniwget2(hostname, port, path, size, addr, addrlen, scope_id, status_code); +} + diff --git a/thirdparty/miniupnpc/miniwget.h b/thirdparty/miniupnpc/miniwget.h new file mode 100644 index 0000000000..f5572c2544 --- /dev/null +++ b/thirdparty/miniupnpc/miniwget.h @@ -0,0 +1,27 @@ +/* $Id: miniwget.h,v 1.12 2016/01/24 17:24:36 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2016 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#ifndef MINIWGET_H_INCLUDED +#define MINIWGET_H_INCLUDED + +#include "miniupnpc_declspec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +MINIUPNP_LIBSPEC void * miniwget(const char *, int *, unsigned int, int *); + +MINIUPNP_LIBSPEC void * miniwget_getaddr(const char *, int *, char *, int, unsigned int, int *); + +int parseURL(const char *, char *, unsigned short *, char * *, unsigned int *); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/miniupnpc/miniwget_private.h b/thirdparty/miniupnpc/miniwget_private.h new file mode 100644 index 0000000000..e4eaac8085 --- /dev/null +++ b/thirdparty/miniupnpc/miniwget_private.h @@ -0,0 +1,15 @@ +/* $Id: miniwget_private.h,v 1.1 2018/04/06 10:17:58 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#ifndef MINIWGET_INTERNAL_H_INCLUDED +#define MINIWGET_INTERNAL_H_INCLUDED + +#include "miniupnpc_socketdef.h" + +void * getHTTPResponse(SOCKET s, int * size, int * status_code); + +#endif diff --git a/thirdparty/miniupnpc/minixml.c b/thirdparty/miniupnpc/minixml.c new file mode 100644 index 0000000000..ed2d3c759c --- /dev/null +++ b/thirdparty/miniupnpc/minixml.c @@ -0,0 +1,231 @@ +/* $Id: minixml.c,v 1.10 2012/03/05 19:42:47 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * minixml.c : the minimum size a xml parser can be ! */ +/* Project : miniupnp + * webpage: http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * Author : Thomas Bernard + +Copyright (c) 2005-2017, Thomas BERNARD +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +*/ +#include <string.h> +#include "minixml.h" + +/* parseatt : used to parse the argument list + * return 0 (false) in case of success and -1 (true) if the end + * of the xmlbuffer is reached. */ +static int parseatt(struct xmlparser * p) +{ + const char * attname; + int attnamelen; + const char * attvalue; + int attvaluelen; + while(p->xml < p->xmlend) + { + if(*p->xml=='/' || *p->xml=='>') + return 0; + if( !IS_WHITE_SPACE(*p->xml) ) + { + char sep; + attname = p->xml; + attnamelen = 0; + while(*p->xml!='=' && !IS_WHITE_SPACE(*p->xml) ) + { + attnamelen++; p->xml++; + if(p->xml >= p->xmlend) + return -1; + } + while(*(p->xml++) != '=') + { + if(p->xml >= p->xmlend) + return -1; + } + while(IS_WHITE_SPACE(*p->xml)) + { + p->xml++; + if(p->xml >= p->xmlend) + return -1; + } + sep = *p->xml; + if(sep=='\'' || sep=='\"') + { + p->xml++; + if(p->xml >= p->xmlend) + return -1; + attvalue = p->xml; + attvaluelen = 0; + while(*p->xml != sep) + { + attvaluelen++; p->xml++; + if(p->xml >= p->xmlend) + return -1; + } + } + else + { + attvalue = p->xml; + attvaluelen = 0; + while( !IS_WHITE_SPACE(*p->xml) + && *p->xml != '>' && *p->xml != '/') + { + attvaluelen++; p->xml++; + if(p->xml >= p->xmlend) + return -1; + } + } + /*printf("%.*s='%.*s'\n", + attnamelen, attname, attvaluelen, attvalue);*/ + if(p->attfunc) + p->attfunc(p->data, attname, attnamelen, attvalue, attvaluelen); + } + p->xml++; + } + return -1; +} + +/* parseelt parse the xml stream and + * call the callback functions when needed... */ +static void parseelt(struct xmlparser * p) +{ + int i; + const char * elementname; + while(p->xml < (p->xmlend - 1)) + { + if((p->xml + 4) <= p->xmlend && (0 == memcmp(p->xml, "<!--", 4))) + { + p->xml += 3; + /* ignore comments */ + do + { + p->xml++; + if ((p->xml + 3) >= p->xmlend) + return; + } + while(memcmp(p->xml, "-->", 3) != 0); + p->xml += 3; + } + else if((p->xml)[0]=='<' && (p->xml)[1]!='?') + { + i = 0; elementname = ++p->xml; + while( !IS_WHITE_SPACE(*p->xml) + && (*p->xml!='>') && (*p->xml!='/') + ) + { + i++; p->xml++; + if (p->xml >= p->xmlend) + return; + /* to ignore namespace : */ + if(*p->xml==':') + { + i = 0; + elementname = ++p->xml; + } + } + if(i>0) + { + if(p->starteltfunc) + p->starteltfunc(p->data, elementname, i); + if(parseatt(p)) + return; + if(*p->xml!='/') + { + const char * data; + i = 0; data = ++p->xml; + if (p->xml >= p->xmlend) + return; + while( IS_WHITE_SPACE(*p->xml) ) + { + i++; p->xml++; + if (p->xml >= p->xmlend) + return; + } + /* CDATA are at least 9 + 3 characters long : <![CDATA[ ]]> */ + if((p->xmlend >= (p->xml + (9 + 3))) && (memcmp(p->xml, "<![CDATA[", 9) == 0)) + { + /* CDATA handling */ + p->xml += 9; + data = p->xml; + i = 0; + while(memcmp(p->xml, "]]>", 3) != 0) + { + i++; p->xml++; + if ((p->xml + 3) >= p->xmlend) + return; + } + if(i>0 && p->datafunc) + p->datafunc(p->data, data, i); + while(*p->xml!='<') + { + p->xml++; + if (p->xml >= p->xmlend) + return; + } + } + else + { + while(*p->xml!='<') + { + i++; p->xml++; + if ((p->xml + 1) >= p->xmlend) + return; + } + if(i>0 && p->datafunc && *(p->xml + 1) == '/') + p->datafunc(p->data, data, i); + } + } + } + else if(*p->xml == '/') + { + i = 0; elementname = ++p->xml; + if (p->xml >= p->xmlend) + return; + while((*p->xml != '>')) + { + i++; p->xml++; + if (p->xml >= p->xmlend) + return; + } + if(p->endeltfunc) + p->endeltfunc(p->data, elementname, i); + p->xml++; + } + } + else + { + p->xml++; + } + } +} + +/* the parser must be initialized before calling this function */ +void parsexml(struct xmlparser * parser) +{ + parser->xml = parser->xmlstart; + parser->xmlend = parser->xmlstart + parser->xmlsize; + parseelt(parser); +} + + diff --git a/thirdparty/miniupnpc/minixml.h b/thirdparty/miniupnpc/minixml.h new file mode 100644 index 0000000000..19e6f513bf --- /dev/null +++ b/thirdparty/miniupnpc/minixml.h @@ -0,0 +1,37 @@ +/* $Id: minixml.h,v 1.6 2006/11/30 11:47:21 nanard Exp $ */ +/* minimal xml parser + * + * Project : miniupnp + * Website : http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#ifndef MINIXML_H_INCLUDED +#define MINIXML_H_INCLUDED +#define IS_WHITE_SPACE(c) ((c==' ') || (c=='\t') || (c=='\r') || (c=='\n')) + +/* if a callback function pointer is set to NULL, + * the function is not called */ +struct xmlparser { + const char *xmlstart; + const char *xmlend; + const char *xml; /* pointer to current character */ + int xmlsize; + void * data; + void (*starteltfunc) (void *, const char *, int); + void (*endeltfunc) (void *, const char *, int); + void (*datafunc) (void *, const char *, int); + void (*attfunc) (void *, const char *, int, const char *, int); +}; + +/* parsexml() + * the xmlparser structure must be initialized before the call + * the following structure members have to be initialized : + * xmlstart, xmlsize, data, *func + * xml is for internal usage, xmlend is computed automatically */ +void parsexml(struct xmlparser *); + +#endif + diff --git a/thirdparty/miniupnpc/minixmlvalid.c b/thirdparty/miniupnpc/minixmlvalid.c new file mode 100644 index 0000000000..dad1488122 --- /dev/null +++ b/thirdparty/miniupnpc/minixmlvalid.c @@ -0,0 +1,163 @@ +/* $Id: minixmlvalid.c,v 1.7 2015/07/15 12:41:15 nanard Exp $ */ +/* MiniUPnP Project + * http://miniupnp.tuxfamily.org/ or http://miniupnp.free.fr/ + * minixmlvalid.c : + * validation program for the minixml parser + * + * (c) 2006-2011 Thomas Bernard */ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include "minixml.h" + +/* xml event structure */ +struct event { + enum { ELTSTART, ELTEND, ATT, CHARDATA } type; + const char * data; + int len; +}; + +struct eventlist { + int n; + struct event * events; +}; + +/* compare 2 xml event lists + * return 0 if the two lists are equals */ +int evtlistcmp(struct eventlist * a, struct eventlist * b) +{ + int i; + struct event * ae, * be; + if(a->n != b->n) + { + printf("event number not matching : %d != %d\n", a->n, b->n); + /*return 1;*/ + } + for(i=0; i<a->n; i++) + { + ae = a->events + i; + be = b->events + i; + if( (ae->type != be->type) + ||(ae->len != be->len) + ||memcmp(ae->data, be->data, ae->len)) + { + printf("Found a difference : %d '%.*s' != %d '%.*s'\n", + ae->type, ae->len, ae->data, + be->type, be->len, be->data); + return 1; + } + } + return 0; +} + +/* Test data */ +static const char xmldata[] = +"<xmlroot>\n" +" <elt1 att1=\"attvalue1\" att2=\"attvalue2\">" +"character data" +"</elt1> \n \t" +"<elt1b/>" +"<elt1>\n<![CDATA[ <html>stuff !\n ]]> \n</elt1>\n" +"<elt2a> \t<elt2b>chardata1</elt2b><elt2b> chardata2 </elt2b></elt2a>" +"</xmlroot>"; + +static const struct event evtref[] = +{ + {ELTSTART, "xmlroot", 7}, + {ELTSTART, "elt1", 4}, + /* attributes */ + {CHARDATA, "character data", 14}, + {ELTEND, "elt1", 4}, + {ELTSTART, "elt1b", 5}, + {ELTSTART, "elt1", 4}, + {CHARDATA, " <html>stuff !\n ", 16}, + {ELTEND, "elt1", 4}, + {ELTSTART, "elt2a", 5}, + {ELTSTART, "elt2b", 5}, + {CHARDATA, "chardata1", 9}, + {ELTEND, "elt2b", 5}, + {ELTSTART, "elt2b", 5}, + {CHARDATA, " chardata2 ", 11}, + {ELTEND, "elt2b", 5}, + {ELTEND, "elt2a", 5}, + {ELTEND, "xmlroot", 7} +}; + +void startelt(void * data, const char * p, int l) +{ + struct eventlist * evtlist = data; + struct event * evt; + evt = evtlist->events + evtlist->n; + /*printf("startelt : %.*s\n", l, p);*/ + evt->type = ELTSTART; + evt->data = p; + evt->len = l; + evtlist->n++; +} + +void endelt(void * data, const char * p, int l) +{ + struct eventlist * evtlist = data; + struct event * evt; + evt = evtlist->events + evtlist->n; + /*printf("endelt : %.*s\n", l, p);*/ + evt->type = ELTEND; + evt->data = p; + evt->len = l; + evtlist->n++; +} + +void chardata(void * data, const char * p, int l) +{ + struct eventlist * evtlist = data; + struct event * evt; + evt = evtlist->events + evtlist->n; + /*printf("chardata : '%.*s'\n", l, p);*/ + evt->type = CHARDATA; + evt->data = p; + evt->len = l; + evtlist->n++; +} + +int testxmlparser(const char * xml, int size) +{ + int r; + struct eventlist evtlist; + struct eventlist evtlistref; + struct xmlparser parser; + evtlist.n = 0; + evtlist.events = malloc(sizeof(struct event)*100); + if(evtlist.events == NULL) + { + fprintf(stderr, "Memory allocation error.\n"); + return -1; + } + memset(&parser, 0, sizeof(parser)); + parser.xmlstart = xml; + parser.xmlsize = size; + parser.data = &evtlist; + parser.starteltfunc = startelt; + parser.endeltfunc = endelt; + parser.datafunc = chardata; + parsexml(&parser); + printf("%d events\n", evtlist.n); + /* compare */ + evtlistref.n = sizeof(evtref)/sizeof(struct event); + evtlistref.events = (struct event *)evtref; + r = evtlistcmp(&evtlistref, &evtlist); + free(evtlist.events); + return r; +} + +int main(int argc, char * * argv) +{ + int r; + (void)argc; (void)argv; + + r = testxmlparser(xmldata, sizeof(xmldata)-1); + if(r) + printf("minixml validation test failed\n"); + return r; +} + diff --git a/thirdparty/miniupnpc/portlistingparse.c b/thirdparty/miniupnpc/portlistingparse.c new file mode 100644 index 0000000000..55859f2714 --- /dev/null +++ b/thirdparty/miniupnpc/portlistingparse.c @@ -0,0 +1,172 @@ +/* $Id: portlistingparse.c,v 1.9 2015/07/15 12:41:13 nanard Exp $ */ +/* MiniUPnP project + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * (c) 2011-2016 Thomas Bernard + * This software is subject to the conditions detailed + * in the LICENCE file provided within the distribution */ +#include <string.h> +#include <stdlib.h> +#ifdef DEBUG +#include <stdio.h> +#endif /* DEBUG */ +#include "portlistingparse.h" +#include "minixml.h" + +/* list of the elements */ +static const struct { + const portMappingElt code; + const char * const str; +} elements[] = { + { PortMappingEntry, "PortMappingEntry"}, + { NewRemoteHost, "NewRemoteHost"}, + { NewExternalPort, "NewExternalPort"}, + { NewProtocol, "NewProtocol"}, + { NewInternalPort, "NewInternalPort"}, + { NewInternalClient, "NewInternalClient"}, + { NewEnabled, "NewEnabled"}, + { NewDescription, "NewDescription"}, + { NewLeaseTime, "NewLeaseTime"}, + { PortMappingEltNone, NULL} +}; + +/* Helper function */ +static UNSIGNED_INTEGER +atoui(const char * p, int l) +{ + UNSIGNED_INTEGER r = 0; + while(l > 0 && *p) + { + if(*p >= '0' && *p <= '9') + r = r*10 + (*p - '0'); + else + break; + p++; + l--; + } + return r; +} + +/* Start element handler */ +static void +startelt(void * d, const char * name, int l) +{ + int i; + struct PortMappingParserData * pdata = (struct PortMappingParserData *)d; + pdata->curelt = PortMappingEltNone; + for(i = 0; elements[i].str; i++) + { + if(strlen(elements[i].str) == (size_t)l && memcmp(name, elements[i].str, l) == 0) + { + pdata->curelt = elements[i].code; + break; + } + } + if(pdata->curelt == PortMappingEntry) + { + struct PortMapping * pm; + pm = calloc(1, sizeof(struct PortMapping)); + if(pm == NULL) + { + /* malloc error */ +#ifdef DEBUG + fprintf(stderr, "%s: error allocating memory", + "startelt"); +#endif /* DEBUG */ + return; + } + pm->l_next = pdata->l_head; /* insert in list */ + pdata->l_head = pm; + } +} + +/* End element handler */ +static void +endelt(void * d, const char * name, int l) +{ + struct PortMappingParserData * pdata = (struct PortMappingParserData *)d; + (void)name; + (void)l; + pdata->curelt = PortMappingEltNone; +} + +/* Data handler */ +static void +data(void * d, const char * data, int l) +{ + struct PortMapping * pm; + struct PortMappingParserData * pdata = (struct PortMappingParserData *)d; + pm = pdata->l_head; + if(!pm) + return; + if(l > 63) + l = 63; + switch(pdata->curelt) + { + case NewRemoteHost: + memcpy(pm->remoteHost, data, l); + pm->remoteHost[l] = '\0'; + break; + case NewExternalPort: + pm->externalPort = (unsigned short)atoui(data, l); + break; + case NewProtocol: + if(l > 3) + l = 3; + memcpy(pm->protocol, data, l); + pm->protocol[l] = '\0'; + break; + case NewInternalPort: + pm->internalPort = (unsigned short)atoui(data, l); + break; + case NewInternalClient: + memcpy(pm->internalClient, data, l); + pm->internalClient[l] = '\0'; + break; + case NewEnabled: + pm->enabled = (unsigned char)atoui(data, l); + break; + case NewDescription: + memcpy(pm->description, data, l); + pm->description[l] = '\0'; + break; + case NewLeaseTime: + pm->leaseTime = atoui(data, l); + break; + default: + break; + } +} + + +/* Parse the PortMappingList XML document for IGD version 2 + */ +void +ParsePortListing(const char * buffer, int bufsize, + struct PortMappingParserData * pdata) +{ + struct xmlparser parser; + + memset(pdata, 0, sizeof(struct PortMappingParserData)); + /* init xmlparser */ + parser.xmlstart = buffer; + parser.xmlsize = bufsize; + parser.data = pdata; + parser.starteltfunc = startelt; + parser.endeltfunc = endelt; + parser.datafunc = data; + parser.attfunc = 0; + parsexml(&parser); +} + +void +FreePortListing(struct PortMappingParserData * pdata) +{ + struct PortMapping * pm; + while((pm = pdata->l_head) != NULL) + { + /* remove from list */ + pdata->l_head = pm->l_next; + free(pm); + } +} + diff --git a/thirdparty/miniupnpc/portlistingparse.h b/thirdparty/miniupnpc/portlistingparse.h new file mode 100644 index 0000000000..e3957a3f4c --- /dev/null +++ b/thirdparty/miniupnpc/portlistingparse.h @@ -0,0 +1,65 @@ +/* $Id: portlistingparse.h,v 1.10 2014/11/01 10:37:32 nanard Exp $ */ +/* MiniUPnP project + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * (c) 2011-2015 Thomas Bernard + * This software is subject to the conditions detailed + * in the LICENCE file provided within the distribution */ +#ifndef PORTLISTINGPARSE_H_INCLUDED +#define PORTLISTINGPARSE_H_INCLUDED + +#include "miniupnpc_declspec.h" +/* for the definition of UNSIGNED_INTEGER */ +#include "miniupnpctypes.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* sample of PortMappingEntry : + <p:PortMappingEntry> + <p:NewRemoteHost>202.233.2.1</p:NewRemoteHost> + <p:NewExternalPort>2345</p:NewExternalPort> + <p:NewProtocol>TCP</p:NewProtocol> + <p:NewInternalPort>2345</p:NewInternalPort> + <p:NewInternalClient>192.168.1.137</p:NewInternalClient> + <p:NewEnabled>1</p:NewEnabled> + <p:NewDescription>dooom</p:NewDescription> + <p:NewLeaseTime>345</p:NewLeaseTime> + </p:PortMappingEntry> + */ +typedef enum { PortMappingEltNone, + PortMappingEntry, NewRemoteHost, + NewExternalPort, NewProtocol, + NewInternalPort, NewInternalClient, + NewEnabled, NewDescription, + NewLeaseTime } portMappingElt; + +struct PortMapping { + struct PortMapping * l_next; /* list next element */ + UNSIGNED_INTEGER leaseTime; + unsigned short externalPort; + unsigned short internalPort; + char remoteHost[64]; + char internalClient[64]; + char description[64]; + char protocol[4]; + unsigned char enabled; +}; + +struct PortMappingParserData { + struct PortMapping * l_head; /* list head */ + portMappingElt curelt; +}; + +MINIUPNP_LIBSPEC void +ParsePortListing(const char * buffer, int bufsize, + struct PortMappingParserData * pdata); + +MINIUPNP_LIBSPEC void +FreePortListing(struct PortMappingParserData * pdata); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/miniupnpc/receivedata.c b/thirdparty/miniupnpc/receivedata.c new file mode 100644 index 0000000000..7b9cc5b778 --- /dev/null +++ b/thirdparty/miniupnpc/receivedata.c @@ -0,0 +1,99 @@ +/* $Id: receivedata.c,v 1.7 2015/11/09 21:51:41 nanard Exp $ */ +/* Project : miniupnp + * Website : http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2011-2014 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +#include <stdio.h> +#include <string.h> +#ifdef _WIN32 +#include <winsock2.h> +#include <ws2tcpip.h> +#else /* _WIN32 */ +#include <unistd.h> +#if defined(__amigaos__) && !defined(__amigaos4__) +#define socklen_t int +#else /* #if defined(__amigaos__) && !defined(__amigaos4__) */ +#include <sys/select.h> +#endif /* #else defined(__amigaos__) && !defined(__amigaos4__) */ +#include <sys/socket.h> +#include <netinet/in.h> +#if !defined(__amigaos__) && !defined(__amigaos4__) +#include <poll.h> +#endif /* !defined(__amigaos__) && !defined(__amigaos4__) */ +#include <errno.h> +#define MINIUPNPC_IGNORE_EINTR +#endif /* _WIN32 */ + +#include "receivedata.h" + +int +receivedata(SOCKET socket, + char * data, int length, + int timeout, unsigned int * scope_id) +{ +#ifdef MINIUPNPC_GET_SRC_ADDR + struct sockaddr_storage src_addr; + socklen_t src_addr_len = sizeof(src_addr); +#endif /* MINIUPNPC_GET_SRC_ADDR */ + int n; +#if !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) + /* using poll */ + struct pollfd fds[1]; /* for the poll */ +#ifdef MINIUPNPC_IGNORE_EINTR + do { +#endif /* MINIUPNPC_IGNORE_EINTR */ + fds[0].fd = socket; + fds[0].events = POLLIN; + n = poll(fds, 1, timeout); +#ifdef MINIUPNPC_IGNORE_EINTR + } while(n < 0 && errno == EINTR); +#endif /* MINIUPNPC_IGNORE_EINTR */ + if(n < 0) { + PRINT_SOCKET_ERROR("poll"); + return -1; + } else if(n == 0) { + /* timeout */ + return 0; + } +#else /* !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) */ + /* using select under _WIN32 and amigaos */ + fd_set socketSet; + TIMEVAL timeval; + FD_ZERO(&socketSet); + FD_SET(socket, &socketSet); + timeval.tv_sec = timeout / 1000; + timeval.tv_usec = (timeout % 1000) * 1000; + n = select(FD_SETSIZE, &socketSet, NULL, NULL, &timeval); + if(n < 0) { + PRINT_SOCKET_ERROR("select"); + return -1; + } else if(n == 0) { + return 0; + } +#endif /* !defined(_WIN32) && !defined(__amigaos__) && !defined(__amigaos4__) */ +#ifdef MINIUPNPC_GET_SRC_ADDR + memset(&src_addr, 0, sizeof(src_addr)); + n = recvfrom(socket, data, length, 0, + (struct sockaddr *)&src_addr, &src_addr_len); +#else /* MINIUPNPC_GET_SRC_ADDR */ + n = recv(socket, data, length, 0); +#endif /* MINIUPNPC_GET_SRC_ADDR */ + if(n<0) { + PRINT_SOCKET_ERROR("recv"); + } +#ifdef MINIUPNPC_GET_SRC_ADDR + if (src_addr.ss_family == AF_INET6) { + const struct sockaddr_in6 * src_addr6 = (struct sockaddr_in6 *)&src_addr; +#ifdef DEBUG + printf("scope_id=%u\n", src_addr6->sin6_scope_id); +#endif /* DEBUG */ + if(scope_id) + *scope_id = src_addr6->sin6_scope_id; + } +#endif /* MINIUPNPC_GET_SRC_ADDR */ + return n; +} + diff --git a/thirdparty/miniupnpc/receivedata.h b/thirdparty/miniupnpc/receivedata.h new file mode 100644 index 0000000000..c9fdc561f8 --- /dev/null +++ b/thirdparty/miniupnpc/receivedata.h @@ -0,0 +1,21 @@ +/* $Id: receivedata.h,v 1.3 2012/06/23 22:34:47 nanard Exp $ */ +/* Project: miniupnp + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * Author: Thomas Bernard + * Copyright (c) 2011-2018 Thomas Bernard + * This software is subjects to the conditions detailed + * in the LICENCE file provided within this distribution */ +#ifndef RECEIVEDATA_H_INCLUDED +#define RECEIVEDATA_H_INCLUDED + +#include "miniupnpc_socketdef.h" + +/* Reads data from the specified socket. + * Returns the number of bytes read if successful, zero if no bytes were + * read or if we timed out. Returns negative if there was an error. */ +int receivedata(SOCKET socket, + char * data, int length, + int timeout, unsigned int * scope_id); + +#endif + diff --git a/thirdparty/miniupnpc/upnpc.c b/thirdparty/miniupnpc/upnpc.c new file mode 100644 index 0000000000..0c65cbe8c0 --- /dev/null +++ b/thirdparty/miniupnpc/upnpc.c @@ -0,0 +1,861 @@ +/* $Id: upnpc.c,v 1.119 2018/03/13 23:34:46 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#ifdef _WIN32 +#include <winsock2.h> +#define snprintf _snprintf +#else +/* for IPPROTO_TCP / IPPROTO_UDP */ +#include <netinet/in.h> +#endif +#include <ctype.h> +#include "miniwget.h" +#include "miniupnpc.h" +#include "upnpcommands.h" +#include "portlistingparse.h" +#include "upnperrors.h" +#include "miniupnpcstrings.h" + +/* protofix() checks if protocol is "UDP" or "TCP" + * returns NULL if not */ +const char * protofix(const char * proto) +{ + static const char proto_tcp[4] = { 'T', 'C', 'P', 0}; + static const char proto_udp[4] = { 'U', 'D', 'P', 0}; + int i, b; + for(i=0, b=1; i<4; i++) + b = b && ( (proto[i] == proto_tcp[i]) + || (proto[i] == (proto_tcp[i] | 32)) ); + if(b) + return proto_tcp; + for(i=0, b=1; i<4; i++) + b = b && ( (proto[i] == proto_udp[i]) + || (proto[i] == (proto_udp[i] | 32)) ); + if(b) + return proto_udp; + return 0; +} + +/* is_int() checks if parameter is an integer or not + * 1 for integer + * 0 for not an integer */ +int is_int(char const* s) +{ + if(s == NULL) + return 0; + while(*s) { + /* #define isdigit(c) ((c) >= '0' && (c) <= '9') */ + if(!isdigit(*s)) + return 0; + s++; + } + return 1; +} + +static void DisplayInfos(struct UPNPUrls * urls, + struct IGDdatas * data) +{ + char externalIPAddress[40]; + char connectionType[64]; + char status[64]; + char lastconnerr[64]; + unsigned int uptime = 0; + unsigned int brUp, brDown; + time_t timenow, timestarted; + int r; + if(UPNP_GetConnectionTypeInfo(urls->controlURL, + data->first.servicetype, + connectionType) != UPNPCOMMAND_SUCCESS) + printf("GetConnectionTypeInfo failed.\n"); + else + printf("Connection Type : %s\n", connectionType); + if(UPNP_GetStatusInfo(urls->controlURL, data->first.servicetype, + status, &uptime, lastconnerr) != UPNPCOMMAND_SUCCESS) + printf("GetStatusInfo failed.\n"); + else + printf("Status : %s, uptime=%us, LastConnectionError : %s\n", + status, uptime, lastconnerr); + if(uptime > 0) { + timenow = time(NULL); + timestarted = timenow - uptime; + printf(" Time started : %s", ctime(×tarted)); + } + if(UPNP_GetLinkLayerMaxBitRates(urls->controlURL_CIF, data->CIF.servicetype, + &brDown, &brUp) != UPNPCOMMAND_SUCCESS) { + printf("GetLinkLayerMaxBitRates failed.\n"); + } else { + printf("MaxBitRateDown : %u bps", brDown); + if(brDown >= 1000000) { + printf(" (%u.%u Mbps)", brDown / 1000000, (brDown / 100000) % 10); + } else if(brDown >= 1000) { + printf(" (%u Kbps)", brDown / 1000); + } + printf(" MaxBitRateUp %u bps", brUp); + if(brUp >= 1000000) { + printf(" (%u.%u Mbps)", brUp / 1000000, (brUp / 100000) % 10); + } else if(brUp >= 1000) { + printf(" (%u Kbps)", brUp / 1000); + } + printf("\n"); + } + r = UPNP_GetExternalIPAddress(urls->controlURL, + data->first.servicetype, + externalIPAddress); + if(r != UPNPCOMMAND_SUCCESS) { + printf("GetExternalIPAddress failed. (errorcode=%d)\n", r); + } else { + printf("ExternalIPAddress = %s\n", externalIPAddress); + } +} + +static void GetConnectionStatus(struct UPNPUrls * urls, + struct IGDdatas * data) +{ + unsigned int bytessent, bytesreceived, packetsreceived, packetssent; + DisplayInfos(urls, data); + bytessent = UPNP_GetTotalBytesSent(urls->controlURL_CIF, data->CIF.servicetype); + bytesreceived = UPNP_GetTotalBytesReceived(urls->controlURL_CIF, data->CIF.servicetype); + packetssent = UPNP_GetTotalPacketsSent(urls->controlURL_CIF, data->CIF.servicetype); + packetsreceived = UPNP_GetTotalPacketsReceived(urls->controlURL_CIF, data->CIF.servicetype); + printf("Bytes: Sent: %8u\tRecv: %8u\n", bytessent, bytesreceived); + printf("Packets: Sent: %8u\tRecv: %8u\n", packetssent, packetsreceived); +} + +static void ListRedirections(struct UPNPUrls * urls, + struct IGDdatas * data) +{ + int r; + int i = 0; + char index[6]; + char intClient[40]; + char intPort[6]; + char extPort[6]; + char protocol[4]; + char desc[80]; + char enabled[6]; + char rHost[64]; + char duration[16]; + /*unsigned int num=0; + UPNP_GetPortMappingNumberOfEntries(urls->controlURL, data->servicetype, &num); + printf("PortMappingNumberOfEntries : %u\n", num);*/ + printf(" i protocol exPort->inAddr:inPort description remoteHost leaseTime\n"); + do { + snprintf(index, 6, "%d", i); + rHost[0] = '\0'; enabled[0] = '\0'; + duration[0] = '\0'; desc[0] = '\0'; + extPort[0] = '\0'; intPort[0] = '\0'; intClient[0] = '\0'; + r = UPNP_GetGenericPortMappingEntry(urls->controlURL, + data->first.servicetype, + index, + extPort, intClient, intPort, + protocol, desc, enabled, + rHost, duration); + if(r==0) + /* + printf("%02d - %s %s->%s:%s\tenabled=%s leaseDuration=%s\n" + " desc='%s' rHost='%s'\n", + i, protocol, extPort, intClient, intPort, + enabled, duration, + desc, rHost); + */ + printf("%2d %s %5s->%s:%-5s '%s' '%s' %s\n", + i, protocol, extPort, intClient, intPort, + desc, rHost, duration); + else + printf("GetGenericPortMappingEntry() returned %d (%s)\n", + r, strupnperror(r)); + i++; + } while(r==0); +} + +static void NewListRedirections(struct UPNPUrls * urls, + struct IGDdatas * data) +{ + int r; + int i = 0; + struct PortMappingParserData pdata; + struct PortMapping * pm; + + memset(&pdata, 0, sizeof(struct PortMappingParserData)); + r = UPNP_GetListOfPortMappings(urls->controlURL, + data->first.servicetype, + "0", + "65535", + "TCP", + "1000", + &pdata); + if(r == UPNPCOMMAND_SUCCESS) + { + printf(" i protocol exPort->inAddr:inPort description remoteHost leaseTime\n"); + for(pm = pdata.l_head; pm != NULL; pm = pm->l_next) + { + printf("%2d %s %5hu->%s:%-5hu '%s' '%s' %u\n", + i, pm->protocol, pm->externalPort, pm->internalClient, + pm->internalPort, + pm->description, pm->remoteHost, + (unsigned)pm->leaseTime); + i++; + } + FreePortListing(&pdata); + } + else + { + printf("GetListOfPortMappings() returned %d (%s)\n", + r, strupnperror(r)); + } + r = UPNP_GetListOfPortMappings(urls->controlURL, + data->first.servicetype, + "0", + "65535", + "UDP", + "1000", + &pdata); + if(r == UPNPCOMMAND_SUCCESS) + { + for(pm = pdata.l_head; pm != NULL; pm = pm->l_next) + { + printf("%2d %s %5hu->%s:%-5hu '%s' '%s' %u\n", + i, pm->protocol, pm->externalPort, pm->internalClient, + pm->internalPort, + pm->description, pm->remoteHost, + (unsigned)pm->leaseTime); + i++; + } + FreePortListing(&pdata); + } + else + { + printf("GetListOfPortMappings() returned %d (%s)\n", + r, strupnperror(r)); + } +} + +/* Test function + * 1 - get connection type + * 2 - get extenal ip address + * 3 - Add port mapping + * 4 - get this port mapping from the IGD */ +static int SetRedirectAndTest(struct UPNPUrls * urls, + struct IGDdatas * data, + const char * iaddr, + const char * iport, + const char * eport, + const char * proto, + const char * leaseDuration, + const char * description, + int addAny) +{ + char externalIPAddress[40]; + char intClient[40]; + char intPort[6]; + char reservedPort[6]; + char duration[16]; + int r; + + if(!iaddr || !iport || !eport || !proto) + { + fprintf(stderr, "Wrong arguments\n"); + return -1; + } + proto = protofix(proto); + if(!proto) + { + fprintf(stderr, "invalid protocol\n"); + return -1; + } + + r = UPNP_GetExternalIPAddress(urls->controlURL, + data->first.servicetype, + externalIPAddress); + if(r!=UPNPCOMMAND_SUCCESS) + printf("GetExternalIPAddress failed.\n"); + else + printf("ExternalIPAddress = %s\n", externalIPAddress); + + if (addAny) { + r = UPNP_AddAnyPortMapping(urls->controlURL, data->first.servicetype, + eport, iport, iaddr, description, + proto, 0, leaseDuration, reservedPort); + if(r==UPNPCOMMAND_SUCCESS) + eport = reservedPort; + else + printf("AddAnyPortMapping(%s, %s, %s) failed with code %d (%s)\n", + eport, iport, iaddr, r, strupnperror(r)); + } else { + r = UPNP_AddPortMapping(urls->controlURL, data->first.servicetype, + eport, iport, iaddr, description, + proto, 0, leaseDuration); + if(r!=UPNPCOMMAND_SUCCESS) { + printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", + eport, iport, iaddr, r, strupnperror(r)); + return -2; + } + } + + r = UPNP_GetSpecificPortMappingEntry(urls->controlURL, + data->first.servicetype, + eport, proto, NULL/*remoteHost*/, + intClient, intPort, NULL/*desc*/, + NULL/*enabled*/, duration); + if(r!=UPNPCOMMAND_SUCCESS) { + printf("GetSpecificPortMappingEntry() failed with code %d (%s)\n", + r, strupnperror(r)); + return -2; + } else { + printf("InternalIP:Port = %s:%s\n", intClient, intPort); + printf("external %s:%s %s is redirected to internal %s:%s (duration=%s)\n", + externalIPAddress, eport, proto, intClient, intPort, duration); + } + return 0; +} + +static int +RemoveRedirect(struct UPNPUrls * urls, + struct IGDdatas * data, + const char * eport, + const char * proto, + const char * remoteHost) +{ + int r; + if(!proto || !eport) + { + fprintf(stderr, "invalid arguments\n"); + return -1; + } + proto = protofix(proto); + if(!proto) + { + fprintf(stderr, "protocol invalid\n"); + return -1; + } + r = UPNP_DeletePortMapping(urls->controlURL, data->first.servicetype, eport, proto, remoteHost); + if(r!=UPNPCOMMAND_SUCCESS) { + printf("UPNP_DeletePortMapping() failed with code : %d\n", r); + return -2; + }else { + printf("UPNP_DeletePortMapping() returned : %d\n", r); + } + return 0; +} + +static int +RemoveRedirectRange(struct UPNPUrls * urls, + struct IGDdatas * data, + const char * ePortStart, char const * ePortEnd, + const char * proto, const char * manage) +{ + int r; + + if (!manage) + manage = "0"; + + if(!proto || !ePortStart || !ePortEnd) + { + fprintf(stderr, "invalid arguments\n"); + return -1; + } + proto = protofix(proto); + if(!proto) + { + fprintf(stderr, "protocol invalid\n"); + return -1; + } + r = UPNP_DeletePortMappingRange(urls->controlURL, data->first.servicetype, ePortStart, ePortEnd, proto, manage); + if(r!=UPNPCOMMAND_SUCCESS) { + printf("UPNP_DeletePortMappingRange() failed with code : %d\n", r); + return -2; + }else { + printf("UPNP_DeletePortMappingRange() returned : %d\n", r); + } + return 0; +} + +/* IGD:2, functions for service WANIPv6FirewallControl:1 */ +static void GetFirewallStatus(struct UPNPUrls * urls, struct IGDdatas * data) +{ + unsigned int bytessent, bytesreceived, packetsreceived, packetssent; + int firewallEnabled = 0, inboundPinholeAllowed = 0; + + UPNP_GetFirewallStatus(urls->controlURL_6FC, data->IPv6FC.servicetype, &firewallEnabled, &inboundPinholeAllowed); + printf("FirewallEnabled: %d & Inbound Pinhole Allowed: %d\n", firewallEnabled, inboundPinholeAllowed); + printf("GetFirewallStatus:\n Firewall Enabled: %s\n Inbound Pinhole Allowed: %s\n", (firewallEnabled)? "Yes":"No", (inboundPinholeAllowed)? "Yes":"No"); + + bytessent = UPNP_GetTotalBytesSent(urls->controlURL_CIF, data->CIF.servicetype); + bytesreceived = UPNP_GetTotalBytesReceived(urls->controlURL_CIF, data->CIF.servicetype); + packetssent = UPNP_GetTotalPacketsSent(urls->controlURL_CIF, data->CIF.servicetype); + packetsreceived = UPNP_GetTotalPacketsReceived(urls->controlURL_CIF, data->CIF.servicetype); + printf("Bytes: Sent: %8u\tRecv: %8u\n", bytessent, bytesreceived); + printf("Packets: Sent: %8u\tRecv: %8u\n", packetssent, packetsreceived); +} + +/* Test function + * 1 - Add pinhole + * 2 - Check if pinhole is working from the IGD side */ +static void SetPinholeAndTest(struct UPNPUrls * urls, struct IGDdatas * data, + const char * remoteaddr, const char * eport, + const char * intaddr, const char * iport, + const char * proto, const char * lease_time) +{ + char uniqueID[8]; + /*int isWorking = 0;*/ + int r; + char proto_tmp[8]; + + if(!intaddr || !remoteaddr || !iport || !eport || !proto || !lease_time) + { + fprintf(stderr, "Wrong arguments\n"); + return; + } + if(atoi(proto) == 0) + { + const char * protocol; + protocol = protofix(proto); + if(protocol && (strcmp("TCP", protocol) == 0)) + { + snprintf(proto_tmp, sizeof(proto_tmp), "%d", IPPROTO_TCP); + proto = proto_tmp; + } + else if(protocol && (strcmp("UDP", protocol) == 0)) + { + snprintf(proto_tmp, sizeof(proto_tmp), "%d", IPPROTO_UDP); + proto = proto_tmp; + } + else + { + fprintf(stderr, "invalid protocol\n"); + return; + } + } + r = UPNP_AddPinhole(urls->controlURL_6FC, data->IPv6FC.servicetype, remoteaddr, eport, intaddr, iport, proto, lease_time, uniqueID); + if(r!=UPNPCOMMAND_SUCCESS) + printf("AddPinhole([%s]:%s -> [%s]:%s) failed with code %d (%s)\n", + remoteaddr, eport, intaddr, iport, r, strupnperror(r)); + else + { + printf("AddPinhole: ([%s]:%s -> [%s]:%s) / Pinhole ID = %s\n", + remoteaddr, eport, intaddr, iport, uniqueID); + /*r = UPNP_CheckPinholeWorking(urls->controlURL_6FC, data->servicetype_6FC, uniqueID, &isWorking); + if(r!=UPNPCOMMAND_SUCCESS) + printf("CheckPinholeWorking() failed with code %d (%s)\n", r, strupnperror(r)); + printf("CheckPinholeWorking: Pinhole ID = %s / IsWorking = %s\n", uniqueID, (isWorking)? "Yes":"No");*/ + } +} + +/* Test function + * 1 - Check if pinhole is working from the IGD side + * 2 - Update pinhole */ +static void GetPinholeAndUpdate(struct UPNPUrls * urls, struct IGDdatas * data, + const char * uniqueID, const char * lease_time) +{ + int isWorking = 0; + int r; + + if(!uniqueID || !lease_time) + { + fprintf(stderr, "Wrong arguments\n"); + return; + } + r = UPNP_CheckPinholeWorking(urls->controlURL_6FC, data->IPv6FC.servicetype, uniqueID, &isWorking); + printf("CheckPinholeWorking: Pinhole ID = %s / IsWorking = %s\n", uniqueID, (isWorking)? "Yes":"No"); + if(r!=UPNPCOMMAND_SUCCESS) + printf("CheckPinholeWorking() failed with code %d (%s)\n", r, strupnperror(r)); + if(isWorking || r==709) + { + r = UPNP_UpdatePinhole(urls->controlURL_6FC, data->IPv6FC.servicetype, uniqueID, lease_time); + printf("UpdatePinhole: Pinhole ID = %s with Lease Time: %s\n", uniqueID, lease_time); + if(r!=UPNPCOMMAND_SUCCESS) + printf("UpdatePinhole: ID (%s) failed with code %d (%s)\n", uniqueID, r, strupnperror(r)); + } +} + +/* Test function + * Get pinhole timeout + */ +static void GetPinholeOutboundTimeout(struct UPNPUrls * urls, struct IGDdatas * data, + const char * remoteaddr, const char * eport, + const char * intaddr, const char * iport, + const char * proto) +{ + int timeout = 0; + int r; + + if(!intaddr || !remoteaddr || !iport || !eport || !proto) + { + fprintf(stderr, "Wrong arguments\n"); + return; + } + + r = UPNP_GetOutboundPinholeTimeout(urls->controlURL_6FC, data->IPv6FC.servicetype, remoteaddr, eport, intaddr, iport, proto, &timeout); + if(r!=UPNPCOMMAND_SUCCESS) + printf("GetOutboundPinholeTimeout([%s]:%s -> [%s]:%s) failed with code %d (%s)\n", + intaddr, iport, remoteaddr, eport, r, strupnperror(r)); + else + printf("GetOutboundPinholeTimeout: ([%s]:%s -> [%s]:%s) / Timeout = %d\n", intaddr, iport, remoteaddr, eport, timeout); +} + +static void +GetPinholePackets(struct UPNPUrls * urls, + struct IGDdatas * data, const char * uniqueID) +{ + int r, pinholePackets = 0; + if(!uniqueID) + { + fprintf(stderr, "invalid arguments\n"); + return; + } + r = UPNP_GetPinholePackets(urls->controlURL_6FC, data->IPv6FC.servicetype, uniqueID, &pinholePackets); + if(r!=UPNPCOMMAND_SUCCESS) + printf("GetPinholePackets() failed with code %d (%s)\n", r, strupnperror(r)); + else + printf("GetPinholePackets: Pinhole ID = %s / PinholePackets = %d\n", uniqueID, pinholePackets); +} + +static void +CheckPinhole(struct UPNPUrls * urls, + struct IGDdatas * data, const char * uniqueID) +{ + int r, isWorking = 0; + if(!uniqueID) + { + fprintf(stderr, "invalid arguments\n"); + return; + } + r = UPNP_CheckPinholeWorking(urls->controlURL_6FC, data->IPv6FC.servicetype, uniqueID, &isWorking); + if(r!=UPNPCOMMAND_SUCCESS) + printf("CheckPinholeWorking() failed with code %d (%s)\n", r, strupnperror(r)); + else + printf("CheckPinholeWorking: Pinhole ID = %s / IsWorking = %s\n", uniqueID, (isWorking)? "Yes":"No"); +} + +static void +RemovePinhole(struct UPNPUrls * urls, + struct IGDdatas * data, const char * uniqueID) +{ + int r; + if(!uniqueID) + { + fprintf(stderr, "invalid arguments\n"); + return; + } + r = UPNP_DeletePinhole(urls->controlURL_6FC, data->IPv6FC.servicetype, uniqueID); + printf("UPNP_DeletePinhole() returned : %d\n", r); +} + + +/* sample upnp client program */ +int main(int argc, char ** argv) +{ + char command = 0; + char ** commandargv = 0; + int commandargc = 0; + struct UPNPDev * devlist = 0; + char lanaddr[64] = "unset"; /* my ip address on the LAN */ + int i; + const char * rootdescurl = 0; + const char * multicastif = 0; + const char * minissdpdpath = 0; + int localport = UPNP_LOCAL_PORT_ANY; + int retcode = 0; + int error = 0; + int ipv6 = 0; + unsigned char ttl = 2; /* defaulting to 2 */ + const char * description = 0; + +#ifdef _WIN32 + WSADATA wsaData; + int nResult = WSAStartup(MAKEWORD(2,2), &wsaData); + if(nResult != NO_ERROR) + { + fprintf(stderr, "WSAStartup() failed.\n"); + return -1; + } +#endif + printf("upnpc : miniupnpc library test client, version %s.\n", MINIUPNPC_VERSION_STRING); + printf(" (c) 2005-2018 Thomas Bernard.\n"); + printf("Go to http://miniupnp.free.fr/ or https://miniupnp.tuxfamily.org/\n" + "for more information.\n"); + /* command line processing */ + for(i=1; i<argc; i++) + { + if(0 == strcmp(argv[i], "--help") || 0 == strcmp(argv[i], "-h")) + { + command = 0; + break; + } + if(argv[i][0] == '-') + { + if(argv[i][1] == 'u') + rootdescurl = argv[++i]; + else if(argv[i][1] == 'm') + { + multicastif = argv[++i]; + minissdpdpath = ""; /* Disable usage of minissdpd */ + } + else if(argv[i][1] == 'z') + { + char junk; + if(sscanf(argv[++i], "%d%c", &localport, &junk)!=1 || + localport<0 || localport>65535 || + (localport >1 && localport < 1024)) + { + fprintf(stderr, "Invalid localport '%s'\n", argv[i]); + localport = UPNP_LOCAL_PORT_ANY; + break; + } + } + else if(argv[i][1] == 'p') + minissdpdpath = argv[++i]; + else if(argv[i][1] == '6') + ipv6 = 1; + else if(argv[i][1] == 'e') + description = argv[++i]; + else if(argv[i][1] == 't') + ttl = (unsigned char)atoi(argv[++i]); + else + { + command = argv[i][1]; + i++; + commandargv = argv + i; + commandargc = argc - i; + break; + } + } + else + { + fprintf(stderr, "option '%s' invalid\n", argv[i]); + } + } + + if(!command + || (command == 'a' && commandargc<4) + || (command == 'd' && argc<2) + || (command == 'r' && argc<2) + || (command == 'A' && commandargc<6) + || (command == 'U' && commandargc<2) + || (command == 'D' && commandargc<1)) + { + fprintf(stderr, "Usage :\t%s [options] -a ip port external_port protocol [duration]\n\t\tAdd port redirection\n", argv[0]); + fprintf(stderr, " \t%s [options] -d external_port protocol <remote host>\n\t\tDelete port redirection\n", argv[0]); + fprintf(stderr, " \t%s [options] -s\n\t\tGet Connection status\n", argv[0]); + fprintf(stderr, " \t%s [options] -l\n\t\tList redirections\n", argv[0]); + fprintf(stderr, " \t%s [options] -L\n\t\tList redirections (using GetListOfPortMappings (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -n ip port external_port protocol [duration]\n\t\tAdd (any) port redirection allowing IGD to use alternative external_port (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -N external_port_start external_port_end protocol [manage]\n\t\tDelete range of port redirections (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -r port1 [external_port1] protocol1 [port2 [external_port2] protocol2] [...]\n\t\tAdd all redirections to the current host\n", argv[0]); + fprintf(stderr, " \t%s [options] -A remote_ip remote_port internal_ip internal_port protocol lease_time\n\t\tAdd Pinhole (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -U uniqueID new_lease_time\n\t\tUpdate Pinhole (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -C uniqueID\n\t\tCheck if Pinhole is Working (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -K uniqueID\n\t\tGet Number of packets going through the rule (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -D uniqueID\n\t\tDelete Pinhole (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -S\n\t\tGet Firewall status (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -G remote_ip remote_port internal_ip internal_port protocol\n\t\tGet Outbound Pinhole Timeout (for IGD:2 only)\n", argv[0]); + fprintf(stderr, " \t%s [options] -P\n\t\tGet Presentation url\n", argv[0]); + fprintf(stderr, "\nprotocol is UDP or TCP\n"); + fprintf(stderr, "Options:\n"); + fprintf(stderr, " -e description : set description for port mapping.\n"); + fprintf(stderr, " -6 : use ip v6 instead of ip v4.\n"); + fprintf(stderr, " -u url : bypass discovery process by providing the XML root description url.\n"); + fprintf(stderr, " -m address/interface : provide ip address (ip v4) or interface name (ip v4 or v6) to use for sending SSDP multicast packets.\n"); + fprintf(stderr, " -z localport : SSDP packets local (source) port (1024-65535).\n"); + fprintf(stderr, " -p path : use this path for MiniSSDPd socket.\n"); + fprintf(stderr, " -t ttl : set multicast TTL. Default value is 2.\n"); + return 1; + } + + if( rootdescurl + || (devlist = upnpDiscover(2000, multicastif, minissdpdpath, + localport, ipv6, ttl, &error))) + { + struct UPNPDev * device; + struct UPNPUrls urls; + struct IGDdatas data; + if(devlist) + { + printf("List of UPNP devices found on the network :\n"); + for(device = devlist; device; device = device->pNext) + { + printf(" desc: %s\n st: %s\n\n", + device->descURL, device->st); + } + } + else if(!rootdescurl) + { + printf("upnpDiscover() error code=%d\n", error); + } + i = 1; + if( (rootdescurl && UPNP_GetIGDFromUrl(rootdescurl, &urls, &data, lanaddr, sizeof(lanaddr))) + || (i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)))) + { + switch(i) { + case 1: + printf("Found valid IGD : %s\n", urls.controlURL); + break; + case 2: + printf("Found a (not connected?) IGD : %s\n", urls.controlURL); + printf("Trying to continue anyway\n"); + break; + case 3: + printf("UPnP device found. Is it an IGD ? : %s\n", urls.controlURL); + printf("Trying to continue anyway\n"); + break; + default: + printf("Found device (igd ?) : %s\n", urls.controlURL); + printf("Trying to continue anyway\n"); + } + printf("Local LAN ip address : %s\n", lanaddr); + #if 0 + printf("getting \"%s\"\n", urls.ipcondescURL); + descXML = miniwget(urls.ipcondescURL, &descXMLsize); + if(descXML) + { + /*fwrite(descXML, 1, descXMLsize, stdout);*/ + free(descXML); descXML = NULL; + } + #endif + + switch(command) + { + case 'l': + DisplayInfos(&urls, &data); + ListRedirections(&urls, &data); + break; + case 'L': + NewListRedirections(&urls, &data); + break; + case 'a': + if (SetRedirectAndTest(&urls, &data, + commandargv[0], commandargv[1], + commandargv[2], commandargv[3], + (commandargc > 4)?commandargv[4]:"0", + description, 0) < 0) + retcode = 2; + break; + case 'd': + if (RemoveRedirect(&urls, &data, commandargv[0], commandargv[1], + commandargc > 2 ? commandargv[2] : NULL) < 0) + retcode = 2; + break; + case 'n': /* aNy */ + if (SetRedirectAndTest(&urls, &data, + commandargv[0], commandargv[1], + commandargv[2], commandargv[3], + (commandargc > 4)?commandargv[4]:"0", + description, 1) < 0) + retcode = 2; + break; + case 'N': + if (commandargc < 3) + fprintf(stderr, "too few arguments\n"); + + if (RemoveRedirectRange(&urls, &data, commandargv[0], commandargv[1], commandargv[2], + commandargc > 3 ? commandargv[3] : NULL) < 0) + retcode = 2; + break; + case 's': + GetConnectionStatus(&urls, &data); + break; + case 'r': + i = 0; + while(i<commandargc) + { + if(!is_int(commandargv[i])) { + /* 1st parameter not an integer : error */ + fprintf(stderr, "command -r : %s is not an port number\n", commandargv[i]); + retcode = 1; + break; + } else if(is_int(commandargv[i+1])){ + /* 2nd parameter is an integer : <port> <external_port> <protocol> */ + if (SetRedirectAndTest(&urls, &data, + lanaddr, commandargv[i], + commandargv[i+1], commandargv[i+2], "0", + description, 0) < 0) + retcode = 2; + i+=3; /* 3 parameters parsed */ + } else { + /* 2nd parameter not an integer : <port> <protocol> */ + if (SetRedirectAndTest(&urls, &data, + lanaddr, commandargv[i], + commandargv[i], commandargv[i+1], "0", + description, 0) < 0) + retcode = 2; + i+=2; /* 2 parameters parsed */ + } + } + break; + case 'A': + SetPinholeAndTest(&urls, &data, + commandargv[0], commandargv[1], + commandargv[2], commandargv[3], + commandargv[4], commandargv[5]); + break; + case 'U': + GetPinholeAndUpdate(&urls, &data, + commandargv[0], commandargv[1]); + break; + case 'C': + for(i=0; i<commandargc; i++) + { + CheckPinhole(&urls, &data, commandargv[i]); + } + break; + case 'K': + for(i=0; i<commandargc; i++) + { + GetPinholePackets(&urls, &data, commandargv[i]); + } + break; + case 'D': + for(i=0; i<commandargc; i++) + { + RemovePinhole(&urls, &data, commandargv[i]); + } + break; + case 'S': + GetFirewallStatus(&urls, &data); + break; + case 'G': + GetPinholeOutboundTimeout(&urls, &data, + commandargv[0], commandargv[1], + commandargv[2], commandargv[3], + commandargv[4]); + break; + case 'P': + printf("Presentation URL found:\n"); + printf(" %s\n", data.presentationurl); + break; + default: + fprintf(stderr, "Unknown switch -%c\n", command); + retcode = 1; + } + + FreeUPNPUrls(&urls); + } + else + { + fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n"); + retcode = 1; + } + freeUPNPDevlist(devlist); devlist = 0; + } + else + { + fprintf(stderr, "No IGD UPnP Device found on the network !\n"); + retcode = 1; + } +#ifdef _WIN32 + nResult = WSACleanup(); + if(nResult != NO_ERROR) { + fprintf(stderr, "WSACleanup() failed.\n"); + } +#endif /* _WIN32 */ + return retcode; +} + diff --git a/thirdparty/miniupnpc/upnpcommands.c b/thirdparty/miniupnpc/upnpcommands.c new file mode 100644 index 0000000000..b6a693a93a --- /dev/null +++ b/thirdparty/miniupnpc/upnpcommands.c @@ -0,0 +1,1241 @@ +/* $Id: upnpcommands.c,v 1.49 2018/03/13 23:34:47 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * Project : miniupnp + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided in this distribution. + * */ +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include "upnpcommands.h" +#include "miniupnpc.h" +#include "portlistingparse.h" +#include "upnpreplyparse.h" + +static UNSIGNED_INTEGER +my_atoui(const char * s) +{ + return s ? ((UNSIGNED_INTEGER)STRTOUI(s, NULL, 0)) : 0; +} + +/* + * */ +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesSent(const char * controlURL, + const char * servicetype) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + unsigned int r = 0; + char * p; + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetTotalBytesSent", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + /*DisplayNameValueList(buffer, bufsize);*/ + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "NewTotalBytesSent"); + r = my_atoui(p); + ClearNameValueList(&pdata); + return r; +} + +/* + * */ +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesReceived(const char * controlURL, + const char * servicetype) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + unsigned int r = 0; + char * p; + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetTotalBytesReceived", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + /*DisplayNameValueList(buffer, bufsize);*/ + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "NewTotalBytesReceived"); + r = my_atoui(p); + ClearNameValueList(&pdata); + return r; +} + +/* + * */ +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsSent(const char * controlURL, + const char * servicetype) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + unsigned int r = 0; + char * p; + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetTotalPacketsSent", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + /*DisplayNameValueList(buffer, bufsize);*/ + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "NewTotalPacketsSent"); + r = my_atoui(p); + ClearNameValueList(&pdata); + return r; +} + +/* + * */ +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsReceived(const char * controlURL, + const char * servicetype) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + unsigned int r = 0; + char * p; + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetTotalPacketsReceived", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + /*DisplayNameValueList(buffer, bufsize);*/ + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "NewTotalPacketsReceived"); + r = my_atoui(p); + ClearNameValueList(&pdata); + return r; +} + +/* UPNP_GetStatusInfo() call the corresponding UPNP method + * returns the current status and uptime */ +MINIUPNP_LIBSPEC int +UPNP_GetStatusInfo(const char * controlURL, + const char * servicetype, + char * status, + unsigned int * uptime, + char * lastconnerror) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + char * p; + char * up; + char * err; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!status && !uptime) + return UPNPCOMMAND_INVALID_ARGS; + + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetStatusInfo", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + /*DisplayNameValueList(buffer, bufsize);*/ + free(buffer); buffer = NULL; + up = GetValueFromNameValueList(&pdata, "NewUptime"); + p = GetValueFromNameValueList(&pdata, "NewConnectionStatus"); + err = GetValueFromNameValueList(&pdata, "NewLastConnectionError"); + if(p && up) + ret = UPNPCOMMAND_SUCCESS; + + if(status) { + if(p){ + strncpy(status, p, 64 ); + status[63] = '\0'; + }else + status[0]= '\0'; + } + + if(uptime) { + if(up) + sscanf(up,"%u",uptime); + else + *uptime = 0; + } + + if(lastconnerror) { + if(err) { + strncpy(lastconnerror, err, 64 ); + lastconnerror[63] = '\0'; + } else + lastconnerror[0] = '\0'; + } + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + ClearNameValueList(&pdata); + return ret; +} + +/* UPNP_GetConnectionTypeInfo() call the corresponding UPNP method + * returns the connection type */ +MINIUPNP_LIBSPEC int +UPNP_GetConnectionTypeInfo(const char * controlURL, + const char * servicetype, + char * connectionType) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + char * p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!connectionType) + return UPNPCOMMAND_INVALID_ARGS; + + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetConnectionTypeInfo", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "NewConnectionType"); + /*p = GetValueFromNameValueList(&pdata, "NewPossibleConnectionTypes");*/ + /* PossibleConnectionTypes will have several values.... */ + if(p) { + strncpy(connectionType, p, 64 ); + connectionType[63] = '\0'; + ret = UPNPCOMMAND_SUCCESS; + } else + connectionType[0] = '\0'; + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + ClearNameValueList(&pdata); + return ret; +} + +/* UPNP_GetLinkLayerMaxBitRate() call the corresponding UPNP method. + * Returns 2 values: Downloadlink bandwidth and Uplink bandwidth. + * One of the values can be null + * Note : GetLinkLayerMaxBitRates belongs to WANPPPConnection:1 only + * We can use the GetCommonLinkProperties from WANCommonInterfaceConfig:1 */ +MINIUPNP_LIBSPEC int +UPNP_GetLinkLayerMaxBitRates(const char * controlURL, + const char * servicetype, + unsigned int * bitrateDown, + unsigned int * bitrateUp) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + char * down; + char * up; + char * p; + + if(!bitrateDown && !bitrateUp) + return UPNPCOMMAND_INVALID_ARGS; + + /* shouldn't we use GetCommonLinkProperties ? */ + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetCommonLinkProperties", 0, &bufsize))) { + /*"GetLinkLayerMaxBitRates", 0, &bufsize);*/ + return UPNPCOMMAND_HTTP_ERROR; + } + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + /*down = GetValueFromNameValueList(&pdata, "NewDownstreamMaxBitRate");*/ + /*up = GetValueFromNameValueList(&pdata, "NewUpstreamMaxBitRate");*/ + down = GetValueFromNameValueList(&pdata, "NewLayer1DownstreamMaxBitRate"); + up = GetValueFromNameValueList(&pdata, "NewLayer1UpstreamMaxBitRate"); + /*GetValueFromNameValueList(&pdata, "NewWANAccessType");*/ + /*GetValueFromNameValueList(&pdata, "NewPhysicalLinkStatus");*/ + if(down && up) + ret = UPNPCOMMAND_SUCCESS; + + if(bitrateDown) { + if(down) + sscanf(down,"%u",bitrateDown); + else + *bitrateDown = 0; + } + + if(bitrateUp) { + if(up) + sscanf(up,"%u",bitrateUp); + else + *bitrateUp = 0; + } + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + ClearNameValueList(&pdata); + return ret; +} + + +/* UPNP_GetExternalIPAddress() call the corresponding UPNP method. + * if the third arg is not null the value is copied to it. + * at least 16 bytes must be available + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR Either an UPnP error code or an unknown error. + * + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + */ +MINIUPNP_LIBSPEC int +UPNP_GetExternalIPAddress(const char * controlURL, + const char * servicetype, + char * extIpAdd) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + char * p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!extIpAdd || !controlURL || !servicetype) + return UPNPCOMMAND_INVALID_ARGS; + + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetExternalIPAddress", 0, &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + /*printf("external ip = %s\n", GetValueFromNameValueList(&pdata, "NewExternalIPAddress") );*/ + p = GetValueFromNameValueList(&pdata, "NewExternalIPAddress"); + if(p) { + strncpy(extIpAdd, p, 16 ); + extIpAdd[15] = '\0'; + ret = UPNPCOMMAND_SUCCESS; + } else + extIpAdd[0] = '\0'; + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_AddPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration) +{ + struct UPNParg * AddPortMappingArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!inPort || !inClient || !proto || !extPort) + return UPNPCOMMAND_INVALID_ARGS; + + AddPortMappingArgs = calloc(9, sizeof(struct UPNParg)); + if(AddPortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + AddPortMappingArgs[0].elt = "NewRemoteHost"; + AddPortMappingArgs[0].val = remoteHost; + AddPortMappingArgs[1].elt = "NewExternalPort"; + AddPortMappingArgs[1].val = extPort; + AddPortMappingArgs[2].elt = "NewProtocol"; + AddPortMappingArgs[2].val = proto; + AddPortMappingArgs[3].elt = "NewInternalPort"; + AddPortMappingArgs[3].val = inPort; + AddPortMappingArgs[4].elt = "NewInternalClient"; + AddPortMappingArgs[4].val = inClient; + AddPortMappingArgs[5].elt = "NewEnabled"; + AddPortMappingArgs[5].val = "1"; + AddPortMappingArgs[6].elt = "NewPortMappingDescription"; + AddPortMappingArgs[6].val = desc?desc:"libminiupnpc"; + AddPortMappingArgs[7].elt = "NewLeaseDuration"; + AddPortMappingArgs[7].val = leaseDuration?leaseDuration:"0"; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "AddPortMapping", AddPortMappingArgs, + &bufsize); + free(AddPortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + /*DisplayNameValueList(buffer, bufsize);*/ + /*buffer[bufsize] = '\0';*/ + /*puts(buffer);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) { + /*printf("AddPortMapping errorCode = '%s'\n", resVal); */ + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } else { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_AddAnyPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration, + char * reservedPort) +{ + struct UPNParg * AddPortMappingArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!inPort || !inClient || !proto || !extPort) + return UPNPCOMMAND_INVALID_ARGS; + + AddPortMappingArgs = calloc(9, sizeof(struct UPNParg)); + if(AddPortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + AddPortMappingArgs[0].elt = "NewRemoteHost"; + AddPortMappingArgs[0].val = remoteHost; + AddPortMappingArgs[1].elt = "NewExternalPort"; + AddPortMappingArgs[1].val = extPort; + AddPortMappingArgs[2].elt = "NewProtocol"; + AddPortMappingArgs[2].val = proto; + AddPortMappingArgs[3].elt = "NewInternalPort"; + AddPortMappingArgs[3].val = inPort; + AddPortMappingArgs[4].elt = "NewInternalClient"; + AddPortMappingArgs[4].val = inClient; + AddPortMappingArgs[5].elt = "NewEnabled"; + AddPortMappingArgs[5].val = "1"; + AddPortMappingArgs[6].elt = "NewPortMappingDescription"; + AddPortMappingArgs[6].val = desc?desc:"libminiupnpc"; + AddPortMappingArgs[7].elt = "NewLeaseDuration"; + AddPortMappingArgs[7].val = leaseDuration?leaseDuration:"0"; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "AddAnyPortMapping", AddPortMappingArgs, + &bufsize); + free(AddPortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } else { + char *p; + + p = GetValueFromNameValueList(&pdata, "NewReservedPort"); + if(p) { + strncpy(reservedPort, p, 6); + reservedPort[5] = '\0'; + ret = UPNPCOMMAND_SUCCESS; + } else { + ret = UPNPCOMMAND_INVALID_RESPONSE; + } + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_DeletePortMapping(const char * controlURL, const char * servicetype, + const char * extPort, const char * proto, + const char * remoteHost) +{ + /*struct NameValueParserData pdata;*/ + struct UPNParg * DeletePortMappingArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!extPort || !proto) + return UPNPCOMMAND_INVALID_ARGS; + + DeletePortMappingArgs = calloc(4, sizeof(struct UPNParg)); + if(DeletePortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + DeletePortMappingArgs[0].elt = "NewRemoteHost"; + DeletePortMappingArgs[0].val = remoteHost; + DeletePortMappingArgs[1].elt = "NewExternalPort"; + DeletePortMappingArgs[1].val = extPort; + DeletePortMappingArgs[2].elt = "NewProtocol"; + DeletePortMappingArgs[2].val = proto; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "DeletePortMapping", + DeletePortMappingArgs, &bufsize); + free(DeletePortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } else { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_DeletePortMappingRange(const char * controlURL, const char * servicetype, + const char * extPortStart, const char * extPortEnd, + const char * proto, + const char * manage) +{ + struct UPNParg * DeletePortMappingArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!extPortStart || !extPortEnd || !proto || !manage) + return UPNPCOMMAND_INVALID_ARGS; + + DeletePortMappingArgs = calloc(5, sizeof(struct UPNParg)); + if(DeletePortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + DeletePortMappingArgs[0].elt = "NewStartPort"; + DeletePortMappingArgs[0].val = extPortStart; + DeletePortMappingArgs[1].elt = "NewEndPort"; + DeletePortMappingArgs[1].val = extPortEnd; + DeletePortMappingArgs[2].elt = "NewProtocol"; + DeletePortMappingArgs[2].val = proto; + DeletePortMappingArgs[3].elt = "NewManage"; + DeletePortMappingArgs[3].val = manage; + + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "DeletePortMappingRange", + DeletePortMappingArgs, &bufsize); + free(DeletePortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } else { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_GetGenericPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * index, + char * extPort, + char * intClient, + char * intPort, + char * protocol, + char * desc, + char * enabled, + char * rHost, + char * duration) +{ + struct NameValueParserData pdata; + struct UPNParg * GetPortMappingArgs; + char * buffer; + int bufsize; + char * p; + int r = UPNPCOMMAND_UNKNOWN_ERROR; + if(!index) + return UPNPCOMMAND_INVALID_ARGS; + intClient[0] = '\0'; + intPort[0] = '\0'; + GetPortMappingArgs = calloc(2, sizeof(struct UPNParg)); + if(GetPortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + GetPortMappingArgs[0].elt = "NewPortMappingIndex"; + GetPortMappingArgs[0].val = index; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetGenericPortMappingEntry", + GetPortMappingArgs, &bufsize); + free(GetPortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + p = GetValueFromNameValueList(&pdata, "NewRemoteHost"); + if(p && rHost) + { + strncpy(rHost, p, 64); + rHost[63] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "NewExternalPort"); + if(p && extPort) + { + strncpy(extPort, p, 6); + extPort[5] = '\0'; + r = UPNPCOMMAND_SUCCESS; + } + p = GetValueFromNameValueList(&pdata, "NewProtocol"); + if(p && protocol) + { + strncpy(protocol, p, 4); + protocol[3] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "NewInternalClient"); + if(p) + { + strncpy(intClient, p, 16); + intClient[15] = '\0'; + r = 0; + } + p = GetValueFromNameValueList(&pdata, "NewInternalPort"); + if(p) + { + strncpy(intPort, p, 6); + intPort[5] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "NewEnabled"); + if(p && enabled) + { + strncpy(enabled, p, 4); + enabled[3] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "NewPortMappingDescription"); + if(p && desc) + { + strncpy(desc, p, 80); + desc[79] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "NewLeaseDuration"); + if(p && duration) + { + strncpy(duration, p, 16); + duration[15] = '\0'; + } + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + r = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &r); + } + ClearNameValueList(&pdata); + return r; +} + +MINIUPNP_LIBSPEC int +UPNP_GetPortMappingNumberOfEntries(const char * controlURL, + const char * servicetype, + unsigned int * numEntries) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + char* p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + if(!(buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetPortMappingNumberOfEntries", 0, + &bufsize))) { + return UPNPCOMMAND_HTTP_ERROR; + } +#ifdef DEBUG + DisplayNameValueList(buffer, bufsize); +#endif + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + p = GetValueFromNameValueList(&pdata, "NewPortMappingNumberOfEntries"); + if(numEntries && p) { + *numEntries = 0; + sscanf(p, "%u", numEntries); + ret = UPNPCOMMAND_SUCCESS; + } + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + + ClearNameValueList(&pdata); + return ret; +} + +/* UPNP_GetSpecificPortMappingEntry retrieves an existing port mapping + * the result is returned in the intClient and intPort strings + * please provide 16 and 6 bytes of data */ +MINIUPNP_LIBSPEC int +UPNP_GetSpecificPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * extPort, + const char * proto, + const char * remoteHost, + char * intClient, + char * intPort, + char * desc, + char * enabled, + char * leaseDuration) +{ + struct NameValueParserData pdata; + struct UPNParg * GetPortMappingArgs; + char * buffer; + int bufsize; + char * p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!intPort || !intClient || !extPort || !proto) + return UPNPCOMMAND_INVALID_ARGS; + + GetPortMappingArgs = calloc(4, sizeof(struct UPNParg)); + if(GetPortMappingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + GetPortMappingArgs[0].elt = "NewRemoteHost"; + GetPortMappingArgs[0].val = remoteHost; + GetPortMappingArgs[1].elt = "NewExternalPort"; + GetPortMappingArgs[1].val = extPort; + GetPortMappingArgs[2].elt = "NewProtocol"; + GetPortMappingArgs[2].val = proto; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetSpecificPortMappingEntry", + GetPortMappingArgs, &bufsize); + free(GetPortMappingArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + p = GetValueFromNameValueList(&pdata, "NewInternalClient"); + if(p) { + strncpy(intClient, p, 16); + intClient[15] = '\0'; + ret = UPNPCOMMAND_SUCCESS; + } else + intClient[0] = '\0'; + + p = GetValueFromNameValueList(&pdata, "NewInternalPort"); + if(p) { + strncpy(intPort, p, 6); + intPort[5] = '\0'; + } else + intPort[0] = '\0'; + + p = GetValueFromNameValueList(&pdata, "NewEnabled"); + if(p && enabled) { + strncpy(enabled, p, 4); + enabled[3] = '\0'; + } + + p = GetValueFromNameValueList(&pdata, "NewPortMappingDescription"); + if(p && desc) { + strncpy(desc, p, 80); + desc[79] = '\0'; + } + + p = GetValueFromNameValueList(&pdata, "NewLeaseDuration"); + if(p && leaseDuration) + { + strncpy(leaseDuration, p, 16); + leaseDuration[15] = '\0'; + } + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + + ClearNameValueList(&pdata); + return ret; +} + +/* UPNP_GetListOfPortMappings() + * + * Possible UPNP Error codes : + * 606 Action not Authorized + * 730 PortMappingNotFound - no port mapping is found in the specified range. + * 733 InconsistantParameters - NewStartPort and NewEndPort values are not + * consistent. + */ +MINIUPNP_LIBSPEC int +UPNP_GetListOfPortMappings(const char * controlURL, + const char * servicetype, + const char * startPort, + const char * endPort, + const char * protocol, + const char * numberOfPorts, + struct PortMappingParserData * data) +{ + struct NameValueParserData pdata; + struct UPNParg * GetListOfPortMappingsArgs; + const char * p; + char * buffer; + int bufsize; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!startPort || !endPort || !protocol) + return UPNPCOMMAND_INVALID_ARGS; + + GetListOfPortMappingsArgs = calloc(6, sizeof(struct UPNParg)); + if(GetListOfPortMappingsArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + GetListOfPortMappingsArgs[0].elt = "NewStartPort"; + GetListOfPortMappingsArgs[0].val = startPort; + GetListOfPortMappingsArgs[1].elt = "NewEndPort"; + GetListOfPortMappingsArgs[1].val = endPort; + GetListOfPortMappingsArgs[2].elt = "NewProtocol"; + GetListOfPortMappingsArgs[2].val = protocol; + GetListOfPortMappingsArgs[3].elt = "NewManage"; + GetListOfPortMappingsArgs[3].val = "1"; + GetListOfPortMappingsArgs[4].elt = "NewNumberOfPorts"; + GetListOfPortMappingsArgs[4].val = numberOfPorts?numberOfPorts:"1000"; + + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetListOfPortMappings", + GetListOfPortMappingsArgs, &bufsize); + free(GetListOfPortMappingsArgs); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + /*p = GetValueFromNameValueList(&pdata, "NewPortListing");*/ + /*if(p) { + printf("NewPortListing : %s\n", p); + }*/ + /*printf("NewPortListing(%d chars) : %s\n", + pdata.portListingLength, pdata.portListing);*/ + if(pdata.portListing) + { + /*struct PortMapping * pm; + int i = 0;*/ + ParsePortListing(pdata.portListing, pdata.portListingLength, + data); + ret = UPNPCOMMAND_SUCCESS; + /* + for(pm = data->head.lh_first; pm != NULL; pm = pm->entries.le_next) + { + printf("%2d %s %5hu->%s:%-5hu '%s' '%s'\n", + i, pm->protocol, pm->externalPort, pm->internalClient, + pm->internalPort, + pm->description, pm->remoteHost); + i++; + } + */ + /*FreePortListing(&data);*/ + } + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + ClearNameValueList(&pdata); + + /*printf("%.*s", bufsize, buffer);*/ + + return ret; +} + +/* IGD:2, functions for service WANIPv6FirewallControl:1 */ +MINIUPNP_LIBSPEC int +UPNP_GetFirewallStatus(const char * controlURL, + const char * servicetype, + int * firewallEnabled, + int * inboundPinholeAllowed) +{ + struct NameValueParserData pdata; + char * buffer; + int bufsize; + char * fe, *ipa, *p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!firewallEnabled || !inboundPinholeAllowed) + return UPNPCOMMAND_INVALID_ARGS; + + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetFirewallStatus", 0, &bufsize); + if(!buffer) { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + fe = GetValueFromNameValueList(&pdata, "FirewallEnabled"); + ipa = GetValueFromNameValueList(&pdata, "InboundPinholeAllowed"); + if(ipa && fe) + ret = UPNPCOMMAND_SUCCESS; + if(fe) + *firewallEnabled = my_atoui(fe); + /*else + *firewallEnabled = 0;*/ + if(ipa) + *inboundPinholeAllowed = my_atoui(ipa); + /*else + *inboundPinholeAllowed = 0;*/ + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) + { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_GetOutboundPinholeTimeout(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + int * opTimeout) +{ + struct UPNParg * GetOutboundPinholeTimeoutArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + char * p; + int ret; + + if(!intPort || !intClient || !proto || !remotePort || !remoteHost) + return UPNPCOMMAND_INVALID_ARGS; + + GetOutboundPinholeTimeoutArgs = calloc(6, sizeof(struct UPNParg)); + if(GetOutboundPinholeTimeoutArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + GetOutboundPinholeTimeoutArgs[0].elt = "RemoteHost"; + GetOutboundPinholeTimeoutArgs[0].val = remoteHost; + GetOutboundPinholeTimeoutArgs[1].elt = "RemotePort"; + GetOutboundPinholeTimeoutArgs[1].val = remotePort; + GetOutboundPinholeTimeoutArgs[2].elt = "Protocol"; + GetOutboundPinholeTimeoutArgs[2].val = proto; + GetOutboundPinholeTimeoutArgs[3].elt = "InternalPort"; + GetOutboundPinholeTimeoutArgs[3].val = intPort; + GetOutboundPinholeTimeoutArgs[4].elt = "InternalClient"; + GetOutboundPinholeTimeoutArgs[4].val = intClient; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetOutboundPinholeTimeout", GetOutboundPinholeTimeoutArgs, &bufsize); + free(GetOutboundPinholeTimeoutArgs); + if(!buffer) + return UPNPCOMMAND_HTTP_ERROR; + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) + { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } + else + { + ret = UPNPCOMMAND_SUCCESS; + p = GetValueFromNameValueList(&pdata, "OutboundPinholeTimeout"); + if(p) + *opTimeout = my_atoui(p); + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_AddPinhole(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + const char * leaseTime, + char * uniqueID) +{ + struct UPNParg * AddPinholeArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + char * p; + int ret; + + if(!intPort || !intClient || !proto || !remoteHost || !remotePort || !leaseTime) + return UPNPCOMMAND_INVALID_ARGS; + + AddPinholeArgs = calloc(7, sizeof(struct UPNParg)); + if(AddPinholeArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + /* RemoteHost can be wilcarded */ + if(strncmp(remoteHost, "empty", 5)==0) + { + AddPinholeArgs[0].elt = "RemoteHost"; + AddPinholeArgs[0].val = ""; + } + else + { + AddPinholeArgs[0].elt = "RemoteHost"; + AddPinholeArgs[0].val = remoteHost; + } + AddPinholeArgs[1].elt = "RemotePort"; + AddPinholeArgs[1].val = remotePort; + AddPinholeArgs[2].elt = "Protocol"; + AddPinholeArgs[2].val = proto; + AddPinholeArgs[3].elt = "InternalPort"; + AddPinholeArgs[3].val = intPort; + if(strncmp(intClient, "empty", 5)==0) + { + AddPinholeArgs[4].elt = "InternalClient"; + AddPinholeArgs[4].val = ""; + } + else + { + AddPinholeArgs[4].elt = "InternalClient"; + AddPinholeArgs[4].val = intClient; + } + AddPinholeArgs[5].elt = "LeaseTime"; + AddPinholeArgs[5].val = leaseTime; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "AddPinhole", AddPinholeArgs, &bufsize); + free(AddPinholeArgs); + if(!buffer) + return UPNPCOMMAND_HTTP_ERROR; + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + p = GetValueFromNameValueList(&pdata, "UniqueID"); + if(p) + { + strncpy(uniqueID, p, 8); + uniqueID[7] = '\0'; + } + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) + { + /*printf("AddPortMapping errorCode = '%s'\n", resVal);*/ + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } + else + { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_UpdatePinhole(const char * controlURL, const char * servicetype, + const char * uniqueID, + const char * leaseTime) +{ + struct UPNParg * UpdatePinholeArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!uniqueID || !leaseTime) + return UPNPCOMMAND_INVALID_ARGS; + + UpdatePinholeArgs = calloc(3, sizeof(struct UPNParg)); + if(UpdatePinholeArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + UpdatePinholeArgs[0].elt = "UniqueID"; + UpdatePinholeArgs[0].val = uniqueID; + UpdatePinholeArgs[1].elt = "NewLeaseTime"; + UpdatePinholeArgs[1].val = leaseTime; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "UpdatePinhole", UpdatePinholeArgs, &bufsize); + free(UpdatePinholeArgs); + if(!buffer) + return UPNPCOMMAND_HTTP_ERROR; + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) + { + /*printf("AddPortMapping errorCode = '%s'\n", resVal); */ + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } + else + { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_DeletePinhole(const char * controlURL, const char * servicetype, const char * uniqueID) +{ + /*struct NameValueParserData pdata;*/ + struct UPNParg * DeletePinholeArgs; + char * buffer; + int bufsize; + struct NameValueParserData pdata; + const char * resVal; + int ret; + + if(!uniqueID) + return UPNPCOMMAND_INVALID_ARGS; + + DeletePinholeArgs = calloc(2, sizeof(struct UPNParg)); + if(DeletePinholeArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + DeletePinholeArgs[0].elt = "UniqueID"; + DeletePinholeArgs[0].val = uniqueID; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "DeletePinhole", DeletePinholeArgs, &bufsize); + free(DeletePinholeArgs); + if(!buffer) + return UPNPCOMMAND_HTTP_ERROR; + /*DisplayNameValueList(buffer, bufsize);*/ + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + resVal = GetValueFromNameValueList(&pdata, "errorCode"); + if(resVal) + { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(resVal, "%d", &ret); + } + else + { + ret = UPNPCOMMAND_SUCCESS; + } + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_CheckPinholeWorking(const char * controlURL, const char * servicetype, + const char * uniqueID, int * isWorking) +{ + struct NameValueParserData pdata; + struct UPNParg * CheckPinholeWorkingArgs; + char * buffer; + int bufsize; + char * p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!uniqueID) + return UPNPCOMMAND_INVALID_ARGS; + + CheckPinholeWorkingArgs = calloc(4, sizeof(struct UPNParg)); + if(CheckPinholeWorkingArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + CheckPinholeWorkingArgs[0].elt = "UniqueID"; + CheckPinholeWorkingArgs[0].val = uniqueID; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "CheckPinholeWorking", CheckPinholeWorkingArgs, &bufsize); + free(CheckPinholeWorkingArgs); + if(!buffer) + { + return UPNPCOMMAND_HTTP_ERROR; + } + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + p = GetValueFromNameValueList(&pdata, "IsWorking"); + if(p) + { + *isWorking=my_atoui(p); + ret = UPNPCOMMAND_SUCCESS; + } + else + *isWorking = 0; + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) + { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + + ClearNameValueList(&pdata); + return ret; +} + +MINIUPNP_LIBSPEC int +UPNP_GetPinholePackets(const char * controlURL, const char * servicetype, + const char * uniqueID, int * packets) +{ + struct NameValueParserData pdata; + struct UPNParg * GetPinholePacketsArgs; + char * buffer; + int bufsize; + char * p; + int ret = UPNPCOMMAND_UNKNOWN_ERROR; + + if(!uniqueID) + return UPNPCOMMAND_INVALID_ARGS; + + GetPinholePacketsArgs = calloc(4, sizeof(struct UPNParg)); + if(GetPinholePacketsArgs == NULL) + return UPNPCOMMAND_MEM_ALLOC_ERROR; + GetPinholePacketsArgs[0].elt = "UniqueID"; + GetPinholePacketsArgs[0].val = uniqueID; + buffer = simpleUPnPcommand(-1, controlURL, servicetype, + "GetPinholePackets", GetPinholePacketsArgs, &bufsize); + free(GetPinholePacketsArgs); + if(!buffer) + return UPNPCOMMAND_HTTP_ERROR; + ParseNameValue(buffer, bufsize, &pdata); + free(buffer); buffer = NULL; + + p = GetValueFromNameValueList(&pdata, "PinholePackets"); + if(p) + { + *packets=my_atoui(p); + ret = UPNPCOMMAND_SUCCESS; + } + + p = GetValueFromNameValueList(&pdata, "errorCode"); + if(p) + { + ret = UPNPCOMMAND_UNKNOWN_ERROR; + sscanf(p, "%d", &ret); + } + + ClearNameValueList(&pdata); + return ret; +} + + diff --git a/thirdparty/miniupnpc/upnpcommands.h b/thirdparty/miniupnpc/upnpcommands.h new file mode 100644 index 0000000000..0c6d501666 --- /dev/null +++ b/thirdparty/miniupnpc/upnpcommands.h @@ -0,0 +1,348 @@ +/* $Id: upnpcommands.h,v 1.32 2018/03/13 23:34:47 nanard Exp $ */ +/* Miniupnp project : http://miniupnp.free.fr/ + * Author : Thomas Bernard + * Copyright (c) 2005-2018 Thomas Bernard + * This software is subject to the conditions detailed in the + * LICENCE file provided within this distribution */ +#ifndef UPNPCOMMANDS_H_INCLUDED +#define UPNPCOMMANDS_H_INCLUDED + +#include "miniupnpc_declspec.h" +#include "miniupnpctypes.h" + +/* MiniUPnPc return codes : */ +#define UPNPCOMMAND_SUCCESS (0) +#define UPNPCOMMAND_UNKNOWN_ERROR (-1) +#define UPNPCOMMAND_INVALID_ARGS (-2) +#define UPNPCOMMAND_HTTP_ERROR (-3) +#define UPNPCOMMAND_INVALID_RESPONSE (-4) +#define UPNPCOMMAND_MEM_ALLOC_ERROR (-5) + +#ifdef __cplusplus +extern "C" { +#endif + +struct PortMappingParserData; + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesSent(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalBytesReceived(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsSent(const char * controlURL, + const char * servicetype); + +MINIUPNP_LIBSPEC UNSIGNED_INTEGER +UPNP_GetTotalPacketsReceived(const char * controlURL, + const char * servicetype); + +/* UPNP_GetStatusInfo() + * status and lastconnerror are 64 byte buffers + * Return values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error code */ +MINIUPNP_LIBSPEC int +UPNP_GetStatusInfo(const char * controlURL, + const char * servicetype, + char * status, + unsigned int * uptime, + char * lastconnerror); + +/* UPNP_GetConnectionTypeInfo() + * argument connectionType is a 64 character buffer + * Return Values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error code */ +MINIUPNP_LIBSPEC int +UPNP_GetConnectionTypeInfo(const char * controlURL, + const char * servicetype, + char * connectionType); + +/* UPNP_GetExternalIPAddress() call the corresponding UPNP method. + * if the third arg is not null the value is copied to it. + * at least 16 bytes must be available + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR Either an UPnP error code or an unknown error. + * + * possible UPnP Errors : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. */ +MINIUPNP_LIBSPEC int +UPNP_GetExternalIPAddress(const char * controlURL, + const char * servicetype, + char * extIpAdd); + +/* UPNP_GetLinkLayerMaxBitRates() + * call WANCommonInterfaceConfig:1#GetCommonLinkProperties + * + * return values : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. */ +MINIUPNP_LIBSPEC int +UPNP_GetLinkLayerMaxBitRates(const char* controlURL, + const char* servicetype, + unsigned int * bitrateDown, + unsigned int * bitrateUp); + +/* UPNP_AddPortMapping() + * if desc is NULL, it will be defaulted to "libminiupnpc" + * remoteHost is usually NULL because IGD don't support it. + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR. Either an UPnP error code or an unknown error. + * + * List of possible UPnP errors for AddPortMapping : + * errorCode errorDescription (short) - Description (long) + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization and + * the sender was not authorized. + * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be + * wild-carded + * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded + * 718 ConflictInMappingEntry - The port mapping entry specified conflicts + * with a mapping assigned previously to another client + * 724 SamePortValuesRequired - Internal and External port values + * must be the same + * 725 OnlyPermanentLeasesSupported - The NAT implementation only supports + * permanent lease times on port mappings + * 726 RemoteHostOnlySupportsWildcard - RemoteHost must be a wildcard + * and cannot be a specific IP address or DNS name + * 727 ExternalPortOnlySupportsWildcard - ExternalPort must be a wildcard and + * cannot be a specific port value + * 728 NoPortMapsAvailable - There are not enough free ports available to + * complete port mapping. + * 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed + * due to conflict with other mechanisms. + * 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded + */ +MINIUPNP_LIBSPEC int +UPNP_AddPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration); + +/* UPNP_AddAnyPortMapping() + * if desc is NULL, it will be defaulted to "libminiupnpc" + * remoteHost is usually NULL because IGD don't support it. + * + * Return values : + * 0 : SUCCESS + * NON ZERO : ERROR. Either an UPnP error code or an unknown error. + * + * List of possible UPnP errors for AddPortMapping : + * errorCode errorDescription (short) - Description (long) + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization and + * the sender was not authorized. + * 715 WildCardNotPermittedInSrcIP - The source IP address cannot be + * wild-carded + * 716 WildCardNotPermittedInExtPort - The external port cannot be wild-carded + * 728 NoPortMapsAvailable - There are not enough free ports available to + * complete port mapping. + * 729 ConflictWithOtherMechanisms - Attempted port mapping is not allowed + * due to conflict with other mechanisms. + * 732 WildCardNotPermittedInIntPort - The internal port cannot be wild-carded + */ +MINIUPNP_LIBSPEC int +UPNP_AddAnyPortMapping(const char * controlURL, const char * servicetype, + const char * extPort, + const char * inPort, + const char * inClient, + const char * desc, + const char * proto, + const char * remoteHost, + const char * leaseDuration, + char * reservedPort); + +/* UPNP_DeletePortMapping() + * Use same argument values as what was used for AddPortMapping(). + * remoteHost is usually NULL because IGD don't support it. + * Return Values : + * 0 : SUCCESS + * NON ZERO : error. Either an UPnP error code or an undefined error. + * + * List of possible UPnP errors for DeletePortMapping : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 714 NoSuchEntryInArray - The specified value does not exist in the array */ +MINIUPNP_LIBSPEC int +UPNP_DeletePortMapping(const char * controlURL, const char * servicetype, + const char * extPort, const char * proto, + const char * remoteHost); + +/* UPNP_DeletePortRangeMapping() + * Use same argument values as what was used for AddPortMapping(). + * remoteHost is usually NULL because IGD don't support it. + * Return Values : + * 0 : SUCCESS + * NON ZERO : error. Either an UPnP error code or an undefined error. + * + * List of possible UPnP errors for DeletePortMapping : + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 730 PortMappingNotFound - This error message is returned if no port + * mapping is found in the specified range. + * 733 InconsistentParameters - NewStartPort and NewEndPort values are not consistent. */ +MINIUPNP_LIBSPEC int +UPNP_DeletePortMappingRange(const char * controlURL, const char * servicetype, + const char * extPortStart, const char * extPortEnd, + const char * proto, + const char * manage); + +/* UPNP_GetPortMappingNumberOfEntries() + * not supported by all routers */ +MINIUPNP_LIBSPEC int +UPNP_GetPortMappingNumberOfEntries(const char* controlURL, + const char* servicetype, + unsigned int * num); + +/* UPNP_GetSpecificPortMappingEntry() + * retrieves an existing port mapping + * params : + * in extPort + * in proto + * in remoteHost + * out intClient (16 bytes) + * out intPort (6 bytes) + * out desc (80 bytes) + * out enabled (4 bytes) + * out leaseDuration (16 bytes) + * + * return value : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. + * + * List of possible UPnP errors for _GetSpecificPortMappingEntry : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 501 Action Failed - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 714 NoSuchEntryInArray - The specified value does not exist in the array. + */ +MINIUPNP_LIBSPEC int +UPNP_GetSpecificPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * extPort, + const char * proto, + const char * remoteHost, + char * intClient, + char * intPort, + char * desc, + char * enabled, + char * leaseDuration); + +/* UPNP_GetGenericPortMappingEntry() + * params : + * in index + * out extPort (6 bytes) + * out intClient (16 bytes) + * out intPort (6 bytes) + * out protocol (4 bytes) + * out desc (80 bytes) + * out enabled (4 bytes) + * out rHost (64 bytes) + * out duration (16 bytes) + * + * return value : + * UPNPCOMMAND_SUCCESS, UPNPCOMMAND_INVALID_ARGS, UPNPCOMMAND_UNKNOWN_ERROR + * or a UPnP Error Code. + * + * Possible UPNP Error codes : + * 402 Invalid Args - See UPnP Device Architecture section on Control. + * 606 Action not authorized - The action requested REQUIRES authorization + * and the sender was not authorized. + * 713 SpecifiedArrayIndexInvalid - The specified array index is out of bounds + */ +MINIUPNP_LIBSPEC int +UPNP_GetGenericPortMappingEntry(const char * controlURL, + const char * servicetype, + const char * index, + char * extPort, + char * intClient, + char * intPort, + char * protocol, + char * desc, + char * enabled, + char * rHost, + char * duration); + +/* UPNP_GetListOfPortMappings() Available in IGD v2 + * + * + * Possible UPNP Error codes : + * 606 Action not Authorized + * 730 PortMappingNotFound - no port mapping is found in the specified range. + * 733 InconsistantParameters - NewStartPort and NewEndPort values are not + * consistent. + */ +MINIUPNP_LIBSPEC int +UPNP_GetListOfPortMappings(const char * controlURL, + const char * servicetype, + const char * startPort, + const char * endPort, + const char * protocol, + const char * numberOfPorts, + struct PortMappingParserData * data); + +/* IGD:2, functions for service WANIPv6FirewallControl:1 */ +MINIUPNP_LIBSPEC int +UPNP_GetFirewallStatus(const char * controlURL, + const char * servicetype, + int * firewallEnabled, + int * inboundPinholeAllowed); + +MINIUPNP_LIBSPEC int +UPNP_GetOutboundPinholeTimeout(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + int * opTimeout); + +MINIUPNP_LIBSPEC int +UPNP_AddPinhole(const char * controlURL, const char * servicetype, + const char * remoteHost, + const char * remotePort, + const char * intClient, + const char * intPort, + const char * proto, + const char * leaseTime, + char * uniqueID); + +MINIUPNP_LIBSPEC int +UPNP_UpdatePinhole(const char * controlURL, const char * servicetype, + const char * uniqueID, + const char * leaseTime); + +MINIUPNP_LIBSPEC int +UPNP_DeletePinhole(const char * controlURL, const char * servicetype, const char * uniqueID); + +MINIUPNP_LIBSPEC int +UPNP_CheckPinholeWorking(const char * controlURL, const char * servicetype, + const char * uniqueID, int * isWorking); + +MINIUPNP_LIBSPEC int +UPNP_GetPinholePackets(const char * controlURL, const char * servicetype, + const char * uniqueID, int * packets); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/thirdparty/miniupnpc/upnpdev.c b/thirdparty/miniupnpc/upnpdev.c new file mode 100644 index 0000000000..d89a9934c3 --- /dev/null +++ b/thirdparty/miniupnpc/upnpdev.c @@ -0,0 +1,23 @@ +/* $Id: upnpdev.c,v 1.1 2015/08/28 12:14:19 nanard Exp $ */ +/* Project : miniupnp + * Web : http://miniupnp.free.fr/ + * Author : Thomas BERNARD + * copyright (c) 2005-2015 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENSE file. */ +#include <stdlib.h> +#include "upnpdev.h" + +/* freeUPNPDevlist() should be used to + * free the chained list returned by upnpDiscover() */ +void freeUPNPDevlist(struct UPNPDev * devlist) +{ + struct UPNPDev * next; + while(devlist) + { + next = devlist->pNext; + free(devlist); + devlist = next; + } +} + diff --git a/thirdparty/miniupnpc/upnpdev.h b/thirdparty/miniupnpc/upnpdev.h new file mode 100644 index 0000000000..f4ae174426 --- /dev/null +++ b/thirdparty/miniupnpc/upnpdev.h @@ -0,0 +1,36 @@ +/* $Id: upnpdev.h,v 1.1 2015/08/28 12:14:19 nanard Exp $ */ +/* Project : miniupnp + * Web : http://miniupnp.free.fr/ + * Author : Thomas BERNARD + * copyright (c) 2005-2018 Thomas Bernard + * This software is subjet to the conditions detailed in the + * provided LICENSE file. */ +#ifndef UPNPDEV_H_INCLUDED +#define UPNPDEV_H_INCLUDED + +#include "miniupnpc_declspec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct UPNPDev { + struct UPNPDev * pNext; + char * descURL; + char * st; + char * usn; + unsigned int scope_id; + char buffer[3]; +}; + +/* freeUPNPDevlist() + * free list returned by upnpDiscover() */ +MINIUPNP_LIBSPEC void freeUPNPDevlist(struct UPNPDev * devlist); + + +#ifdef __cplusplus +} +#endif + + +#endif /* UPNPDEV_H_INCLUDED */ diff --git a/thirdparty/miniupnpc/upnperrors.c b/thirdparty/miniupnpc/upnperrors.c new file mode 100644 index 0000000000..40a2e7857f --- /dev/null +++ b/thirdparty/miniupnpc/upnperrors.c @@ -0,0 +1,107 @@ +/* $Id: upnperrors.c,v 1.5 2011/04/10 11:19:36 nanard Exp $ */ +/* Project : miniupnp + * Author : Thomas BERNARD + * copyright (c) 2007 Thomas Bernard + * All Right reserved. + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * This software is subjet to the conditions detailed in the + * provided LICENCE file. */ +#include <string.h> +#include "upnperrors.h" +#include "upnpcommands.h" +#include "miniupnpc.h" + +const char * strupnperror(int err) +{ + const char * s = NULL; + switch(err) { + case UPNPCOMMAND_SUCCESS: + s = "Success"; + break; + case UPNPCOMMAND_UNKNOWN_ERROR: + s = "Miniupnpc Unknown Error"; + break; + case UPNPCOMMAND_INVALID_ARGS: + s = "Miniupnpc Invalid Arguments"; + break; + case UPNPCOMMAND_INVALID_RESPONSE: + s = "Miniupnpc Invalid response"; + break; + case UPNPDISCOVER_SOCKET_ERROR: + s = "Miniupnpc Socket error"; + break; + case UPNPDISCOVER_MEMORY_ERROR: + s = "Miniupnpc Memory allocation error"; + break; + case 401: + s = "Invalid Action"; + break; + case 402: + s = "Invalid Args"; + break; + case 501: + s = "Action Failed"; + break; + case 606: + s = "Action not authorized"; + break; + case 701: + s = "PinholeSpaceExhausted"; + break; + case 702: + s = "FirewallDisabled"; + break; + case 703: + s = "InboundPinholeNotAllowed"; + break; + case 704: + s = "NoSuchEntry"; + break; + case 705: + s = "ProtocolNotSupported"; + break; + case 706: + s = "InternalPortWildcardingNotAllowed"; + break; + case 707: + s = "ProtocolWildcardingNotAllowed"; + break; + case 708: + s = "WildcardNotPermittedInSrcIP"; + break; + case 709: + s = "NoPacketSent"; + break; + case 713: + s = "SpecifiedArrayIndexInvalid"; + break; + case 714: + s = "NoSuchEntryInArray"; + break; + case 715: + s = "WildCardNotPermittedInSrcIP"; + break; + case 716: + s = "WildCardNotPermittedInExtPort"; + break; + case 718: + s = "ConflictInMappingEntry"; + break; + case 724: + s = "SamePortValuesRequired"; + break; + case 725: + s = "OnlyPermanentLeasesSupported"; + break; + case 726: + s = "RemoteHostOnlySupportsWildcard"; + break; + case 727: + s = "ExternalPortOnlySupportsWildcard"; + break; + default: + s = "UnknownError"; + break; + } + return s; +} diff --git a/thirdparty/miniupnpc/upnperrors.h b/thirdparty/miniupnpc/upnperrors.h new file mode 100644 index 0000000000..8499d9a1c9 --- /dev/null +++ b/thirdparty/miniupnpc/upnperrors.h @@ -0,0 +1,26 @@ +/* $Id: upnperrors.h,v 1.2 2008/07/02 23:31:15 nanard Exp $ */ +/* (c) 2007-2015 Thomas Bernard + * All rights reserved. + * MiniUPnP Project. + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * This software is subjet to the conditions detailed in the + * provided LICENCE file. */ +#ifndef UPNPERRORS_H_INCLUDED +#define UPNPERRORS_H_INCLUDED + +#include "miniupnpc_declspec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* strupnperror() + * Return a string description of the UPnP error code + * or NULL for undefinded errors */ +MINIUPNP_LIBSPEC const char * strupnperror(int err); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/thirdparty/miniupnpc/upnpreplyparse.c b/thirdparty/miniupnpc/upnpreplyparse.c new file mode 100644 index 0000000000..68a47c0278 --- /dev/null +++ b/thirdparty/miniupnpc/upnpreplyparse.c @@ -0,0 +1,196 @@ +/* $Id: upnpreplyparse.c,v 1.19 2015/07/15 10:29:11 nanard Exp $ */ +/* vim: tabstop=4 shiftwidth=4 noexpandtab + * MiniUPnP project + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * (c) 2006-2017 Thomas Bernard + * This software is subject to the conditions detailed + * in the LICENCE file provided within the distribution */ + +#include <stdlib.h> +#include <string.h> +#include <stdio.h> + +#include "upnpreplyparse.h" +#include "minixml.h" + +static void +NameValueParserStartElt(void * d, const char * name, int l) +{ + struct NameValueParserData * data = (struct NameValueParserData *)d; + data->topelt = 1; + if(l>63) + l = 63; + memcpy(data->curelt, name, l); + data->curelt[l] = '\0'; + data->cdata = NULL; + data->cdatalen = 0; +} + +static void +NameValueParserEndElt(void * d, const char * name, int namelen) +{ + struct NameValueParserData * data = (struct NameValueParserData *)d; + struct NameValue * nv; + (void)name; + (void)namelen; + if(!data->topelt) + return; + if(strcmp(data->curelt, "NewPortListing") != 0) + { + int l; + /* standard case. Limited to n chars strings */ + l = data->cdatalen; + nv = malloc(sizeof(struct NameValue)); + if(nv == NULL) + { + /* malloc error */ +#ifdef DEBUG + fprintf(stderr, "%s: error allocating memory", + "NameValueParserEndElt"); +#endif /* DEBUG */ + return; + } + if(l>=(int)sizeof(nv->value)) + l = sizeof(nv->value) - 1; + strncpy(nv->name, data->curelt, 64); + nv->name[63] = '\0'; + if(data->cdata != NULL) + { + memcpy(nv->value, data->cdata, l); + nv->value[l] = '\0'; + } + else + { + nv->value[0] = '\0'; + } + nv->l_next = data->l_head; /* insert in list */ + data->l_head = nv; + } + data->cdata = NULL; + data->cdatalen = 0; + data->topelt = 0; +} + +static void +NameValueParserGetData(void * d, const char * datas, int l) +{ + struct NameValueParserData * data = (struct NameValueParserData *)d; + if(strcmp(data->curelt, "NewPortListing") == 0) + { + /* specific case for NewPortListing which is a XML Document */ + data->portListing = malloc(l + 1); + if(!data->portListing) + { + /* malloc error */ +#ifdef DEBUG + fprintf(stderr, "%s: error allocating memory", + "NameValueParserGetData"); +#endif /* DEBUG */ + return; + } + memcpy(data->portListing, datas, l); + data->portListing[l] = '\0'; + data->portListingLength = l; + } + else + { + /* standard case. */ + data->cdata = datas; + data->cdatalen = l; + } +} + +void +ParseNameValue(const char * buffer, int bufsize, + struct NameValueParserData * data) +{ + struct xmlparser parser; + memset(data, 0, sizeof(struct NameValueParserData)); + /* init xmlparser object */ + parser.xmlstart = buffer; + parser.xmlsize = bufsize; + parser.data = data; + parser.starteltfunc = NameValueParserStartElt; + parser.endeltfunc = NameValueParserEndElt; + parser.datafunc = NameValueParserGetData; + parser.attfunc = 0; + parsexml(&parser); +} + +void +ClearNameValueList(struct NameValueParserData * pdata) +{ + struct NameValue * nv; + if(pdata->portListing) + { + free(pdata->portListing); + pdata->portListing = NULL; + pdata->portListingLength = 0; + } + while((nv = pdata->l_head) != NULL) + { + pdata->l_head = nv->l_next; + free(nv); + } +} + +char * +GetValueFromNameValueList(struct NameValueParserData * pdata, + const char * Name) +{ + struct NameValue * nv; + char * p = NULL; + for(nv = pdata->l_head; + (nv != NULL) && (p == NULL); + nv = nv->l_next) + { + if(strcmp(nv->name, Name) == 0) + p = nv->value; + } + return p; +} + +#if 0 +/* useless now that minixml ignores namespaces by itself */ +char * +GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata, + const char * Name) +{ + struct NameValue * nv; + char * p = NULL; + char * pname; + for(nv = pdata->head.lh_first; + (nv != NULL) && (p == NULL); + nv = nv->entries.le_next) + { + pname = strrchr(nv->name, ':'); + if(pname) + pname++; + else + pname = nv->name; + if(strcmp(pname, Name)==0) + p = nv->value; + } + return p; +} +#endif + +/* debug all-in-one function + * do parsing then display to stdout */ +#ifdef DEBUG +void +DisplayNameValueList(char * buffer, int bufsize) +{ + struct NameValueParserData pdata; + struct NameValue * nv; + ParseNameValue(buffer, bufsize, &pdata); + for(nv = pdata.l_head; + nv != NULL; + nv = nv->l_next) + { + printf("%s = %s\n", nv->name, nv->value); + } + ClearNameValueList(&pdata); +} +#endif /* DEBUG */ + diff --git a/thirdparty/miniupnpc/upnpreplyparse.h b/thirdparty/miniupnpc/upnpreplyparse.h new file mode 100644 index 0000000000..6badd15b26 --- /dev/null +++ b/thirdparty/miniupnpc/upnpreplyparse.h @@ -0,0 +1,63 @@ +/* $Id: upnpreplyparse.h,v 1.19 2014/10/27 16:33:19 nanard Exp $ */ +/* MiniUPnP project + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * (c) 2006-2013 Thomas Bernard + * This software is subject to the conditions detailed + * in the LICENCE file provided within the distribution */ + +#ifndef UPNPREPLYPARSE_H_INCLUDED +#define UPNPREPLYPARSE_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +struct NameValue { + struct NameValue * l_next; + char name[64]; + char value[128]; +}; + +struct NameValueParserData { + struct NameValue * l_head; + char curelt[64]; + char * portListing; + int portListingLength; + int topelt; + const char * cdata; + int cdatalen; +}; + +/* ParseNameValue() */ +void +ParseNameValue(const char * buffer, int bufsize, + struct NameValueParserData * data); + +/* ClearNameValueList() */ +void +ClearNameValueList(struct NameValueParserData * pdata); + +/* GetValueFromNameValueList() */ +char * +GetValueFromNameValueList(struct NameValueParserData * pdata, + const char * Name); + +#if 0 +/* GetValueFromNameValueListIgnoreNS() */ +char * +GetValueFromNameValueListIgnoreNS(struct NameValueParserData * pdata, + const char * Name); +#endif + +/* DisplayNameValueList() */ +#ifdef DEBUG +void +DisplayNameValueList(char * buffer, int bufsize); +#endif + +#ifdef __cplusplus +} +#endif + +#endif + |