Index: ktorrent/ktorrent.notifyrc =================================================================== --- ktorrent/ktorrent.notifyrc +++ ktorrent/ktorrent.notifyrc @@ -429,7 +429,7 @@ Name[bg]=Торентът не може да бъде поставен на опашка Name[bs]=Ne mogu da stavim torent u red Name[ca]=No s'ha pogut posar el torrent a la cua -Name[ca@valencia]=No s'ha pogut posar el torrent a la cua +Name[ca]=No s'ha pogut posar a la cua el torrent Name[cs]=Torrent nelze zařadit do fronty Name[da]=Torrent kan ikke sættes i kø Name[de]=Torrent kann nicht in die Warteschlange eingereiht werden Index: ktorrent/org.kde.ktorrent.desktop =================================================================== --- ktorrent/org.kde.ktorrent.desktop +++ ktorrent/org.kde.ktorrent.desktop @@ -1,7 +1,5 @@ [Desktop Entry] Name=KTorrent -Name[ar]=سيولك -Name[ast]=KTorrent Name[be]=KTorrent Name[bg]=KTorrent Name[bs]=KTorent @@ -124,32 +122,32 @@ MimeType=application/x-bittorrent;application/x-torrent;x-scheme-handler/magnet; X-DBUS-StartupType=Unique X-DBUS-ServiceName=org.kde.ktorrent -Comment=A BitTorrent program by KDE -Comment[ast]=Un programa BitTorrent fechu por KDE -Comment[ca]=Un programa de BitTorrent, creat per la comunitat KDE -Comment[ca@valencia]=Un programa de BitTorrent, creat per la comunitat KDE -Comment[cs]=BitTorrent od KDE -Comment[da]=Et BitTorrent-program fra KDE -Comment[de]=Ein BitTorrent-Programm von KDE -Comment[el]=Μία εφαρμογή BitTorrent από το KDE -Comment[en_GB]=A BitTorrent program by KDE -Comment[es]=Un programa de BitTorrent de KDE -Comment[fr]=Un programme BitTorrent par KDE -Comment[gl]=Un aplicativo BitTorrent por KDE. -Comment[it]=Un programma BitTorrent di KDE -Comment[nl]=Een BitTorrent-programma door KDE -Comment[pl]=Klient bittorrent w ramach KDE -Comment[pt]=Um programa de BitTorrent do KDE -Comment[pt_BR]=Um programa BitTorrent do KDE -Comment[sl]=Program za BitTorrent s strani KDE -Comment[sr]=Битторент програм из КДЕ‑а -Comment[sr@ijekavian]=Битторент програм из КДЕ‑а -Comment[sr@ijekavianlatin]=Bittorrent program iz KDE‑a -Comment[sr@latin]=Bittorrent program iz KDE‑a -Comment[sv]=Ett BitTorrent-program av KDE -Comment[tr]=KDE tarafından BitTorrent uygulaması -Comment[uk]=Програма BitTorrent від KDE -Comment[x-test]=xxA BitTorrent program by KDExx -Comment[zh_CN]=KDE 的 BitTorrent 程序 +X-DBUS-ServiceName=org.ktorrent.ktorrent +Comment=A BitTorrent program for KDE +Comment[be]=Кліент BitTorrent для KDE +Comment[bg]=Клиент за торент в KDE +Comment[bs]=BirTorent program za KDE +Comment[ca]=Un programa de BitTorrent per al KDE +Comment[ca@valencia]=Un programa de BitTorrent per al KDE +Comment[cs]=BitTorrent pro KDE +Comment[da]=Et BitTorrent-program til KDE +Comment[de]=Ein BitTorrent-Programm für die KDE-Arbeitsumgebung +Comment[el]=Μία εφαρμογή BitTorrent για το KDE +Comment[en_GB]=A BitTorrent program for KDE +Comment[es]=Un programa de BitTorrent para KDE +Comment[et]=KDE BitTorrenti rakendus +Comment[fi]=KDE:n BitTorrent-ohjelma +Comment[fr]=Un programme BitTorrent pour KDE +Comment[ga]=Clár BitTorrent KDE +Comment[gl]=Un aplicativo BitTorrent de KDE. +Comment[hne]=केडीई बर बिटटोरेंट प्रोग्राम +Comment[hr]=Program BitTorrent za KDE +Comment[hu]=Egy BitTorrent program KDE-hez +Comment[is]=BitTorrent forrit fyrir KDE +Comment[it]=Un programma BitTorrent per KDE +Comment[ja]=KDE のための BitTorrent プログラム +Comment[kk]=KDE-нің BitTorrent бағдарламасы +Comment[km]=កម្មវិធី BitTorrent សម្រាប់ KDE +Comment[ko]=KDE를 위한 비트토렌트 프로그램 Terminal=false Categories=Qt;KDE;Network;FileTransfer;P2P; Index: plasma/applet/plasma-applet-ktorrent.desktop =================================================================== --- plasma/applet/plasma-applet-ktorrent.desktop +++ plasma/applet/plasma-applet-ktorrent.desktop @@ -67,7 +67,7 @@ Comment[ar]=ودجة بلازما تراقب سيلًا معيّنًا Comment[bs]=Plazma grafička kontrola za praćenje jednog torenta Comment[ca]=Estri de Plasma per a mantenir el seguiment d'un sol torrent -Comment[ca@valencia]=Estri de Plasma per a mantindre el seguiment d'un sol torrent +Comment[ca]=Estri Plasma per a mantenir el seguiment d'un sol torrent Comment[cs]=Plasma widget pro sledování jednoho torrentu Comment[da]=Plasma-widget til at holde styr på en enkelt torrent Comment[de]=Plasmoid zum Überwachen eines einzelnen Torrents Index: plasma/dataengine/plasma-dataengine-ktorrent.desktop =================================================================== --- plasma/dataengine/plasma-dataengine-ktorrent.desktop +++ plasma/dataengine/plasma-dataengine-ktorrent.desktop @@ -1,7 +1,5 @@ [Desktop Entry] Name=KTorrent -Name[ar]=سيولك -Name[ast]=KTorrent Name[be]=KTorrent Name[bg]=KTorrent Name[bs]=KTorent @@ -59,11 +57,9 @@ Name[zh_CN]=KTorrent Name[zh_TW]=KTorrent Comment=KTorrent data engine, for getting information from KTorrent -Comment[ar]=محرّك بيانات «سيولك»، لأخذ المعلومات من «سيولك» -Comment[ast]=Motor de datos de KTorrent pa consiguir información de KTorrent Comment[bs]=KTorentov pogon podataka, za dobivanje informacija od KTorenta -Comment[ca]=Motor de dades del KTorrent, per obtenir informació des del KTorrent -Comment[ca@valencia]=Motor de dades del KTorrent, per obtindre informació des del KTorrent +Comment[ca]=Motor de dades del KTorrent, per obtenir informació del KTorrent +Comment[ca@valencia]=Motor de dades del KTorrent, per obtindre informació del KTorrent Comment[cs]=Datový nástroj KTorrentu pro získání informací z KTorrentu Comment[da]=KTorrrent datamotor, til at hente information fra KTorrent Comment[de]=KTorrent-Datenmodul zum Abrufen von Informationen von KTorrent Index: plugins/htmlinterface/CMakeLists.txt =================================================================== --- plugins/htmlinterface/CMakeLists.txt +++ plugins/htmlinterface/CMakeLists.txt @@ -1,4 +1,4 @@ -set(kthtmlinterfaceplugin_SRC htmlinterfaceplugin.cpp mongoose.c webserver.cpp torrentlistgenerator.cpp) +set(kthtmlinterfaceplugin_SRC htmlinterfaceplugin.cpp webserver.cpp torrentlistgenerator.cpp) ki18n_wrap_ui(kthtmlinterfaceplugin_SRC htmlinterfacewidget.ui) @@ -10,6 +10,7 @@ target_link_libraries( ktorrent_htmlinterface + microhttpd ktcore KF5::Torrent KF5::ConfigCore Index: plugins/htmlinterface/html/3rdpartylicenses.txt =================================================================== --- plugins/htmlinterface/html/3rdpartylicenses.txt +++ plugins/htmlinterface/html/3rdpartylicenses.txt @@ -114,23 +114,23 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@angular/core@5.2.7 +@angular/core@5.2.8 MIT MIT -@angular/platform-browser@5.2.7 +@angular/platform-browser@5.2.8 MIT MIT -@angular/forms@5.2.7 +@angular/forms@5.2.8 MIT MIT -@angular/common@5.2.7 +@angular/common@5.2.8 MIT MIT -@angular/material@5.2.3 +@angular/material@5.2.4 MIT The MIT License @@ -154,7 +154,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@angular/cdk@5.2.3 +@angular/cdk@5.2.4 MIT The MIT License @@ -178,10 +178,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@angular/animations@5.2.7 +@angular/animations@5.2.8 MIT MIT -@angular/platform-browser-dynamic@5.2.7 +@angular/platform-browser-dynamic@5.2.8 MIT MIT \ No newline at end of file Index: plugins/htmlinterface/html/LICENSE =================================================================== --- /dev/null +++ plugins/htmlinterface/html/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, 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 +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. Index: plugins/htmlinterface/html/index.html =================================================================== --- plugins/htmlinterface/html/index.html +++ plugins/htmlinterface/html/index.html @@ -1 +1 @@ -KtorrentWeb \ No newline at end of file +KtorrentWeb \ No newline at end of file Index: plugins/htmlinterface/html/main.67e7326ac7837a7d62a8.bundle.js =================================================================== --- plugins/htmlinterface/html/main.67e7326ac7837a7d62a8.bundle.js +++ /dev/null @@ -1 +0,0 @@ -webpackJsonp([1],{"+3/4":function(t,e,n){"use strict";n.d(e,"a",function(){return o});var r=n("TToO"),o=function(t){function e(e){t.call(this),this.scheduler=e}return Object(r.b)(e,t),e.create=function(t){return new e(t)},e.dispatch=function(t){t.subscriber.complete()},e.prototype._subscribe=function(t){var n=this.scheduler;if(n)return n.schedule(e.dispatch,0,{subscriber:t});t.complete()},e}(n("YaPU").a)},"+CnV":function(t,e,n){"use strict";n.d(e,"a",function(){return r});var r=function(t){var e,r=n("AMGY").a.Symbol;return"function"==typeof r?r.observable?e=r.observable:(e=r("observable"),r.observable=e):e="@@observable",e}()},"/iUD":function(t,e,n){"use strict";e.a=function(t){return"function"==typeof t}},"/nXB":function(t,e,n){"use strict";e.a=function(){for(var t=[],e=0;e1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof l&&(n=t.pop()),null===a&&1===t.length&&t[0]instanceof r.a?t[0]:Object(s.a)(n)(new o.a(t,a))};var r=n("YaPU"),o=n("Veqx"),i=n("1Q68"),s=n("8D5t")},0:function(t,e,n){t.exports=n("x35b")},"1Q68":function(t,e,n){"use strict";e.a=function(t){return t&&"function"==typeof t.schedule}},"3a3m":function(t,e,n){"use strict";var r=n("TToO"),o=n("g5jc"),i=n("YaPU"),s=n("OVmG"),a=n("VwZZ");function l(){return function(t){return t.lift(new u(t))}}var u=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new c(t,n),o=e.subscribe(r);return r.closed||(r.connection=n.connect()),o},t}(),c=function(t){function e(e,n){t.call(this,e),this.connectable=n}return Object(r.b)(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(s.a),h=function(t){function e(e,n){t.call(this),this.source=e,this.subjectFactory=n,this._refCount=0,this._isComplete=!1}return Object(r.b)(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new a.a).add(this.source.subscribe(new d(this.getSubject(),this))),t.closed?(this._connection=null,t=a.a.EMPTY):this._connection=t),t},e.prototype.refCount=function(){return l()(this)},e}(i.a).prototype,p={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:h._subscribe},_isComplete:{value:h._isComplete,writable:!0},getSubject:{value:h.getSubject},connect:{value:h.connect},refCount:{value:h.refCount}},d=function(t){function e(e,n){t.call(this,e),this.connectable=n}return Object(r.b)(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(o.b);function f(){return new o.a}e.a=function(){return function(t){return l()((e=f,function(t){var n;n="function"==typeof e?e:function(){return e};var r=Object.create(t,p);return r.source=t,r.subjectFactory=n,r})(t));var e}}},"8D5t":function(t,e,n){"use strict";var r=n("Qnch");function o(t){return t}e.a=function(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),Object(r.a)(o,null,t)}},AMGY:function(t,e,n){"use strict";(function(t){n.d(e,"a",function(){return i});var r="undefined"!=typeof window&&window,o="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,i=r||"undefined"!=typeof t&&t||o}).call(e,n("DuR2"))},BX3T:function(t,e,n){"use strict";n.d(e,"a",function(){return r});var r=Array.isArray||function(t){return t&&"number"==typeof t.length}},DuR2:function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},GK6M:function(t,e,n){"use strict";e.a=function(t){return r=t,i};var r,o=n("fKB6");function i(){try{return r.apply(this,arguments)}catch(t){return o.a.e=t,o.a}}},Jnfr:function(t,e){function n(t){return Promise.resolve().then(function(){throw new Error("Cannot find module '"+t+"'.")})}n.keys=function(){return[]},n.resolve=n,t.exports=n,n.id="Jnfr"},N4j0:function(t,e,n){"use strict";n.d(e,"a",function(){return r});var r=function(t){return t&&"number"==typeof t.length}},OVmG:function(t,e,n){"use strict";n.d(e,"a",function(){return l});var r=n("TToO"),o=n("/iUD"),i=n("VwZZ"),s=n("t7NR"),a=n("tLDX"),l=function(t){function e(n,r,o){switch(t.call(this),this.syncErrorValue=null,this.syncErrorThrown=!1,this.syncErrorThrowable=!1,this.isStopped=!1,arguments.length){case 0:this.destination=s.a;break;case 1:if(!n){this.destination=s.a;break}if("object"==typeof n){n instanceof e?(this.syncErrorThrowable=n.syncErrorThrowable,this.destination=n,this.destination.add(this)):(this.syncErrorThrowable=!0,this.destination=new u(this,n));break}default:this.syncErrorThrowable=!0,this.destination=new u(this,n,r,o)}}return Object(r.b)(e,t),e.prototype[a.a]=function(){return this},e.create=function(t,n,r){var o=new e(t,n,r);return o.syncErrorThrowable=!1,o},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parent,e=this._parents;return this._parent=null,this._parents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parent=t,this._parents=e,this},e}(i.a),u=function(t){function e(e,n,r,i){var a;t.call(this),this._parentSubscriber=e;var l=this;Object(o.a)(n)?a=n:n&&(a=n.next,r=n.error,i=n.complete,n!==s.a&&(l=Object.create(n),Object(o.a)(l.unsubscribe)&&this.add(l.unsubscribe.bind(l)),l.unsubscribe=this.unsubscribe.bind(this))),this._context=l,this._next=a,this._error=r,this._complete=i}return Object(r.b)(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber;if(this._error)e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else{if(!e.syncErrorThrowable)throw this.unsubscribe(),t;e.syncErrorValue=t,e.syncErrorThrown=!0,this.unsubscribe()}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){throw this.unsubscribe(),t}},e.prototype.__tryOrSetError=function(t,e,n){try{e.call(this._context,n)}catch(e){return t.syncErrorValue=e,t.syncErrorThrown=!0,!0}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(l)},PIsA:function(t,e,n){"use strict";var r=n("AMGY"),o=n("N4j0"),i=n("cQXm"),s=n("dgOU"),a=n("YaPU"),l=n("etqZ"),u=n("TToO"),c=function(t){function e(e,n,r){t.call(this),this.parent=e,this.outerValue=n,this.outerIndex=r,this.index=0}return Object(u.b)(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n("OVmG").a),h=n("+CnV");e.a=function(t,e,n,u){var p=new c(t,n,u);if(p.closed)return null;if(e instanceof a.a)return e._isScalar?(p.next(e.value),p.complete(),null):(p.syncErrorThrowable=!0,e.subscribe(p));if(Object(o.a)(e)){for(var d=0,f=e.length;d0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(i.a)},Rf9G:function(t,e,n){"use strict";e.a=function(){return Object(r.a)()(this)};var r=n("3a3m")},TILf:function(t,e,n){"use strict";n.d(e,"a",function(){return o});var r=n("TToO"),o=function(t){function e(e,n){t.call(this),this.value=e,this.scheduler=n,this._isScalar=!0,n&&(this._isScalar=!1)}return Object(r.b)(e,t),e.create=function(t,n){return new e(t,n)},e.dispatch=function(t){var e=t.value,n=t.subscriber;t.done?n.complete():(n.next(e),n.closed||(t.done=!0,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.value,r=this.scheduler;if(r)return r.schedule(e.dispatch,0,{done:!1,value:n,subscriber:t});t.next(n),t.closed||t.complete()},e}(n("YaPU").a)},TToO:function(t,e,n){"use strict";e.b=function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},n.d(e,"a",function(){return o});var r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?new e(t,r):1===o?new i.a(t[0],r):new s.a(r)},e.dispatch=function(t){var e=t.array,n=t.index,r=t.subscriber;n>=t.count?r.complete():(r.next(e[n]),r.closed||(t.index=n+1,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.array,r=n.length,o=this.scheduler;if(o)return o.schedule(e.dispatch,0,{array:n,index:0,count:r,subscriber:t});for(var i=0;i ");else if("object"==typeof e){var o=[];for(var i in e)if(e.hasOwnProperty(i)){var s=e[i];o.push(i+":"+("string"==typeof s?JSON.stringify(s):T(s)))}r="{"+o.join(", ")+"}"}return"StaticInjectorError"+(n?"("+n+")":"")+"["+r+"]: "+t.replace(H,"\n ")}function X(t,e){return new Error(q(t,e))}var G="ngDebugContext",Z="ngOriginalError",Q="ngErrorLogger";function K(t){return t[G]}function W(t){return t[Z]}function $(t){for(var e=[],n=1;n0)t._bootstrapComponents.forEach(function(t){return e.bootstrap(t)});else{if(!t.instance.ngDoBootstrap)throw new Error("The module "+T(t.instance.constructor)+' was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.');t.instance.ngDoBootstrap(e)}this._modules.push(t)},t.prototype.onDestroy=function(t){this._destroyListeners.push(t)},Object.defineProperty(t.prototype,"injector",{get:function(){return this._injector},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){if(this._destroyed)throw new Error("The platform has already been destroyed!");this._modules.slice().forEach(function(t){return t.destroy()}),this._destroyListeners.forEach(function(t){return t()}),this._destroyed=!0},Object.defineProperty(t.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!0,configurable:!0}),t}();function Kt(t,e){return Array.isArray(e)?e.reduce(Kt,t):Object(r.a)({},t,e)}var Wt=function(){function t(t,e,n,r,a,l){var u=this;this._zone=t,this._console=e,this._injector=n,this._exceptionHandler=r,this._componentFactoryResolver=a,this._initStatus=l,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._enforceNoNewChanges=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._enforceNoNewChanges=qt(),this._zone.onMicrotaskEmpty.subscribe({next:function(){u._zone.run(function(){u.tick()})}});var c=new o.a(function(t){u._stable=u._zone.isStable&&!u._zone.hasPendingMacrotasks&&!u._zone.hasPendingMicrotasks,u._zone.runOutsideAngular(function(){t.next(u._stable),t.complete()})}),h=new o.a(function(t){var e;u._zone.runOutsideAngular(function(){e=u._zone.onStable.subscribe(function(){At.assertNotInAngularZone(),S(function(){u._stable||u._zone.hasPendingMacrotasks||u._zone.hasPendingMicrotasks||(u._stable=!0,t.next(!0))})})});var n=u._zone.onUnstable.subscribe(function(){At.assertInAngularZone(),u._stable&&(u._stable=!1,u._zone.runOutsideAngular(function(){t.next(!1)}))});return function(){e.unsubscribe(),n.unsubscribe()}});this.isStable=Object(i.a)(c,s.a.call(h))}return t.prototype.bootstrap=function(t,e){var n,r=this;if(!this._initStatus.done)throw new Error("Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.");n=t instanceof ft?t:this._componentFactoryResolver.resolveComponentFactory(t),this.componentTypes.push(n.componentType);var o=n instanceof Et?null:this._injector.get(Ct),i=n.create(I.NULL,[],e||n.selector,o);i.onDestroy(function(){r._unloadComponent(i)});var s=i.injector.get(Vt,null);return s&&i.injector.get(Mt).registerApplication(i.location.nativeElement,s),this._loadComponent(i),qt()&&this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode."),i},t.prototype.tick=function(){var e=this;if(this._runningTick)throw new Error("ApplicationRef.tick is called recursively");var n=t._tickScope();try{this._runningTick=!0,this._views.forEach(function(t){return t.detectChanges()}),this._enforceNoNewChanges&&this._views.forEach(function(t){return t.checkNoChanges()})}catch(t){this._zone.runOutsideAngular(function(){return e._exceptionHandler.handleError(t)})}finally{this._runningTick=!1,Tt(n)}},t.prototype.attachView=function(t){var e=t;this._views.push(e),e.attachToAppRef(this)},t.prototype.detachView=function(t){var e=t;$t(this._views,e),e.detachFromAppRef()},t.prototype._loadComponent=function(t){this.attachView(t.hostView),this.tick(),this.components.push(t),this._injector.get(ut,[]).concat(this._bootstrapListeners).forEach(function(e){return e(t)})},t.prototype._unloadComponent=function(t){this.detachView(t.hostView),$t(this.components,t)},t.prototype.ngOnDestroy=function(){this._views.slice().forEach(function(t){return t.destroy()})},Object.defineProperty(t.prototype,"viewCount",{get:function(){return this._views.length},enumerable:!0,configurable:!0}),t._tickScope=Ot("ApplicationRef#tick()"),t}();function $t(t,e){var n=t.indexOf(e);n>-1&&t.splice(n,1)}var Jt=function(){},te=function(){var t={Important:1,DashCase:2};return t[t.Important]="Important",t[t.DashCase]="DashCase",t}(),ee=function(){},ne=function(t){this.nativeElement=t},re=function(){function t(){this.dirty=!0,this._results=[],this.changes=new kt,this.length=0}return t.prototype.map=function(t){return this._results.map(t)},t.prototype.filter=function(t){return this._results.filter(t)},t.prototype.find=function(t){return this._results.find(t)},t.prototype.reduce=function(t,e){return this._results.reduce(t,e)},t.prototype.forEach=function(t){this._results.forEach(t)},t.prototype.some=function(t){return this._results.some(t)},t.prototype.toArray=function(){return this._results.slice()},t.prototype[x()]=function(){return this._results[x()]()},t.prototype.toString=function(){return this._results.toString()},t.prototype.reset=function(t){this._results=function t(e){return e.reduce(function(e,n){var r=Array.isArray(n)?t(n):n;return e.concat(r)},[])}(t),this.dirty=!1,this.length=this._results.length,this.last=this._results[this.length-1],this.first=this._results[0]},t.prototype.notifyOnChanges=function(){this.changes.emit(this)},t.prototype.setDirty=function(){this.dirty=!0},t.prototype.destroy=function(){this.changes.complete(),this.changes.unsubscribe()},t}(),oe=function(){},ie=function(){},se=function(){},ae=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(r.b)(e,t),e}(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(r.b)(e,t),e}(se)),le=function(){function t(t,e,n){this._debugContext=n,this.nativeNode=t,e&&e instanceof ue?e.addChild(this):this.parent=null,this.listeners=[]}return Object.defineProperty(t.prototype,"injector",{get:function(){return this._debugContext.injector},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentInstance",{get:function(){return this._debugContext.component},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._debugContext.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"references",{get:function(){return this._debugContext.references},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"providerTokens",{get:function(){return this._debugContext.providerTokens},enumerable:!0,configurable:!0}),t}(),ue=function(t){function e(e,n,r){var o=t.call(this,e,n,r)||this;return o.properties={},o.attributes={},o.classes={},o.styles={},o.childNodes=[],o.nativeElement=e,o}return Object(r.b)(e,t),e.prototype.addChild=function(t){t&&(this.childNodes.push(t),t.parent=this)},e.prototype.removeChild=function(t){var e=this.childNodes.indexOf(t);-1!==e&&(t.parent=null,this.childNodes.splice(e,1))},e.prototype.insertChildrenAfter=function(t,e){var n,r=this,o=this.childNodes.indexOf(t);-1!==o&&((n=this.childNodes).splice.apply(n,[o+1,0].concat(e)),e.forEach(function(t){t.parent&&t.parent.removeChild(t),t.parent=r}))},e.prototype.insertBefore=function(t,e){var n=this.childNodes.indexOf(t);-1===n?this.addChild(e):(e.parent&&e.parent.removeChild(e),e.parent=this,this.childNodes.splice(n,0,e))},e.prototype.query=function(t){return this.queryAll(t)[0]||null},e.prototype.queryAll=function(t){var e=[];return ce(this,t,e),e},e.prototype.queryAllNodes=function(t){var e=[];return he(this,t,e),e},Object.defineProperty(e.prototype,"children",{get:function(){return this.childNodes.filter(function(t){return t instanceof e})},enumerable:!0,configurable:!0}),e.prototype.triggerEventHandler=function(t,e){this.listeners.forEach(function(n){n.name==t&&n.callback(e)})},e}(le);function ce(t,e,n){t.childNodes.forEach(function(t){t instanceof ue&&(e(t)&&n.push(t),ce(t,e,n))})}function he(t,e,n){t instanceof ue&&t.childNodes.forEach(function(t){e(t)&&n.push(t),t instanceof ue&&he(t,e,n)})}var pe=new Map;function de(t){return pe.get(t)||null}function fe(t){pe.set(t.nativeNode,t)}function me(t,e){var n=ge(t),r=ge(e);return n&&r?function(t,e,n){for(var r=t[x()](),o=e[x()]();;){var i=r.next(),s=o.next();if(i.done&&s.done)return!0;if(i.done||s.done)return!1;if(!n(i.value,s.value))return!1}}(t,e,me):!(n||!t||"object"!=typeof t&&"function"!=typeof t||r||!e||"object"!=typeof e&&"function"!=typeof e)||O(t,e)}var ye=function(){function t(t){this.wrapped=t}return t.wrap=function(e){return new t(e)},t.unwrap=function(e){return t.isWrapped(e)?e.wrapped:e},t.isWrapped=function(e){return e instanceof t},t}(),_e=function(){function t(t,e,n){this.previousValue=t,this.currentValue=e,this.firstChange=n}return t.prototype.isFirstChange=function(){return this.firstChange},t}();function ge(t){return!!ve(t)&&(Array.isArray(t)||!(t instanceof Map)&&x()in t)}function ve(t){return null!==t&&("function"==typeof t||"object"==typeof t)}var be=function(){function t(){}return t.prototype.supports=function(t){return ge(t)},t.prototype.create=function(t){return new Ee(t)},t}(),we=function(t,e){return e},Ee=function(){function t(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||we}return t.prototype.forEachItem=function(t){var e;for(e=this._itHead;null!==e;e=e._next)t(e)},t.prototype.forEachOperation=function(t){for(var e=this._itHead,n=this._removalsHead,r=0,o=null;e||n;){var i=!n||e&&e.currentIndex=n.length)&&(e=n.length-1),e<0)return null;var r=n[e];return r.viewContainerParent=null,Kn(n,e),Ke.dirtyParentQueries(r),Zn(r),r}function Gn(t,e,n){var r=e?yn(e,e.def.lastRenderRootNode):t.renderElement;Sn(n,2,n.renderer.parentNode(r),n.renderer.nextSibling(r),void 0)}function Zn(t){Sn(t,3,null,null,void 0)}function Qn(t,e,n){e>=t.length?t.push(n):t.splice(e,0,n)}function Kn(t,e){e>=t.length-1?t.pop():t.splice(e,1)}var Wn=new Object;function $n(t,e,n,r,o,i){return new Jn(t,e,n,r,o,i)}var Jn=function(t){function e(e,n,r,o,i,s){var a=t.call(this)||this;return a.selector=e,a.componentType=n,a._inputs=o,a._outputs=i,a.ngContentSelectors=s,a.viewDefFactory=r,a}return Object(r.b)(e,t),Object.defineProperty(e.prototype,"inputs",{get:function(){var t=[],e=this._inputs;for(var n in e)t.push({propName:n,templateName:e[n]});return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){var t=[];for(var e in this._outputs)t.push({propName:e,templateName:this._outputs[e]});return t},enumerable:!0,configurable:!0}),e.prototype.create=function(t,e,n,r){if(!r)throw new Error("ngModule should be provided");var o=xn(this.viewDefFactory),i=o.nodes[0].element.componentProvider.nodeIndex,s=Ke.createRootView(t,e||[],n,o,r,Wn),a=Ge(s,i).instance;return n&&s.renderer.setAttribute(Xe(s,0).renderElement,"ng-version",f.full),new tr(s,new or(s),a)},e}(ft),tr=function(t){function e(e,n,r){var o=t.call(this)||this;return o._view=e,o._viewRef=n,o._component=r,o._elDef=o._view.def.nodes[0],o.hostView=n,o.changeDetectorRef=n,o.instance=r,o}return Object(r.b)(e,t),Object.defineProperty(e.prototype,"location",{get:function(){return new ne(Xe(this._view,this._elDef.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"injector",{get:function(){return new lr(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"componentType",{get:function(){return this._component.constructor},enumerable:!0,configurable:!0}),e.prototype.destroy=function(){this._viewRef.destroy()},e.prototype.onDestroy=function(t){this._viewRef.onDestroy(t)},e}(function(){});function er(t,e,n){return new nr(t,e,n)}var nr=function(){function t(t,e,n){this._view=t,this._elDef=e,this._data=n,this._embeddedViews=[]}return Object.defineProperty(t.prototype,"element",{get:function(){return new ne(this._data.renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"injector",{get:function(){return new lr(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parentInjector",{get:function(){for(var t=this._view,e=this._elDef.parent;!e&&t;)e=mn(t),t=t.parent;return t?new lr(t,e):new lr(this._view,null)},enumerable:!0,configurable:!0}),t.prototype.clear=function(){for(var t=this._embeddedViews.length-1;t>=0;t--){var e=Xn(this._data,t);Ke.destroyView(e)}},t.prototype.get=function(t){var e=this._embeddedViews[t];if(e){var n=new or(e);return n.attachToViewContainerRef(this),n}return null},Object.defineProperty(t.prototype,"length",{get:function(){return this._embeddedViews.length},enumerable:!0,configurable:!0}),t.prototype.createEmbeddedView=function(t,e,n){var r=t.createEmbeddedView(e||{});return this.insert(r,n),r},t.prototype.createComponent=function(t,e,n,r,o){var i=n||this.parentInjector;o||t instanceof Et||(o=i.get(Ct));var s=t.create(i,r,void 0,o);return this.insert(s.hostView,e),s},t.prototype.insert=function(t,e){if(t.destroyed)throw new Error("Cannot insert a destroyed View in a ViewContainer!");var n,r,o,i,s=t;return o=s._view,i=(n=this._data).viewContainer._embeddedViews,null!==(r=e)&&void 0!==r||(r=i.length),o.viewContainerParent=this._view,Qn(i,r,o),function(t,e){var n=fn(e);if(n&&n!==t&&!(16&e.state)){e.state|=16;var r=n.template._projectedViews;r||(r=n.template._projectedViews=[]),r.push(e),function(t,n){if(!(4&n.flags)){e.parent.def.nodeFlags|=4,n.flags|=4;for(var r=n.parent;r;)r.childFlags|=4,r=r.parent}}(0,e.parentNodeDef)}}(n,o),Ke.dirtyParentQueries(o),Gn(n,r>0?i[r-1]:null,o),s.attachToViewContainerRef(this),t},t.prototype.move=function(t,e){if(t.destroyed)throw new Error("Cannot move a destroyed View in a ViewContainer!");var n,r,o,i,s,a=this._embeddedViews.indexOf(t._view);return o=e,s=(i=(n=this._data).viewContainer._embeddedViews)[r=a],Kn(i,r),null==o&&(o=i.length),Qn(i,o,s),Ke.dirtyParentQueries(s),Zn(s),Gn(n,o>0?i[o-1]:null,s),t},t.prototype.indexOf=function(t){return this._embeddedViews.indexOf(t._view)},t.prototype.remove=function(t){var e=Xn(this._data,t);e&&Ke.destroyView(e)},t.prototype.detach=function(t){var e=Xn(this._data,t);return e?new or(e):null},t}();function rr(t){return new or(t)}var or=function(){function t(t){this._view=t,this._viewContainerRef=null,this._appRef=null}return Object.defineProperty(t.prototype,"rootNodes",{get:function(){return Sn(this._view,0,void 0,void 0,t=[]),t;var t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._view.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"destroyed",{get:function(){return 0!=(128&this._view.state)},enumerable:!0,configurable:!0}),t.prototype.markForCheck=function(){hn(this._view)},t.prototype.detach=function(){this._view.state&=-5},t.prototype.detectChanges=function(){var t=this._view.root.rendererFactory;t.begin&&t.begin();try{Ke.checkAndUpdateView(this._view)}finally{t.end&&t.end()}},t.prototype.checkNoChanges=function(){Ke.checkNoChangesView(this._view)},t.prototype.reattach=function(){this._view.state|=4},t.prototype.onDestroy=function(t){this._view.disposables||(this._view.disposables=[]),this._view.disposables.push(t)},t.prototype.destroy=function(){this._appRef?this._appRef.detachView(this):this._viewContainerRef&&this._viewContainerRef.detach(this._viewContainerRef.indexOf(this)),Ke.destroyView(this._view)},t.prototype.detachFromAppRef=function(){this._appRef=null,Zn(this._view),Ke.dirtyParentQueries(this._view)},t.prototype.attachToAppRef=function(t){if(this._viewContainerRef)throw new Error("This view is already attached to a ViewContainer!");this._appRef=t},t.prototype.attachToViewContainerRef=function(t){if(this._appRef)throw new Error("This view is already attached directly to the ApplicationRef!");this._viewContainerRef=t},t}();function ir(t,e){return new sr(t,e)}var sr=function(t){function e(e,n){var r=t.call(this)||this;return r._parentView=e,r._def=n,r}return Object(r.b)(e,t),e.prototype.createEmbeddedView=function(t){return new or(Ke.createEmbeddedView(this._parentView,this._def,this._def.element.template,t))},Object.defineProperty(e.prototype,"elementRef",{get:function(){return new ne(Xe(this._parentView,this._def.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),e}(oe);function ar(t,e){return new lr(t,e)}var lr=function(){function t(t,e){this.view=t,this.elDef=e}return t.prototype.get=function(t,e){return void 0===e&&(e=I.THROW_IF_NOT_FOUND),Ke.resolveDep(this.view,this.elDef,!!this.elDef&&0!=(33554432&this.elDef.flags),{flags:0,token:t,tokenKey:nn(t)},e)},t}();function ur(t,e){var n=t.def.nodes[e];if(1&n.flags){var r=Xe(t,n.nodeIndex);return n.element.template?r.template:r.renderElement}if(2&n.flags)return qe(t,n.nodeIndex).renderText;if(20240&n.flags)return Ge(t,n.nodeIndex).instance;throw new Error("Illegal state: read nodeValue for node index "+e)}function cr(t){return new hr(t.renderer)}var hr=function(){function t(t){this.delegate=t}return t.prototype.selectRootElement=function(t){return this.delegate.selectRootElement(t)},t.prototype.createElement=function(t,e){var n=Dn(e),r=this.delegate.createElement(n[1],n[0]);return t&&this.delegate.appendChild(t,r),r},t.prototype.createViewRoot=function(t){return t},t.prototype.createTemplateAnchor=function(t){var e=this.delegate.createComment("");return t&&this.delegate.appendChild(t,e),e},t.prototype.createText=function(t,e){var n=this.delegate.createText(e);return t&&this.delegate.appendChild(t,n),n},t.prototype.projectNodes=function(t,e){for(var n=0;n0,e.provider.value,e.provider.deps);if(e.outputs.length)for(var r=0;r0,r=e.provider;switch(201347067&e.flags){case 512:return Ar(t,e.parent,n,r.value,r.deps);case 1024:return function(t,e,n,r,o){var i=o.length;switch(i){case 0:return r();case 1:return r(Dr(t,e,n,o[0]));case 2:return r(Dr(t,e,n,o[0]),Dr(t,e,n,o[1]));case 3:return r(Dr(t,e,n,o[0]),Dr(t,e,n,o[1]),Dr(t,e,n,o[2]));default:for(var s=Array(i),a=0;a0)u=m,Zr(m)||(c=m);else for(;u&&f===u.nodeIndex+u.childCount;){var g=u.parent;g&&(g.childFlags|=u.childFlags,g.childMatchedQueries|=u.childMatchedQueries),c=(u=g)&&Zr(u)?u.renderParent:u}}return{factory:null,nodeFlags:s,rootNodeFlags:a,nodeMatchedQueries:l,flags:t,nodes:e,updateDirectives:n||tn,updateRenderer:r||tn,handleEvent:function(t,n,r,o){return e[n].element.handleEvent(t,r,o)},bindingCount:o,outputCount:i,lastRenderRootNode:d}}function Zr(t){return 0!=(1&t.flags)&&null===t.element.name}function Qr(t,e,n){var r=e.element&&e.element.template;if(r){if(!r.lastRenderRootNode)throw new Error("Illegal State: Embedded templates without nodes are not allowed!");if(r.lastRenderRootNode&&16777216&r.lastRenderRootNode.flags)throw new Error("Illegal State: Last root node of a template can't have embedded views, at index "+e.nodeIndex+"!")}if(20224&e.flags&&0==(1&(t?t.flags:0)))throw new Error("Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index "+e.nodeIndex+"!");if(e.query){if(67108864&e.flags&&(!t||0==(16384&t.flags)))throw new Error("Illegal State: Content Query nodes need to be children of directives, at index "+e.nodeIndex+"!");if(134217728&e.flags&&t)throw new Error("Illegal State: View Query nodes have to be top level nodes, at index "+e.nodeIndex+"!")}if(e.childCount){var o=t?t.nodeIndex+t.childCount:n-1;if(e.nodeIndex<=o&&e.nodeIndex+e.childCount>o)throw new Error("Illegal State: childCount of node leads outside of parent, at index "+e.nodeIndex+"!")}}function Kr(t,e,n,r){var o=Jr(t.root,t.renderer,t,e,n);return to(o,t.component,r),eo(o),o}function Wr(t,e,n){var r=Jr(t,t.renderer,null,null,e);return to(r,n,n),eo(r),r}function $r(t,e,n,r){var o,i=e.element.componentRendererType;return o=i?t.root.rendererFactory.createRenderer(r,i):t.root.renderer,Jr(t.root,o,t,e.element.componentProvider,n)}function Jr(t,e,n,r,o){var i=new Array(o.nodes.length),s=o.outputCount?new Array(o.outputCount):null;return{def:o,parent:n,viewContainerParent:null,parentNodeDef:r,context:null,component:null,nodes:i,state:13,root:t,renderer:e,oldValues:new Array(o.bindingCount),disposables:s,initIndex:-1}}function to(t,e,n){t.component=e,t.context=n}function eo(t){var e;_n(t)&&(e=Xe(t.parent,t.parentNodeDef.parent.nodeIndex).renderElement);for(var n=t.def,r=t.nodes,o=0;o0&&Fn(t,e,0,n)&&(d=!0),p>1&&Fn(t,e,1,r)&&(d=!0),p>2&&Fn(t,e,2,o)&&(d=!0),p>3&&Fn(t,e,3,i)&&(d=!0),p>4&&Fn(t,e,4,s)&&(d=!0),p>5&&Fn(t,e,5,a)&&(d=!0),p>6&&Fn(t,e,6,l)&&(d=!0),p>7&&Fn(t,e,7,u)&&(d=!0),p>8&&Fn(t,e,8,c)&&(d=!0),p>9&&Fn(t,e,9,h)&&(d=!0),d}(t,e,n,r,o,i,s,a,l,u,c,h);case 2:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=!1,d=e.bindings,f=d.length;if(f>0&&un(t,e,0,n)&&(p=!0),f>1&&un(t,e,1,r)&&(p=!0),f>2&&un(t,e,2,o)&&(p=!0),f>3&&un(t,e,3,i)&&(p=!0),f>4&&un(t,e,4,s)&&(p=!0),f>5&&un(t,e,5,a)&&(p=!0),f>6&&un(t,e,6,l)&&(p=!0),f>7&&un(t,e,7,u)&&(p=!0),f>8&&un(t,e,8,c)&&(p=!0),f>9&&un(t,e,9,h)&&(p=!0),p){var m=e.text.prefix;f>0&&(m+=Xr(n,d[0])),f>1&&(m+=Xr(r,d[1])),f>2&&(m+=Xr(o,d[2])),f>3&&(m+=Xr(i,d[3])),f>4&&(m+=Xr(s,d[4])),f>5&&(m+=Xr(a,d[5])),f>6&&(m+=Xr(l,d[6])),f>7&&(m+=Xr(u,d[7])),f>8&&(m+=Xr(c,d[8])),f>9&&(m+=Xr(h,d[9]));var y=qe(t,e.nodeIndex).renderText;t.renderer.setValue(y,m)}return p}(t,e,n,r,o,i,s,a,l,u,c,h);case 16384:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=Ge(t,e.nodeIndex),d=p.instance,f=!1,m=void 0,y=e.bindings.length;return y>0&&ln(t,e,0,n)&&(f=!0,m=Ir(t,p,e,0,n,m)),y>1&&ln(t,e,1,r)&&(f=!0,m=Ir(t,p,e,1,r,m)),y>2&&ln(t,e,2,o)&&(f=!0,m=Ir(t,p,e,2,o,m)),y>3&&ln(t,e,3,i)&&(f=!0,m=Ir(t,p,e,3,i,m)),y>4&&ln(t,e,4,s)&&(f=!0,m=Ir(t,p,e,4,s,m)),y>5&&ln(t,e,5,a)&&(f=!0,m=Ir(t,p,e,5,a,m)),y>6&&ln(t,e,6,l)&&(f=!0,m=Ir(t,p,e,6,l,m)),y>7&&ln(t,e,7,u)&&(f=!0,m=Ir(t,p,e,7,u,m)),y>8&&ln(t,e,8,c)&&(f=!0,m=Ir(t,p,e,8,c,m)),y>9&&ln(t,e,9,h)&&(f=!0,m=Ir(t,p,e,9,h,m)),m&&d.ngOnChanges(m),65536&e.flags&&Ye(t,256,e.nodeIndex)&&d.ngOnInit(),262144&e.flags&&d.ngDoCheck(),f}(t,e,n,r,o,i,s,a,l,u,c,h);case 32:case 64:case 128:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=e.bindings,d=!1,f=p.length;if(f>0&&un(t,e,0,n)&&(d=!0),f>1&&un(t,e,1,r)&&(d=!0),f>2&&un(t,e,2,o)&&(d=!0),f>3&&un(t,e,3,i)&&(d=!0),f>4&&un(t,e,4,s)&&(d=!0),f>5&&un(t,e,5,a)&&(d=!0),f>6&&un(t,e,6,l)&&(d=!0),f>7&&un(t,e,7,u)&&(d=!0),f>8&&un(t,e,8,c)&&(d=!0),f>9&&un(t,e,9,h)&&(d=!0),d){var m=Ze(t,e.nodeIndex),y=void 0;switch(201347067&e.flags){case 32:y=new Array(p.length),f>0&&(y[0]=n),f>1&&(y[1]=r),f>2&&(y[2]=o),f>3&&(y[3]=i),f>4&&(y[4]=s),f>5&&(y[5]=a),f>6&&(y[6]=l),f>7&&(y[7]=u),f>8&&(y[8]=c),f>9&&(y[9]=h);break;case 64:y={},f>0&&(y[p[0].name]=n),f>1&&(y[p[1].name]=r),f>2&&(y[p[2].name]=o),f>3&&(y[p[3].name]=i),f>4&&(y[p[4].name]=s),f>5&&(y[p[5].name]=a),f>6&&(y[p[6].name]=l),f>7&&(y[p[7].name]=u),f>8&&(y[p[8].name]=c),f>9&&(y[p[9].name]=h);break;case 128:var _=n;switch(f){case 1:y=_.transform(n);break;case 2:y=_.transform(r);break;case 3:y=_.transform(r,o);break;case 4:y=_.transform(r,o,i);break;case 5:y=_.transform(r,o,i,s);break;case 6:y=_.transform(r,o,i,s,a);break;case 7:y=_.transform(r,o,i,s,a,l);break;case 8:y=_.transform(r,o,i,s,a,l,u);break;case 9:y=_.transform(r,o,i,s,a,l,u,c);break;case 10:y=_.transform(r,o,i,s,a,l,u,c,h)}}m.value=y}return d}(t,e,n,r,o,i,s,a,l,u,c,h);default:throw"unreachable"}}(t,e,r,o,i,s,a,l,u,c,h,p):function(t,e,n){switch(201347067&e.flags){case 1:return function(t,e,n){for(var r=!1,o=0;o0&&cn(t,e,0,n),p>1&&cn(t,e,1,r),p>2&&cn(t,e,2,o),p>3&&cn(t,e,3,i),p>4&&cn(t,e,4,s),p>5&&cn(t,e,5,a),p>6&&cn(t,e,6,l),p>7&&cn(t,e,7,u),p>8&&cn(t,e,8,c),p>9&&cn(t,e,9,h)}(t,e,r,o,i,s,a,l,u,c,h,p):function(t,e,n){for(var r=0;r0){var r=t.slice(0,n),o=r.toLowerCase(),i=t.slice(n+1).trim();e.maybeSetNormalizedName(r,o),e.headers.has(o)?e.headers.get(o).push(i):e.headers.set(o,[i])}})}:function(){e.headers=new Map,Object.keys(t).forEach(function(n){var r=t[n],o=n.toLowerCase();"string"==typeof r&&(r=[r]),r.length>0&&(e.headers.set(o,r),e.maybeSetNormalizedName(n,o))})}:this.headers=new Map}return t.prototype.has=function(t){return this.init(),this.headers.has(t.toLowerCase())},t.prototype.get=function(t){this.init();var e=this.headers.get(t.toLowerCase());return e&&e.length>0?e[0]:null},t.prototype.keys=function(){return this.init(),Array.from(this.normalizedNames.values())},t.prototype.getAll=function(t){return this.init(),this.headers.get(t.toLowerCase())||null},t.prototype.append=function(t,e){return this.clone({name:t,value:e,op:"a"})},t.prototype.set=function(t,e){return this.clone({name:t,value:e,op:"s"})},t.prototype.delete=function(t,e){return this.clone({name:t,value:e,op:"d"})},t.prototype.maybeSetNormalizedName=function(t,e){this.normalizedNames.has(e)||this.normalizedNames.set(e,t)},t.prototype.init=function(){var e=this;this.lazyInit&&(this.lazyInit instanceof t?this.copyFrom(this.lazyInit):this.lazyInit(),this.lazyInit=null,this.lazyUpdate&&(this.lazyUpdate.forEach(function(t){return e.applyUpdate(t)}),this.lazyUpdate=null))},t.prototype.copyFrom=function(t){var e=this;t.init(),Array.from(t.headers.keys()).forEach(function(n){e.headers.set(n,t.headers.get(n)),e.normalizedNames.set(n,t.normalizedNames.get(n))})},t.prototype.clone=function(e){var n=new t;return n.lazyInit=this.lazyInit&&this.lazyInit instanceof t?this.lazyInit:this,n.lazyUpdate=(this.lazyUpdate||[]).concat([e]),n},t.prototype.applyUpdate=function(t){var e=t.name.toLowerCase();switch(t.op){case"a":case"s":var n=t.value;if("string"==typeof n&&(n=[n]),0===n.length)return;this.maybeSetNormalizedName(t.name,e);var r=("a"===t.op?this.headers.get(e):void 0)||[];r.push.apply(r,n),this.headers.set(e,r);break;case"d":var o=t.value;if(o){var i=this.headers.get(e);if(!i)return;0===(i=i.filter(function(t){return-1===o.indexOf(t)})).length?(this.headers.delete(e),this.normalizedNames.delete(e)):this.headers.set(e,i)}else this.headers.delete(e),this.normalizedNames.delete(e)}},t.prototype.forEach=function(t){var e=this;this.init(),Array.from(this.normalizedNames.keys()).forEach(function(n){return t(e.normalizedNames.get(n),e.headers.get(n))})},t}(),M=function(){function t(){}return t.prototype.encodeKey=function(t){return F(t)},t.prototype.encodeValue=function(t){return F(t)},t.prototype.decodeKey=function(t){return decodeURIComponent(t)},t.prototype.decodeValue=function(t){return decodeURIComponent(t)},t}();function F(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/gi,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%2B/gi,"+").replace(/%3D/gi,"=").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}var L=function(){function t(t){void 0===t&&(t={});var e,n,r,o=this;if(this.updates=null,this.cloneFrom=null,this.encoder=t.encoder||new M,t.fromString){if(t.fromObject)throw new Error("Cannot specify both fromString and fromObject.");this.map=(e=t.fromString,n=this.encoder,r=new Map,e.length>0&&e.split("&").forEach(function(t){var e=t.indexOf("="),o=-1==e?[n.decodeKey(t),""]:[n.decodeKey(t.slice(0,e)),n.decodeValue(t.slice(e+1))],i=o[0],s=o[1],a=r.get(i)||[];a.push(s),r.set(i,a)}),r)}else t.fromObject?(this.map=new Map,Object.keys(t.fromObject).forEach(function(e){var n=t.fromObject[e];o.map.set(e,Array.isArray(n)?n:[n])})):this.map=null}return t.prototype.has=function(t){return this.init(),this.map.has(t)},t.prototype.get=function(t){this.init();var e=this.map.get(t);return e?e[0]:null},t.prototype.getAll=function(t){return this.init(),this.map.get(t)||null},t.prototype.keys=function(){return this.init(),Array.from(this.map.keys())},t.prototype.append=function(t,e){return this.clone({param:t,value:e,op:"a"})},t.prototype.set=function(t,e){return this.clone({param:t,value:e,op:"s"})},t.prototype.delete=function(t,e){return this.clone({param:t,value:e,op:"d"})},t.prototype.toString=function(){var t=this;return this.init(),this.keys().map(function(e){var n=t.encoder.encodeKey(e);return t.map.get(e).map(function(e){return n+"="+t.encoder.encodeValue(e)}).join("&")}).join("&")},t.prototype.clone=function(e){var n=new t({encoder:this.encoder});return n.cloneFrom=this.cloneFrom||this,n.updates=(this.updates||[]).concat([e]),n},t.prototype.init=function(){var t=this;null===this.map&&(this.map=new Map),null!==this.cloneFrom&&(this.cloneFrom.init(),this.cloneFrom.keys().forEach(function(e){return t.map.set(e,t.cloneFrom.map.get(e))}),this.updates.forEach(function(e){switch(e.op){case"a":case"s":var n=("a"===e.op?t.map.get(e.param):void 0)||[];n.push(e.value),t.map.set(e.param,n);break;case"d":if(void 0===e.value){t.map.delete(e.param);break}var r=t.map.get(e.param)||[],o=r.indexOf(e.value);-1!==o&&r.splice(o,1),r.length>0?t.map.set(e.param,r):t.map.delete(e.param)}}),this.cloneFrom=null)},t}();function B(t){return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer}function H(t){return"undefined"!=typeof Blob&&t instanceof Blob}function z(t){return"undefined"!=typeof FormData&&t instanceof FormData}var U=function(){function t(t,e,n,r){var o;if(this.url=e,this.body=null,this.reportProgress=!1,this.withCredentials=!1,this.responseType="json",this.method=t.toUpperCase(),function(t){switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"JSONP":return!1;default:return!0}}(this.method)||r?(this.body=void 0!==n?n:null,o=r):o=n,o&&(this.reportProgress=!!o.reportProgress,this.withCredentials=!!o.withCredentials,o.responseType&&(this.responseType=o.responseType),o.headers&&(this.headers=o.headers),o.params&&(this.params=o.params)),this.headers||(this.headers=new V),this.params){var i=this.params.toString();if(0===i.length)this.urlWithParams=e;else{var s=e.indexOf("?");this.urlWithParams=e+(-1===s?"?":s=200&&this.status<300}}(),X=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;return n.type=Y.ResponseHeader,n}return Object(l.b)(e,t),e.prototype.clone=function(t){return void 0===t&&(t={}),new e({headers:t.headers||this.headers,status:void 0!==t.status?t.status:this.status,statusText:t.statusText||this.statusText,url:t.url||this.url||void 0})},e}(q),G=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;return n.type=Y.Response,n.body=void 0!==e.body?e.body:null,n}return Object(l.b)(e,t),e.prototype.clone=function(t){return void 0===t&&(t={}),new e({body:void 0!==t.body?t.body:this.body,headers:t.headers||this.headers,status:void 0!==t.status?t.status:this.status,statusText:t.statusText||this.statusText,url:t.url||this.url||void 0})},e}(q),Z=function(t){function e(e){var n=t.call(this,e,0,"Unknown Error")||this;return n.name="HttpErrorResponse",n.ok=!1,n.message=n.status>=200&&n.status<300?"Http failure during parsing for "+(e.url||"(unknown url)"):"Http failure response for "+(e.url||"(unknown url)")+": "+e.status+" "+e.statusText,n.error=e.error||null,n}return Object(l.b)(e,t),e}(q);function Q(t,e){return{body:e,headers:t.headers,observe:t.observe,params:t.params,reportProgress:t.reportProgress,responseType:t.responseType,withCredentials:t.withCredentials}}var K=function(){function t(t){this.handler=t}return t.prototype.request=function(t,e,n){var r,o=this;if(void 0===n&&(n={}),t instanceof U)r=t;else{var i;i=n.headers instanceof V?n.headers:new V(n.headers);var l=void 0;n.params&&(l=n.params instanceof L?n.params:new L({fromObject:n.params})),r=new U(t,e,void 0!==n.body?n.body:null,{headers:i,params:l,reportProgress:n.reportProgress,responseType:n.responseType||"json",withCredentials:n.withCredentials})}var u=(function(t,e){return function(t,e){return Object(a.a)(t,e,1)}(t,e)(this)}).call(s(r),function(t){return o.handler.handle(t)});if(t instanceof U||"events"===n.observe)return u;var h=(function(t,e){return c(t,e)(this)}).call(u,function(t){return t instanceof G});switch(n.observe||"body"){case"body":switch(r.responseType){case"arraybuffer":return m.call(h,function(t){if(null!==t.body&&!(t.body instanceof ArrayBuffer))throw new Error("Response is not an ArrayBuffer.");return t.body});case"blob":return m.call(h,function(t){if(null!==t.body&&!(t.body instanceof Blob))throw new Error("Response is not a Blob.");return t.body});case"text":return m.call(h,function(t){if(null!==t.body&&"string"!=typeof t.body)throw new Error("Response is not a string.");return t.body});case"json":default:return m.call(h,function(t){return t.body})}case"response":return h;default:throw new Error("Unreachable: unhandled observe type "+n.observe+"}")}},t.prototype.delete=function(t,e){return void 0===e&&(e={}),this.request("DELETE",t,e)},t.prototype.get=function(t,e){return void 0===e&&(e={}),this.request("GET",t,e)},t.prototype.head=function(t,e){return void 0===e&&(e={}),this.request("HEAD",t,e)},t.prototype.jsonp=function(t,e){return this.request("JSONP",t,{params:(new L).append(e,"JSONP_CALLBACK"),observe:"body",responseType:"json"})},t.prototype.options=function(t,e){return void 0===e&&(e={}),this.request("OPTIONS",t,e)},t.prototype.patch=function(t,e,n){return void 0===n&&(n={}),this.request("PATCH",t,Q(n,e))},t.prototype.post=function(t,e,n){return void 0===n&&(n={}),this.request("POST",t,Q(n,e))},t.prototype.put=function(t,e,n){return void 0===n&&(n={}),this.request("PUT",t,Q(n,e))},t}(),W=function(){function t(t,e){this.next=t,this.interceptor=e}return t.prototype.handle=function(t){return this.interceptor.intercept(t,this.next)},t}(),$=new r.n("HTTP_INTERCEPTORS"),J=function(){function t(){}return t.prototype.intercept=function(t,e){return e.handle(t)},t}(),tt=/^\)\]\}',?\n/,et=function(){},nt=function(){function t(){}return t.prototype.build=function(){return new XMLHttpRequest},t}(),rt=function(){function t(t){this.xhrFactory=t}return t.prototype.handle=function(t){var e=this;if("JSONP"===t.method)throw new Error("Attempted to construct Jsonp request without JsonpClientModule installed.");return new I.a(function(n){var r=e.xhrFactory.build();if(r.open(t.method,t.urlWithParams),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach(function(t,e){return r.setRequestHeader(t,e.join(","))}),t.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),!t.headers.has("Content-Type")){var o=t.detectContentTypeHeader();null!==o&&r.setRequestHeader("Content-Type",o)}if(t.responseType){var i=t.responseType.toLowerCase();r.responseType="json"!==i?i:"text"}var s=t.serializeBody(),a=null,l=function(){if(null!==a)return a;var e=1223===r.status?204:r.status,n=r.statusText||"OK",o=new V(r.getAllResponseHeaders()),i=function(t){return"responseURL"in t&&t.responseURL?t.responseURL:/^X-Request-URL:/m.test(t.getAllResponseHeaders())?t.getResponseHeader("X-Request-URL"):null}(r)||t.url;return a=new X({headers:o,status:e,statusText:n,url:i})},u=function(){var e=l(),o=e.headers,i=e.status,s=e.statusText,a=e.url,u=null;204!==i&&(u="undefined"==typeof r.response?r.responseText:r.response),0===i&&(i=u?200:0);var c=i>=200&&i<300;if("json"===t.responseType&&"string"==typeof u){var h=u;u=u.replace(tt,"");try{u=""!==u?JSON.parse(u):null}catch(t){u=h,c&&(c=!1,u={error:t,text:u})}}c?(n.next(new G({body:u,headers:o,status:i,statusText:s,url:a||void 0})),n.complete()):n.error(new Z({error:u,headers:o,status:i,statusText:s,url:a||void 0}))},c=function(t){var e=new Z({error:t,status:r.status||0,statusText:r.statusText||"Unknown Error"});n.error(e)},h=!1,p=function(e){h||(n.next(l()),h=!0);var o={type:Y.DownloadProgress,loaded:e.loaded};e.lengthComputable&&(o.total=e.total),"text"===t.responseType&&r.responseText&&(o.partialText=r.responseText),n.next(o)},d=function(t){var e={type:Y.UploadProgress,loaded:t.loaded};t.lengthComputable&&(e.total=t.total),n.next(e)};return r.addEventListener("load",u),r.addEventListener("error",c),t.reportProgress&&(r.addEventListener("progress",p),null!==s&&r.upload&&r.upload.addEventListener("progress",d)),r.send(s),n.next({type:Y.Sent}),function(){r.removeEventListener("error",c),r.removeEventListener("load",u),t.reportProgress&&(r.removeEventListener("progress",p),null!==s&&r.upload&&r.upload.removeEventListener("progress",d)),r.abort()}})},t}(),ot=new r.n("XSRF_COOKIE_NAME"),it=new r.n("XSRF_HEADER_NAME"),st=function(){},at=function(){function t(t,e,n){this.doc=t,this.platform=e,this.cookieName=n,this.lastCookieString="",this.lastToken=null,this.parseCount=0}return t.prototype.getToken=function(){if("server"===this.platform)return null;var t=this.doc.cookie||"";return t!==this.lastCookieString&&(this.parseCount++,this.lastToken=S(t,this.cookieName),this.lastCookieString=t),this.lastToken},t}(),lt=function(){function t(t,e){this.tokenService=t,this.headerName=e}return t.prototype.intercept=function(t,e){var n=t.url.toLowerCase();if("GET"===t.method||"HEAD"===t.method||n.startsWith("http://")||n.startsWith("https://"))return e.handle(t);var r=this.tokenService.getToken();return null===r||t.headers.has(this.headerName)||(t=t.clone({headers:t.headers.set(this.headerName,r)})),e.handle(t)},t}(),ut=function(){function t(t,e){this.backend=t,this.injector=e,this.chain=null}return t.prototype.handle=function(t){if(null===this.chain){var e=this.injector.get($,[]);this.chain=e.reduceRight(function(t,e){return new W(t,e)},this.backend)}return this.chain.handle(t)},t}(),ct=function(){function t(){}return t.disable=function(){return{ngModule:t,providers:[{provide:lt,useClass:J}]}},t.withOptions=function(e){return void 0===e&&(e={}),{ngModule:t,providers:[e.cookieName?{provide:ot,useValue:e.cookieName}:[],e.headerName?{provide:it,useValue:e.headerName}:[]]}},t}(),ht=function(){};I.a.prototype.map=m;var pt=function(){function t(t){this.http=t}return t.prototype.getTorrents=function(){return this.http.get("http://localhost:8880/ktorrentdata")},t.prototype.startTorrent=function(t){this.http.post("http://localhost:8880/ktorrentaction",{type:"start",hash:t}).subscribe()},t.prototype.pauseTorrent=function(t){this.http.post("http://localhost:8880/ktorrentaction",{type:"pause",hash:t}).subscribe()},t.prototype.removeTorrent=function(t){this.http.post("http://localhost:8880/ktorrentaction",{type:"remove",hash:t}).subscribe()},t.prototype.startFromMagnetLink=function(t){this.http.post("http://localhost:8880/ktorrentaction",{type:"magnet",magnet:t}).subscribe()},t}(),dt=new r.n("cdk-dir-doc"),ft=function(){return function(t){this.value="ltr",this.change=new r.l,t&&(this.value=(t.body?t.body.dir:null)||(t.documentElement?t.documentElement.dir:null)||"ltr")}}(),mt=function(){};function yt(t){return null!=t&&""+t!="false"}var _t=n("g5jc"),gt=null;function vt(){return gt}var bt,wt={class:"className",innerHtml:"innerHTML",readonly:"readOnly",tabindex:"tabIndex"},Et={"\b":"Backspace","\t":"Tab","\x7f":"Delete","\x1b":"Escape",Del:"Delete",Esc:"Escape",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Menu:"ContextMenu",Scroll:"ScrollLock",Win:"OS"},Ct={A:"1",B:"2",C:"3",D:"4",E:"5",F:"6",G:"7",H:"8",I:"9",J:"*",K:"+",M:"-",N:".",O:"/","`":"0","\x90":"NumLock"};r.Z.Node&&(bt=r.Z.Node.prototype.contains||function(t){return!!(16&this.compareDocumentPosition(t))});var xt,St=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e.prototype.parse=function(t){throw new Error("parse not implemented")},e.makeCurrent=function(){var t;t=new e,gt||(gt=t)},e.prototype.hasProperty=function(t,e){return e in t},e.prototype.setProperty=function(t,e,n){t[e]=n},e.prototype.getProperty=function(t,e){return t[e]},e.prototype.invoke=function(t,e,n){var r;(r=t)[e].apply(r,n)},e.prototype.logError=function(t){window.console&&(console.error?console.error(t):console.log(t))},e.prototype.log=function(t){window.console&&window.console.log&&window.console.log(t)},e.prototype.logGroup=function(t){window.console&&window.console.group&&window.console.group(t)},e.prototype.logGroupEnd=function(){window.console&&window.console.groupEnd&&window.console.groupEnd()},Object.defineProperty(e.prototype,"attrToPropMap",{get:function(){return wt},enumerable:!0,configurable:!0}),e.prototype.contains=function(t,e){return bt.call(t,e)},e.prototype.querySelector=function(t,e){return t.querySelector(e)},e.prototype.querySelectorAll=function(t,e){return t.querySelectorAll(e)},e.prototype.on=function(t,e,n){t.addEventListener(e,n,!1)},e.prototype.onAndCancel=function(t,e,n){return t.addEventListener(e,n,!1),function(){t.removeEventListener(e,n,!1)}},e.prototype.dispatchEvent=function(t,e){t.dispatchEvent(e)},e.prototype.createMouseEvent=function(t){var e=this.getDefaultDocument().createEvent("MouseEvent");return e.initEvent(t,!0,!0),e},e.prototype.createEvent=function(t){var e=this.getDefaultDocument().createEvent("Event");return e.initEvent(t,!0,!0),e},e.prototype.preventDefault=function(t){t.preventDefault(),t.returnValue=!1},e.prototype.isPrevented=function(t){return t.defaultPrevented||null!=t.returnValue&&!t.returnValue},e.prototype.getInnerHTML=function(t){return t.innerHTML},e.prototype.getTemplateContent=function(t){return"content"in t&&this.isTemplateElement(t)?t.content:null},e.prototype.getOuterHTML=function(t){return t.outerHTML},e.prototype.nodeName=function(t){return t.nodeName},e.prototype.nodeValue=function(t){return t.nodeValue},e.prototype.type=function(t){return t.type},e.prototype.content=function(t){return this.hasProperty(t,"content")?t.content:t},e.prototype.firstChild=function(t){return t.firstChild},e.prototype.nextSibling=function(t){return t.nextSibling},e.prototype.parentElement=function(t){return t.parentNode},e.prototype.childNodes=function(t){return t.childNodes},e.prototype.childNodesAsList=function(t){for(var e=t.childNodes,n=new Array(e.length),r=0;r0},e.prototype.tagName=function(t){return t.tagName},e.prototype.attributeMap=function(t){for(var e=new Map,n=t.attributes,r=0;r0;a||(a=t[s]=[]);var u=ae(e)?Zone.root:Zone.current;if(0===a.length)a.push({zone:u,handler:i});else{for(var c=!1,h=0;h-1},e}(Bt),fe=["alt","control","meta","shift"],me={alt:function(t){return t.altKey},control:function(t){return t.ctrlKey},meta:function(t){return t.metaKey},shift:function(t){return t.shiftKey}},ye=function(t){function e(e){return t.call(this,e)||this}return Object(l.b)(e,t),e.prototype.supports=function(t){return null!=e.parseEventName(t)},e.prototype.addEventListener=function(t,n,r){var o=e.parseEventName(n),i=e.eventCallback(o.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(function(){return vt().onAndCancel(t,o.domEventName,i)})},e.parseEventName=function(t){var n=t.toLowerCase().split("."),r=n.shift();if(0===n.length||"keydown"!==r&&"keyup"!==r)return null;var o=e._normalizeKey(n.pop()),i="";if(fe.forEach(function(t){var e=n.indexOf(t);e>-1&&(n.splice(e,1),i+=t+".")}),i+=o,0!=n.length||0===o.length)return null;var s={};return s.domEventName=r,s.fullKey=i,s},e.getEventFullKey=function(t){var e="",n=vt().getEventKey(t);return" "===(n=n.toLowerCase())?n="space":"."===n&&(n="dot"),fe.forEach(function(r){r!=n&&(0,me[r])(t)&&(e+=r+".")}),e+=n},e.eventCallback=function(t,n,r){return function(o){e.getEventFullKey(o)===t&&r.runGuarded(function(){return n(o)})}},e._normalizeKey=function(t){switch(t){case"esc":return"escape";default:return t}},e}(Bt),_e=function(){function t(t,e){this.defaultDoc=t,this.DOM=e;var n=this.DOM.createHtmlDocument();if(this.inertBodyElement=n.body,null==this.inertBodyElement){var r=this.DOM.createElement("html",n);this.inertBodyElement=this.DOM.createElement("body",n),this.DOM.appendChild(r,this.inertBodyElement),this.DOM.appendChild(n,r)}this.DOM.setInnerHTML(this.inertBodyElement,''),!this.inertBodyElement.querySelector||this.inertBodyElement.querySelector("svg")?(this.DOM.setInnerHTML(this.inertBodyElement,'

'),this.getInertBodyElement=this.inertBodyElement.querySelector&&this.inertBodyElement.querySelector("svg img")&&function(){try{return!!window.DOMParser}catch(t){return!1}}()?this.getInertBodyElement_DOMParser:this.getInertBodyElement_InertDocument):this.getInertBodyElement=this.getInertBodyElement_XHR}return t.prototype.getInertBodyElement_XHR=function(t){t=""+t+"";try{t=encodeURI(t)}catch(t){return null}var e=new XMLHttpRequest;e.responseType="document",e.open("GET","data:text/html;charset=utf-8,"+t,!1),e.send(null);var n=e.response.body;return n.removeChild(n.firstChild),n},t.prototype.getInertBodyElement_DOMParser=function(t){t=""+t+"";try{var e=(new window.DOMParser).parseFromString(t,"text/html").body;return e.removeChild(e.firstChild),e}catch(t){return null}},t.prototype.getInertBodyElement_InertDocument=function(t){var e=this.DOM.createElement("template");return"content"in e?(this.DOM.setInnerHTML(e,t),e):(this.DOM.setInnerHTML(this.inertBodyElement,t),this.defaultDoc.documentMode&&this.stripCustomNsAttrs(this.inertBodyElement),this.inertBodyElement)},t.prototype.stripCustomNsAttrs=function(t){var e=this;this.DOM.attributeMap(t).forEach(function(n,r){"xmlns:ns1"!==r&&0!==r.indexOf("ns1:")||e.DOM.removeAttribute(t,r)});for(var n=0,r=this.DOM.childNodesAsList(t);n")):this.sanitizedSomething=!0},t.prototype.endElement=function(t){var e=this.DOM.nodeName(t).toLowerCase();ke.hasOwnProperty(e)&&!xe.hasOwnProperty(e)&&(this.buf.push(""))},t.prototype.chars=function(t){this.buf.push(je(t))},t.prototype.checkClobberedElement=function(t,e){if(e&&this.DOM.contains(t,e))throw new Error("Failed to sanitize html because the element is clobbered: "+this.DOM.getOuterHTML(t));return e},t}(),Ie=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Ne=/([^\#-~ |!])/g;function je(t){return t.replace(/&/g,"&").replace(Ie,function(t){return"&#"+(1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320)+65536)+";"}).replace(Ne,function(t){return"&#"+t.charCodeAt(0)+";"}).replace(//g,">")}var Ve=new RegExp("^([-,.\"'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?|(?:repeating-)?(?:linear|radial)-gradient|(?:calc|attr))\\([-0-9.%, #a-zA-Z]+\\))$","g"),Me=/^url\(([^)]+)\)$/,Fe=function(){},Le=function(t){function e(e){var n=t.call(this)||this;return n._doc=e,n}return Object(l.b)(e,t),e.prototype.sanitize=function(t,e){if(null==e)return null;switch(t){case r.C.NONE:return e;case r.C.HTML:return e instanceof He?e.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(e,"HTML"),function(t,e){var n=vt(),o=null;try{Ce=Ce||new _e(t,n);var i=e?String(e):"";o=Ce.getInertBodyElement(i);var s=5,a=i;do{if(0===s)throw new Error("Failed to sanitize html because the input is unstable");s--,i=a,a=n.getInnerHTML(o),o=Ce.getInertBodyElement(i)}while(i!==a);var l=new Re,u=l.sanitizeChildren(n.getTemplateContent(o)||o);return Object(r.O)()&&l.sanitizedSomething&&n.log("WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss)."),u}finally{if(o)for(var c=n.getTemplateContent(o)||o,h=0,p=n.childNodesAsList(c);h=0},t.prototype.isFocusable=function(t){return function(t){return!function(t){return function(t){return"input"==t.nodeName.toLowerCase()}(t)&&"hidden"==t.type}(t)&&(function(t){var e=t.nodeName.toLowerCase();return"input"===e||"select"===e||"button"===e||"textarea"===e}(t)||function(t){return function(t){return"a"==t.nodeName.toLowerCase()}(t)&&t.hasAttribute("href")}(t)||t.hasAttribute("contenteditable")||Pn(t))}(t)&&!this.isDisabled(t)&&this.isVisible(t)},t}();function Pn(t){if(!t.hasAttribute("tabindex")||void 0===t.tabIndex)return!1;var e=t.getAttribute("tabindex");return"-32768"!=e&&!(!e||isNaN(parseInt(e,10)))}function Dn(t){if(!Pn(t))return null;var e=parseInt(t.getAttribute("tabindex")||"",10);return isNaN(e)?-1:e}var Rn=function(){function t(t,e,n,r,o){void 0===o&&(o=!1),this._element=t,this._checker=e,this._ngZone=n,this._document=r,this._enabled=!0,o||this.attachAnchors()}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._startAnchor.tabIndex=this._endAnchor.tabIndex=this._enabled?0:-1)},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){this._startAnchor&&this._startAnchor.parentNode&&this._startAnchor.parentNode.removeChild(this._startAnchor),this._endAnchor&&this._endAnchor.parentNode&&this._endAnchor.parentNode.removeChild(this._endAnchor),this._startAnchor=this._endAnchor=null},t.prototype.attachAnchors=function(){var t=this;this._startAnchor||(this._startAnchor=this._createAnchor()),this._endAnchor||(this._endAnchor=this._createAnchor()),this._ngZone.runOutsideAngular(function(){t._startAnchor.addEventListener("focus",function(){t.focusLastTabbableElement()}),t._endAnchor.addEventListener("focus",function(){t.focusFirstTabbableElement()}),t._element.parentNode&&(t._element.parentNode.insertBefore(t._startAnchor,t._element),t._element.parentNode.insertBefore(t._endAnchor,t._element.nextSibling))})},t.prototype.focusInitialElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusInitialElement())})})},t.prototype.focusFirstTabbableElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusFirstTabbableElement())})})},t.prototype.focusLastTabbableElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusLastTabbableElement())})})},t.prototype._getRegionBoundary=function(t){for(var e=this._element.querySelectorAll("[cdk-focus-region-"+t+"], [cdkFocusRegion"+t+"], [cdk-focus-"+t+"]"),n=0;n=0;n--){var r=e[n].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[n]):null;if(r)return r}return null},t.prototype._createAnchor=function(){var t=this._document.createElement("div");return t.tabIndex=this._enabled?0:-1,t.classList.add("cdk-visually-hidden"),t.classList.add("cdk-focus-trap-anchor"),t},t.prototype._executeOnStable=function(t){this._ngZone.isStable?t():this._ngZone.onStable.asObservable().pipe(En(1)).subscribe(t)},t}(),In=function(){function t(t,e,n){this._checker=t,this._ngZone=e,this._document=n}return t.prototype.create=function(t,e){return void 0===e&&(e=!1),new Rn(t,this._checker,this._ngZone,this._document,e)},t}();function Nn(t,e){return(t.getAttribute(e)||"").match(/\S+/g)||[]}var jn=0,Vn=new Map,Mn=null,Fn=function(){function t(t){this._document=t}return t.prototype.describe=function(t,e){this._canBeDescribed(t,e)&&(Vn.has(e)||this._createMessageElement(e),this._isElementDescribedByMessage(t,e)||this._addMessageReference(t,e))},t.prototype.removeDescription=function(t,e){if(this._canBeDescribed(t,e)){this._isElementDescribedByMessage(t,e)&&this._removeMessageReference(t,e);var n=Vn.get(e);n&&0===n.referenceCount&&this._deleteMessageElement(e),Mn&&0===Mn.childNodes.length&&this._deleteMessagesContainer()}},t.prototype.ngOnDestroy=function(){for(var t=this._document.querySelectorAll("[cdk-describedby-host]"),e=0;e=0?this.period=Number(n)<1?1:Number(n):Object(nr.a)(n)&&(r=n),Object(nr.a)(r)||(r=kn),this.scheduler=r,this.dueTime=(i=e)instanceof Date&&!isNaN(+i)?+e-this.scheduler.now():e}return Object(l.b)(e,t),e.create=function(t,n,r){return void 0===t&&(t=0),new e(t,n,r)},e.dispatch=function(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}},e.prototype._subscribe=function(t){return this.scheduler.schedule(e.dispatch,this.dueTime,{index:0,period:this.period,subscriber:t})},e}(I.a).create;function or(t,e){return void 0===e&&(e=kn),n=function(){return rr(t,e)},function(t){return t.lift(new Jn(n))};var n}var ir=n("/nXB"),sr=function(){function t(t,e){this._ngZone=t,this._platform=e,this._scrolled=new _t.a,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map}return t.prototype.register=function(t){var e=this,n=t.elementScrolled().subscribe(function(){return e._scrolled.next(t)});this.scrollContainers.set(t,n)},t.prototype.deregister=function(t){var e=this.scrollContainers.get(t);e&&(e.unsubscribe(),this.scrollContainers.delete(t))},t.prototype.scrolled=function(t){var e=this;return void 0===t&&(t=20),this._platform.isBrowser?I.a.create(function(n){e._globalSubscription||e._addGlobalListener();var r=t>0?e._scrolled.pipe(or(t)).subscribe(n):e._scrolled.subscribe(n);return e._scrolledCount++,function(){r.unsubscribe(),e._scrolledCount--,e._scrolledCount||e._removeGlobalListener()}}):s()},t.prototype.ngOnDestroy=function(){var t=this;this._removeGlobalListener(),this.scrollContainers.forEach(function(e,n){return t.deregister(n)})},t.prototype.ancestorScrolled=function(t,e){var n=this.getAncestorScrollContainers(t);return this.scrolled(e).pipe(c(function(t){return!t||n.indexOf(t)>-1}))},t.prototype.getAncestorScrollContainers=function(t){var e=this,n=[];return this.scrollContainers.forEach(function(r,o){e._scrollableContainsElement(o,t)&&n.push(o)}),n},t.prototype._scrollableContainsElement=function(t,e){var n=e.nativeElement,r=t.getElementRef().nativeElement;do{if(n==r)return!0}while(n=n.parentElement);return!1},t.prototype._addGlobalListener=function(){var t=this;this._globalSubscription=this._ngZone.runOutsideAngular(function(){return Kn(window.document,"scroll").subscribe(function(){return t._scrolled.next()})})},t.prototype._removeGlobalListener=function(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)},t}();function ar(t,e,n){return t||new sr(e,n)}var lr=function(){function t(t,e){var n=this;this._platform=t,this._change=t.isBrowser?e.runOutsideAngular(function(){return Object(ir.a)(Kn(window,"resize"),Kn(window,"orientationchange"))}):s(),this._invalidateCache=this.change().subscribe(function(){return n._updateViewportSize()})}return t.prototype.ngOnDestroy=function(){this._invalidateCache.unsubscribe()},t.prototype.getViewportSize=function(){this._viewportSize||this._updateViewportSize();var t={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),t},t.prototype.getViewportRect=function(){var t=this.getViewportScrollPosition(),e=this.getViewportSize(),n=e.width,r=e.height;return{top:t.top,left:t.left,bottom:t.top+r,right:t.left+n,height:r,width:n}},t.prototype.getViewportScrollPosition=function(){if(!this._platform.isBrowser)return{top:0,left:0};var t=document.documentElement.getBoundingClientRect();return{top:-t.top||document.body.scrollTop||window.scrollY||document.documentElement.scrollTop||0,left:-t.left||document.body.scrollLeft||window.scrollX||document.documentElement.scrollLeft||0}},t.prototype.change=function(t){return void 0===t&&(t=20),t>0?this._change.pipe(or(t)):this._change},t.prototype._updateViewportSize=function(){this._viewportSize=this._platform.isBrowser?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0}},t}();function ur(t,e,n){return t||new lr(e,n)}var cr=function(){};function hr(){throw Error("Host already has a portal attached")}var pr=function(){function t(){}return t.prototype.attach=function(t){return null==t&&function(){throw Error("Attempting to attach a portal to a null PortalOutlet")}(),t.hasAttached()&&hr(),this._attachedHost=t,t.attach(this)},t.prototype.detach=function(){var t=this._attachedHost;null==t?function(){throw Error("Attempting to detach a portal that is not attached to a host")}():(this._attachedHost=null,t.detach())},Object.defineProperty(t.prototype,"isAttached",{get:function(){return null!=this._attachedHost},enumerable:!0,configurable:!0}),t.prototype.setAttachedHost=function(t){this._attachedHost=t},t}(),dr=function(t){function e(e,n,r){var o=t.call(this)||this;return o.component=e,o.viewContainerRef=n,o.injector=r,o}return Object(l.b)(e,t),e}(pr),fr=function(t){function e(e,n,r){var o=t.call(this)||this;return o.templateRef=e,o.viewContainerRef=n,o.context=r,o}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"origin",{get:function(){return this.templateRef.elementRef},enumerable:!0,configurable:!0}),e.prototype.attach=function(e,n){return void 0===n&&(n=this.context),this.context=n,t.prototype.attach.call(this,e)},e.prototype.detach=function(){return this.context=void 0,t.prototype.detach.call(this)},e}(pr),mr=function(){function t(){this._isDisposed=!1}return t.prototype.hasAttached=function(){return!!this._attachedPortal},t.prototype.attach=function(t){return t||function(){throw Error("Must provide a portal to attach")}(),this.hasAttached()&&hr(),this._isDisposed&&function(){throw Error("This PortalOutlet has already been disposed")}(),t instanceof dr?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof fr?(this._attachedPortal=t,this.attachTemplatePortal(t)):void function(){throw Error("Attempting to attach an unknown Portal type. BasePortalOutlet accepts either a ComponentPortal or a TemplatePortal.")}()},t.prototype.detach=function(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()},t.prototype.dispose=function(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0},t.prototype.setDisposeFn=function(t){this._disposeFn=t},t.prototype._invokeDisposeFn=function(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)},t}(),yr=function(t){function e(e,n,r,o){var i=t.call(this)||this;return i.outletElement=e,i._componentFactoryResolver=n,i._appRef=r,i._defaultInjector=o,i}return Object(l.b)(e,t),e.prototype.attachComponentPortal=function(t){var e,n=this,r=this._componentFactoryResolver.resolveComponentFactory(t.component);return t.viewContainerRef?(e=t.viewContainerRef.createComponent(r,t.viewContainerRef.length,t.injector||t.viewContainerRef.parentInjector),this.setDisposeFn(function(){return e.destroy()})):(e=r.create(t.injector||this._defaultInjector),this._appRef.attachView(e.hostView),this.setDisposeFn(function(){n._appRef.detachView(e.hostView),e.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(e)),e},e.prototype.attachTemplatePortal=function(t){var e=this,n=t.viewContainerRef,r=n.createEmbeddedView(t.templateRef,t.context);return r.detectChanges(),r.rootNodes.forEach(function(t){return e.outletElement.appendChild(t)}),this.setDisposeFn(function(){var t=n.indexOf(r);-1!==t&&n.remove(t)}),r},e.prototype.dispose=function(){t.prototype.dispose.call(this),null!=this.outletElement.parentNode&&this.outletElement.parentNode.removeChild(this.outletElement)},e.prototype._getComponentRootNode=function(t){return t.hostView.rootNodes[0]},e}(mr),_r=function(t){function e(e,n){var o=t.call(this)||this;return o._componentFactoryResolver=e,o._viewContainerRef=n,o._isInitialized=!1,o.attached=new r.l,o}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"_deprecatedPortal",{get:function(){return this.portal},set:function(t){this.portal=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_deprecatedPortalHost",{get:function(){return this.portal},set:function(t){this.portal=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"portal",{get:function(){return this._attachedPortal},set:function(e){(!this.hasAttached()||e||this._isInitialized)&&(this.hasAttached()&&t.prototype.detach.call(this),e&&t.prototype.attach.call(this,e),this._attachedPortal=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"attachedRef",{get:function(){return this._attachedRef},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){this._isInitialized=!0},e.prototype.ngOnDestroy=function(){t.prototype.dispose.call(this),this._attachedPortal=null,this._attachedRef=null},e.prototype.attachComponentPortal=function(e){e.setAttachedHost(this);var n=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,r=this._componentFactoryResolver.resolveComponentFactory(e.component),o=n.createComponent(r,n.length,e.injector||n.parentInjector);return t.prototype.setDisposeFn.call(this,function(){return o.destroy()}),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o},e.prototype.attachTemplatePortal=function(e){var n=this;e.setAttachedHost(this);var r=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return t.prototype.setDisposeFn.call(this,function(){return n._viewContainerRef.clear()}),this._attachedPortal=e,this._attachedRef=r,this.attached.emit(r),r},e}(mr),gr=function(){},vr=function(){function t(t,e){this._parentInjector=t,this._customTokens=e}return t.prototype.get=function(t,e){var n=this._customTokens.get(t);return"undefined"!=typeof n?n:this._parentInjector.get(t,e)},t}(),br=function(){function t(){}return t.prototype.enable=function(){},t.prototype.disable=function(){},t.prototype.attach=function(){},t}(),wr=function(){return function(t){var e=this;this.scrollStrategy=new br,this.panelClass="",this.hasBackdrop=!1,this.backdropClass="cdk-overlay-dark-backdrop",this.direction="ltr",t&&Object.keys(t).filter(function(e){return"undefined"!=typeof t[e]}).forEach(function(n){return e[n]=t[n]})}}();function Er(){return Error("Scroll strategy has already been attached.")}var Cr=function(){function t(t,e,n,r){var o=this;this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=n,this._config=r,this._scrollSubscription=null,this._detach=function(){o.disable(),o._overlayRef.hasAttached()&&o._ngZone.run(function(){return o._overlayRef.detach()})}}return t.prototype.attach=function(t){if(this._overlayRef)throw Er();this._overlayRef=t},t.prototype.enable=function(){var t=this;if(!this._scrollSubscription){var e=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=e.subscribe(function(){var e=t._viewportRuler.getViewportScrollPosition().top;Math.abs(e-t._initialScrollPosition)>t._config.threshold?t._detach():t._overlayRef.updatePosition()})):this._scrollSubscription=e.subscribe(this._detach)}},t.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},t}(),xr=function(){function t(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:"",left:""},this._isEnabled=!1,this._document=e}return t.prototype.attach=function(){},t.prototype.enable=function(){if(this._canBeEnabled()){var t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||"",this._previousHTMLStyles.top=t.style.top||"",t.style.left=-this._previousScrollPosition.left+"px",t.style.top=-this._previousScrollPosition.top+"px",t.classList.add("cdk-global-scrollblock"),this._isEnabled=!0}},t.prototype.disable=function(){if(this._isEnabled){var t=this._document.documentElement,e=this._document.body,n=t.style.scrollBehavior||"",r=e.style.scrollBehavior||"";this._isEnabled=!1,t.style.left=this._previousHTMLStyles.left,t.style.top=this._previousHTMLStyles.top,t.classList.remove("cdk-global-scrollblock"),t.style.scrollBehavior=e.style.scrollBehavior="auto",window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),t.style.scrollBehavior=n,e.style.scrollBehavior=r}},t.prototype._canBeEnabled=function(){if(this._document.documentElement.classList.contains("cdk-global-scrollblock")||this._isEnabled)return!1;var t=this._document.body,e=this._viewportRuler.getViewportSize();return t.scrollHeight>e.height||t.scrollWidth>e.width},t}();function Sr(t,e){return e.some(function(e){return t.bottome.bottom||t.righte.right})}function Or(t,e){return e.some(function(e){return t.tope.bottom||t.lefte.right})}var Tr=function(){function t(t,e,n,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=n,this._config=r,this._scrollSubscription=null}return t.prototype.attach=function(t){if(this._overlayRef)throw Er();this._overlayRef=t},t.prototype.enable=function(){var t=this;this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(function(){if(t._overlayRef.updatePosition(),t._config&&t._config.autoClose){var e=t._overlayRef.overlayElement.getBoundingClientRect(),n=t._viewportRuler.getViewportSize(),r=n.width,o=n.height;Sr(e,[{width:r,height:o,bottom:o,right:r,top:0,left:0}])&&(t.disable(),t._ngZone.run(function(){return t._overlayRef.detach()}))}}))},t.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},t}(),kr=function(){return function(t,e,n,r){var o=this;this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=n,this.noop=function(){return new br},this.close=function(t){return new Cr(o._scrollDispatcher,o._ngZone,o._viewportRuler,t)},this.block=function(){return new xr(o._viewportRuler,o._document)},this.reposition=function(t){return new Tr(o._scrollDispatcher,o._viewportRuler,o._ngZone,t)},this._document=r}}(),Ar=function(){function t(t,e,n,r,o,i){this._portalOutlet=t,this._pane=e,this._config=n,this._ngZone=r,this._keyboardDispatcher=o,this._document=i,this._backdropElement=null,this._backdropClick=new _t.a,this._attachments=new _t.a,this._detachments=new _t.a,this._keydownEvents=new _t.a,n.scrollStrategy&&n.scrollStrategy.attach(this)}return Object.defineProperty(t.prototype,"overlayElement",{get:function(){return this._pane},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backdropElement",{get:function(){return this._backdropElement},enumerable:!0,configurable:!0}),t.prototype.attach=function(t){var e=this,n=this._portalOutlet.attach(t);return this._config.positionStrategy&&this._config.positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._config.scrollStrategy&&this._config.scrollStrategy.enable(),this._ngZone.onStable.asObservable().pipe(En(1)).subscribe(function(){e.hasAttached()&&e.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&(Array.isArray(this._config.panelClass)?this._config.panelClass.forEach(function(t){return e._pane.classList.add(t)}):this._pane.classList.add(this._config.panelClass)),this._attachments.next(),this._keyboardDispatcher.add(this),n},t.prototype.detach=function(){if(this.hasAttached()){this.detachBackdrop(),this._togglePointerEvents(!1),this._config.positionStrategy&&this._config.positionStrategy.detach&&this._config.positionStrategy.detach(),this._config.scrollStrategy&&this._config.scrollStrategy.disable();var t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),t}},t.prototype.dispose=function(){var t=this.hasAttached();this._config.positionStrategy&&this._config.positionStrategy.dispose(),this._config.scrollStrategy&&this._config.scrollStrategy.disable(),this.detachBackdrop(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),t&&this._detachments.next(),this._detachments.complete()},t.prototype.hasAttached=function(){return this._portalOutlet.hasAttached()},t.prototype.backdropClick=function(){return this._backdropClick.asObservable()},t.prototype.attachments=function(){return this._attachments.asObservable()},t.prototype.detachments=function(){return this._detachments.asObservable()},t.prototype.keydownEvents=function(){return this._keydownEvents.asObservable()},t.prototype.getConfig=function(){return this._config},t.prototype.updatePosition=function(){this._config.positionStrategy&&this._config.positionStrategy.apply()},t.prototype.updateSize=function(t){this._config=Object(l.a)({},this._config,t),this._updateElementSize()},t.prototype.setDirection=function(t){this._config=Object(l.a)({},this._config,{direction:t}),this._updateElementDirection()},t.prototype._updateElementDirection=function(){this._pane.setAttribute("dir",this._config.direction)},t.prototype._updateElementSize=function(){(this._config.width||0===this._config.width)&&(this._pane.style.width=Pr(this._config.width)),(this._config.height||0===this._config.height)&&(this._pane.style.height=Pr(this._config.height)),(this._config.minWidth||0===this._config.minWidth)&&(this._pane.style.minWidth=Pr(this._config.minWidth)),(this._config.minHeight||0===this._config.minHeight)&&(this._pane.style.minHeight=Pr(this._config.minHeight)),(this._config.maxWidth||0===this._config.maxWidth)&&(this._pane.style.maxWidth=Pr(this._config.maxWidth)),(this._config.maxHeight||0===this._config.maxHeight)&&(this._pane.style.maxHeight=Pr(this._config.maxHeight))},t.prototype._togglePointerEvents=function(t){this._pane.style.pointerEvents=t?"auto":"none"},t.prototype._attachBackdrop=function(){var t=this;this._backdropElement=this._document.createElement("div"),this._backdropElement.classList.add("cdk-overlay-backdrop"),this._config.backdropClass&&this._backdropElement.classList.add(this._config.backdropClass),this._pane.parentElement.insertBefore(this._backdropElement,this._pane),this._backdropElement.addEventListener("click",function(e){return t._backdropClick.next(e)}),"undefined"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(function(){requestAnimationFrame(function(){t._backdropElement&&t._backdropElement.classList.add("cdk-overlay-backdrop-showing")})}):this._backdropElement.classList.add("cdk-overlay-backdrop-showing")},t.prototype._updateStackingOrder=function(){this._pane.nextSibling&&this._pane.parentNode.appendChild(this._pane)},t.prototype.detachBackdrop=function(){var t=this,e=this._backdropElement;if(e){var n=function(){e&&e.parentNode&&e.parentNode.removeChild(e),t._backdropElement==e&&(t._backdropElement=null)};e.classList.remove("cdk-overlay-backdrop-showing"),this._config.backdropClass&&e.classList.remove(this._config.backdropClass),e.addEventListener("transitionend",n),e.style.pointerEvents="none",this._ngZone.runOutsideAngular(function(){setTimeout(n,500)})}},t}();function Pr(t){return"string"==typeof t?t:t+"px"}var Dr=function(){function t(t,e,n,r,o){this._connectedTo=n,this._viewportRuler=r,this._document=o,this._dir="ltr",this._offsetX=0,this._offsetY=0,this.scrollables=[],this._resizeSubscription=Sn.a.EMPTY,this._preferredPositions=[],this._applied=!1,this._positionLocked=!1,this._onPositionChange=new _t.a,this._origin=this._connectedTo.nativeElement,this.withFallbackPosition(t,e)}return Object.defineProperty(t.prototype,"_isRtl",{get:function(){return"rtl"===this._dir},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onPositionChange",{get:function(){return this._onPositionChange.asObservable()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positions",{get:function(){return this._preferredPositions},enumerable:!0,configurable:!0}),t.prototype.attach=function(t){var e=this;this._pane=t.overlayElement,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(function(){return e.apply()})},t.prototype.dispose=function(){this._applied=!1,this._resizeSubscription.unsubscribe(),this._onPositionChange.complete()},t.prototype.detach=function(){this._applied=!1,this._resizeSubscription.unsubscribe()},t.prototype.apply=function(){if(this._applied&&this._positionLocked&&this._lastConnectedPosition)this.recalculateLastPosition();else{this._applied=!0;for(var t,e,n=this._pane,r=this._origin.getBoundingClientRect(),o=n.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),s=0,a=this._preferredPositions;s-1&&this._attachedOverlays.splice(e,1),0===this._attachedOverlays.length&&this._unsubscribeFromKeydownEvents()},t.prototype._subscribeToKeydownEvents=function(){var t=this,e=Kn(this._document.body,"keydown",!0);this._keydownEventSubscription=e.pipe(c(function(){return!!t._attachedOverlays.length})).subscribe(function(e){t._selectOverlayFromEvent(e)._keydownEvents.next(e)})},t.prototype._unsubscribeFromKeydownEvents=function(){this._keydownEventSubscription&&(this._keydownEventSubscription.unsubscribe(),this._keydownEventSubscription=null)},t.prototype._selectOverlayFromEvent=function(t){return this._attachedOverlays.find(function(e){return e.overlayElement===t.target||e.overlayElement.contains(t.target)})||this._attachedOverlays[this._attachedOverlays.length-1]},t}();function jr(t,e){return t||new Nr(e)}var Vr=function(){function t(t){this._document=t}return t.prototype.ngOnDestroy=function(){this._containerElement&&this._containerElement.parentNode&&this._containerElement.parentNode.removeChild(this._containerElement)},t.prototype.getContainerElement=function(){return this._containerElement||this._createContainer(),this._containerElement},t.prototype._createContainer=function(){var t=this._document.createElement("div");t.classList.add("cdk-overlay-container"),this._document.body.appendChild(t),this._containerElement=t},t}();function Mr(t,e){return t||new Vr(e)}var Fr=0,Lr=function(){function t(t,e,n,r,o,i,s,a,l){this.scrollStrategies=t,this._overlayContainer=e,this._componentFactoryResolver=n,this._positionBuilder=r,this._keyboardDispatcher=o,this._appRef=i,this._injector=s,this._ngZone=a,this._document=l}return t.prototype.create=function(t){var e=this._createPaneElement(),n=this._createPortalOutlet(e);return new Ar(n,e,new wr(t),this._ngZone,this._keyboardDispatcher,this._document)},t.prototype.position=function(){return this._positionBuilder},t.prototype._createPaneElement=function(){var t=this._document.createElement("div");return t.id="cdk-overlay-"+Fr++,t.classList.add("cdk-overlay-pane"),this._overlayContainer.getContainerElement().appendChild(t),t},t.prototype._createPortalOutlet=function(t){return new yr(t,this._componentFactoryResolver,this._appRef,this._injector)},t}(),Br=new r.n("cdk-connected-overlay-scroll-strategy");function Hr(t){return function(){return t.scrollStrategies.reposition()}}var zr=function(){},Ur=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return I.a.of(this.value);case"E":return I.a.throw(this.error);case"C":return I.a.empty()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return"undefined"!=typeof e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}(),Yr=function(t){function e(e,n){t.call(this),this.sources=e,this.resultSelector=n}return Object(l.b)(e,t),e.create=function(){for(var t=[],n=0;nt?{max:{max:t,actual:e.value}}:null}},t.required=function(t){return Jr(t.value)?{required:!0}:null},t.requiredTrue=function(t){return!0===t.value?null:{required:!0}},t.email=function(t){return to.test(t.value)?null:{email:!0}},t.minLength=function(t){return function(e){if(Jr(e.value))return null;var n=e.value?e.value.length:0;return nt?{maxlength:{requiredLength:t,actualLength:n}}:null}},t.pattern=function(e){return e?("string"==typeof e?(r="","^"!==e.charAt(0)&&(r+="^"),r+=e,"$"!==e.charAt(e.length-1)&&(r+="$"),n=new RegExp(r)):(r=e.toString(),n=e),function(t){if(Jr(t.value))return null;var e=t.value;return n.test(e)?null:{pattern:{requiredPattern:r,actualValue:e}}}):t.nullValidator;var n,r},t.nullValidator=function(t){return null},t.compose=function(t){if(!t)return null;var e=t.filter(no);return 0==e.length?null:function(t){return oo(function(t,n){return e.map(function(e){return e(t)})}(t))}},t.composeAsync=function(t){if(!t)return null;var e=t.filter(no);return 0==e.length?null:function(t){var n=function(t,n){return e.map(function(e){return e(t)})}(t).map(ro);return m.call(Xr(n),oo)}},t}();function no(t){return null!=t}function ro(t){var e=Object(r._3)(t)?Kr(t):t;if(!Object(r._2)(e))throw new Error("Expected validator to return Promise or Observable.");return e}function oo(t){var e=t.reduce(function(t,e){return null!=e?Object(l.a)({},t,e):t},{});return 0===Object.keys(e).length?null:e}var io=new r.n("NgValueAccessor"),so=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"checked",t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),ao=new r.n("CompositionEventMode"),lo=function(){function t(t,e,n){var r;this._renderer=t,this._elementRef=e,this._compositionMode=n,this.onChange=function(t){},this.onTouched=function(){},this._composing=!1,null==this._compositionMode&&(this._compositionMode=(r=vt()?vt().getUserAgent():"",!/android (\d+)/.test(r.toLowerCase())))}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._handleInput=function(t){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(t)},t.prototype._compositionStart=function(){this._composing=!0},t.prototype._compositionEnd=function(t){this._composing=!1,this._compositionMode&&this.onChange(t)},t}();function uo(t){return t.validate?function(e){return t.validate(e)}:t}function co(t){return t.validate?function(e){return t.validate(e)}:t}var ho=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}();function po(){throw new Error("unimplemented")}var fo=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._parent=null,e.name=null,e.valueAccessor=null,e._rawValidators=[],e._rawAsyncValidators=[],e}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"validator",{get:function(){return po()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return po()},enumerable:!0,configurable:!0}),e}(Wr),mo=function(){function t(){this._accessors=[]}return t.prototype.add=function(t,e){this._accessors.push([t,e])},t.prototype.remove=function(t){for(var e=this._accessors.length-1;e>=0;--e)if(this._accessors[e][1]===t)return void this._accessors.splice(e,1)},t.prototype.select=function(t){var e=this;this._accessors.forEach(function(n){e._isSameGroup(n,t)&&n[1]!==t&&n[1].fireUncheck(t.value)})},t.prototype._isSameGroup=function(t,e){return!!t[0].control&&t[0]._parent===e._control._parent&&t[1].name===e.name},t}(),yo=function(){function t(t,e,n,r){this._renderer=t,this._elementRef=e,this._registry=n,this._injector=r,this.onChange=function(){},this.onTouched=function(){}}return t.prototype.ngOnInit=function(){this._control=this._injector.get(fo),this._checkName(),this._registry.add(this._control,this)},t.prototype.ngOnDestroy=function(){this._registry.remove(this)},t.prototype.writeValue=function(t){this._state=t===this.value,this._renderer.setProperty(this._elementRef.nativeElement,"checked",this._state)},t.prototype.registerOnChange=function(t){var e=this;this._fn=t,this.onChange=function(){t(e.value),e._registry.select(e)}},t.prototype.fireUncheck=function(t){this.writeValue(t)},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._checkName=function(){this.name&&this.formControlName&&this.name!==this.formControlName&&this._throwNameError(),!this.name&&this.formControlName&&(this.name=this.formControlName)},t.prototype._throwNameError=function(){throw new Error('\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: \n ')},t}();function _o(t,e){return e.path.concat([t])}function go(t,e){t||Eo(e,"Cannot find control with"),e.valueAccessor||Eo(e,"No value accessor for form control with"),t.validator=eo.compose([t.validator,e.validator]),t.asyncValidator=eo.composeAsync([t.asyncValidator,e.asyncValidator]),e.valueAccessor.writeValue(t.value),function(t,e){e.valueAccessor.registerOnChange(function(n){t._pendingValue=n,t._pendingChange=!0,t._pendingDirty=!0,"change"===t.updateOn&&vo(t,e)})}(t,e),function(t,e){t.registerOnChange(function(t,n){e.valueAccessor.writeValue(t),n&&e.viewToModelUpdate(t)})}(t,e),function(t,e){e.valueAccessor.registerOnTouched(function(){t._pendingTouched=!0,"blur"===t.updateOn&&t._pendingChange&&vo(t,e),"submit"!==t.updateOn&&t.markAsTouched()})}(t,e),e.valueAccessor.setDisabledState&&t.registerOnDisabledChange(function(t){e.valueAccessor.setDisabledState(t)}),e._rawValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})}),e._rawAsyncValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})})}function vo(t,e){e.viewToModelUpdate(t._pendingValue),t._pendingDirty&&t.markAsDirty(),t.setValue(t._pendingValue,{emitModelToViewChange:!1}),t._pendingChange=!1}function bo(t,e){null==t&&Eo(e,"Cannot find control with"),t.validator=eo.compose([t.validator,e.validator]),t.asyncValidator=eo.composeAsync([t.asyncValidator,e.asyncValidator])}function wo(t){return Eo(t,"There is no FormControl instance attached to form control element with")}function Eo(t,e){var n;throw n=t.path.length>1?"path: '"+t.path.join(" -> ")+"'":t.path[0]?"name: '"+t.path+"'":"unspecified name attribute",new Error(e+" "+n)}function Co(t){return null!=t?eo.compose(t.map(uo)):null}function xo(t){return null!=t?eo.composeAsync(t.map(co)):null}var So=[so,function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",parseFloat(t))},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),ho,function(){function t(t,e){this._renderer=t,this._elementRef=e,this._optionMap=new Map,this._idCounter=0,this.onChange=function(t){},this.onTouched=function(){},this._compareWith=r._4}return Object.defineProperty(t.prototype,"compareWith",{set:function(t){if("function"!=typeof t)throw new Error("compareWith must be a function, but received "+JSON.stringify(t));this._compareWith=t},enumerable:!0,configurable:!0}),t.prototype.writeValue=function(t){this.value=t;var e=this._getOptionId(t);null==e&&this._renderer.setProperty(this._elementRef.nativeElement,"selectedIndex",-1);var n=function(t,e){return null==t?""+e:(e&&"object"==typeof e&&(e="Object"),(t+": "+e).slice(0,50))}(e,t);this._renderer.setProperty(this._elementRef.nativeElement,"value",n)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){e.value=e._getOptionValue(n),t(e.value)}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._registerOption=function(){return(this._idCounter++).toString()},t.prototype._getOptionId=function(t){for(var e=0,n=Array.from(this._optionMap.keys());e-1)}}else e=function(t,e){t._setSelected(!1)};this._optionMap.forEach(e)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){var r=[];if(n.hasOwnProperty("selectedOptions"))for(var o=n.selectedOptions,i=0;i-1&&t.splice(n,1)}var ko=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e.prototype.ngOnInit=function(){this._checkParentType(),this.formDirective.addFormGroup(this)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeFormGroup(this)},Object.defineProperty(e.prototype,"control",{get:function(){return this.formDirective.getFormGroup(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return _o(this.name,this._parent)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return Co(this._validators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return xo(this._asyncValidators)},enumerable:!0,configurable:!0}),e.prototype._checkParentType=function(){},e}($r),Ao=function(t){function e(e){return t.call(this,e)||this}return Object(l.b)(e,t),e}(function(){function t(t){this._cd=t}return Object.defineProperty(t.prototype,"ngClassUntouched",{get:function(){return!!this._cd.control&&this._cd.control.untouched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassTouched",{get:function(){return!!this._cd.control&&this._cd.control.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPristine",{get:function(){return!!this._cd.control&&this._cd.control.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassDirty",{get:function(){return!!this._cd.control&&this._cd.control.dirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassValid",{get:function(){return!!this._cd.control&&this._cd.control.valid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassInvalid",{get:function(){return!!this._cd.control&&this._cd.control.invalid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPending",{get:function(){return!!this._cd.control&&this._cd.control.pending},enumerable:!0,configurable:!0}),t}());function Po(t){var e=Ro(t)?t.validators:t;return Array.isArray(e)?Co(e):e||null}function Do(t,e){var n=Ro(e)?e.asyncValidators:t;return Array.isArray(n)?xo(n):n||null}function Ro(t){return null!=t&&!Array.isArray(t)&&"object"==typeof t}var Io=function(){function t(t,e){this.validator=t,this.asyncValidator=e,this._onCollectionChange=function(){},this.pristine=!0,this.touched=!1,this._onDisabledChange=[]}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valid",{get:function(){return"VALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invalid",{get:function(){return"INVALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pending",{get:function(){return"PENDING"==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disabled",{get:function(){return"DISABLED"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"enabled",{get:function(){return"DISABLED"!==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dirty",{get:function(){return!this.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"untouched",{get:function(){return!this.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateOn",{get:function(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"},enumerable:!0,configurable:!0}),t.prototype.setValidators=function(t){this.validator=Po(t)},t.prototype.setAsyncValidators=function(t){this.asyncValidator=Do(t)},t.prototype.clearValidators=function(){this.validator=null},t.prototype.clearAsyncValidators=function(){this.asyncValidator=null},t.prototype.markAsTouched=function(t){void 0===t&&(t={}),this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)},t.prototype.markAsUntouched=function(t){void 0===t&&(t={}),this.touched=!1,this._pendingTouched=!1,this._forEachChild(function(t){t.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype.markAsDirty=function(t){void 0===t&&(t={}),this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)},t.prototype.markAsPristine=function(t){void 0===t&&(t={}),this.pristine=!0,this._pendingDirty=!1,this._forEachChild(function(t){t.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype.markAsPending=function(t){void 0===t&&(t={}),this.status="PENDING",this._parent&&!t.onlySelf&&this._parent.markAsPending(t)},t.prototype.disable=function(t){void 0===t&&(t={}),this.status="DISABLED",this.errors=null,this._forEachChild(function(e){e.disable(Object(l.a)({},t,{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!0)})},t.prototype.enable=function(t){void 0===t&&(t={}),this.status="VALID",this._forEachChild(function(e){e.enable(Object(l.a)({},t,{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!1)})},t.prototype._updateAncestors=function(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),this._parent._updatePristine(),this._parent._updateTouched())},t.prototype.setParent=function(t){this._parent=t},t.prototype.updateValueAndValidity=function(t){void 0===t&&(t={}),this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),"VALID"!==this.status&&"PENDING"!==this.status||this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)},t.prototype._updateTreeValidity=function(t){void 0===t&&(t={emitEvent:!0}),this._forEachChild(function(e){return e._updateTreeValidity(t)}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})},t.prototype._setInitialStatus=function(){this.status=this._allControlsDisabled()?"DISABLED":"VALID"},t.prototype._runValidator=function(){return this.validator?this.validator(this):null},t.prototype._runAsyncValidator=function(t){var e=this;if(this.asyncValidator){this.status="PENDING";var n=ro(this.asyncValidator(this));this._asyncValidationSubscription=n.subscribe(function(n){return e.setErrors(n,{emitEvent:t})})}},t.prototype._cancelExistingSubscription=function(){this._asyncValidationSubscription&&this._asyncValidationSubscription.unsubscribe()},t.prototype.setErrors=function(t,e){void 0===e&&(e={}),this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)},t.prototype.get=function(t){return function(t,e,n){return null==e?null:(e instanceof Array||(e=e.split(".")),e instanceof Array&&0===e.length?null:e.reduce(function(t,e){return t instanceof jo?t.controls[e]||null:t instanceof Vo&&t.at(e)||null},t))}(this,t)},t.prototype.getError=function(t,e){var n=e?this.get(e):this;return n&&n.errors?n.errors[t]:null},t.prototype.hasError=function(t,e){return!!this.getError(t,e)},Object.defineProperty(t.prototype,"root",{get:function(){for(var t=this;t._parent;)t=t._parent;return t},enumerable:!0,configurable:!0}),t.prototype._updateControlsErrors=function(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)},t.prototype._initObservables=function(){this.valueChanges=new r.l,this.statusChanges=new r.l},t.prototype._calculateStatus=function(){return this._allControlsDisabled()?"DISABLED":this.errors?"INVALID":this._anyControlsHaveStatus("PENDING")?"PENDING":this._anyControlsHaveStatus("INVALID")?"INVALID":"VALID"},t.prototype._anyControlsHaveStatus=function(t){return this._anyControls(function(e){return e.status===t})},t.prototype._anyControlsDirty=function(){return this._anyControls(function(t){return t.dirty})},t.prototype._anyControlsTouched=function(){return this._anyControls(function(t){return t.touched})},t.prototype._updatePristine=function(t){void 0===t&&(t={}),this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype._updateTouched=function(t){void 0===t&&(t={}),this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype._isBoxedValue=function(t){return"object"==typeof t&&null!==t&&2===Object.keys(t).length&&"value"in t&&"disabled"in t},t.prototype._registerOnCollectionChange=function(t){this._onCollectionChange=t},t.prototype._setUpdateStrategy=function(t){Ro(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)},t}(),No=function(t){function e(e,n,r){void 0===e&&(e=null);var o=t.call(this,Po(n),Do(r,n))||this;return o._onChange=[],o._applyFormState(e),o._setUpdateStrategy(n),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o._initObservables(),o}return Object(l.b)(e,t),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(function(t){return t(n.value,!1!==e.emitViewToModelChange)}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){void 0===e&&(e={}),this.setValue(t,e)},e.prototype.reset=function(t,e){void 0===t&&(t=null),void 0===e&&(e={}),this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1},e.prototype._updateValue=function(){},e.prototype._anyControls=function(t){return!1},e.prototype._allControlsDisabled=function(){return this.disabled},e.prototype.registerOnChange=function(t){this._onChange.push(t)},e.prototype._clearChangeFns=function(){this._onChange=[],this._onDisabledChange=[],this._onCollectionChange=function(){}},e.prototype.registerOnDisabledChange=function(t){this._onDisabledChange.push(t)},e.prototype._forEachChild=function(t){},e.prototype._syncPendingControls=function(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))},e.prototype._applyFormState=function(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t},e}(Io),jo=function(t){function e(e,n,r){var o=t.call(this,Po(n),Do(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return Object(l.b)(e,t),e.prototype.registerControl=function(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)},e.prototype.addControl=function(t,e){this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.removeControl=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.contains=function(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled},e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),Object.keys(t).forEach(function(r){n._throwIfControlMissing(r),n.controls[r].setValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),Object.keys(t).forEach(function(r){n.controls[r]&&n.controls[r].patchValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this._reduceChildren({},function(t,e,n){return t[n]=e instanceof No?e.value:e.getRawValue(),t})},e.prototype._syncPendingControls=function(){var t=this._reduceChildren(!1,function(t,e){return!!e._syncPendingControls()||t});return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!Object.keys(this.controls).length)throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.controls[t])throw new Error("Cannot find form control with name: "+t+".")},e.prototype._forEachChild=function(t){var e=this;Object.keys(this.controls).forEach(function(n){return t(e.controls[n],n)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){e.setParent(t),e._registerOnCollectionChange(t._onCollectionChange)})},e.prototype._updateValue=function(){this.value=this._reduceValue()},e.prototype._anyControls=function(t){var e=this,n=!1;return this._forEachChild(function(r,o){n=n||e.contains(o)&&t(r)}),n},e.prototype._reduceValue=function(){var t=this;return this._reduceChildren({},function(e,n,r){return(n.enabled||t.disabled)&&(e[r]=n.value),e})},e.prototype._reduceChildren=function(t,e){var n=t;return this._forEachChild(function(t,r){n=e(n,t,r)}),n},e.prototype._allControlsDisabled=function(){for(var t=0,e=Object.keys(this.controls);t0||this.disabled},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control with name: '"+n+"'.")})},e}(Io),Vo=function(t){function e(e,n,r){var o=t.call(this,Po(n),Do(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return Object(l.b)(e,t),e.prototype.at=function(t){return this.controls[t]},e.prototype.push=function(t){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.insert=function(t,e){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity()},e.prototype.removeAt=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),this.updateValueAndValidity()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity(),this._onCollectionChange()},Object.defineProperty(e.prototype,"length",{get:function(){return this.controls.length},enumerable:!0,configurable:!0}),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),t.forEach(function(t,r){n._throwIfControlMissing(r),n.at(r).setValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),t.forEach(function(t,r){n.at(r)&&n.at(r).patchValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t=[]),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this.controls.map(function(t){return t instanceof No?t.value:t.getRawValue()})},e.prototype._syncPendingControls=function(){var t=this.controls.reduce(function(t,e){return!!e._syncPendingControls()||t},!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!this.controls.length)throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.at(t))throw new Error("Cannot find form control at index "+t)},e.prototype._forEachChild=function(t){this.controls.forEach(function(e,n){t(e,n)})},e.prototype._updateValue=function(){var t=this;this.value=this.controls.filter(function(e){return e.enabled||t.disabled}).map(function(t){return t.value})},e.prototype._anyControls=function(t){return this.controls.some(function(e){return e.enabled&&t(e)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){return t._registerControl(e)})},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control at index: "+n+".")})},e.prototype._allControlsDisabled=function(){for(var t=0,e=this.controls;t0||this.disabled},e.prototype._registerControl=function(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)},e}(Io),Mo=Promise.resolve(null),Fo=function(t){function e(e,n){var o=t.call(this)||this;return o.submitted=!1,o._directives=[],o.ngSubmit=new r.l,o.form=new jo({},Co(e),xo(n)),o}return Object(l.b)(e,t),e.prototype.ngAfterViewInit=function(){this._setUpdateStrategy()},Object.defineProperty(e.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"controls",{get:function(){return this.form.controls},enumerable:!0,configurable:!0}),e.prototype.addControl=function(t){var e=this;Mo.then(function(){var n=e._findContainer(t.path);t.control=n.registerControl(t.name,t.control),go(t.control,t),t.control.updateValueAndValidity({emitEvent:!1}),e._directives.push(t)})},e.prototype.getControl=function(t){return this.form.get(t.path)},e.prototype.removeControl=function(t){var e=this;Mo.then(function(){var n=e._findContainer(t.path);n&&n.removeControl(t.name),To(e._directives,t)})},e.prototype.addFormGroup=function(t){var e=this;Mo.then(function(){var n=e._findContainer(t.path),r=new jo({});bo(r,t),n.registerControl(t.name,r),r.updateValueAndValidity({emitEvent:!1})})},e.prototype.removeFormGroup=function(t){var e=this;Mo.then(function(){var n=e._findContainer(t.path);n&&n.removeControl(t.name)})},e.prototype.getFormGroup=function(t){return this.form.get(t.path)},e.prototype.updateModel=function(t,e){var n=this;Mo.then(function(){n.form.get(t.path).setValue(e)})},e.prototype.setValue=function(t){this.control.setValue(t)},e.prototype.onSubmit=function(t){return this.submitted=!0,Oo(this.form,this._directives),this.ngSubmit.emit(t),!1},e.prototype.onReset=function(){this.resetForm()},e.prototype.resetForm=function(t){void 0===t&&(t=void 0),this.form.reset(t),this.submitted=!1},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)},e.prototype._findContainer=function(t){return t.pop(),t.length?this.form.get(t):this.form},e}($r),Lo='\n

\n \n
\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });',Bo='\n
\n
\n \n
\n
\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });',Ho='\n
\n
\n \n
\n
',zo=function(){function t(){}return t.modelParentException=function(){throw new Error('\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup\'s partner directive "formControlName" instead. Example:\n\n '+Lo+'\n\n Or, if you\'d like to avoid registering this form control, indicate that it\'s standalone in ngModelOptions:\n\n Example:\n\n \n
\n \n \n
\n ')},t.formGroupNameException=function(){throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n "+Bo+"\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n "+Ho)},t.missingNameException=function(){throw new Error('If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as \'standalone\' in ngModelOptions.\n\n Example 1: \n Example 2: ')},t.modelGroupParentException=function(){throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n "+Bo+"\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n "+Ho)},t}(),Uo=function(t){function e(e,n,r){var o=t.call(this)||this;return o._parent=e,o._validators=n,o._asyncValidators=r,o}return Object(l.b)(e,t),e.prototype._checkParentType=function(){this._parent instanceof e||this._parent instanceof Fo||zo.modelGroupParentException()},e}(ko),Yo=Promise.resolve(null),qo=function(t){function e(e,n,o,i){var s=t.call(this)||this;return s.control=new No,s._registered=!1,s.update=new r.l,s._parent=e,s._rawValidators=n||[],s._rawAsyncValidators=o||[],s.valueAccessor=function(t,e){if(!e)return null;var n=void 0,r=void 0,o=void 0;return e.forEach(function(e){var i;e.constructor===lo?n=e:(i=e,So.some(function(t){return i.constructor===t})?(r&&Eo(t,"More than one built-in value accessor matches form control with"),r=e):(o&&Eo(t,"More than one custom value accessor matches form control with"),o=e))}),o||r||n||(Eo(t,"No valid value accessor for form control with"),null)}(s,i),s}return Object(l.b)(e,t),e.prototype.ngOnChanges=function(t){this._checkForErrors(),this._registered||this._setUpControl(),"isDisabled"in t&&this._updateDisabled(t),function(t,e){if(!t.hasOwnProperty("model"))return!1;var n=t.model;return!!n.isFirstChange()||!Object(r._4)(e,n.currentValue)}(t,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeControl(this)},Object.defineProperty(e.prototype,"path",{get:function(){return this._parent?_o(this.name,this._parent):[this.name]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return Co(this._rawValidators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return xo(this._rawAsyncValidators)},enumerable:!0,configurable:!0}),e.prototype.viewToModelUpdate=function(t){this.viewModel=t,this.update.emit(t)},e.prototype._setUpControl=function(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)},e.prototype._isStandalone=function(){return!this._parent||!(!this.options||!this.options.standalone)},e.prototype._setUpStandalone=function(){go(this.control,this),this.control.updateValueAndValidity({emitEvent:!1})},e.prototype._checkForErrors=function(){this._isStandalone()||this._checkParentType(),this._checkName()},e.prototype._checkParentType=function(){!(this._parent instanceof Uo)&&this._parent instanceof ko?zo.formGroupNameException():this._parent instanceof Uo||this._parent instanceof Fo||zo.modelParentException()},e.prototype._checkName=function(){this.options&&this.options.name&&(this.name=this.options.name),this._isStandalone()||this.name||zo.missingNameException()},e.prototype._updateValue=function(t){var e=this;Yo.then(function(){e.control.setValue(t,{emitViewToModelChange:!1})})},e.prototype._updateDisabled=function(t){var e=this,n=t.isDisabled.currentValue,r=""===n||n&&"false"!==n;Yo.then(function(){r&&!e.control.disabled?e.control.disable():!r&&e.control.disabled&&e.control.enable()})},e}(fo),Xo=function(){function t(){}return t.controlParentException=function(){throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n "+Lo)},t.ngModelGroupException=function(){throw new Error('formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a "form" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n '+Bo+"\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n "+Ho)},t.missingFormException=function(){throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n "+Lo)},t.groupParentException=function(){throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n "+Bo)},t.arrayParentException=function(){throw new Error('formArrayName must be used with a parent formGroup directive. You\'ll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n \n
\n
\n
\n \n
\n
\n
\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl(\'SF\')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });')},t.disabledAttrWarning=function(){console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n ")},t}(),Go=function(t){function e(e,n){var o=t.call(this)||this;return o._validators=e,o._asyncValidators=n,o.submitted=!1,o.directives=[],o.form=null,o.ngSubmit=new r.l,o}return Object(l.b)(e,t),e.prototype.ngOnChanges=function(t){this._checkFormPresent(),t.hasOwnProperty("form")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations())},Object.defineProperty(e.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),e.prototype.addControl=function(t){var e=this.form.get(t.path);return go(e,t),e.updateValueAndValidity({emitEvent:!1}),this.directives.push(t),e},e.prototype.getControl=function(t){return this.form.get(t.path)},e.prototype.removeControl=function(t){To(this.directives,t)},e.prototype.addFormGroup=function(t){var e=this.form.get(t.path);bo(e,t),e.updateValueAndValidity({emitEvent:!1})},e.prototype.removeFormGroup=function(t){},e.prototype.getFormGroup=function(t){return this.form.get(t.path)},e.prototype.addFormArray=function(t){var e=this.form.get(t.path);bo(e,t),e.updateValueAndValidity({emitEvent:!1})},e.prototype.removeFormArray=function(t){},e.prototype.getFormArray=function(t){return this.form.get(t.path)},e.prototype.updateModel=function(t,e){this.form.get(t.path).setValue(e)},e.prototype.onSubmit=function(t){return this.submitted=!0,Oo(this.form,this.directives),this.ngSubmit.emit(t),!1},e.prototype.onReset=function(){this.resetForm()},e.prototype.resetForm=function(t){void 0===t&&(t=void 0),this.form.reset(t),this.submitted=!1},e.prototype._updateDomValue=function(){var t=this;this.directives.forEach(function(e){var n=t.form.get(e.path);e.control!==n&&(function(t,e){e.valueAccessor.registerOnChange(function(){return wo(e)}),e.valueAccessor.registerOnTouched(function(){return wo(e)}),e._rawValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(null)}),e._rawAsyncValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(null)}),t&&t._clearChangeFns()}(e.control,e),n&&go(n,e),e.control=n)}),this.form._updateTreeValidity({emitEvent:!1})},e.prototype._updateRegistrations=function(){var t=this;this.form._registerOnCollectionChange(function(){return t._updateDomValue()}),this._oldForm&&this._oldForm._registerOnCollectionChange(function(){}),this._oldForm=this.form},e.prototype._updateValidators=function(){var t=Co(this._validators);this.form.validator=eo.compose([this.form.validator,t]);var e=xo(this._asyncValidators);this.form.asyncValidator=eo.composeAsync([this.form.asyncValidator,e])},e.prototype._checkFormPresent=function(){this.form||Xo.missingFormException()},e}($r),Zo=function(){},Qo=function(){},Ko=n("TILf"),Wo=n("N4j0"),$o=n("cQXm"),Jo=n("etqZ"),ti=function(t){function e(e,n){if(t.call(this),this.scheduler=n,null==e)throw new Error("iterator cannot be null.");this.iterator=ri(e)}return Object(l.b)(e,t),e.create=function(t,n){return new e(t,n)},e.dispatch=function(t){var e=t.index,n=t.iterator,r=t.subscriber;if(t.hasError)r.error(t.error);else{var o=n.next();o.done?r.complete():(r.next(o.value),t.index=e+1,r.closed?"function"==typeof n.return&&n.return():this.schedule(t))}},e.prototype._subscribe=function(t){var n=this.iterator,r=this.scheduler;if(r)return r.schedule(e.dispatch,0,{index:0,iterator:n,subscriber:t});for(;;){var o=n.next();if(o.done){t.complete();break}if(t.next(o.value),t.closed){"function"==typeof n.return&&n.return();break}}},e}(I.a),ei=function(){function t(t,e,n){void 0===e&&(e=0),void 0===n&&(n=t.length),this.str=t,this.idx=e,this.len=n}return t.prototype[Jo.a]=function(){return this},t.prototype.next=function(){return this.idxoi?oi:o:o}()),this.arr=t,this.idx=e,this.len=n}return t.prototype[Jo.a]=function(){return this},t.prototype.next=function(){return this.idx=t.length?r.complete():(r.next(e[n]),t.index=n+1,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.arrayLike,r=this.scheduler,o=n.length;if(r)return r.schedule(e.dispatch,0,{arrayLike:n,index:0,length:o,subscriber:t});for(var i=0;i1?new i.a(t,n):new wn.a(n),e)}}var pi=function(){},di="*";function fi(t,e){return void 0===e&&(e=null),{type:2,steps:t,options:e}}function mi(t){return{type:6,styles:t,offset:null}}function yi(t){Promise.resolve(null).then(t)}var _i=function(){function t(){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this.parentPlayer=null,this.totalTime=0}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.onStart=function(t){this._onStartFns.push(t)},t.prototype.onDone=function(t){this._onDoneFns.push(t)},t.prototype.onDestroy=function(t){this._onDestroyFns.push(t)},t.prototype.hasStarted=function(){return this._started},t.prototype.init=function(){},t.prototype.play=function(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0},t.prototype.triggerMicrotask=function(){var t=this;yi(function(){return t._onFinish()})},t.prototype._onStart=function(){this._onStartFns.forEach(function(t){return t()}),this._onStartFns=[]},t.prototype.pause=function(){},t.prototype.restart=function(){},t.prototype.finish=function(){this._onFinish()},t.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(function(t){return t()}),this._onDestroyFns=[])},t.prototype.reset=function(){},t.prototype.setPosition=function(t){},t.prototype.getPosition=function(){return 0},t.prototype.triggerCallback=function(t){var e="start"==t?this._onStartFns:this._onDoneFns;e.forEach(function(t){return t()}),e.length=0},t}(),gi=function(){function t(t){var e=this;this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;var n=0,r=0,o=0,i=this.players.length;0==i?yi(function(){return e._onFinish()}):this.players.forEach(function(t){t.onDone(function(){++n==i&&e._onFinish()}),t.onDestroy(function(){++r==i&&e._onDestroy()}),t.onStart(function(){++o==i&&e._onStart()})}),this.totalTime=this.players.reduce(function(t,e){return Math.max(t,e.totalTime)},0)}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.init=function(){this.players.forEach(function(t){return t.init()})},t.prototype.onStart=function(t){this._onStartFns.push(t)},t.prototype._onStart=function(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(function(t){return t()}),this._onStartFns=[])},t.prototype.onDone=function(t){this._onDoneFns.push(t)},t.prototype.onDestroy=function(t){this._onDestroyFns.push(t)},t.prototype.hasStarted=function(){return this._started},t.prototype.play=function(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(function(t){return t.play()})},t.prototype.pause=function(){this.players.forEach(function(t){return t.pause()})},t.prototype.restart=function(){this.players.forEach(function(t){return t.restart()})},t.prototype.finish=function(){this._onFinish(),this.players.forEach(function(t){return t.finish()})},t.prototype.destroy=function(){this._onDestroy()},t.prototype._onDestroy=function(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(function(t){return t.destroy()}),this._onDestroyFns.forEach(function(t){return t()}),this._onDestroyFns=[])},t.prototype.reset=function(){this.players.forEach(function(t){return t.reset()}),this._destroyed=!1,this._finished=!1,this._started=!1},t.prototype.setPosition=function(t){var e=t*this.totalTime;this.players.forEach(function(t){var n=t.totalTime?Math.min(1,e/t.totalTime):1;t.setPosition(n)})},t.prototype.getPosition=function(){var t=0;return this.players.forEach(function(e){var n=e.getPosition();t=Math.min(n,t)}),t},t.prototype.beforeDestroy=function(){this.players.forEach(function(t){t.beforeDestroy&&t.beforeDestroy()})},t.prototype.triggerCallback=function(t){var e="start"==t?this._onStartFns:this._onDoneFns;e.forEach(function(t){return t()}),e.length=0},t}(),vi="!",bi=function(){};function wi(t){return Error("A hint was already declared for 'align=\""+t+"\"'.")}var Ei=0,Ci=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o._elementRef=e,o._changeDetectorRef=n,o._showAlwaysAnimate=!1,o._subscriptAnimationState="",o._hintLabel="",o._hintLabelId="mat-hint-"+Ei++,o._labelOptions=r||{},o.floatLabel=o._labelOptions.float||"auto",o}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"dividerColor",{get:function(){return this.color},set:function(t){this.color=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hideRequiredMarker",{get:function(){return this._hideRequiredMarker},set:function(t){this._hideRequiredMarker=yt(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_shouldAlwaysFloat",{get:function(){return"always"===this._floatLabel&&!this._showAlwaysAnimate},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_canLabelFloat",{get:function(){return"never"!==this._floatLabel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hintLabel",{get:function(){return this._hintLabel},set:function(t){this._hintLabel=t,this._processHints()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"floatPlaceholder",{get:function(){return this._floatLabel},set:function(t){this.floatLabel=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"floatLabel",{get:function(){return this._floatLabel},set:function(t){t!==this._floatLabel&&(this._floatLabel=t||this._labelOptions.float||"auto",this._changeDetectorRef.markForCheck())},enumerable:!0,configurable:!0}),e.prototype.ngAfterContentInit=function(){var t=this;this._validateControlChild(),this._control.controlType&&this._elementRef.nativeElement.classList.add("mat-form-field-type-"+this._control.controlType),this._control.stateChanges.pipe(hi(null)).subscribe(function(){t._validatePlaceholders(),t._syncDescribedByIds(),t._changeDetectorRef.markForCheck()});var e=this._control.ngControl;e&&e.valueChanges&&e.valueChanges.subscribe(function(){t._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(hi(null)).subscribe(function(){t._processHints(),t._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(hi(null)).subscribe(function(){t._syncDescribedByIds(),t._changeDetectorRef.markForCheck()})},e.prototype.ngAfterContentChecked=function(){this._validateControlChild()},e.prototype.ngAfterViewInit=function(){this._subscriptAnimationState="enter",this._changeDetectorRef.detectChanges()},e.prototype._shouldForward=function(t){var e=this._control?this._control.ngControl:null;return e&&e[t]},e.prototype._hasPlaceholder=function(){return!(!this._control.placeholder&&!this._placeholderChild)},e.prototype._hasLabel=function(){return!!this._labelChild},e.prototype._shouldLabelFloat=function(){return this._canLabelFloat&&(this._control.shouldLabelFloat||this._control.shouldPlaceholderFloat||this._shouldAlwaysFloat)},e.prototype._hideControlPlaceholder=function(){return!this._hasLabel()||!this._shouldLabelFloat()},e.prototype._hasFloatingLabel=function(){return this._hasLabel()||this._hasPlaceholder()},e.prototype._getDisplayedMessages=function(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?"error":"hint"},e.prototype._animateAndLockLabel=function(){var t=this;this._hasFloatingLabel()&&this._canLabelFloat&&(this._showAlwaysAnimate=!0,this._floatLabel="always",Kn(this._label.nativeElement,"transitionend").pipe(En(1)).subscribe(function(){t._showAlwaysAnimate=!1}),this._changeDetectorRef.markForCheck())},e.prototype._validatePlaceholders=function(){if(this._control.placeholder&&this._placeholderChild)throw Error("Placeholder attribute and child element were both specified.")},e.prototype._processHints=function(){this._validateHints(),this._syncDescribedByIds()},e.prototype._validateHints=function(){var t,e,n=this;this._hintChildren&&this._hintChildren.forEach(function(r){if("start"===r.align){if(t||n.hintLabel)throw wi("start");t=r}else if("end"===r.align){if(e)throw wi("end");e=r}})},e.prototype._syncDescribedByIds=function(){if(this._control){var t=[];if("hint"===this._getDisplayedMessages()){var e=this._hintChildren?this._hintChildren.find(function(t){return"start"===t.align}):null,n=this._hintChildren?this._hintChildren.find(function(t){return"end"===t.align}):null;e?t.push(e.id):this._hintLabel&&t.push(this._hintLabelId),n&&t.push(n.id)}else this._errorChildren&&(t=this._errorChildren.map(function(t){return t.id}));this._control.setDescribedByIds(t)}},e.prototype._validateControlChild=function(){if(!this._control)throw Error("mat-form-field must contain a MatFormFieldControl.")},e}(un(function(t){this._elementRef=t},"primary")),xi=function(){},Si=function(t){function e(e){t.call(this),this.observableFactory=e}return Object(l.b)(e,t),e.create=function(t){return new e(t)},e.prototype._subscribe=function(t){return new Oi(t,this.observableFactory)},e}(I.a),Oi=function(t){function e(e,n){t.call(this,e),this.factory=n,this.tryDefer()}return Object(l.b)(e,t),e.prototype.tryDefer=function(){try{this._callFactory()}catch(t){this._error(t)}},e.prototype._callFactory=function(){var t=this.factory();t&&this.add(Object($n.a)(this,t))},e}(Wn.a),Ti=Si.create,ki="accent",Ai="primary",Pi=["mat-button","mat-flat-button","mat-icon-button","mat-raised-button","mat-stroked-button","mat-mini-fab","mat-fab"],Di=function(t){function e(e,n,r){var o=t.call(this,e)||this;o._platform=n,o._focusMonitor=r,o._isRoundButton=o._hasHostAttributes("mat-fab","mat-mini-fab"),o._isIconButton=o._hasHostAttributes("mat-icon-button");for(var i=0,s=Pi;i-1&&(this.openDialogs.splice(e,1),this.openDialogs.length||(this._ariaHiddenElements.forEach(function(t,e){t?e.setAttribute("aria-hidden",t):e.removeAttribute("aria-hidden")}),this._ariaHiddenElements.clear(),this._afterAllClosed.next()))},t.prototype._hideNonDialogContentFromAssistiveTechnology=function(){var t=this._overlayContainer.getContainerElement();if(t.parentElement)for(var e=t.parentElement.children,n=e.length-1;n>-1;n--){var r=e[n];r===t||"SCRIPT"===r.nodeName||"STYLE"===r.nodeName||r.hasAttribute("aria-live")||(this._ariaHiddenElements.set(r,r.getAttribute("aria-hidden")),r.setAttribute("aria-hidden","true"))}},t}(),Ui=0,Yi=function(){function t(t,e,n){this.dialogRef=t,this._elementRef=e,this._dialog=n,this.ariaLabel="Close dialog"}return t.prototype.ngOnInit=function(){this.dialogRef||(this.dialogRef=Zi(this._elementRef,this._dialog.openDialogs))},t.prototype.ngOnChanges=function(t){var e=t._matDialogClose||t._matDialogCloseResult;e&&(this.dialogResult=e.currentValue)},t}(),qi=function(){function t(t,e,n){this._dialogRef=t,this._elementRef=e,this._dialog=n,this.id="mat-dialog-title-"+Ui++}return t.prototype.ngOnInit=function(){var t=this;this._dialogRef||(this._dialogRef=Zi(this._elementRef,this._dialog.openDialogs)),this._dialogRef&&Promise.resolve().then(function(){var e=t._dialogRef._containerInstance;e&&!e._ariaLabelledBy&&(e._ariaLabelledBy=t.id)})},t}(),Xi=function(){},Gi=function(){};function Zi(t,e){for(var n=t.nativeElement.parentElement;n&&!n.classList.contains("mat-dialog-container");)n=n.parentElement;return n?e.find(function(t){return t.id===n.id}):null}var Qi=function(){},Ki=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new Wi(t,this.notifier))},t}(),Wi=function(t){function e(e,n){t.call(this,e),this.notifier=n,this.add(Object($n.a)(this,n))}return Object(l.b)(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.complete()},e.prototype.notifyComplete=function(){},e}(Wn.a),$i=["button","checkbox","file","hidden","image","radio","range","reset","submit"],Ji=0,ts=function(t){function e(e,n,r,o,i,s,a){var l=t.call(this,s,o,i,r)||this;return l._elementRef=e,l._platform=n,l.ngControl=r,l._uid="mat-input-"+Ji++,l._isServer=!1,l.focused=!1,l.stateChanges=new _t.a,l.controlType="mat-input",l._disabled=!1,l.placeholder="",l._required=!1,l._type="text",l._readonly=!1,l._neverEmptyInputTypes=["date","datetime","datetime-local","month","time","week"].filter(function(t){return nn().has(t)}),l._inputValueAccessor=a||l._elementRef.nativeElement,l._previousNativeValue=l.value,l.id=l.id,n.IOS&&e.nativeElement.addEventListener("keyup",function(t){var e=t.target;e.value||e.selectionStart||e.selectionEnd||(e.setSelectionRange(1,1),e.setSelectionRange(0,0))}),l._isServer=!l._platform.isBrowser,l}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"disabled",{get:function(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled},set:function(t){this._disabled=yt(t),this.focused&&(this.focused=!1,this.stateChanges.next())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},set:function(t){this._id=t||this._uid},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"required",{get:function(){return this._required},set:function(t){this._required=yt(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(t){this._type=t||"text",this._validateType(),!this._isTextarea()&&nn().has(this._type)&&(this._elementRef.nativeElement.type=this._type)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._inputValueAccessor.value},set:function(t){t!==this.value&&(this._inputValueAccessor.value=t,this.stateChanges.next())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readonly",{get:function(){return this._readonly},set:function(t){this._readonly=yt(t)},enumerable:!0,configurable:!0}),e.prototype.ngOnChanges=function(){this.stateChanges.next()},e.prototype.ngOnDestroy=function(){this.stateChanges.complete()},e.prototype.ngDoCheck=function(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue()},e.prototype.focus=function(){this._elementRef.nativeElement.focus()},e.prototype._focusChanged=function(t){t===this.focused||this.readonly||(this.focused=t,this.stateChanges.next())},e.prototype._onInput=function(){},e.prototype._dirtyCheckNativeValue=function(){var t=this.value;this._previousNativeValue!==t&&(this._previousNativeValue=t,this.stateChanges.next())},e.prototype._validateType=function(){if($i.indexOf(this._type)>-1)throw Error('Input type "'+this._type+"\" isn't supported by matInput.")},e.prototype._isNeverEmpty=function(){return this._neverEmptyInputTypes.indexOf(this._type)>-1},e.prototype._isBadInput=function(){var t=this._elementRef.nativeElement.validity;return t&&t.badInput},e.prototype._isTextarea=function(){var t=this._elementRef.nativeElement,e=this._platform.isBrowser?t.nodeName:t.name;return!!e&&"textarea"===e.toLowerCase()},Object.defineProperty(e.prototype,"empty",{get:function(){return!this._isNeverEmpty()&&!this._elementRef.nativeElement.value&&!this._isBadInput()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shouldLabelFloat",{get:function(){return this.focused||!this.empty},enumerable:!0,configurable:!0}),e.prototype.setDescribedByIds=function(t){this._ariaDescribedby=t.join(" ")},e.prototype.onContainerClick=function(){this.focus()},e}(function(t){return function(t){function e(){for(var e=[],n=0;n0&&!this._renderChangeSubscription&&this._observeRenderChanges()},t.prototype.ngOnDestroy=function(){this._rowPlaceholder.viewContainer.clear(),this._headerRowPlaceholder.viewContainer.clear(),this._onDestroy.next(),this._onDestroy.complete(),this.dataSource instanceof Ii&&this.dataSource.disconnect(this)},t.prototype.renderRows=function(){var t=this,e=this._dataDiffer.diff(this._data);if(e){var n=this._rowPlaceholder.viewContainer;e.forEachOperation(function(e,r,o){if(null==e.previousIndex)t._insertRow(e.item,o);else if(null==o)n.remove(r);else{var i=n.get(r);n.move(i,o)}}),this._updateRowIndexContext(),e.forEachIdentityChange(function(t){n.get(t.currentIndex).context.$implicit=t.item})}},t.prototype.setHeaderRowDef=function(t){this._headerRowDef=t,this._headerRowDefChanged=!0},t.prototype.addColumnDef=function(t){this._customColumnDefs.add(t)},t.prototype.removeColumnDef=function(t){this._customColumnDefs.delete(t)},t.prototype.addRowDef=function(t){this._customRowDefs.add(t)},t.prototype.removeRowDef=function(t){this._customRowDefs.delete(t)},t.prototype._cacheColumnDefs=function(){var t=this;this._columnDefsByName.clear();var e=this._contentColumnDefs?this._contentColumnDefs.toArray():[];this._customColumnDefs.forEach(function(t){return e.push(t)}),e.forEach(function(e){if(t._columnDefsByName.has(e.name))throw Error('Duplicate column definition name provided: "'+e.name+'".');t._columnDefsByName.set(e.name,e)})},t.prototype._cacheRowDefs=function(){var t=this;this._rowDefs=this._contentRowDefs?this._contentRowDefs.toArray():[],this._customRowDefs.forEach(function(e){return t._rowDefs.push(e)});var e=this._rowDefs.filter(function(t){return!t.when});if(e.length>1)throw Error("There can only be one default row without a when predicate function.");this._defaultRowDef=e[0]},t.prototype._renderUpdatedColumns=function(){var t=this;this._rowDefs.forEach(function(e){e.getColumnsDiff()&&(t._dataDiffer.diff([]),t._rowPlaceholder.viewContainer.clear(),t.renderRows())}),this._headerRowDef&&this._headerRowDef.getColumnsDiff()&&this._renderHeaderRow()},t.prototype._switchDataSource=function(t){this._data=[],this.dataSource instanceof Ii&&this.dataSource.disconnect(this),this._renderChangeSubscription&&(this._renderChangeSubscription.unsubscribe(),this._renderChangeSubscription=null),t||(this._dataDiffer&&this._dataDiffer.diff([]),this._rowPlaceholder.viewContainer.clear()),this._dataSource=t},t.prototype._observeRenderChanges=function(){var t,e=this;if(this.dataSource){var n;if(this.dataSource.connect instanceof Function?n=this.dataSource.connect(this):this.dataSource instanceof I.a?n=this.dataSource:Array.isArray(this.dataSource)&&(n=s(this.dataSource)),void 0===n)throw Error("Provided data source did not match an array, Observable, or DataSource");this._renderChangeSubscription=n.pipe((t=this._onDestroy,function(e){return e.lift(new Ki(t))})).subscribe(function(t){e._data=t,e.renderRows()})}},t.prototype._renderHeaderRow=function(){this._headerRowPlaceholder.viewContainer.length>0&&this._headerRowPlaceholder.viewContainer.clear();var t=this._getHeaderCellTemplatesForRow(this._headerRowDef);t.length&&(this._headerRowPlaceholder.viewContainer.createEmbeddedView(this._headerRowDef.template,{cells:t}),t.forEach(function(t){hs.mostRecentCellOutlet&&hs.mostRecentCellOutlet._viewContainer.createEmbeddedView(t.template,{})}),this._changeDetectorRef.markForCheck())},t.prototype._getRowDef=function(t,e){if(1==this._rowDefs.length)return this._rowDefs[0];var n=this._rowDefs.find(function(n){return n.when&&n.when(e,t)})||this._defaultRowDef;if(!n)throw Error("Could not find a matching row definition for the provided row data.");return n},t.prototype._insertRow=function(t,e){var n=this._getRowDef(t,e),r={$implicit:t};this._rowPlaceholder.viewContainer.createEmbeddedView(n.template,r,e),this._getCellTemplatesForRow(n).forEach(function(t){hs.mostRecentCellOutlet&&hs.mostRecentCellOutlet._viewContainer.createEmbeddedView(t.template,r)}),this._changeDetectorRef.markForCheck()},t.prototype._updateRowIndexContext=function(){for(var t=this._rowPlaceholder.viewContainer,e=0,n=t.length;e=r.length&&(o=0),r[o]},e.prototype.ngOnChanges=function(){this._stateChanges.next()},e.prototype.ngOnDestroy=function(){this._stateChanges.complete()},e}(ln(function(){})),ws=function(){return function(){this.changes=new _t.a,this.sortButtonLabel=function(t){return"Change sorting for "+t},this.sortDescriptionLabel=function(t,e){return"Sorted by "+t+" "+("asc"==e?"ascending":"descending")}}}();function Es(t){return t||new ws}var Cs=function(t){function e(e,n,r,o){var i=t.call(this)||this;if(i._intl=e,i._sort=r,i._cdkColumnDef=o,i._showIndicatorHint=!1,i._arrowDirection="",i._disableViewStateAnimation=!1,i.arrowPosition="after",!r)throw Error("MatSortHeader must be placed within a parent element with the MatSort directive.");return i._rerenderSubscription=Object(ir.a)(r.sortChange,r._stateChanges,e.changes).subscribe(function(){i._isSorted()&&i._updateArrowDirection(),!i._isSorted()&&i._viewState&&"active"===i._viewState.toState&&(i._disableViewStateAnimation=!1,i._setAnimationTransitionState({fromState:"active",toState:i._arrowDirection})),n.markForCheck()}),i}return Object(l.b)(e,t),Object.defineProperty(e.prototype,"disableClear",{get:function(){return this._disableClear},set:function(t){this._disableClear=yt(t)},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){!this.id&&this._cdkColumnDef&&(this.id=this._cdkColumnDef.name),this._updateArrowDirection(),this._setAnimationTransitionState({toState:this._isSorted()?"active":this._arrowDirection}),this._sort.register(this)},e.prototype.ngOnDestroy=function(){this._sort.deregister(this),this._rerenderSubscription.unsubscribe()},e.prototype._setIndicatorHintVisible=function(t){this._isDisabled()&&t||(this._showIndicatorHint=t,this._isSorted()||(this._updateArrowDirection(),this._setAnimationTransitionState(this._showIndicatorHint?{fromState:this._arrowDirection,toState:"hint"}:{fromState:"hint",toState:this._arrowDirection})))},e.prototype._setAnimationTransitionState=function(t){this._viewState=t,this._disableViewStateAnimation&&(this._viewState={toState:t.toState})},e.prototype._handleClick=function(){if(!this._isDisabled()){this._sort.sort(this),"hint"!==this._viewState.toState&&"active"!==this._viewState.toState||(this._disableViewStateAnimation=!0);var t=this._isSorted()?{fromState:this._arrowDirection,toState:"active"}:{fromState:"active",toState:this._arrowDirection};this._setAnimationTransitionState(t),this._showIndicatorHint=!1}},e.prototype._isSorted=function(){return this._sort.active==this.id&&("asc"===this._sort.direction||"desc"===this._sort.direction)},e.prototype._getArrowDirectionState=function(){return(this._isSorted()?"active-":"")+this._arrowDirection},e.prototype._getArrowViewState=function(){var t=this._viewState.fromState;return(t?t+"-to-":"")+this._viewState.toState},e.prototype._updateArrowDirection=function(){this._arrowDirection=this._isSorted()?this._sort.direction:this.start||this._sort.start},e.prototype._isDisabled=function(){return this._sort.disabled||this.disabled},e}(ln(function(){})),xs=function(){},Ss=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(gs),Os=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(ps),Ts=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(ds),ks=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(fs),As=function(t){function e(e,n){var r=t.call(this,e,n)||this;return n.nativeElement.classList.add("mat-column-"+e.cssClassFriendlyName),r}return Object(l.b)(e,t),e}(function(t,e){e.nativeElement.classList.add("cdk-column-"+t.cssClassFriendlyName)}),Ps=function(t){function e(e,n){var r=t.call(this,e,n)||this;return n.nativeElement.classList.add("mat-column-"+e.cssClassFriendlyName),r}return Object(l.b)(e,t),e}(function(t,e){e.nativeElement.classList.add("cdk-column-"+t.cssClassFriendlyName)}),Ds=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(us),Rs=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(cs),Is=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(function(){}),Ns=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e}(function(){}),js=function(){},Vs=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o._platform=n,o._document=r,o}return Object(l.b)(e,t),e.prototype.ngAfterViewInit=function(){var t=this;Object(r.O)()&&this._platform.isBrowser&&(this._checkToolbarMixedModes(),this._toolbarRows.changes.subscribe(function(){return t._checkToolbarMixedModes()}))},e.prototype._checkToolbarMixedModes=function(){var t=this;this._toolbarRows.length&&[].slice.call(this._elementRef.nativeElement.childNodes).filter(function(t){return!(t.classList&&t.classList.contains("mat-toolbar-row"))}).filter(function(e){return e.nodeType!==(t._document?t._document.COMMENT_NODE:8)}).some(function(t){return t.textContent.trim()})&&function(){throw Error("MatToolbar: Attempting to combine different toolbar modes. Either specify multiple `` elements explicitly or just place content inside of a `` for a single row.")}()},e}(un(function(t){this._elementRef=t})),Ms=function(){},Fs=function(){function t(t,e){this.dialog=t,this.torrentsService=e,this.title="app"}return t.prototype.openMagnet=function(){var t=this;this.dialog.open(Ls,{height:"220px",width:"450px"}).afterClosed().subscribe(function(e){e&&t.torrentsService.startFromMagnetLink(e)})},t}(),Ls=function(){function t(t){this.renderer=t}return t.prototype.submit=function(t){13===t.keyCode&&document.getElementById("start").click()},t}(),Bs=r.W({encapsulation:2,styles:[".mat-dialog-container{box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12);display:block;padding:24px;border-radius:2px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%}@media screen and (-ms-high-contrast:active){.mat-dialog-container{outline:solid 1px}}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:12px 0;display:flex;flex-wrap:wrap;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button+.mat-button,.mat-dialog-actions .mat-button+.mat-raised-button,.mat-dialog-actions .mat-raised-button+.mat-button,.mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-button+.mat-raised-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:0;margin-right:8px}"],data:{animation:[{type:7,name:"slideDialog",definitions:[{type:0,name:"enter",styles:{type:6,styles:{transform:"none",opacity:1},offset:null},options:void 0},{type:0,name:"void",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0) scale(0.9)",opacity:0},offset:null},options:void 0},{type:0,name:"exit",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0)",opacity:0},offset:null},options:void 0},{type:1,expr:"* => *",animation:{type:4,styles:null,timings:"400ms cubic-bezier(0.25, 0.8, 0.25, 1)"},options:null}],options:{}}]}});function Hs(t){return r._16(0,[(t()(),r.T(0,null,null,0))],null,null)}function zs(t){return r._16(0,[r._13(402653184,1,{_portalOutlet:0}),(t()(),r.T(16777216,null,null,1,null,Hs)),r.X(2,212992,[[1,4]],0,_r,[r.h,r.H],{portal:[0,"portal"]},null)],function(t,e){t(e,2,0,"")},null)}var Us=r.U("mat-dialog-container",ji,function(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"mat-dialog-container",[["class","mat-dialog-container"],["tabindex","-1"]],[[1,"id",0],[1,"role",0],[1,"aria-labelledby",0],[1,"aria-label",0],[1,"aria-describedby",0],[40,"@slideDialog",0]],[["component","@slideDialog.start"],["component","@slideDialog.done"]],function(t,e,n){var o=!0;return"component:@slideDialog.start"===e&&(o=!1!==r._9(t,1)._onAnimationStart(n)&&o),"component:@slideDialog.done"===e&&(o=!1!==r._9(t,1)._onAnimationDone(n)&&o),o},zs,Bs)),r.X(1,49152,null,0,ji,[r.i,In,r.f,[2,R]],null,null)],null,function(t,e){t(e,0,0,r._9(e,1)._id,null==r._9(e,1)._config?null:r._9(e,1)._config.role,null!=r._9(e,1)._config&&r._9(e,1)._config.ariaLabel?null:r._9(e,1)._ariaLabelledBy,null==r._9(e,1)._config?null:r._9(e,1)._config.ariaLabel,(null==r._9(e,1)._config?null:r._9(e,1)._config.ariaDescribedBy)||null,r._9(e,1)._state)})},{},{},[]),Ys=r.W({encapsulation:2,styles:[".mat-toolbar-row,.mat-toolbar-single-row{display:flex;box-sizing:border-box;padding:0 16px;width:100%;flex-direction:row;align-items:center;white-space:nowrap}.mat-toolbar-multiple-rows{display:flex;box-sizing:border-box;flex-direction:column;width:100%}.mat-toolbar-multiple-rows{min-height:64px}.mat-toolbar-row,.mat-toolbar-single-row{height:64px}@media (max-width:599px){.mat-toolbar-multiple-rows{min-height:56px}.mat-toolbar-row,.mat-toolbar-single-row{height:56px}}"],data:{}});function qs(t){return r._16(2,[r._8(null,0),r._8(null,1)],null,null)}var Xs=r.W({encapsulation:2,styles:[".mat-button,.mat-flat-button,.mat-icon-button,.mat-stroked-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px}.mat-button[disabled],.mat-flat-button[disabled],.mat-icon-button[disabled],.mat-stroked-button[disabled]{cursor:default}.mat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-button.cdk-program-focused .mat-button-focus-overlay,.mat-flat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-flat-button.cdk-program-focused .mat-button-focus-overlay,.mat-icon-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-icon-button.cdk-program-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-button .mat-button-focus-overlay,.mat-icon-button .mat-button-focus-overlay{transition:none;opacity:0}.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:1}.mat-raised-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1)}.mat-raised-button[disabled]{cursor:default}.mat-raised-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-raised-button.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-raised-button::-moz-focus-inner{border:0}.mat-raised-button:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-raised-button:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-raised-button[disabled]{box-shadow:none}.mat-stroked-button{border:1px solid currentColor;padding:0 15px;line-height:34px}.mat-stroked-button:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-flat-button:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:56px;height:56px;padding:0;flex-shrink:0}.mat-fab[disabled]{cursor:default}.mat-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-fab.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-fab::-moz-focus-inner{border:0}.mat-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-fab[disabled]{box-shadow:none}.mat-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-fab .mat-button-wrapper{padding:16px 0;display:inline-block;line-height:24px}.mat-mini-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:40px;height:40px;padding:0;flex-shrink:0}.mat-mini-fab[disabled]{cursor:default}.mat-mini-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-mini-fab.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-mini-fab::-moz-focus-inner{border:0}.mat-mini-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-mini-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-mini-fab[disabled]{box-shadow:none}.mat-mini-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-mini-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-mini-fab .mat-button-wrapper{padding:8px 0;display:inline-block;line-height:24px}.mat-icon-button{padding:0;min-width:0;width:40px;height:40px;flex-shrink:0;line-height:40px;border-radius:50%}.mat-icon-button .mat-icon,.mat-icon-button i{line-height:24px}.mat-button,.mat-fab,.mat-icon-button,.mat-mini-fab,.mat-raised-button{color:currentColor}.mat-button .mat-button-wrapper>*,.mat-fab .mat-button-wrapper>*,.mat-icon-button .mat-button-wrapper>*,.mat-mini-fab .mat-button-wrapper>*,.mat-raised-button .mat-button-wrapper>*{vertical-align:middle}.mat-button-focus-overlay,.mat-button-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-button-focus-overlay{background-color:rgba(0,0,0,.12);border-radius:inherit;opacity:0;transition:opacity .2s cubic-bezier(.35,0,.25,1),background-color .2s cubic-bezier(.35,0,.25,1)}@media screen and (-ms-high-contrast:active){.mat-button-focus-overlay{background-color:rgba(255,255,255,.5)}}.mat-button-ripple-round{border-radius:50%;z-index:1}@media screen and (-ms-high-contrast:active){.mat-button,.mat-fab,.mat-flat-button,.mat-icon-button,.mat-mini-fab,.mat-raised-button{outline:solid 1px}}"],data:{}});function Gs(t){return r._16(2,[r._13(402653184,1,{ripple:0}),(t()(),r.Y(1,0,null,null,1,"span",[["class","mat-button-wrapper"]],null,null,null,null,null)),r._8(null,0),(t()(),r.Y(3,0,null,null,1,"div",[["class","mat-button-ripple mat-ripple"],["matRipple",""]],[[2,"mat-button-ripple-round",null],[2,"mat-ripple-unbounded",null]],null,null,null,null)),r.X(4,212992,[[1,4]],0,_n,[r.i,r.u,Je,[2,yn]],{centered:[0,"centered"],disabled:[1,"disabled"],trigger:[2,"trigger"]},null),(t()(),r.Y(5,0,null,null,0,"div",[["class","mat-button-focus-overlay"]],null,null,null,null,null))],function(t,e){var n=e.component;t(e,4,0,n._isIconButton,n._isRippleDisabled(),n._getHostElement())},function(t,e){var n=e.component;t(e,3,0,n._isRoundButton||n._isIconButton,r._9(e,4).unbounded)})}var Zs=r.W({encapsulation:2,styles:[".mat-sort-header-container{display:flex;cursor:pointer}.mat-sort-header-disabled .mat-sort-header-container{cursor:default}.mat-sort-header-position-before{flex-direction:row-reverse}.mat-sort-header-button{border:none;background:0 0;display:flex;align-items:center;padding:0;cursor:inherit;outline:0;font:inherit;color:currentColor}.mat-sort-header-arrow{height:12px;width:12px;min-width:12px;margin:0 0 0 6px;position:relative;display:flex}.mat-sort-header-position-before .mat-sort-header-arrow{margin:0 6px 0 0}.mat-sort-header-stem{background:currentColor;height:10px;width:2px;margin:auto;display:flex;align-items:center}.mat-sort-header-indicator{width:100%;height:2px;display:flex;align-items:center;position:absolute;top:0;left:0}.mat-sort-header-pointer-middle{margin:auto;height:2px;width:2px;background:currentColor;transform:rotate(45deg)}.mat-sort-header-pointer-left,.mat-sort-header-pointer-right{background:currentColor;width:6px;height:2px;position:absolute;top:0}.mat-sort-header-pointer-left{transform-origin:right;left:0}.mat-sort-header-pointer-right{transform-origin:left;right:0}"],data:{animation:[{type:7,name:"indicator",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"translateY(0px)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"translateY(10px)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"leftPointer",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"rotate(-45deg)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"rotate(45deg)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"rightPointer",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"rotate(45deg)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"rotate(-45deg)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"arrowOpacity",definitions:[{type:0,name:"desc-to-active, asc-to-active, active",styles:{type:6,styles:{opacity:1},offset:null},options:void 0},{type:0,name:"desc-to-hint, asc-to-hint, hint",styles:{type:6,styles:{opacity:.54},offset:null},options:void 0},{type:0,name:"hint-to-desc, active-to-desc, desc, hint-to-asc, active-to-asc, asc",styles:{type:6,styles:{opacity:0},offset:null},options:void 0},{type:1,expr:"* => asc, * => desc, * => active, * => hint",animation:{type:4,styles:null,timings:"0ms"},options:null},{type:1,expr:"* <=> *",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"arrowPosition",definitions:[{type:1,expr:"* => desc-to-hint, * => desc-to-active",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(-25%)"},offset:null},{type:6,styles:{transform:"translateY(0)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => hint-to-desc, * => active-to-desc",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(0)"},offset:null},{type:6,styles:{transform:"translateY(25%)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => asc-to-hint, * => asc-to-active",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(25%)"},offset:null},{type:6,styles:{transform:"translateY(0)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => hint-to-asc, * => active-to-asc",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(0)"},offset:null},{type:6,styles:{transform:"translateY(-25%)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:0,name:"desc-to-hint, asc-to-hint, hint, desc-to-active, asc-to-active, active",styles:{type:6,styles:{transform:"translateY(0)"},offset:null},options:void 0},{type:0,name:"hint-to-desc, active-to-desc, desc",styles:{type:6,styles:{transform:"translateY(-25%)"},offset:null},options:void 0},{type:0,name:"hint-to-asc, active-to-asc, asc",styles:{type:6,styles:{transform:"translateY(25%)"},offset:null},options:void 0}],options:{}},{type:7,name:"allowChildren",definitions:[{type:1,expr:"* <=> *",animation:[{type:11,selector:"@*",animation:{type:9,options:null},options:{optional:!0}}],options:null}],options:{}}]}});function Qs(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"span",[["class","cdk-visually-hidden"]],null,null,null,null,null)),(t()(),r._15(1,null,["\xa0",""]))],null,function(t,e){var n=e.component;t(e,1,0,n._intl.sortDescriptionLabel(n.id,n._sort.direction))})}function Ks(t){return r._16(2,[(t()(),r.Y(0,0,null,null,8,"div",[["class","mat-sort-header-container"]],[[2,"mat-sort-header-sorted",null],[2,"mat-sort-header-position-before",null]],null,null,null,null)),(t()(),r.Y(1,0,null,null,1,"button",[["class","mat-sort-header-button"],["type","button"]],[[1,"disabled",0],[1,"aria-label",0]],[[null,"focus"],[null,"blur"]],function(t,e,n){var r=!0,o=t.component;return"focus"===e&&(r=!1!==o._setIndicatorHintVisible(!0)&&r),"blur"===e&&(r=!1!==o._setIndicatorHintVisible(!1)&&r),r},null,null)),r._8(null,0),(t()(),r.Y(3,0,null,null,5,"div",[["class","mat-sort-header-arrow"]],[[24,"@arrowOpacity",0],[24,"@arrowPosition",0],[24,"@allowChildren",0]],[[null,"@arrowPosition.start"],[null,"@arrowPosition.done"]],function(t,e,n){var r=!0,o=t.component;return"@arrowPosition.start"===e&&(r=0!=(o._disableViewStateAnimation=!0)&&r),"@arrowPosition.done"===e&&(r=0!=(o._disableViewStateAnimation=!1)&&r),r},null,null)),(t()(),r.Y(4,0,null,null,0,"div",[["class","mat-sort-header-stem"]],null,null,null,null,null)),(t()(),r.Y(5,0,null,null,3,"div",[["class","mat-sort-header-indicator"]],[[24,"@indicator",0]],null,null,null,null)),(t()(),r.Y(6,0,null,null,0,"div",[["class","mat-sort-header-pointer-left"]],[[24,"@leftPointer",0]],null,null,null,null)),(t()(),r.Y(7,0,null,null,0,"div",[["class","mat-sort-header-pointer-right"]],[[24,"@rightPointer",0]],null,null,null,null)),(t()(),r.Y(8,0,null,null,0,"div",[["class","mat-sort-header-pointer-middle"]],null,null,null,null,null)),(t()(),r.T(16777216,null,null,1,null,Qs)),r.X(10,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null)],function(t,e){t(e,10,0,e.component._isSorted())},function(t,e){var n=e.component;t(e,0,0,n._isSorted(),"before"==n.arrowPosition),t(e,1,0,n._isDisabled()||null,n._intl.sortButtonLabel(n.id)),t(e,3,0,n._getArrowViewState(),n._getArrowViewState(),n._getArrowDirectionState()),t(e,5,0,n._getArrowDirectionState()),t(e,6,0,n._getArrowDirectionState()),t(e,7,0,n._getArrowDirectionState())})}var Ws=r.W({encapsulation:2,styles:[".mat-table{display:block}.mat-header-row{min-height:56px}.mat-row{min-height:48px}.mat-header-row,.mat-row{display:flex;border-bottom-width:1px;border-bottom-style:solid;align-items:center;padding:0 24px;box-sizing:border-box}.mat-header-row::after,.mat-row::after{display:inline-block;min-height:inherit;content:''}.mat-cell,.mat-header-cell{flex:1;overflow:hidden;word-wrap:break-word}"],data:{}});function $s(t){return r._16(2,[r._13(402653184,1,{_rowPlaceholder:0}),r._13(402653184,2,{_headerRowPlaceholder:0}),(t()(),r.Y(2,16777216,null,null,1,null,null,null,null,null,null,null)),r.X(3,16384,[[2,4]],0,_s,[r.H],null,null),(t()(),r.Y(4,16777216,null,null,1,null,null,null,null,null,null,null)),r.X(5,16384,[[1,4]],0,ys,[r.H],null,null)],null,null)}var Js=r.W({encapsulation:2,styles:[],data:{}});function ta(t){return r._16(2,[(t()(),r.Y(0,16777216,null,null,1,null,null,null,null,null,null,null)),r.X(1,16384,null,0,hs,[r.H],null,null)],null,null)}var ea,na=r.W({encapsulation:2,styles:[],data:{}});function ra(t){return r._16(2,[(t()(),r.Y(0,16777216,null,null,1,null,null,null,null,null,null,null)),r.X(1,16384,null,0,hs,[r.H],null,null)],null,null)}!function(t){t[t.NOT_STARTED=0]="NOT_STARTED",t[t.SEEDING_COMPLETE=1]="SEEDING_COMPLETE",t[t.DOWNLOAD_COMPLETE=2]="DOWNLOAD_COMPLETE",t[t.SEEDING=3]="SEEDING",t[t.DOWNLOADING=4]="DOWNLOADING",t[t.STALLED=5]="STALLED",t[t.STOPPED=6]="STOPPED",t[t.ALLOCATING_DISKSPACE=7]="ALLOCATING_DISKSPACE",t[t.ERROR=8]="ERROR",t[t.QUEUED=9]="QUEUED",t[t.CHECKING_DATA=10]="CHECKING_DATA",t[t.NO_SPACE_LEFT=11]="NO_SPACE_LEFT",t[t.PAUSED=12]="PAUSED",t[t.SUPERSEEDING=13]="SUPERSEEDING",t[t.INVALID_STATUS=14]="INVALID_STATUS"}(ea||(ea={}));var oa=function(){function t(){}return t.fromJson=function(e){var n=new t;return n.name=e.name,n.infoHash=e.infoHash,n.status=ea[ea[e.status]],n.timeAdded=new Date(0),n.timeAdded.setUTCSeconds(e.timeAdded/1e3),n.bytesDownloaded=e.bytesDownloaded,n.bytesUploaded=e.bytesUploaded,n.totalBytes=e.totalBytes,n.totalBytesToDownload=e.totalBytesToDownload,n.percentDone=e.bytesDownloaded/e.totalBytesToDownload*100,n.downloadRate=e.downloadRate,n.uploadRate=e.uploadRate,n.numPeers=e.numPeers,n.seeders=e.seeders,n.seedersTotal=e.seedersTotal,n.leechers=e.leechers,n.leechersTotal=e.leechersTotal,n.running=e.running,n.numFiles=e.numFiles,n},t}(),ia=function(){function t(t){this.torrentsService=t,this.displayedColumns=["actions","name","infoHash","status","timeAdded","bytesDownloaded","bytesUploaded","totalBytes","totalBytesToDownload","downloadRate","uploadRate","numPeers"]}return t.prototype.ngOnInit=function(){var e=this;this.torrentObserver=this.torrentsService.getTorrents().map(function(t){return t.torrents.map(function(t){return oa.fromJson(t)})}),this.getTorrents(),setInterval(function(){return e.getTorrents()},t.REFRESH_RATE)},t.prototype.getTorrents=function(){var t=this;this.torrentObserver.subscribe(function(e){return t.torrents=e})},t.prototype.status=function(t){return ea[t.status]},t.prototype.humanReadable=function(t,e){return void 0===e&&(e=["","k","M","G","T"]),t<900?this.fixed(t)+e[0]:e.length>1?this.humanReadable(t/1e3,e.slice(1)):this.fixed(t)+e[0]},t.prototype.fixed=function(t){return Math.round(100*t)/100},t.prototype.startTorrent=function(t){this.torrentsService.startTorrent(t)},t.prototype.pauseTorrent=function(t){this.torrentsService.pauseTorrent(t)},t.prototype.removeTorrent=function(t){this.torrentsService.removeTorrent(t)},t.REFRESH_RATE=5e3,t}(),sa=r.W({encapsulation:0,styles:[[".mat-column-actions[_ngcontent-%COMP%]{-webkit-box-flex:10;-ms-flex:10 5 10px;flex:10 5 10px}.mat-column-actions[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{min-width:30px;padding:0}.mat-column-name[_ngcontent-%COMP%]{-webkit-box-flex:40;-ms-flex:40 10 60px;flex:40 10 60px}.mat-column-infoHash[_ngcontent-%COMP%]{-webkit-box-flex:20;-ms-flex:20 10 50px;flex:20 10 50px}.mat-column-status[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 50px;flex:5 10 50px}.mat-column-bytesDownloaded[_ngcontent-%COMP%], .mat-column-bytesUploaded[_ngcontent-%COMP%], .mat-column-bytesUploded[_ngcontent-%COMP%], .mat-column-timeAdded[_ngcontent-%COMP%], .mat-column-totalBytes[_ngcontent-%COMP%], .mat-column-totalBytesToDownload[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 20px;flex:5 10 20px}.mat-column-downloadRate[_ngcontent-%COMP%], .mat-column-numPeers[_ngcontent-%COMP%], .mat-column-seeders[_ngcontent-%COMP%], .mat-column-seedersTotal[_ngcontent-%COMP%], .mat-column-uploadRate[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 10px;flex:5 10 10px}"]],data:{}});function aa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Actions"]))],null,null)}function la(t){return r._16(0,[(t()(),r.Y(0,0,null,null,20,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(-1,null,["\n \t"])),(t()(),r.Y(3,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.startTorrent(t.context.$implicit.infoHash)&&r),r},Gs,Xs)),r.X(4,180224,null,0,Di,[r.i,Je,Un],null,null),(t()(),r._15(-1,0,["\n \t\t"])),(t()(),r.Y(6,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),r._15(-1,null,["play_arrow"])),(t()(),r._15(-1,null,["\n \t"])),(t()(),r.Y(9,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.pauseTorrent(t.context.$implicit.infoHash)&&r),r},Gs,Xs)),r.X(10,180224,null,0,Di,[r.i,Je,Un],null,null),(t()(),r._15(-1,0,["\n \t\t"])),(t()(),r.Y(12,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),r._15(-1,null,["pause"])),(t()(),r._15(-1,null,["\n \t"])),(t()(),r.Y(15,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.removeTorrent(t.context.$implicit.infoHash)&&r),r},Gs,Xs)),r.X(16,180224,null,0,Di,[r.i,Je,Un],null,null),(t()(),r._15(-1,0,["\n \t\t"])),(t()(),r.Y(18,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),r._15(-1,null,["delete"])),(t()(),r._15(-1,null,["\n\t "]))],null,function(t,e){t(e,3,0,r._9(e,4).disabled||null),t(e,9,0,r._9(e,10).disabled||null),t(e,15,0,r._9(e,16).disabled||null)})}function ua(t){return r._16(0,[(t()(),r.Y(0,0,null,null,3,"mat-header-cell",[["class","mat-header-cell"],["mat-sort-header",""],["role","columnheader"]],[[2,"mat-sort-header-disabled",null]],[[null,"click"],[null,"mouseenter"],[null,"longpress"],[null,"mouseleave"]],function(t,e,n){var o=!0;return"click"===e&&(o=!1!==r._9(t,1)._handleClick()&&o),"mouseenter"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!0)&&o),"longpress"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!0)&&o),"mouseleave"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!1)&&o),o},Ks,Zs)),r.X(1,245760,null,0,Cs,[ws,r.f,[2,bs],[2,fs]],{id:[0,"id"]},null),r.X(2,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,0,["Name"]))],function(t,e){t(e,1,0,"")},function(t,e){t(e,0,0,r._9(e,1)._isDisabled())})}function ca(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,["",""]))],null,function(t,e){t(e,2,0,e.context.$implicit.name)})}function ha(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Info Hash"]))],null,null)}function pa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" ",""]))],null,function(t,e){t(e,2,0,e.context.$implicit.infoHash)})}function da(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Status"]))],null,null)}function fa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.status(e.context.$implicit))})}function ma(t){return r._16(0,[(t()(),r.Y(0,0,null,null,3,"mat-header-cell",[["class","mat-header-cell"],["mat-sort-header",""],["role","columnheader"]],[[2,"mat-sort-header-disabled",null]],[[null,"click"],[null,"mouseenter"],[null,"longpress"],[null,"mouseleave"]],function(t,e,n){var o=!0;return"click"===e&&(o=!1!==r._9(t,1)._handleClick()&&o),"mouseenter"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!0)&&o),"longpress"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!0)&&o),"mouseleave"===e&&(o=!1!==r._9(t,1)._setIndicatorHintVisible(!1)&&o),o},Ks,Zs)),r.X(1,245760,null,0,Cs,[ws,r.f,[2,bs],[2,fs]],{id:[0,"id"]},null),r.X(2,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,0,["Time Added"]))],function(t,e){t(e,1,0,"")},function(t,e){t(e,0,0,r._9(e,1)._isDisabled())})}function ya(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.context.$implicit.timeAdded)})}function _a(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Bytes Downloaded"]))],null,null)}function ga(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.bytesDownloaded))})}function va(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Bytes Uploaded"]))],null,null)}function ba(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.bytesUploaded))})}function wa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Total Bytes"]))],null,null)}function Ea(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.totalBytes))})}function Ca(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Done"]))],null,null)}function xa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,["","%"]))],null,function(t,e){t(e,2,0,e.component.fixed(e.context.$implicit.percentDone))})}function Sa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Download Rate"]))],null,null)}function Oa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,["","B/s"]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.downloadRate))})}function Ta(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Upload Rate"]))],null,null)}function ka(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,["","B/s"]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.uploadRate))})}function Aa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),r.X(1,16384,null,0,As,[fs,r.i],null,null),(t()(),r._15(-1,null,["Peers"]))],null,null)}function Pa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),r.X(1,16384,null,0,Ps,[fs,r.i],null,null),(t()(),r._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.context.$implicit.numPeers)})}function Da(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"mat-header-row",[["class","mat-header-row"],["role","row"]],null,null,null,ta,Js)),r.X(1,49152,null,0,Is,[],null,null)],null,null)}function Ra(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"mat-row",[["class","mat-row"],["role","row"]],null,null,null,ra,na)),r.X(1,49152,null,0,Ns,[],null,null)],null,null)}function Ia(t){return r._16(0,[r._13(402653184,1,{sort:0}),(t()(),r.Y(1,0,null,null,197,"div",[["class","torrent-list mat-elevation-z8"]],null,null,null,null,null)),(t()(),r._15(-1,null,["\n "])),(t()(),r.Y(3,0,null,null,194,"mat-table",[["class","mat-table"],["matSort",""]],null,null,null,$s,Ws)),r.X(4,671744,[[1,4]],0,bs,[],null,null),r.X(5,2342912,[["table",4]],3,Ss,[r.p,r.f,r.i,[8,null]],{dataSource:[0,"dataSource"]},null),r._13(603979776,2,{_contentColumnDefs:1}),r._13(603979776,3,{_contentRowDefs:1}),r._13(335544320,4,{_headerRowDef:0}),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(10,0,null,null,13,null,null,null,null,null,null,null)),r.X(11,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,5,{cell:0}),r._13(335544320,6,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,aa)),r.X(17,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[6,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,la)),r.X(21,16384,null,0,Os,[r.E],null,null),r._11(2048,[[5,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(25,0,null,null,13,null,null,null,null,null,null,null)),r.X(26,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,7,{cell:0}),r._13(335544320,8,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ua)),r.X(32,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[8,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ca)),r.X(36,16384,null,0,Os,[r.E],null,null),r._11(2048,[[7,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(40,0,null,null,13,null,null,null,null,null,null,null)),r.X(41,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,9,{cell:0}),r._13(335544320,10,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ha)),r.X(47,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[10,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,pa)),r.X(51,16384,null,0,Os,[r.E],null,null),r._11(2048,[[9,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(55,0,null,null,13,null,null,null,null,null,null,null)),r.X(56,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,11,{cell:0}),r._13(335544320,12,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,da)),r.X(62,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[12,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,fa)),r.X(66,16384,null,0,Os,[r.E],null,null),r._11(2048,[[11,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(70,0,null,null,13,null,null,null,null,null,null,null)),r.X(71,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,13,{cell:0}),r._13(335544320,14,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ma)),r.X(77,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[14,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ya)),r.X(81,16384,null,0,Os,[r.E],null,null),r._11(2048,[[13,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(85,0,null,null,13,null,null,null,null,null,null,null)),r.X(86,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,15,{cell:0}),r._13(335544320,16,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,_a)),r.X(92,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[16,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ga)),r.X(96,16384,null,0,Os,[r.E],null,null),r._11(2048,[[15,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(100,0,null,null,13,null,null,null,null,null,null,null)),r.X(101,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,17,{cell:0}),r._13(335544320,18,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,va)),r.X(107,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[18,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ba)),r.X(111,16384,null,0,Os,[r.E],null,null),r._11(2048,[[17,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(115,0,null,null,13,null,null,null,null,null,null,null)),r.X(116,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,19,{cell:0}),r._13(335544320,20,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,wa)),r.X(122,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[20,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Ea)),r.X(126,16384,null,0,Os,[r.E],null,null),r._11(2048,[[19,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(130,0,null,null,13,null,null,null,null,null,null,null)),r.X(131,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,21,{cell:0}),r._13(335544320,22,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Ca)),r.X(137,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[22,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,xa)),r.X(141,16384,null,0,Os,[r.E],null,null),r._11(2048,[[21,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(145,0,null,null,13,null,null,null,null,null,null,null)),r.X(146,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,23,{cell:0}),r._13(335544320,24,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Sa)),r.X(152,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[24,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Oa)),r.X(156,16384,null,0,Os,[r.E],null,null),r._11(2048,[[23,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(160,0,null,null,13,null,null,null,null,null,null,null)),r.X(161,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,25,{cell:0}),r._13(335544320,26,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Ta)),r.X(167,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[26,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,ka)),r.X(171,16384,null,0,Os,[r.E],null,null),r._11(2048,[[25,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.Y(175,0,null,null,13,null,null,null,null,null,null,null)),r.X(176,16384,null,2,ks,[],{name:[0,"name"]},null),r._13(335544320,27,{cell:0}),r._13(335544320,28,{headerCell:0}),r._11(2048,[[2,4]],fs,null,[ks]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Aa)),r.X(182,16384,null,0,Ts,[r.E],null,null),r._11(2048,[[28,4]],ds,null,[Ts]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Pa)),r.X(186,16384,null,0,Os,[r.E],null,null),r._11(2048,[[27,4]],ps,null,[Os]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n\n "])),(t()(),r.T(0,null,null,2,null,Da)),r.X(191,540672,null,0,Ds,[r.E,r.p],{columns:[0,"columns"]},null),r._11(2048,[[4,4]],us,null,[Ds]),(t()(),r._15(-1,null,["\n "])),(t()(),r.T(0,null,null,2,null,Ra)),r.X(195,540672,null,0,Rs,[r.E,r.p],{columns:[0,"columns"]},null),r._11(2048,[[3,4]],cs,null,[Rs]),(t()(),r._15(-1,null,["\n "])),(t()(),r._15(-1,null,["\n"]))],function(t,e){var n=e.component;t(e,5,0,n.torrents),t(e,11,0,"actions"),t(e,26,0,"name"),t(e,41,0,"infoHash"),t(e,56,0,"status"),t(e,71,0,"timeAdded"),t(e,86,0,"bytesDownloaded"),t(e,101,0,"bytesUploaded"),t(e,116,0,"totalBytes"),t(e,131,0,"totalBytesToDownload"),t(e,146,0,"downloadRate"),t(e,161,0,"uploadRate"),t(e,176,0,"numPeers"),t(e,191,0,n.displayedColumns),t(e,195,0,n.displayedColumns)},null)}var Na=r.W({encapsulation:2,styles:[".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none}.mat-form-field-prefix .mat-icon,.mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-prefix .mat-icon-button,.mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform:perspective(100px);-ms-transform:none;transform-origin:0 0;transition:transform .4s cubic-bezier(.25,.8,.25,1),color .4s cubic-bezier(.25,.8,.25,1),width .4s cubic-bezier(.25,.8,.25,1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label,.mat-form-field-empty.mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;height:1px;width:100%}.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.mat-form-field-underline .mat-form-field-ripple{position:absolute;top:0;left:0;width:100%;height:2px;transform-origin:50%;transform:scaleX(.5);visibility:hidden;opacity:0;transition:background-color .3s cubic-bezier(.55,0,.55,.2)}.mat-form-field-invalid:not(.mat-focused) .mat-form-field-underline .mat-form-field-ripple{height:1px}.mat-focused .mat-form-field-underline .mat-form-field-ripple,.mat-form-field-invalid .mat-form-field-underline .mat-form-field-ripple{visibility:visible;opacity:1;transform:scaleX(1);transition:transform .3s cubic-bezier(.25,.8,.25,1),opacity .1s cubic-bezier(.25,.8,.25,1),background-color .3s cubic-bezier(.25,.8,.25,1)}.mat-form-field-subscript-wrapper{position:absolute;width:100%;overflow:hidden}.mat-form-field-label-wrapper .mat-icon,.mat-form-field-subscript-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}",".mat-input-element{font:inherit;background:0 0;color:currentColor;border:none;outline:0;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element::-ms-clear,.mat-input-element::-ms-reveal{display:none}.mat-input-element[type=date]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=month]::after,.mat-input-element[type=time]::after,.mat-input-element[type=week]::after{content:' ';white-space:pre;width:1px}.mat-input-element::placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element::-moz-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element::-webkit-input-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element:-ms-input-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent!important;transition:none}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-autosize{resize:none}"],data:{animation:[{type:7,name:"transitionMessages",definitions:[{type:0,name:"enter",styles:{type:6,styles:{opacity:1,transform:"translateY(0%)"},offset:null},options:void 0},{type:1,expr:"void => enter",animation:[{type:6,styles:{opacity:0,transform:"translateY(-100%)"},offset:null},{type:4,styles:null,timings:"300ms cubic-bezier(0.55, 0, 0.55, 0.2)"}],options:null}],options:{}}]}});function ja(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"div",[["class","mat-input-prefix mat-form-field-prefix"]],null,null,null,null,null)),r._8(null,0)],null,null)}function Va(t){return r._16(0,[(t()(),r.Y(0,0,null,null,2,null,null,null,null,null,null,null)),r._8(null,2),(t()(),r._15(2,null,["",""]))],null,function(t,e){t(e,2,0,e.component._control.placeholder)})}function Ma(t){return r._16(0,[r._8(null,3),(t()(),r.T(0,null,null,0))],null,null)}function Fa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"span",[["aria-hidden","true"],["class","mat-placeholder-required mat-form-field-required-marker"]],null,null,null,null,null)),(t()(),r._15(-1,null,["\xa0*"]))],null,null)}function La(t){return r._16(0,[(t()(),r.Y(0,0,[[4,0],["label",1]],null,7,"label",[["class","mat-form-field-label mat-input-placeholder mat-form-field-placeholder"]],[[1,"for",0],[1,"aria-owns",0],[2,"mat-empty",null],[2,"mat-form-field-empty",null],[2,"mat-accent",null],[2,"mat-warn",null]],null,null,null,null)),r.X(1,16384,null,0,A,[],{ngSwitch:[0,"ngSwitch"]},null),(t()(),r.T(16777216,null,null,1,null,Va)),r.X(3,278528,null,0,P,[r.H,r.E,A],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),r.T(16777216,null,null,1,null,Ma)),r.X(5,278528,null,0,P,[r.H,r.E,A],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),r.T(16777216,null,null,1,null,Fa)),r.X(7,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null)],function(t,e){var n=e.component;t(e,1,0,n._hasLabel()),t(e,3,0,!1),t(e,5,0,!0),t(e,7,0,!n.hideRequiredMarker&&n._control.required&&!n._control.disabled)},function(t,e){var n=e.component;t(e,0,0,n._control.id,n._control.id,n._control.empty&&!n._shouldAlwaysFloat,n._control.empty&&!n._shouldAlwaysFloat,"accent"==n.color,"warn"==n.color)})}function Ba(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"div",[["class","mat-input-suffix mat-form-field-suffix"]],null,null,null,null,null)),r._8(null,4)],null,null)}function Ha(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"div",[],[[24,"@transitionMessages",0]],null,null,null,null)),r._8(null,5)],null,function(t,e){t(e,0,0,e.component._subscriptAnimationState)})}function za(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"div",[["class","mat-hint"]],[[8,"id",0]],null,null,null,null)),(t()(),r._15(1,null,["",""]))],null,function(t,e){var n=e.component;t(e,0,0,n._hintLabelId),t(e,1,0,n.hintLabel)})}function Ua(t){return r._16(0,[(t()(),r.Y(0,0,null,null,5,"div",[["class","mat-input-hint-wrapper mat-form-field-hint-wrapper"]],[[24,"@transitionMessages",0]],null,null,null,null)),(t()(),r.T(16777216,null,null,1,null,za)),r.X(2,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null),r._8(null,6),(t()(),r.Y(4,0,null,null,0,"div",[["class","mat-input-hint-spacer mat-form-field-hint-spacer"]],null,null,null,null,null)),r._8(null,7)],function(t,e){t(e,2,0,e.component.hintLabel)},function(t,e){t(e,0,0,e.component._subscriptAnimationState)})}function Ya(t){return r._16(2,[r._13(402653184,1,{underlineRef:0}),r._13(402653184,2,{_connectionContainerRef:0}),r._13(402653184,3,{_inputContainerRef:0}),r._13(671088640,4,{_label:0}),(t()(),r.Y(4,0,null,null,18,"div",[["class","mat-input-wrapper mat-form-field-wrapper"]],null,null,null,null,null)),(t()(),r.Y(5,0,[[2,0],["connectionContainer",1]],null,9,"div",[["class","mat-input-flex mat-form-field-flex"]],null,[[null,"click"]],function(t,e,n){var r=!0,o=t.component;return"click"===e&&(r=!1!==(o._control.onContainerClick&&o._control.onContainerClick(n))&&r),r},null,null)),(t()(),r.T(16777216,null,null,1,null,ja)),r.X(7,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null),(t()(),r.Y(8,0,[[3,0],["inputContainer",1]],null,4,"div",[["class","mat-input-infix mat-form-field-infix"]],null,null,null,null,null)),r._8(null,1),(t()(),r.Y(10,0,null,null,2,"span",[["class","mat-form-field-label-wrapper mat-input-placeholder-wrapper mat-form-field-placeholder-wrapper"]],null,null,null,null,null)),(t()(),r.T(16777216,null,null,1,null,La)),r.X(12,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null),(t()(),r.T(16777216,null,null,1,null,Ba)),r.X(14,16384,null,0,O,[r.H,r.E],{ngIf:[0,"ngIf"]},null),(t()(),r.Y(15,0,[[1,0],["underline",1]],null,1,"div",[["class","mat-input-underline mat-form-field-underline"]],null,null,null,null,null)),(t()(),r.Y(16,0,null,null,0,"span",[["class","mat-input-ripple mat-form-field-ripple"]],[[2,"mat-accent",null],[2,"mat-warn",null]],null,null,null,null)),(t()(),r.Y(17,0,null,null,5,"div",[["class","mat-input-subscript-wrapper mat-form-field-subscript-wrapper"]],null,null,null,null,null)),r.X(18,16384,null,0,A,[],{ngSwitch:[0,"ngSwitch"]},null),(t()(),r.T(16777216,null,null,1,null,Ha)),r.X(20,278528,null,0,P,[r.H,r.E,A],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),r.T(16777216,null,null,1,null,Ua)),r.X(22,278528,null,0,P,[r.H,r.E,A],{ngSwitchCase:[0,"ngSwitchCase"]},null)],function(t,e){var n=e.component;t(e,7,0,n._prefixChildren.length),t(e,12,0,n._hasFloatingLabel()),t(e,14,0,n._suffixChildren.length),t(e,18,0,n._getDisplayedMessages()),t(e,20,0,"error"),t(e,22,0,"hint")},function(t,e){var n=e.component;t(e,16,0,"accent"==n.color,"warn"==n.color)})}var qa=r.W({encapsulation:0,styles:[[""]],data:{}});function Xa(t){return r._16(0,[(t()(),r._15(-1,null,["\n"])),(t()(),r.Y(1,0,null,null,6,"mat-toolbar",[["class","mat-toolbar"]],[[2,"mat-toolbar-multiple-rows",null],[2,"mat-toolbar-single-row",null]],null,null,qs,Ys)),r.X(2,4243456,null,1,Vs,[r.i,Je,R],null,null),r._13(603979776,1,{_toolbarRows:1}),(t()(),r._15(-1,0,["\n "])),(t()(),r.Y(5,0,null,0,1,"span",[],null,null,null,null,null)),(t()(),r._15(-1,null,["KTorrent HTML interface"])),(t()(),r._15(-1,0,["\n"])),(t()(),r._15(-1,null,["\n\n"])),(t()(),r.Y(9,0,null,null,2,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.openMagnet()&&r),r},Gs,Xs)),r.X(10,180224,null,0,Di,[r.i,Je,Un],null,null),(t()(),r._15(-1,0,["Magnet link"])),(t()(),r._15(-1,null,["\n\n"])),(t()(),r.Y(13,0,null,null,1,"app-torrent-list",[],null,null,null,Ia,sa)),r.X(14,114688,null,0,ia,[pt],null,null),(t()(),r._15(-1,null,["\n\n"]))],function(t,e){t(e,14,0)},function(t,e){t(e,1,0,r._9(e,2)._toolbarRows.length,!r._9(e,2)._toolbarRows.length),t(e,9,0,r._9(e,10).disabled||null)})}var Ga=r.U("app-root",Fs,function(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"app-root",[],null,null,null,Xa,qa)),r.X(1,49152,null,0,Fs,[zi,pt],null,null)],null,null)},{},{},[]),Za=r.W({encapsulation:0,styles:["mat-form-field[_ngcontent-%COMP%] {\n width: 100%;\n}"],data:{}});function Qa(t){return r._16(0,[(t()(),r.Y(0,0,null,null,43,"div",[],null,[[null,"keydown"]],function(t,e,n){var r=!0;return"keydown"===e&&(r=!1!==t.component.submit(n)&&r),r},null,null)),(t()(),r._15(-1,null,["\n\t"])),(t()(),r.Y(2,0,null,null,2,"h2",[["class","mat-dialog-title"],["mat-dialog-title",""]],[[8,"id",0]],null,null,null,null)),r.X(3,81920,null,0,qi,[[2,Mi],r.i,zi],null,null),(t()(),r._15(-1,null,["New torrent from magnet link"])),(t()(),r._15(-1,null,["\n\t"])),(t()(),r.Y(6,0,null,null,2,"mat-dialog-content",[["class","mat-dialog-content"]],null,null,null,null,null)),r.X(7,16384,null,0,Xi,[],null,null),(t()(),r._15(-1,null,["Enter magnet link"])),(t()(),r._15(-1,null,["\n\t"])),(t()(),r.Y(10,0,null,null,18,"mat-form-field",[["class","mat-input-container mat-form-field"]],[[2,"mat-input-invalid",null],[2,"mat-form-field-invalid",null],[2,"mat-form-field-can-float",null],[2,"mat-form-field-should-float",null],[2,"mat-form-field-hide-placeholder",null],[2,"mat-form-field-disabled",null],[2,"mat-focused",null],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],null,null,Ya,Na)),r.X(11,7389184,null,7,Ci,[r.i,r.f,[2,vn]],null,null),r._13(335544320,1,{_control:0}),r._13(335544320,2,{_placeholderChild:0}),r._13(335544320,3,{_labelChild:0}),r._13(603979776,4,{_errorChildren:1}),r._13(603979776,5,{_hintChildren:1}),r._13(603979776,6,{_prefixChildren:1}),r._13(603979776,7,{_suffixChildren:1}),(t()(),r._15(-1,1,["\n\t\t"])),(t()(),r.Y(20,0,null,1,7,"input",[["class","mat-input-element mat-form-field-autofill-control"],["matInput",""],["placeholder","Magnet link"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null],[2,"mat-input-server",null],[1,"id",0],[8,"placeholder",0],[8,"disabled",0],[8,"required",0],[8,"readOnly",0],[1,"aria-describedby",0],[1,"aria-invalid",0],[1,"aria-required",0]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"focus"]],function(t,e,n){var o=!0,i=t.component;return"input"===e&&(o=!1!==r._9(t,21)._handleInput(n.target.value)&&o),"blur"===e&&(o=!1!==r._9(t,21).onTouched()&&o),"compositionstart"===e&&(o=!1!==r._9(t,21)._compositionStart()&&o),"compositionend"===e&&(o=!1!==r._9(t,21)._compositionEnd(n.target.value)&&o),"blur"===e&&(o=!1!==r._9(t,26)._focusChanged(!1)&&o),"focus"===e&&(o=!1!==r._9(t,26)._focusChanged(!0)&&o),"input"===e&&(o=!1!==r._9(t,26)._onInput()&&o),"ngModelChange"===e&&(o=!1!==(i.magnet=n)&&o),o},null,null)),r.X(21,16384,null,0,lo,[r.y,r.i,[2,ao]],null,null),r._11(1024,null,io,function(t){return[t]},[lo]),r.X(23,671744,null,0,qo,[[8,null],[8,null],[8,null],[2,io]],{model:[0,"model"]},{update:"ngModelChange"}),r._11(2048,null,fo,null,[qo]),r.X(25,16384,null,0,Ao,[fo],null,null),r.X(26,933888,null,0,ts,[r.i,Je,[2,fo],[2,Fo],[2,Go],cn,[8,null]],{placeholder:[0,"placeholder"]},null),r._11(2048,[[1,4]],bi,null,[ts]),(t()(),r._15(-1,1,["\n\t"])),(t()(),r._15(-1,null,["\n\t"])),(t()(),r.Y(30,0,null,null,12,"mat-dialog-actions",[["class","mat-dialog-actions"]],null,null,null,null,null)),r.X(31,16384,null,0,Gi,[],null,null),(t()(),r._15(-1,null,["\n\t "])),(t()(),r.Y(33,0,null,null,3,"button",[["id","start"],["mat-button",""],["type","button"]],[[8,"disabled",0],[1,"aria-label",0]],[[null,"click"]],function(t,e,n){var o=!0;return"click"===e&&(o=!1!==r._9(t,35).dialogRef.close(r._9(t,35).dialogResult)&&o),o},Gs,Xs)),r.X(34,180224,null,0,Di,[r.i,Je,Un],null,null),r.X(35,606208,null,0,Yi,[[2,Mi],r.i,zi],{dialogResult:[0,"dialogResult"]},null),(t()(),r._15(-1,0,["Start torrent"])),(t()(),r._15(-1,null,["\n\t "])),(t()(),r.Y(38,0,null,null,3,"button",[["mat-button",""],["type","button"]],[[8,"disabled",0],[1,"aria-label",0]],[[null,"click"]],function(t,e,n){var o=!0;return"click"===e&&(o=!1!==r._9(t,40).dialogRef.close(r._9(t,40).dialogResult)&&o),o},Gs,Xs)),r.X(39,180224,null,0,Di,[r.i,Je,Un],null,null),r.X(40,606208,null,0,Yi,[[2,Mi],r.i,zi],{dialogResult:[0,"dialogResult"]},null),(t()(),r._15(-1,0,["Cancel"])),(t()(),r._15(-1,null,["\n\t"])),(t()(),r._15(-1,null,["\n"])),(t()(),r._15(-1,null,["\n"]))],function(t,e){var n=e.component;t(e,3,0),t(e,23,0,n.magnet),t(e,26,0,"Magnet link"),t(e,35,0,n.magnet),t(e,40,0,!1)},function(t,e){t(e,2,0,r._9(e,3).id),t(e,10,1,[r._9(e,11)._control.errorState,r._9(e,11)._control.errorState,r._9(e,11)._canLabelFloat,r._9(e,11)._shouldLabelFloat(),r._9(e,11)._hideControlPlaceholder(),r._9(e,11)._control.disabled,r._9(e,11)._control.focused,r._9(e,11)._shouldForward("untouched"),r._9(e,11)._shouldForward("touched"),r._9(e,11)._shouldForward("pristine"),r._9(e,11)._shouldForward("dirty"),r._9(e,11)._shouldForward("valid"),r._9(e,11)._shouldForward("invalid"),r._9(e,11)._shouldForward("pending")]),t(e,20,1,[r._9(e,25).ngClassUntouched,r._9(e,25).ngClassTouched,r._9(e,25).ngClassPristine,r._9(e,25).ngClassDirty,r._9(e,25).ngClassValid,r._9(e,25).ngClassInvalid,r._9(e,25).ngClassPending,r._9(e,26)._isServer,r._9(e,26).id,r._9(e,26).placeholder,r._9(e,26).disabled,r._9(e,26).required,r._9(e,26).readonly,r._9(e,26)._ariaDescribedby||null,r._9(e,26).errorState,r._9(e,26).required.toString()]),t(e,33,0,r._9(e,34).disabled||null,r._9(e,35).ariaLabel),t(e,38,0,r._9(e,39).disabled||null,r._9(e,40).ariaLabel)})}var Ka=r.U("app-magnet-dialog",Ls,function(t){return r._16(0,[(t()(),r.Y(0,0,null,null,1,"app-magnet-dialog",[],null,null,null,Qa,Za)),r.X(1,49152,null,0,Ls,[r.y],null,null)],null,null)},{},{},[]);function Wa(t){switch(t.length){case 0:return new _i;case 1:return t[0];default:return new gi(t)}}function $a(t,e,n,r,o,i){void 0===o&&(o={}),void 0===i&&(i={});var s=[],a=[],l=-1,u=null;if(r.forEach(function(t){var n=t.offset,r=n==l,c=r&&u||{};Object.keys(t).forEach(function(n){var r=n,a=t[n];if("offset"!==n)switch(r=e.normalizePropertyName(r,s),a){case vi:a=o[n];break;case di:a=i[n];break;default:a=e.normalizeStyleValue(n,r,a,s)}c[r]=a}),r||a.push(c),u=c,l=n}),s.length)throw new Error("Unable to animate due to the following errors:\n - "+s.join("\n - "));return a}function Ja(t,e,n,r){switch(e){case"start":t.onStart(function(){return r(n&&tl(n,"start",t.totalTime))});break;case"done":t.onDone(function(){return r(n&&tl(n,"done",t.totalTime))});break;case"destroy":t.onDestroy(function(){return r(n&&tl(n,"destroy",t.totalTime))})}}function tl(t,e,n){var r=el(t.element,t.triggerName,t.fromState,t.toState,e||t.phaseName,void 0==n?t.totalTime:n),o=t._data;return null!=o&&(r._data=o),r}function el(t,e,n,r,o,i){return void 0===o&&(o=""),void 0===i&&(i=0),{element:t,triggerName:e,fromState:n,toState:r,phaseName:o,totalTime:i}}function nl(t,e,n){var r;return t instanceof Map?(r=t.get(e))||t.set(e,r=n):(r=t[e])||(r=t[e]=n),r}function rl(t){var e=t.indexOf(":");return[t.substring(1,e),t.substr(e+1)]}var ol=function(t,e){return!1},il=function(t,e){return!1},sl=function(t,e,n){return[]};if("undefined"!=typeof Element){if(ol=function(t,e){return t.contains(e)},Element.prototype.matches)il=function(t,e){return t.matches(e)};else{var al=Element.prototype,ll=al.matchesSelector||al.mozMatchesSelector||al.msMatchesSelector||al.oMatchesSelector||al.webkitMatchesSelector;ll&&(il=function(t,e){return ll.apply(t,[e])})}sl=function(t,e,n){var r=[];if(n)r.push.apply(r,t.querySelectorAll(e));else{var o=t.querySelector(e);o&&r.push(o)}return r}}var ul=null,cl=!1;function hl(t){ul||(ul=pl()||{},cl=!!ul.style&&"WebkitAppearance"in ul.style);var e=!0;return ul.style&&!function(t){return"ebkit"==t.substring(1,6)}(t)&&!(e=t in ul.style)&&cl&&(e="Webkit"+t.charAt(0).toUpperCase()+t.substr(1)in ul.style),e}function pl(){return"undefined"!=typeof document?document.body:null}var dl=il,fl=ol,ml=sl,yl=function(){function t(){}return t.prototype.validateStyleProperty=function(t){return hl(t)},t.prototype.matchesElement=function(t,e){return dl(t,e)},t.prototype.containsElement=function(t,e){return fl(t,e)},t.prototype.query=function(t,e,n){return ml(t,e,n)},t.prototype.computeStyle=function(t,e,n){return n||""},t.prototype.animate=function(t,e,n,r,o,i){return void 0===i&&(i=[]),new _i},t}(),_l=function(){function t(){}return t.NOOP=new yl,t}(),gl=1e3;function vl(t){if("number"==typeof t)return t;var e=t.match(/^(-?[\.\d]+)(m?s)/);return!e||e.length<2?0:bl(parseFloat(e[1]),e[2])}function bl(t,e){switch(e){case"s":return t*gl;default:return t}}function wl(t,e,n){return t.hasOwnProperty("duration")?t:function(t,e,n){var r,o=0,i="";if("string"==typeof t){var s=t.match(/^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i);if(null===s)return e.push('The provided timing value "'+t+'" is invalid.'),{duration:0,delay:0,easing:""};r=bl(parseFloat(s[1]),s[2]);var a=s[3];null!=a&&(o=bl(Math.floor(parseFloat(a)),s[4]));var l=s[5];l&&(i=l)}else r=t;if(!n){var u=!1,c=e.length;r<0&&(e.push("Duration values below 0 are not allowed for this animation step."),u=!0),o<0&&(e.push("Delay values below 0 are not allowed for this animation step."),u=!0),u&&e.splice(c,0,'The provided timing value "'+t+'" is invalid.')}return{duration:r,delay:o,easing:i}}(t,e,n)}function El(t,e){return void 0===e&&(e={}),Object.keys(t).forEach(function(n){e[n]=t[n]}),e}function Cl(t,e,n){if(void 0===n&&(n={}),e)for(var r in t)n[r]=t[r];else El(t,n);return n}function xl(t,e){t.style&&Object.keys(e).forEach(function(n){var r=Rl(n);t.style[r]=e[n]})}function Sl(t,e){t.style&&Object.keys(e).forEach(function(e){var n=Rl(e);t.style[n]=""})}function Ol(t){return Array.isArray(t)?1==t.length?t[0]:fi(t):t}var Tl=new RegExp("{{\\s*(.+?)\\s*}}","g");function kl(t){var e=[];if("string"==typeof t){for(var n=t.toString(),r=void 0;r=Tl.exec(n);)e.push(r[1]);Tl.lastIndex=0}return e}function Al(t,e,n){var r=t.toString(),o=r.replace(Tl,function(t,r){var o=e[r];return e.hasOwnProperty(r)||(n.push("Please provide a value for the animation param "+r),o=""),o.toString()});return o==r?t:o}function Pl(t){for(var e=[],n=t.next();!n.done;)e.push(n.value),n=t.next();return e}var Dl=/-+([a-z0-9])/g;function Rl(t){return t.replace(Dl,function(){for(var t=[],e=0;e *";case":leave":return"* => void";case":increment":return function(t,e){return parseFloat(e)>parseFloat(t)};case":decrement":return function(t,e){return parseFloat(e) *"}}(t,n);if("function"==typeof r)return void e.push(r);t=r}var o=t.match(/^(\*|[-\w]+)\s*()\s*(\*|[-\w]+)$/);if(null==o||o.length<4)return n.push('The provided transition expression "'+t+'" is not supported'),e;var i=o[1],s=o[2],a=o[3];e.push(Ml(i,a)),"<"!=s[0]||i==Nl&&a==Nl||e.push(Ml(a,i))}(t,o,r)}):o.push(n),o),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Ul(t.options)}},t.prototype.visitSequence=function(t,e){var n=this;return{type:2,steps:t.steps.map(function(t){return Il(n,t,e)}),options:Ul(t.options)}},t.prototype.visitGroup=function(t,e){var n=this,r=e.currentTime,o=0,i=t.steps.map(function(t){e.currentTime=r;var i=Il(n,t,e);return o=Math.max(o,e.currentTime),i});return e.currentTime=o,{type:3,steps:i,options:Ul(t.options)}},t.prototype.visitAnimate=function(t,e){var n,r=function(t,e){var n=null;if(t.hasOwnProperty("duration"))n=t;else if("number"==typeof t)return Yl(wl(t,e).duration,0,"");var r=t;if(r.split(/\s+/).some(function(t){return"{"==t.charAt(0)&&"{"==t.charAt(1)})){var o=Yl(0,0,"");return o.dynamic=!0,o.strValue=r,o}return Yl((n=n||wl(r,e)).duration,n.delay,n.easing)}(t.timings,e.errors);e.currentAnimateTimings=r;var o=t.styles?t.styles:mi({});if(5==o.type)n=this.visitKeyframes(o,e);else{var i=t.styles,s=!1;if(!i){s=!0;var a={};r.easing&&(a.easing=r.easing),i=mi(a)}e.currentTime+=r.duration+r.delay;var l=this.visitStyle(i,e);l.isEmptyStep=s,n=l}return e.currentAnimateTimings=null,{type:4,timings:r,style:n,options:null}},t.prototype.visitStyle=function(t,e){var n=this._makeStyleAst(t,e);return this._validateStyleAst(n,e),n},t.prototype._makeStyleAst=function(t,e){var n=[];Array.isArray(t.styles)?t.styles.forEach(function(t){"string"==typeof t?t==di?n.push(t):e.errors.push("The provided style string value "+t+" is not allowed."):n.push(t)}):n.push(t.styles);var r=!1,o=null;return n.forEach(function(t){if(zl(t)){var e=t,n=e.easing;if(n&&(o=n,delete e.easing),!r)for(var i in e)if(e[i].toString().indexOf("{{")>=0){r=!0;break}}}),{type:6,styles:n,easing:o,offset:t.offset,containsDynamicStyles:r,options:null}},t.prototype._validateStyleAst=function(t,e){var n=this,r=e.currentAnimateTimings,o=e.currentTime,i=e.currentTime;r&&i>0&&(i-=r.duration+r.delay),t.styles.forEach(function(t){"string"!=typeof t&&Object.keys(t).forEach(function(r){if(n._driver.validateStyleProperty(r)){var s,a,l,u=e.collectedStyles[e.currentQuerySelector],c=u[r],h=!0;c&&(i!=o&&i>=c.startTime&&o<=c.endTime&&(e.errors.push('The CSS property "'+r+'" that exists between the times of "'+c.startTime+'ms" and "'+c.endTime+'ms" is also being animated in a parallel animation between the times of "'+i+'ms" and "'+o+'ms"'),h=!1),i=c.startTime),h&&(u[r]={startTime:i,endTime:o}),e.options&&(s=e.errors,a=e.options.params||{},(l=kl(t[r])).length&&l.forEach(function(t){a.hasOwnProperty(t)||s.push("Unable to resolve the local animation param "+t+" in the given list of values")}))}else e.errors.push('The provided animation property "'+r+'" is not a supported CSS property for animations')})})},t.prototype.visitKeyframes=function(t,e){var n=this,r={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push("keyframes() must be placed inside of a call to animate()"),r;var o=0,i=[],s=!1,a=!1,l=0,u=t.steps.map(function(t){var r=n._makeStyleAst(t,e),u=null!=r.offset?r.offset:function(t){if("string"==typeof t)return null;var e=null;if(Array.isArray(t))t.forEach(function(t){if(zl(t)&&t.hasOwnProperty("offset")){var n=t;e=parseFloat(n.offset),delete n.offset}});else if(zl(t)&&t.hasOwnProperty("offset")){var n=t;e=parseFloat(n.offset),delete n.offset}return e}(r.styles),c=0;return null!=u&&(o++,c=r.offset=u),a=a||c<0||c>1,s=s||c0&&o0?o==p?1:h*o:i[o],a=s*m;e.currentTime=d+f.delay+a,f.duration=a,n._validateStyleAst(t,e),t.offset=s,r.styles.push(t)}),r},t.prototype.visitReference=function(t,e){return{type:8,animation:Il(this,Ol(t.animation),e),options:Ul(t.options)}},t.prototype.visitAnimateChild=function(t,e){return e.depCount++,{type:9,options:Ul(t.options)}},t.prototype.visitAnimateRef=function(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Ul(t.options)}},t.prototype.visitQuery=function(t,e){var n=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;var o=function(t){var e=!!t.split(/\s*,\s*/).find(function(t){return":self"==t});return e&&(t=t.replace(Fl,"")),[t=t.replace(/@\*/g,".ng-trigger").replace(/@\w+/g,function(t){return".ng-trigger-"+t.substr(1)}).replace(/:animating/g,".ng-animating"),e]}(t.selector),i=o[0],s=o[1];e.currentQuerySelector=n.length?n+" "+i:i,nl(e.collectedStyles,e.currentQuerySelector,{});var a=Il(this,Ol(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=n,{type:11,selector:i,limit:r.limit||0,optional:!!r.optional,includeSelf:s,animation:a,originalSelector:t.selector,options:Ul(t.options)}},t.prototype.visitStagger=function(t,e){e.currentQuery||e.errors.push("stagger() can only be used inside of query()");var n="full"===t.timings?{duration:0,delay:0,easing:"full"}:wl(t.timings,e.errors,!0);return{type:12,animation:Il(this,Ol(t.animation),e),timings:n,options:null}},t}(),Hl=function(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null};function zl(t){return!Array.isArray(t)&&"object"==typeof t}function Ul(t){var e;return t?(t=El(t)).params&&(t.params=(e=t.params)?El(e):null):t={},t}function Yl(t,e,n){return{duration:t,delay:e,easing:n}}function ql(t,e,n,r,o,i,s,a){return void 0===s&&(s=null),void 0===a&&(a=!1),{type:1,element:t,keyframes:e,preStyleProps:n,postStyleProps:r,duration:o,delay:i,totalTime:o+i,easing:s,subTimeline:a}}var Xl=function(){function t(){this._map=new Map}return t.prototype.consume=function(t){var e=this._map.get(t);return e?this._map.delete(t):e=[],e},t.prototype.append=function(t,e){var n=this._map.get(t);n||this._map.set(t,n=[]),n.push.apply(n,e)},t.prototype.has=function(t){return this._map.has(t)},t.prototype.clear=function(){this._map.clear()},t}(),Gl=new RegExp(":enter","g"),Zl=new RegExp(":leave","g");function Ql(t,e,n,r,o,i,s,a,l,u){return void 0===i&&(i={}),void 0===s&&(s={}),void 0===u&&(u=[]),(new Kl).buildKeyframes(t,e,n,r,o,i,s,a,l,u)}var Kl=function(){function t(){}return t.prototype.buildKeyframes=function(t,e,n,r,o,i,s,a,l,u){void 0===u&&(u=[]),l=l||new Xl;var c=new $l(t,e,l,r,o,u,[]);c.options=a,c.currentTimeline.setStyles([i],null,c.errors,a),Il(this,n,c);var h=c.timelines.filter(function(t){return t.containsAnimation()});if(h.length&&Object.keys(s).length){var p=h[h.length-1];p.allowOnlyTimelineStyles()||p.setStyles([s],null,c.errors,a)}return h.length?h.map(function(t){return t.buildKeyframes()}):[ql(e,[],[],[],0,0,"",!1)]},t.prototype.visitTrigger=function(t,e){},t.prototype.visitState=function(t,e){},t.prototype.visitTransition=function(t,e){},t.prototype.visitAnimateChild=function(t,e){var n=e.subInstructions.consume(e.element);if(n){var r=e.createSubContext(t.options),o=e.currentTimeline.currentTime,i=this._visitSubInstructions(n,r,r.options);o!=i&&e.transformIntoNewTimeline(i)}e.previousNode=t},t.prototype.visitAnimateRef=function(t,e){var n=e.createSubContext(t.options);n.transformIntoNewTimeline(),this.visitReference(t.animation,n),e.transformIntoNewTimeline(n.currentTimeline.currentTime),e.previousNode=t},t.prototype._visitSubInstructions=function(t,e,n){var r=e.currentTimeline.currentTime,o=null!=n.duration?vl(n.duration):null,i=null!=n.delay?vl(n.delay):null;return 0!==o&&t.forEach(function(t){var n=e.appendInstructionToTimeline(t,o,i);r=Math.max(r,n.duration+n.delay)}),r},t.prototype.visitReference=function(t,e){e.updateOptions(t.options,!0),Il(this,t.animation,e),e.previousNode=t},t.prototype.visitSequence=function(t,e){var n=this,r=e.subContextCount,o=e,i=t.options;if(i&&(i.params||i.delay)&&((o=e.createSubContext(i)).transformIntoNewTimeline(),null!=i.delay)){6==o.previousNode.type&&(o.currentTimeline.snapshotCurrentStyles(),o.previousNode=Wl);var s=vl(i.delay);o.delayNextStep(s)}t.steps.length&&(t.steps.forEach(function(t){return Il(n,t,o)}),o.currentTimeline.applyStylesToKeyframe(),o.subContextCount>r&&o.transformIntoNewTimeline()),e.previousNode=t},t.prototype.visitGroup=function(t,e){var n=this,r=[],o=e.currentTimeline.currentTime,i=t.options&&t.options.delay?vl(t.options.delay):0;t.steps.forEach(function(s){var a=e.createSubContext(t.options);i&&a.delayNextStep(i),Il(n,s,a),o=Math.max(o,a.currentTimeline.currentTime),r.push(a.currentTimeline)}),r.forEach(function(t){return e.currentTimeline.mergeTimelineCollectedStyles(t)}),e.transformIntoNewTimeline(o),e.previousNode=t},t.prototype._visitTiming=function(t,e){if(t.dynamic){var n=t.strValue;return wl(e.params?Al(n,e.params,e.errors):n,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}},t.prototype.visitAnimate=function(t,e){var n=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;n.delay&&(e.incrementTime(n.delay),r.snapshotCurrentStyles());var o=t.style;5==o.type?this.visitKeyframes(o,e):(e.incrementTime(n.duration),this.visitStyle(o,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t},t.prototype.visitStyle=function(t,e){var n=e.currentTimeline,r=e.currentAnimateTimings;!r&&n.getCurrentStyleProperties().length&&n.forwardFrame();var o=r&&r.easing||t.easing;t.isEmptyStep?n.applyEmptyStep(o):n.setStyles(t.styles,o,e.errors,e.options),e.previousNode=t},t.prototype.visitKeyframes=function(t,e){var n=e.currentAnimateTimings,r=e.currentTimeline.duration,o=n.duration,i=e.createSubContext().currentTimeline;i.easing=n.easing,t.styles.forEach(function(t){i.forwardTime((t.offset||0)*o),i.setStyles(t.styles,t.easing,e.errors,e.options),i.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(i),e.transformIntoNewTimeline(r+o),e.previousNode=t},t.prototype.visitQuery=function(t,e){var n=this,r=e.currentTimeline.currentTime,o=t.options||{},i=o.delay?vl(o.delay):0;i&&(6===e.previousNode.type||0==r&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=Wl);var s=r,a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!o.optional,e.errors);e.currentQueryTotal=a.length;var l=null;a.forEach(function(r,o){e.currentQueryIndex=o;var a=e.createSubContext(t.options,r);i&&a.delayNextStep(i),r===e.element&&(l=a.currentTimeline),Il(n,t.animation,a),a.currentTimeline.applyStylesToKeyframe(),s=Math.max(s,a.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(s),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t},t.prototype.visitStagger=function(t,e){var n=e.parentContext,r=e.currentTimeline,o=t.timings,i=Math.abs(o.duration),s=i*(e.currentQueryTotal-1),a=i*e.currentQueryIndex;switch(o.duration<0?"reverse":o.easing){case"reverse":a=s-a;break;case"full":a=n.currentStaggerTime}var l=e.currentTimeline;a&&l.delayNextStep(a);var u=l.currentTime;Il(this,t.animation,e),e.previousNode=t,n.currentStaggerTime=r.currentTime-u+(r.startTime-n.currentTimeline.startTime)},t}(),Wl={},$l=function(){function t(t,e,n,r,o,i,s,a){this._driver=t,this.element=e,this.subInstructions=n,this._enterClassName=r,this._leaveClassName=o,this.errors=i,this.timelines=s,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=Wl,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=a||new Jl(this._driver,e,0),s.push(this.currentTimeline)}return Object.defineProperty(t.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),t.prototype.updateOptions=function(t,e){var n=this;if(t){var r=t,o=this.options;null!=r.duration&&(o.duration=vl(r.duration)),null!=r.delay&&(o.delay=vl(r.delay));var i=r.params;if(i){var s=o.params;s||(s=this.options.params={}),Object.keys(i).forEach(function(t){e&&s.hasOwnProperty(t)||(s[t]=Al(i[t],s,n.errors))})}}},t.prototype._copyOptions=function(){var t={};if(this.options){var e=this.options.params;if(e){var n=t.params={};Object.keys(e).forEach(function(t){n[t]=e[t]})}}return t},t.prototype.createSubContext=function(e,n,r){void 0===e&&(e=null);var o=n||this.element,i=new t(this._driver,o,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(o,r||0));return i.previousNode=this.previousNode,i.currentAnimateTimings=this.currentAnimateTimings,i.options=this._copyOptions(),i.updateOptions(e),i.currentQueryIndex=this.currentQueryIndex,i.currentQueryTotal=this.currentQueryTotal,i.parentContext=this,this.subContextCount++,i},t.prototype.transformIntoNewTimeline=function(t){return this.previousNode=Wl,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline},t.prototype.appendInstructionToTimeline=function(t,e,n){var r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=n?n:0)+t.delay,easing:""},o=new tu(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(o),r},t.prototype.incrementTime=function(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)},t.prototype.delayNextStep=function(t){t>0&&this.currentTimeline.delayNextStep(t)},t.prototype.invokeQuery=function(t,e,n,r,o,i){var s=[];if(r&&s.push(this.element),t.length>0){t=(t=t.replace(Gl,"."+this._enterClassName)).replace(Zl,"."+this._leaveClassName);var a=this._driver.query(this.element,t,1!=n);0!==n&&(a=n<0?a.slice(a.length+n,a.length):a.slice(0,n)),s.push.apply(s,a)}return o||0!=s.length||i.push('`query("'+e+'")` returned zero elements. (Use `query("'+e+'", { optional: true })` if you wish to allow this.)'),s},t}(),Jl=function(){function t(t,e,n,r){this._driver=t,this.element=e,this.startTime=n,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}return t.prototype.containsAnimation=function(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}},t.prototype.getCurrentStyleProperties=function(){return Object.keys(this._currentKeyframe)},Object.defineProperty(t.prototype,"currentTime",{get:function(){return this.startTime+this.duration},enumerable:!0,configurable:!0}),t.prototype.delayNextStep=function(t){var e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t},t.prototype.fork=function(e,n){return this.applyStylesToKeyframe(),new t(this._driver,e,n||this.currentTime,this._elementTimelineStylesLookup)},t.prototype._loadKeyframe=function(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))},t.prototype.forwardFrame=function(){this.duration+=1,this._loadKeyframe()},t.prototype.forwardTime=function(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()},t.prototype._updateStyle=function(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}},t.prototype.allowOnlyTimelineStyles=function(){return this._currentEmptyStepKeyframe!==this._currentKeyframe},t.prototype.applyEmptyStep=function(t){var e=this;t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(function(t){e._backFill[t]=e._globalTimelineStyles[t]||di,e._currentKeyframe[t]=di}),this._currentEmptyStepKeyframe=this._currentKeyframe},t.prototype.setStyles=function(t,e,n,r){var o=this;e&&(this._previousKeyframe.easing=e);var i=r&&r.params||{},s=function(t,e){var n,r={};return t.forEach(function(t){"*"===t?(n=n||Object.keys(e)).forEach(function(t){r[t]=di}):Cl(t,!1,r)}),r}(t,this._globalTimelineStyles);Object.keys(s).forEach(function(t){var e=Al(s[t],i,n);o._pendingStyles[t]=e,o._localTimelineStyles.hasOwnProperty(t)||(o._backFill[t]=o._globalTimelineStyles.hasOwnProperty(t)?o._globalTimelineStyles[t]:di),o._updateStyle(t,e)})},t.prototype.applyStylesToKeyframe=function(){var t=this,e=this._pendingStyles,n=Object.keys(e);0!=n.length&&(this._pendingStyles={},n.forEach(function(n){t._currentKeyframe[n]=e[n]}),Object.keys(this._localTimelineStyles).forEach(function(e){t._currentKeyframe.hasOwnProperty(e)||(t._currentKeyframe[e]=t._localTimelineStyles[e])}))},t.prototype.snapshotCurrentStyles=function(){var t=this;Object.keys(this._localTimelineStyles).forEach(function(e){var n=t._localTimelineStyles[e];t._pendingStyles[e]=n,t._updateStyle(e,n)})},t.prototype.getFinalKeyframe=function(){return this._keyframes.get(this.duration)},Object.defineProperty(t.prototype,"properties",{get:function(){var t=[];for(var e in this._currentKeyframe)t.push(e);return t},enumerable:!0,configurable:!0}),t.prototype.mergeTimelineCollectedStyles=function(t){var e=this;Object.keys(t._styleSummary).forEach(function(n){var r=e._styleSummary[n],o=t._styleSummary[n];(!r||o.time>r.time)&&e._updateStyle(n,o.value)})},t.prototype.buildKeyframes=function(){var t=this;this.applyStylesToKeyframe();var e=new Set,n=new Set,r=1===this._keyframes.size&&0===this.duration,o=[];this._keyframes.forEach(function(i,s){var a=Cl(i,!0);Object.keys(a).forEach(function(t){var r=a[t];r==vi?e.add(t):r==di&&n.add(t)}),r||(a.offset=s/t.duration),o.push(a)});var i=e.size?Pl(e.values()):[],s=n.size?Pl(n.values()):[];if(r){var a=o[0],l=El(a);a.offset=0,l.offset=1,o=[a,l]}return ql(this.element,o,i,s,this.duration,this.startTime,this.easing,!1)},t}(),tu=function(t){function e(e,n,r,o,i,s,a){void 0===a&&(a=!1);var l=t.call(this,e,n,s.delay)||this;return l.element=n,l.keyframes=r,l.preStyleProps=o,l.postStyleProps=i,l._stretchStartingKeyframe=a,l.timings={duration:s.duration,delay:s.delay,easing:s.easing},l}return Object(l.b)(e,t),e.prototype.containsAnimation=function(){return this.keyframes.length>1},e.prototype.buildKeyframes=function(){var t=this.keyframes,e=this.timings,n=e.delay,r=e.duration,o=e.easing;if(this._stretchStartingKeyframe&&n){var i=[],s=r+n,a=n/s,l=Cl(t[0],!1);l.offset=0,i.push(l);var u=Cl(t[0],!1);u.offset=eu(a),i.push(u);for(var c=t.length-1,h=1;h<=c;h++){var p=Cl(t[h],!1);p.offset=eu((n+p.offset*r)/s),i.push(p)}r=s,n=0,o="",t=i}return ql(this.element,t,this.preStyleProps,this.postStyleProps,r,n,o,!0)},e}(Jl);function eu(t,e){void 0===e&&(e=3);var n=Math.pow(10,e-1);return Math.round(t*n)/n}var nu=function(){},ru=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(l.b)(e,t),e.prototype.normalizePropertyName=function(t,e){return Rl(t)},e.prototype.normalizeStyleValue=function(t,e,n,r){var o="",i=n.toString().trim();if(ou[e]&&0!==n&&"0"!==n)if("number"==typeof n)o="px";else{var s=n.match(/^[+-]?[\d\.]+([a-z]*)$/);s&&0==s[1].length&&r.push("Please provide a CSS unit value for "+t+":"+n)}return i+o},e}(nu),ou=function(t){var e={};return"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective".split(",").forEach(function(t){return e[t]=!0}),e}();function iu(t,e,n,r,o,i,s,a,l,u,c,h){return{type:0,element:t,triggerName:e,isRemovalTransition:o,fromState:n,fromStyles:i,toState:r,toStyles:s,timelines:a,queriedElements:l,preStyleProps:u,postStyleProps:c,errors:h}}var su={},au=function(){function t(t,e,n){this._triggerName=t,this.ast=e,this._stateStyles=n}return t.prototype.match=function(t,e){return function(t,e,n){return t.some(function(t){return t(e,n)})}(this.ast.matchers,t,e)},t.prototype.buildStyles=function(t,e,n){var r=this._stateStyles["*"],o=this._stateStyles[t],i=r?r.buildStyles(e,n):{};return o?o.buildStyles(e,n):i},t.prototype.build=function(t,e,n,r,o,i,s,a,u){var c=[],h=this.ast.options&&this.ast.options.params||su,p=this.buildStyles(n,s&&s.params||su,c),d=a&&a.params||su,f=this.buildStyles(r,d,c),m=new Set,y=new Map,_=new Map,g="void"===r,v={params:Object(l.a)({},h,d)},b=Ql(t,e,this.ast.animation,o,i,p,f,v,u,c);if(c.length)return iu(e,this._triggerName,n,r,g,p,f,[],[],y,_,c);b.forEach(function(t){var n=t.element,r=nl(y,n,{});t.preStyleProps.forEach(function(t){return r[t]=!0});var o=nl(_,n,{});t.postStyleProps.forEach(function(t){return o[t]=!0}),n!==e&&m.add(n)});var w=Pl(m.values());return iu(e,this._triggerName,n,r,g,p,f,b,w,y,_)},t}(),lu=function(){function t(t,e){this.styles=t,this.defaultParams=e}return t.prototype.buildStyles=function(t,e){var n={},r=El(this.defaultParams);return Object.keys(t).forEach(function(e){var n=t[e];null!=n&&(r[e]=n)}),this.styles.styles.forEach(function(t){if("string"!=typeof t){var o=t;Object.keys(o).forEach(function(t){var i=o[t];i.length>1&&(i=Al(i,r,e)),n[t]=i})}}),n},t}(),uu=function(){function t(t,e){var n=this;this.name=t,this.ast=e,this.transitionFactories=[],this.states={},e.states.forEach(function(t){n.states[t.name]=new lu(t.style,t.options&&t.options.params||{})}),cu(this.states,"true","1"),cu(this.states,"false","0"),e.transitions.forEach(function(e){n.transitionFactories.push(new au(t,e,n.states))}),this.fallbackTransition=new au(t,{type:1,animation:{type:2,steps:[],options:null},matchers:[function(t,e){return!0}],options:null,queryCount:0,depCount:0},this.states)}return Object.defineProperty(t.prototype,"containsQueries",{get:function(){return this.ast.queryCount>0},enumerable:!0,configurable:!0}),t.prototype.matchTransition=function(t,e){return this.transitionFactories.find(function(n){return n.match(t,e)})||null},t.prototype.matchStyles=function(t,e,n){return this.fallbackTransition.buildStyles(t,e,n)},t}();function cu(t,e,n){t.hasOwnProperty(e)?t.hasOwnProperty(n)||(t[n]=t[e]):t.hasOwnProperty(n)&&(t[e]=t[n])}var hu=new Xl,pu=function(){function t(t,e){this._driver=t,this._normalizer=e,this._animations={},this._playersById={},this.players=[]}return t.prototype.register=function(t,e){var n=[],r=Ll(this._driver,e,n);if(n.length)throw new Error("Unable to build the animation due to the following errors: "+n.join("\n"));this._animations[t]=r},t.prototype._buildPlayer=function(t,e,n){var r=t.element,o=$a(0,this._normalizer,0,t.keyframes,e,n);return this._driver.animate(r,o,t.duration,t.delay,t.easing,[])},t.prototype.create=function(t,e,n){var r=this;void 0===n&&(n={});var o,i=[],s=this._animations[t],a=new Map;if(s?(o=Ql(this._driver,e,s,"ng-enter","ng-leave",{},{},n,hu,i)).forEach(function(t){var e=nl(a,t.element,{});t.postStyleProps.forEach(function(t){return e[t]=null})}):(i.push("The requested animation doesn't exist or has already been destroyed"),o=[]),i.length)throw new Error("Unable to create the animation due to the following errors: "+i.join("\n"));a.forEach(function(t,e){Object.keys(t).forEach(function(n){t[n]=r._driver.computeStyle(e,n,di)})});var l=Wa(o.map(function(t){var e=a.get(t.element);return r._buildPlayer(t,{},e)}));return this._playersById[t]=l,l.onDestroy(function(){return r.destroy(t)}),this.players.push(l),l},t.prototype.destroy=function(t){var e=this._getPlayer(t);e.destroy(),delete this._playersById[t];var n=this.players.indexOf(e);n>=0&&this.players.splice(n,1)},t.prototype._getPlayer=function(t){var e=this._playersById[t];if(!e)throw new Error("Unable to find the timeline player referenced by "+t);return e},t.prototype.listen=function(t,e,n,r){var o=el(e,"","","");return Ja(this._getPlayer(t),n,o,r),function(){}},t.prototype.command=function(t,e,n,r){if("register"!=n)if("create"!=n){var o=this._getPlayer(t);switch(n){case"play":o.play();break;case"pause":o.pause();break;case"reset":o.reset();break;case"restart":o.restart();break;case"finish":o.finish();break;case"init":o.init();break;case"setPosition":o.setPosition(parseFloat(r[0]));break;case"destroy":this.destroy(t)}}else this.create(t,e,r[0]||{});else this.register(t,r[0])},t}(),du=[],fu={namespaceId:"",setForRemoval:null,hasAnimation:!1,removedBeforeQueried:!1},mu={namespaceId:"",setForRemoval:null,hasAnimation:!1,removedBeforeQueried:!0},yu="__ng_removed",_u=function(){function t(t,e){void 0===e&&(e=""),this.namespaceId=e;var n=t&&t.hasOwnProperty("value");if(this.value=function(t){return null!=t?t:null}(n?t.value:t),n){var r=El(t);delete r.value,this.options=r}else this.options={};this.options.params||(this.options.params={})}return Object.defineProperty(t.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),t.prototype.absorbOptions=function(t){var e=t.params;if(e){var n=this.options.params;Object.keys(e).forEach(function(t){null==n[t]&&(n[t]=e[t])})}},t}(),gu=new _u("void"),vu=new _u("DELETED"),bu=function(){function t(t,e,n){this.id=t,this.hostElement=e,this._engine=n,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName="ng-tns-"+t,ku(e,this._hostClassName)}return t.prototype.listen=function(t,e,n,r){var o,i=this;if(!this._triggers.hasOwnProperty(e))throw new Error('Unable to listen on the animation trigger event "'+n+'" because the animation trigger "'+e+"\" doesn't exist!");if(null==n||0==n.length)throw new Error('Unable to listen on the animation trigger "'+e+'" because the provided event is undefined!');if("start"!=(o=n)&&"done"!=o)throw new Error('The provided animation trigger event "'+n+'" for the animation trigger "'+e+'" is not supported!');var s=nl(this._elementListeners,t,[]),a={name:e,phase:n,callback:r};s.push(a);var l=nl(this._engine.statesByElement,t,{});return l.hasOwnProperty(e)||(ku(t,"ng-trigger"),ku(t,"ng-trigger-"+e),l[e]=gu),function(){i._engine.afterFlush(function(){var t=s.indexOf(a);t>=0&&s.splice(t,1),i._triggers[e]||delete l[e]})}},t.prototype.register=function(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)},t.prototype._getTrigger=function(t){var e=this._triggers[t];if(!e)throw new Error('The provided animation trigger "'+t+'" has not been registered!');return e},t.prototype.trigger=function(t,e,n,r){var o=this;void 0===r&&(r=!0);var i=this._getTrigger(e),s=new Eu(this.id,e,t),a=this._engine.statesByElement.get(t);a||(ku(t,"ng-trigger"),ku(t,"ng-trigger-"+e),this._engine.statesByElement.set(t,a={}));var l=a[e],u=new _u(n,this.id);if(!(n&&n.hasOwnProperty("value"))&&l&&u.absorbOptions(l.options),a[e]=u,l){if(l===vu)return s}else l=gu;if("void"===u.value||l.value!==u.value){var c=nl(this._engine.playersByElement,t,[]);c.forEach(function(t){t.namespaceId==o.id&&t.triggerName==e&&t.queued&&t.destroy()});var h=i.matchTransition(l.value,u.value),p=!1;if(!h){if(!r)return;h=i.fallbackTransition,p=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:h,fromState:l,toState:u,player:s,isFallbackTransition:p}),p||(ku(t,"ng-animate-queued"),s.onStart(function(){Au(t,"ng-animate-queued")})),s.onDone(function(){var e=o.players.indexOf(s);e>=0&&o.players.splice(e,1);var n=o._engine.playersByElement.get(t);if(n){var r=n.indexOf(s);r>=0&&n.splice(r,1)}}),this.players.push(s),c.push(s),s}if(!function(t,e){var n=Object.keys(t),r=Object.keys(e);if(n.length!=r.length)return!1;for(var o=0;o=0){for(var r=!1,o=n;o>=0;o--)if(this.driver.containsElement(this._namespaceList[o].hostElement,e)){this._namespaceList.splice(o+1,0,t),r=!0;break}r||this._namespaceList.splice(0,0,t)}else this._namespaceList.push(t);return this.namespacesByHostElement.set(e,t),t},t.prototype.register=function(t,e){var n=this._namespaceLookup[t];return n||(n=this.createNamespace(t,e)),n},t.prototype.registerTrigger=function(t,e,n){var r=this._namespaceLookup[t];r&&r.register(e,n)&&this.totalAnimations++},t.prototype.destroy=function(t,e){var n=this;if(t){var r=this._fetchNamespace(t);this.afterFlush(function(){n.namespacesByHostElement.delete(r.hostElement),delete n._namespaceLookup[t];var e=n._namespaceList.indexOf(r);e>=0&&n._namespaceList.splice(e,1)}),this.afterFlushAnimationsDone(function(){return r.destroy(e)})}},t.prototype._fetchNamespace=function(t){return this._namespaceLookup[t]},t.prototype.fetchNamespacesByElement=function(t){var e=new Set,n=this.statesByElement.get(t);if(n)for(var r=Object.keys(n),o=0;o=0;S--)this._namespaceList[S].drainQueuedTransitions(e).forEach(function(t){var e=t.player;C.push(e);var i=t.element;if(p&&n.driver.containsElement(p,i)){var l=w.get(i),h=m.get(i),d=n._buildInstruction(t,r,h,l);if(d.errors&&d.errors.length)x.push(d);else{if(t.isFallbackTransition)return e.onStart(function(){return Sl(i,d.fromStyles)}),e.onDestroy(function(){return xl(i,d.toStyles)}),void o.push(e);d.timelines.forEach(function(t){return t.stretchStartingKeyframe=!0}),r.append(i,d.timelines),s.push({instruction:d,player:e,element:i}),d.queriedElements.forEach(function(t){return nl(a,t,[]).push(e)}),d.preStyleProps.forEach(function(t,e){var n=Object.keys(t);if(n.length){var r=u.get(e);r||u.set(e,r=new Set),n.forEach(function(t){return r.add(t)})}}),d.postStyleProps.forEach(function(t,e){var n=Object.keys(t),r=c.get(e);r||c.set(e,r=new Set),n.forEach(function(t){return r.add(t)})})}}else e.destroy()});if(x.length){var O=[];x.forEach(function(t){O.push("@"+t.triggerName+" has failed due to:\n"),t.errors.forEach(function(t){return O.push("- "+t+"\n")})}),C.forEach(function(t){return t.destroy()}),this.reportError(O)}var T=new Map,k=new Map;s.forEach(function(t){var e=t.element;r.has(e)&&(k.set(e,e),n._beforeAnimationBuild(t.player.namespaceId,t.instruction,T))}),o.forEach(function(t){var e=t.element;n._getPreviousPlayers(e,!1,t.namespaceId,t.triggerName,null).forEach(function(t){nl(T,e,[]).push(t),t.destroy()})});var A=_.filter(function(t){return Du(t,u,c)}),P=new Map;Su(P,this.driver,v,c,di).forEach(function(t){Du(t,u,c)&&A.push(t)});var D=new Map;f.forEach(function(t,e){Su(D,n.driver,new Set(t),u,vi)}),A.forEach(function(t){var e=P.get(t),n=D.get(t);P.set(t,Object(l.a)({},e,n))});var R=[],I=[],N={};s.forEach(function(t){var e=t.element,s=t.player,a=t.instruction;if(r.has(e)){if(h.has(e))return s.onDestroy(function(){return xl(e,a.toStyles)}),void o.push(s);var l=N;if(k.size>1){for(var u=e,c=[];u=u.parentNode;){var p=k.get(u);if(p){l=p;break}c.push(u)}c.forEach(function(t){return k.set(t,l)})}var d=n._buildAnimation(s.namespaceId,a,T,i,D,P);if(s.setRealPlayer(d),l===N)R.push(s);else{var f=n.playersByElement.get(l);f&&f.length&&(s.parentPlayer=Wa(f)),o.push(s)}}else Sl(e,a.fromStyles),s.onDestroy(function(){return xl(e,a.toStyles)}),I.push(s),h.has(e)&&o.push(s)}),I.forEach(function(t){var e=i.get(t.element);if(e&&e.length){var n=Wa(e);t.setRealPlayer(n)}}),o.forEach(function(t){t.parentPlayer?t.syncPlayerEvents(t.parentPlayer):t.destroy()});for(var j=0;j<_.length;j++){var V,M=(V=_[j])[yu];if(Au(V,"ng-leave"),!M||!M.hasAnimation){var F=[];if(a.size){var L=a.get(V);L&&L.length&&F.push.apply(F,L);for(var B=this.driver.query(V,".ng-animating",!0),H=0;H0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,n):new _i},t}(),Eu=function(){function t(t,e,n){this.namespaceId=t,this.triggerName=e,this.element=n,this._player=new _i,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.queued=!0}return t.prototype.setRealPlayer=function(t){var e=this;this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(function(n){e._queuedCallbacks[n].forEach(function(e){return Ja(t,n,void 0,e)})}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.queued=!1)},t.prototype.getRealPlayer=function(){return this._player},t.prototype.syncPlayerEvents=function(t){var e=this,n=this._player;n.triggerCallback&&t.onStart(function(){return n.triggerCallback("start")}),t.onDone(function(){return e.finish()}),t.onDestroy(function(){return e.destroy()})},t.prototype._queueEvent=function(t,e){nl(this._queuedCallbacks,t,[]).push(e)},t.prototype.onDone=function(t){this.queued&&this._queueEvent("done",t),this._player.onDone(t)},t.prototype.onStart=function(t){this.queued&&this._queueEvent("start",t),this._player.onStart(t)},t.prototype.onDestroy=function(t){this.queued&&this._queueEvent("destroy",t),this._player.onDestroy(t)},t.prototype.init=function(){this._player.init()},t.prototype.hasStarted=function(){return!this.queued&&this._player.hasStarted()},t.prototype.play=function(){!this.queued&&this._player.play()},t.prototype.pause=function(){!this.queued&&this._player.pause()},t.prototype.restart=function(){!this.queued&&this._player.restart()},t.prototype.finish=function(){this._player.finish()},t.prototype.destroy=function(){this.destroyed=!0,this._player.destroy()},t.prototype.reset=function(){!this.queued&&this._player.reset()},t.prototype.setPosition=function(t){this.queued||this._player.setPosition(t)},t.prototype.getPosition=function(){return this.queued?0:this._player.getPosition()},Object.defineProperty(t.prototype,"totalTime",{get:function(){return this._player.totalTime},enumerable:!0,configurable:!0}),t.prototype.triggerCallback=function(t){var e=this._player;e.triggerCallback&&e.triggerCallback(t)},t}();function Cu(t){return t&&1===t.nodeType}function xu(t,e){var n=t.style.display;return t.style.display=null!=e?e:"none",n}function Su(t,e,n,r,o){var i=[];n.forEach(function(t){return i.push(xu(t))});var s=[];r.forEach(function(n,r){var i={};n.forEach(function(t){var n=i[t]=e.computeStyle(r,t,o);n&&0!=n.length||(r[yu]=mu,s.push(r))}),t.set(r,i)});var a=0;return n.forEach(function(t){return xu(t,i[a++])}),s}function Ou(t,e){var n=new Map;if(t.forEach(function(t){return n.set(t,[])}),0==e.length)return n;var r=new Set(e),o=new Map;return e.forEach(function(t){var e=function t(e){if(!e)return 1;var i=o.get(e);if(i)return i;var s=e.parentNode;return i=n.has(s)?s:r.has(s)?1:t(s),o.set(e,i),i}(t);1!==e&&n.get(e).push(t)}),n}var Tu="$$classes";function ku(t,e){if(t.classList)t.classList.add(e);else{var n=t[Tu];n||(n=t[Tu]={}),n[e]=!0}}function Au(t,e){if(t.classList)t.classList.remove(e);else{var n=t[Tu];n&&delete n[e]}}function Pu(t,e,n){Wa(n).onDone(function(){return t.processLeaveNode(e)})}function Du(t,e,n){var r=n.get(t);if(!r)return!1;var o=e.get(t);return o?r.forEach(function(t){return o.add(t)}):e.set(t,r),n.delete(t),!0}var Ru=function(){function t(t,e){var n=this;this._driver=t,this._triggerCache={},this.onRemovalComplete=function(t,e){},this._transitionEngine=new wu(t,e),this._timelineEngine=new pu(t,e),this._transitionEngine.onRemovalComplete=function(t,e){return n.onRemovalComplete(t,e)}}return t.prototype.registerTrigger=function(t,e,n,r,o){var i=t+"-"+r,s=this._triggerCache[i];if(!s){var a=[],l=Ll(this._driver,o,a);if(a.length)throw new Error('The animation trigger "'+r+'" has failed to build due to the following errors:\n - '+a.join("\n - "));s=function(t,e){return new uu(t,e)}(r,l),this._triggerCache[i]=s}this._transitionEngine.registerTrigger(e,r,s)},t.prototype.register=function(t,e){this._transitionEngine.register(t,e)},t.prototype.destroy=function(t,e){this._transitionEngine.destroy(t,e)},t.prototype.onInsert=function(t,e,n,r){this._transitionEngine.insertNode(t,e,n,r)},t.prototype.onRemove=function(t,e,n){this._transitionEngine.removeNode(t,e,n)},t.prototype.disableAnimations=function(t,e){this._transitionEngine.markElementAsDisabled(t,e)},t.prototype.process=function(t,e,n,r){if("@"==n.charAt(0)){var o=rl(n);this._timelineEngine.command(o[0],e,o[1],r)}else this._transitionEngine.trigger(t,e,n,r)},t.prototype.listen=function(t,e,n,r,o){if("@"==n.charAt(0)){var i=rl(n);return this._timelineEngine.listen(i[0],e,i[1],o)}return this._transitionEngine.listen(t,e,n,r,o)},t.prototype.flush=function(t){void 0===t&&(t=-1),this._transitionEngine.flush(t)},Object.defineProperty(t.prototype,"players",{get:function(){return this._transitionEngine.players.concat(this._timelineEngine.players)},enumerable:!0,configurable:!0}),t.prototype.whenRenderingDone=function(){return this._transitionEngine.whenRenderingDone()},t}(),Iu=function(){function t(t,e,n,r){void 0===r&&(r=[]);var o=this;this.element=t,this.keyframes=e,this.options=n,this.previousPlayers=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.previousStyles={},this.currentSnapshot={},this._duration=n.duration,this._delay=n.delay||0,this.time=this._duration+this._delay,(0===this._duration||0===this._delay)&&r.forEach(function(t){var e=t.currentSnapshot;Object.keys(e).forEach(function(t){return o.previousStyles[t]=e[t]})})}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.init=function(){this._buildPlayer(),this._preparePlayerBeforeStart()},t.prototype._buildPlayer=function(){var t=this;if(!this._initialized){this._initialized=!0;var e=this.keyframes.map(function(t){return Cl(t,!1)}),n=Object.keys(this.previousStyles);if(n.length&&e.length){var r=e[0],o=[];if(n.forEach(function(e){r.hasOwnProperty(e)||o.push(e),r[e]=t.previousStyles[e]}),o.length)for(var i=this,s=function(){var t=e[a];o.forEach(function(e){t[e]=Nu(i.element,e)})},a=1;a=0&&t1&&"number"==typeof t[t.length-1]&&(n=t.pop())):"number"==typeof l&&(n=t.pop()),null===a&&1===t.length&&t[0]instanceof r.a?t[0]:Object(s.a)(n)(new o.a(t,a))};var r=n("YaPU"),o=n("Veqx"),i=n("1Q68"),s=n("8D5t")},0:function(t,e,n){t.exports=n("x35b")},"1Q68":function(t,e,n){"use strict";e.a=function(t){return t&&"function"==typeof t.schedule}},"3a3m":function(t,e,n){"use strict";var r=n("TToO"),o=n("g5jc"),i=n("YaPU"),s=n("OVmG"),a=n("VwZZ");function l(){return function(t){return t.lift(new u(t))}}var u=function(){function t(t){this.connectable=t}return t.prototype.call=function(t,e){var n=this.connectable;n._refCount++;var r=new c(t,n),o=e.subscribe(r);return r.closed||(r.connection=n.connect()),o},t}(),c=function(t){function e(e,n){t.call(this,e),this.connectable=n}return Object(r.b)(e,t),e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._refCount;if(e<=0)this.connection=null;else if(t._refCount=e-1,e>1)this.connection=null;else{var n=this.connection,r=t._connection;this.connection=null,!r||n&&r!==n||r.unsubscribe()}}else this.connection=null},e}(s.a),h=function(t){function e(e,n){t.call(this),this.source=e,this.subjectFactory=n,this._refCount=0,this._isComplete=!1}return Object(r.b)(e,t),e.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},e.prototype.getSubject=function(){var t=this._subject;return t&&!t.isStopped||(this._subject=this.subjectFactory()),this._subject},e.prototype.connect=function(){var t=this._connection;return t||(this._isComplete=!1,(t=this._connection=new a.a).add(this.source.subscribe(new d(this.getSubject(),this))),t.closed?(this._connection=null,t=a.a.EMPTY):this._connection=t),t},e.prototype.refCount=function(){return l()(this)},e}(i.a).prototype,p={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:h._subscribe},_isComplete:{value:h._isComplete,writable:!0},getSubject:{value:h.getSubject},connect:{value:h.connect},refCount:{value:h.refCount}},d=function(t){function e(e,n){t.call(this,e),this.connectable=n}return Object(r.b)(e,t),e.prototype._error=function(e){this._unsubscribe(),t.prototype._error.call(this,e)},e.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),t.prototype._complete.call(this)},e.prototype._unsubscribe=function(){var t=this.connectable;if(t){this.connectable=null;var e=t._connection;t._refCount=0,t._subject=null,t._connection=null,e&&e.unsubscribe()}},e}(o.b);function f(){return new o.a}e.a=function(){return function(t){return l()((e=f,function(t){var n;n="function"==typeof e?e:function(){return e};var r=Object.create(t,p);return r.source=t,r.subjectFactory=n,r})(t));var e}}},"8D5t":function(t,e,n){"use strict";var r=n("Qnch");function o(t){return t}e.a=function(t){return void 0===t&&(t=Number.POSITIVE_INFINITY),Object(r.a)(o,null,t)}},AMGY:function(t,e,n){"use strict";(function(t){n.d(e,"a",function(){return i});var r="undefined"!=typeof window&&window,o="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,i=r||"undefined"!=typeof t&&t||o}).call(e,n("DuR2"))},BX3T:function(t,e,n){"use strict";n.d(e,"a",function(){return r});var r=Array.isArray||function(t){return t&&"number"==typeof t.length}},DuR2:function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},GK6M:function(t,e,n){"use strict";e.a=function(t){return r=t,i};var r,o=n("fKB6");function i(){try{return r.apply(this,arguments)}catch(t){return o.a.e=t,o.a}}},Jnfr:function(t,e){function n(t){return Promise.resolve().then(function(){throw new Error("Cannot find module '"+t+"'.")})}n.keys=function(){return[]},n.resolve=n,t.exports=n,n.id="Jnfr"},N4j0:function(t,e,n){"use strict";n.d(e,"a",function(){return r});var r=function(t){return t&&"number"==typeof t.length}},OVmG:function(t,e,n){"use strict";n.d(e,"a",function(){return l});var r=n("TToO"),o=n("/iUD"),i=n("VwZZ"),s=n("t7NR"),a=n("tLDX"),l=function(t){function e(n,r,o){switch(t.call(this),this.syncErrorValue=null,this.syncErrorThrown=!1,this.syncErrorThrowable=!1,this.isStopped=!1,arguments.length){case 0:this.destination=s.a;break;case 1:if(!n){this.destination=s.a;break}if("object"==typeof n){n instanceof e?(this.syncErrorThrowable=n.syncErrorThrowable,this.destination=n,this.destination.add(this)):(this.syncErrorThrowable=!0,this.destination=new u(this,n));break}default:this.syncErrorThrowable=!0,this.destination=new u(this,n,r,o)}}return Object(r.b)(e,t),e.prototype[a.a]=function(){return this},e.create=function(t,n,r){var o=new e(t,n,r);return o.syncErrorThrowable=!1,o},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this))},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){this.destination.error(t),this.unsubscribe()},e.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},e.prototype._unsubscribeAndRecycle=function(){var t=this._parent,e=this._parents;return this._parent=null,this._parents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parent=t,this._parents=e,this},e}(i.a),u=function(t){function e(e,n,r,i){var a;t.call(this),this._parentSubscriber=e;var l=this;Object(o.a)(n)?a=n:n&&(a=n.next,r=n.error,i=n.complete,n!==s.a&&(l=Object.create(n),Object(o.a)(l.unsubscribe)&&this.add(l.unsubscribe.bind(l)),l.unsubscribe=this.unsubscribe.bind(this))),this._context=l,this._next=a,this._error=r,this._complete=i}return Object(r.b)(e,t),e.prototype.next=function(t){if(!this.isStopped&&this._next){var e=this._parentSubscriber;e.syncErrorThrowable?this.__tryOrSetError(e,this._next,t)&&this.unsubscribe():this.__tryOrUnsub(this._next,t)}},e.prototype.error=function(t){if(!this.isStopped){var e=this._parentSubscriber;if(this._error)e.syncErrorThrowable?(this.__tryOrSetError(e,this._error,t),this.unsubscribe()):(this.__tryOrUnsub(this._error,t),this.unsubscribe());else{if(!e.syncErrorThrowable)throw this.unsubscribe(),t;e.syncErrorValue=t,e.syncErrorThrown=!0,this.unsubscribe()}}},e.prototype.complete=function(){var t=this;if(!this.isStopped){var e=this._parentSubscriber;if(this._complete){var n=function(){return t._complete.call(t._context)};e.syncErrorThrowable?(this.__tryOrSetError(e,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},e.prototype.__tryOrUnsub=function(t,e){try{t.call(this._context,e)}catch(t){throw this.unsubscribe(),t}},e.prototype.__tryOrSetError=function(t,e,n){try{e.call(this._context,n)}catch(e){return t.syncErrorValue=e,t.syncErrorThrown=!0,!0}return!1},e.prototype._unsubscribe=function(){var t=this._parentSubscriber;this._context=null,this._parentSubscriber=null,t.unsubscribe()},e}(l)},PIsA:function(t,e,n){"use strict";var r=n("AMGY"),o=n("N4j0"),i=n("cQXm"),s=n("dgOU"),a=n("YaPU"),l=n("etqZ"),u=n("TToO"),c=function(t){function e(e,n,r){t.call(this),this.parent=e,this.outerValue=n,this.outerIndex=r,this.index=0}return Object(u.b)(e,t),e.prototype._next=function(t){this.parent.notifyNext(this.outerValue,t,this.outerIndex,this.index++,this)},e.prototype._error=function(t){this.parent.notifyError(t,this),this.unsubscribe()},e.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},e}(n("OVmG").a),h=n("+CnV");e.a=function(t,e,n,u){var p=new c(t,n,u);if(p.closed)return null;if(e instanceof a.a)return e._isScalar?(p.next(e.value),p.complete(),null):(p.syncErrorThrowable=!0,e.subscribe(p));if(Object(o.a)(e)){for(var d=0,f=e.length;d0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(i.a)},Rf9G:function(t,e,n){"use strict";e.a=function(){return Object(r.a)()(this)};var r=n("3a3m")},TILf:function(t,e,n){"use strict";n.d(e,"a",function(){return o});var r=n("TToO"),o=function(t){function e(e,n){t.call(this),this.value=e,this.scheduler=n,this._isScalar=!0,n&&(this._isScalar=!1)}return Object(r.b)(e,t),e.create=function(t,n){return new e(t,n)},e.dispatch=function(t){var e=t.value,n=t.subscriber;t.done?n.complete():(n.next(e),n.closed||(t.done=!0,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.value,r=this.scheduler;if(r)return r.schedule(e.dispatch,0,{done:!1,value:n,subscriber:t});t.next(n),t.closed||t.complete()},e}(n("YaPU").a)},TToO:function(t,e,n){"use strict";e.b=function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)},n.d(e,"a",function(){return o});var r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},o=Object.assign||function(t){for(var e,n=1,r=arguments.length;n1?new e(t,r):1===o?new i.a(t[0],r):new s.a(r)},e.dispatch=function(t){var e=t.array,n=t.index,r=t.subscriber;n>=t.count?r.complete():(r.next(e[n]),r.closed||(t.index=n+1,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.array,r=n.length,o=this.scheduler;if(o)return o.schedule(e.dispatch,0,{array:n,index:0,count:r,subscriber:t});for(var i=0;i ");else if("object"==typeof e){var o=[];for(var i in e)if(e.hasOwnProperty(i)){var s=e[i];o.push(i+":"+("string"==typeof s?JSON.stringify(s):O(s)))}r="{"+o.join(", ")+"}"}return"StaticInjectorError"+(n?"("+n+")":"")+"["+r+"]: "+t.replace(H,"\n ")}function X(t,e){return new Error(q(t,e))}var G="ngDebugContext",Z="ngOriginalError",Q="ngErrorLogger";function K(t){return t[G]}function W(t){return t[Z]}function $(t){for(var e=[],n=1;n0)t._bootstrapComponents.forEach(function(t){return e.bootstrap(t)});else{if(!t.instance.ngDoBootstrap)throw new Error("The module "+O(t.instance.constructor)+' was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.');t.instance.ngDoBootstrap(e)}this._modules.push(t)},t.prototype.onDestroy=function(t){this._destroyListeners.push(t)},Object.defineProperty(t.prototype,"injector",{get:function(){return this._injector},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){if(this._destroyed)throw new Error("The platform has already been destroyed!");this._modules.slice().forEach(function(t){return t.destroy()}),this._destroyListeners.forEach(function(t){return t()}),this._destroyed=!0},Object.defineProperty(t.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!0,configurable:!0}),t}();function Kt(t,e){return Array.isArray(e)?e.reduce(Kt,t):Object(r.a)({},t,e)}var Wt=function(){function t(t,e,n,r,a,l){var u=this;this._zone=t,this._console=e,this._injector=n,this._exceptionHandler=r,this._componentFactoryResolver=a,this._initStatus=l,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._enforceNoNewChanges=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._enforceNoNewChanges=qt(),this._zone.onMicrotaskEmpty.subscribe({next:function(){u._zone.run(function(){u.tick()})}});var c=new o.a(function(t){u._stable=u._zone.isStable&&!u._zone.hasPendingMacrotasks&&!u._zone.hasPendingMicrotasks,u._zone.runOutsideAngular(function(){t.next(u._stable),t.complete()})}),h=new o.a(function(t){var e;u._zone.runOutsideAngular(function(){e=u._zone.onStable.subscribe(function(){At.assertNotInAngularZone(),S(function(){u._stable||u._zone.hasPendingMacrotasks||u._zone.hasPendingMicrotasks||(u._stable=!0,t.next(!0))})})});var n=u._zone.onUnstable.subscribe(function(){At.assertInAngularZone(),u._stable&&(u._stable=!1,u._zone.runOutsideAngular(function(){t.next(!1)}))});return function(){e.unsubscribe(),n.unsubscribe()}});this.isStable=Object(i.a)(c,s.a.call(h))}return t.prototype.bootstrap=function(t,e){var n,r=this;if(!this._initStatus.done)throw new Error("Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.");n=t instanceof ft?t:this._componentFactoryResolver.resolveComponentFactory(t),this.componentTypes.push(n.componentType);var o=n instanceof Et?null:this._injector.get(Ct),i=n.create(R.NULL,[],e||n.selector,o);i.onDestroy(function(){r._unloadComponent(i)});var s=i.injector.get(Vt,null);return s&&i.injector.get(Mt).registerApplication(i.location.nativeElement,s),this._loadComponent(i),qt()&&this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode."),i},t.prototype.tick=function(){var e=this;if(this._runningTick)throw new Error("ApplicationRef.tick is called recursively");var n=t._tickScope();try{this._runningTick=!0,this._views.forEach(function(t){return t.detectChanges()}),this._enforceNoNewChanges&&this._views.forEach(function(t){return t.checkNoChanges()})}catch(t){this._zone.runOutsideAngular(function(){return e._exceptionHandler.handleError(t)})}finally{this._runningTick=!1,Ot(n)}},t.prototype.attachView=function(t){var e=t;this._views.push(e),e.attachToAppRef(this)},t.prototype.detachView=function(t){var e=t;$t(this._views,e),e.detachFromAppRef()},t.prototype._loadComponent=function(t){this.attachView(t.hostView),this.tick(),this.components.push(t),this._injector.get(ut,[]).concat(this._bootstrapListeners).forEach(function(e){return e(t)})},t.prototype._unloadComponent=function(t){this.detachView(t.hostView),$t(this.components,t)},t.prototype.ngOnDestroy=function(){this._views.slice().forEach(function(t){return t.destroy()})},Object.defineProperty(t.prototype,"viewCount",{get:function(){return this._views.length},enumerable:!0,configurable:!0}),t._tickScope=Tt("ApplicationRef#tick()"),t}();function $t(t,e){var n=t.indexOf(e);n>-1&&t.splice(n,1)}var Jt=function(){},te=function(){var t={Important:1,DashCase:2};return t[t.Important]="Important",t[t.DashCase]="DashCase",t}(),ee=function(){},ne=function(t){this.nativeElement=t},re=function(){function t(){this.dirty=!0,this._results=[],this.changes=new kt,this.length=0}return t.prototype.map=function(t){return this._results.map(t)},t.prototype.filter=function(t){return this._results.filter(t)},t.prototype.find=function(t){return this._results.find(t)},t.prototype.reduce=function(t,e){return this._results.reduce(t,e)},t.prototype.forEach=function(t){this._results.forEach(t)},t.prototype.some=function(t){return this._results.some(t)},t.prototype.toArray=function(){return this._results.slice()},t.prototype[x()]=function(){return this._results[x()]()},t.prototype.toString=function(){return this._results.toString()},t.prototype.reset=function(t){this._results=function t(e){return e.reduce(function(e,n){var r=Array.isArray(n)?t(n):n;return e.concat(r)},[])}(t),this.dirty=!1,this.length=this._results.length,this.last=this._results[this.length-1],this.first=this._results[0]},t.prototype.notifyOnChanges=function(){this.changes.emit(this)},t.prototype.setDirty=function(){this.dirty=!0},t.prototype.destroy=function(){this.changes.complete(),this.changes.unsubscribe()},t}(),oe=function(){},ie=function(){},se=function(){},ae=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(r.b)(e,t),e}(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(r.b)(e,t),e}(se)),le=function(){function t(t,e,n){this._debugContext=n,this.nativeNode=t,e&&e instanceof ue?e.addChild(this):this.parent=null,this.listeners=[]}return Object.defineProperty(t.prototype,"injector",{get:function(){return this._debugContext.injector},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentInstance",{get:function(){return this._debugContext.component},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._debugContext.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"references",{get:function(){return this._debugContext.references},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"providerTokens",{get:function(){return this._debugContext.providerTokens},enumerable:!0,configurable:!0}),t}(),ue=function(t){function e(e,n,r){var o=t.call(this,e,n,r)||this;return o.properties={},o.attributes={},o.classes={},o.styles={},o.childNodes=[],o.nativeElement=e,o}return Object(r.b)(e,t),e.prototype.addChild=function(t){t&&(this.childNodes.push(t),t.parent=this)},e.prototype.removeChild=function(t){var e=this.childNodes.indexOf(t);-1!==e&&(t.parent=null,this.childNodes.splice(e,1))},e.prototype.insertChildrenAfter=function(t,e){var n,r=this,o=this.childNodes.indexOf(t);-1!==o&&((n=this.childNodes).splice.apply(n,[o+1,0].concat(e)),e.forEach(function(t){t.parent&&t.parent.removeChild(t),t.parent=r}))},e.prototype.insertBefore=function(t,e){var n=this.childNodes.indexOf(t);-1===n?this.addChild(e):(e.parent&&e.parent.removeChild(e),e.parent=this,this.childNodes.splice(n,0,e))},e.prototype.query=function(t){return this.queryAll(t)[0]||null},e.prototype.queryAll=function(t){var e=[];return ce(this,t,e),e},e.prototype.queryAllNodes=function(t){var e=[];return he(this,t,e),e},Object.defineProperty(e.prototype,"children",{get:function(){return this.childNodes.filter(function(t){return t instanceof e})},enumerable:!0,configurable:!0}),e.prototype.triggerEventHandler=function(t,e){this.listeners.forEach(function(n){n.name==t&&n.callback(e)})},e}(le);function ce(t,e,n){t.childNodes.forEach(function(t){t instanceof ue&&(e(t)&&n.push(t),ce(t,e,n))})}function he(t,e,n){t instanceof ue&&t.childNodes.forEach(function(t){e(t)&&n.push(t),t instanceof ue&&he(t,e,n)})}var pe=new Map;function de(t){return pe.get(t)||null}function fe(t){pe.set(t.nativeNode,t)}function me(t,e){var n=ge(t),r=ge(e);return n&&r?function(t,e,n){for(var r=t[x()](),o=e[x()]();;){var i=r.next(),s=o.next();if(i.done&&s.done)return!0;if(i.done||s.done)return!1;if(!n(i.value,s.value))return!1}}(t,e,me):!(n||!t||"object"!=typeof t&&"function"!=typeof t||r||!e||"object"!=typeof e&&"function"!=typeof e)||T(t,e)}var ye=function(){function t(t){this.wrapped=t}return t.wrap=function(e){return new t(e)},t.unwrap=function(e){return t.isWrapped(e)?e.wrapped:e},t.isWrapped=function(e){return e instanceof t},t}(),_e=function(){function t(t,e,n){this.previousValue=t,this.currentValue=e,this.firstChange=n}return t.prototype.isFirstChange=function(){return this.firstChange},t}();function ge(t){return!!ve(t)&&(Array.isArray(t)||!(t instanceof Map)&&x()in t)}function ve(t){return null!==t&&("function"==typeof t||"object"==typeof t)}var be=function(){function t(){}return t.prototype.supports=function(t){return ge(t)},t.prototype.create=function(t){return new Ee(t)},t}(),we=function(t,e){return e},Ee=function(){function t(t){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=t||we}return t.prototype.forEachItem=function(t){var e;for(e=this._itHead;null!==e;e=e._next)t(e)},t.prototype.forEachOperation=function(t){for(var e=this._itHead,n=this._removalsHead,r=0,o=null;e||n;){var i=!n||e&&e.currentIndex=n.length)&&(e=n.length-1),e<0)return null;var r=n[e];return r.viewContainerParent=null,Kn(n,e),Ke.dirtyParentQueries(r),Zn(r),r}function Gn(t,e,n){var r=e?yn(e,e.def.lastRenderRootNode):t.renderElement;Sn(n,2,n.renderer.parentNode(r),n.renderer.nextSibling(r),void 0)}function Zn(t){Sn(t,3,null,null,void 0)}function Qn(t,e,n){e>=t.length?t.push(n):t.splice(e,0,n)}function Kn(t,e){e>=t.length-1?t.pop():t.splice(e,1)}var Wn=new Object;function $n(t,e,n,r,o,i){return new Jn(t,e,n,r,o,i)}var Jn=function(t){function e(e,n,r,o,i,s){var a=t.call(this)||this;return a.selector=e,a.componentType=n,a._inputs=o,a._outputs=i,a.ngContentSelectors=s,a.viewDefFactory=r,a}return Object(r.b)(e,t),Object.defineProperty(e.prototype,"inputs",{get:function(){var t=[],e=this._inputs;for(var n in e)t.push({propName:n,templateName:e[n]});return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){var t=[];for(var e in this._outputs)t.push({propName:e,templateName:this._outputs[e]});return t},enumerable:!0,configurable:!0}),e.prototype.create=function(t,e,n,r){if(!r)throw new Error("ngModule should be provided");var o=xn(this.viewDefFactory),i=o.nodes[0].element.componentProvider.nodeIndex,s=Ke.createRootView(t,e||[],n,o,r,Wn),a=Ge(s,i).instance;return n&&s.renderer.setAttribute(Xe(s,0).renderElement,"ng-version",f.full),new tr(s,new or(s),a)},e}(ft),tr=function(t){function e(e,n,r){var o=t.call(this)||this;return o._view=e,o._viewRef=n,o._component=r,o._elDef=o._view.def.nodes[0],o.hostView=n,o.changeDetectorRef=n,o.instance=r,o}return Object(r.b)(e,t),Object.defineProperty(e.prototype,"location",{get:function(){return new ne(Xe(this._view,this._elDef.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"injector",{get:function(){return new lr(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"componentType",{get:function(){return this._component.constructor},enumerable:!0,configurable:!0}),e.prototype.destroy=function(){this._viewRef.destroy()},e.prototype.onDestroy=function(t){this._viewRef.onDestroy(t)},e}(function(){});function er(t,e,n){return new nr(t,e,n)}var nr=function(){function t(t,e,n){this._view=t,this._elDef=e,this._data=n,this._embeddedViews=[]}return Object.defineProperty(t.prototype,"element",{get:function(){return new ne(this._data.renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"injector",{get:function(){return new lr(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"parentInjector",{get:function(){for(var t=this._view,e=this._elDef.parent;!e&&t;)e=mn(t),t=t.parent;return t?new lr(t,e):new lr(this._view,null)},enumerable:!0,configurable:!0}),t.prototype.clear=function(){for(var t=this._embeddedViews.length-1;t>=0;t--){var e=Xn(this._data,t);Ke.destroyView(e)}},t.prototype.get=function(t){var e=this._embeddedViews[t];if(e){var n=new or(e);return n.attachToViewContainerRef(this),n}return null},Object.defineProperty(t.prototype,"length",{get:function(){return this._embeddedViews.length},enumerable:!0,configurable:!0}),t.prototype.createEmbeddedView=function(t,e,n){var r=t.createEmbeddedView(e||{});return this.insert(r,n),r},t.prototype.createComponent=function(t,e,n,r,o){var i=n||this.parentInjector;o||t instanceof Et||(o=i.get(Ct));var s=t.create(i,r,void 0,o);return this.insert(s.hostView,e),s},t.prototype.insert=function(t,e){if(t.destroyed)throw new Error("Cannot insert a destroyed View in a ViewContainer!");var n,r,o,i,s=t;return o=s._view,i=(n=this._data).viewContainer._embeddedViews,null!==(r=e)&&void 0!==r||(r=i.length),o.viewContainerParent=this._view,Qn(i,r,o),function(t,e){var n=fn(e);if(n&&n!==t&&!(16&e.state)){e.state|=16;var r=n.template._projectedViews;r||(r=n.template._projectedViews=[]),r.push(e),function(t,n){if(!(4&n.flags)){e.parent.def.nodeFlags|=4,n.flags|=4;for(var r=n.parent;r;)r.childFlags|=4,r=r.parent}}(0,e.parentNodeDef)}}(n,o),Ke.dirtyParentQueries(o),Gn(n,r>0?i[r-1]:null,o),s.attachToViewContainerRef(this),t},t.prototype.move=function(t,e){if(t.destroyed)throw new Error("Cannot move a destroyed View in a ViewContainer!");var n,r,o,i,s,a=this._embeddedViews.indexOf(t._view);return o=e,s=(i=(n=this._data).viewContainer._embeddedViews)[r=a],Kn(i,r),null==o&&(o=i.length),Qn(i,o,s),Ke.dirtyParentQueries(s),Zn(s),Gn(n,o>0?i[o-1]:null,s),t},t.prototype.indexOf=function(t){return this._embeddedViews.indexOf(t._view)},t.prototype.remove=function(t){var e=Xn(this._data,t);e&&Ke.destroyView(e)},t.prototype.detach=function(t){var e=Xn(this._data,t);return e?new or(e):null},t}();function rr(t){return new or(t)}var or=function(){function t(t){this._view=t,this._viewContainerRef=null,this._appRef=null}return Object.defineProperty(t.prototype,"rootNodes",{get:function(){return Sn(this._view,0,void 0,void 0,t=[]),t;var t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"context",{get:function(){return this._view.context},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"destroyed",{get:function(){return 0!=(128&this._view.state)},enumerable:!0,configurable:!0}),t.prototype.markForCheck=function(){hn(this._view)},t.prototype.detach=function(){this._view.state&=-5},t.prototype.detectChanges=function(){var t=this._view.root.rendererFactory;t.begin&&t.begin();try{Ke.checkAndUpdateView(this._view)}finally{t.end&&t.end()}},t.prototype.checkNoChanges=function(){Ke.checkNoChangesView(this._view)},t.prototype.reattach=function(){this._view.state|=4},t.prototype.onDestroy=function(t){this._view.disposables||(this._view.disposables=[]),this._view.disposables.push(t)},t.prototype.destroy=function(){this._appRef?this._appRef.detachView(this):this._viewContainerRef&&this._viewContainerRef.detach(this._viewContainerRef.indexOf(this)),Ke.destroyView(this._view)},t.prototype.detachFromAppRef=function(){this._appRef=null,Zn(this._view),Ke.dirtyParentQueries(this._view)},t.prototype.attachToAppRef=function(t){if(this._viewContainerRef)throw new Error("This view is already attached to a ViewContainer!");this._appRef=t},t.prototype.attachToViewContainerRef=function(t){if(this._appRef)throw new Error("This view is already attached directly to the ApplicationRef!");this._viewContainerRef=t},t}();function ir(t,e){return new sr(t,e)}var sr=function(t){function e(e,n){var r=t.call(this)||this;return r._parentView=e,r._def=n,r}return Object(r.b)(e,t),e.prototype.createEmbeddedView=function(t){return new or(Ke.createEmbeddedView(this._parentView,this._def,this._def.element.template,t))},Object.defineProperty(e.prototype,"elementRef",{get:function(){return new ne(Xe(this._parentView,this._def.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),e}(oe);function ar(t,e){return new lr(t,e)}var lr=function(){function t(t,e){this.view=t,this.elDef=e}return t.prototype.get=function(t,e){return void 0===e&&(e=R.THROW_IF_NOT_FOUND),Ke.resolveDep(this.view,this.elDef,!!this.elDef&&0!=(33554432&this.elDef.flags),{flags:0,token:t,tokenKey:nn(t)},e)},t}();function ur(t,e){var n=t.def.nodes[e];if(1&n.flags){var r=Xe(t,n.nodeIndex);return n.element.template?r.template:r.renderElement}if(2&n.flags)return qe(t,n.nodeIndex).renderText;if(20240&n.flags)return Ge(t,n.nodeIndex).instance;throw new Error("Illegal state: read nodeValue for node index "+e)}function cr(t){return new hr(t.renderer)}var hr=function(){function t(t){this.delegate=t}return t.prototype.selectRootElement=function(t){return this.delegate.selectRootElement(t)},t.prototype.createElement=function(t,e){var n=Dn(e),r=this.delegate.createElement(n[1],n[0]);return t&&this.delegate.appendChild(t,r),r},t.prototype.createViewRoot=function(t){return t},t.prototype.createTemplateAnchor=function(t){var e=this.delegate.createComment("");return t&&this.delegate.appendChild(t,e),e},t.prototype.createText=function(t,e){var n=this.delegate.createText(e);return t&&this.delegate.appendChild(t,n),n},t.prototype.projectNodes=function(t,e){for(var n=0;n0,e.provider.value,e.provider.deps);if(e.outputs.length)for(var r=0;r0,r=e.provider;switch(201347067&e.flags){case 512:return Ar(t,e.parent,n,r.value,r.deps);case 1024:return function(t,e,n,r,o){var i=o.length;switch(i){case 0:return r();case 1:return r(Dr(t,e,n,o[0]));case 2:return r(Dr(t,e,n,o[0]),Dr(t,e,n,o[1]));case 3:return r(Dr(t,e,n,o[0]),Dr(t,e,n,o[1]),Dr(t,e,n,o[2]));default:for(var s=Array(i),a=0;a0)u=m,Zr(m)||(c=m);else for(;u&&f===u.nodeIndex+u.childCount;){var g=u.parent;g&&(g.childFlags|=u.childFlags,g.childMatchedQueries|=u.childMatchedQueries),c=(u=g)&&Zr(u)?u.renderParent:u}}return{factory:null,nodeFlags:s,rootNodeFlags:a,nodeMatchedQueries:l,flags:t,nodes:e,updateDirectives:n||tn,updateRenderer:r||tn,handleEvent:function(t,n,r,o){return e[n].element.handleEvent(t,r,o)},bindingCount:o,outputCount:i,lastRenderRootNode:d}}function Zr(t){return 0!=(1&t.flags)&&null===t.element.name}function Qr(t,e,n){var r=e.element&&e.element.template;if(r){if(!r.lastRenderRootNode)throw new Error("Illegal State: Embedded templates without nodes are not allowed!");if(r.lastRenderRootNode&&16777216&r.lastRenderRootNode.flags)throw new Error("Illegal State: Last root node of a template can't have embedded views, at index "+e.nodeIndex+"!")}if(20224&e.flags&&0==(1&(t?t.flags:0)))throw new Error("Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index "+e.nodeIndex+"!");if(e.query){if(67108864&e.flags&&(!t||0==(16384&t.flags)))throw new Error("Illegal State: Content Query nodes need to be children of directives, at index "+e.nodeIndex+"!");if(134217728&e.flags&&t)throw new Error("Illegal State: View Query nodes have to be top level nodes, at index "+e.nodeIndex+"!")}if(e.childCount){var o=t?t.nodeIndex+t.childCount:n-1;if(e.nodeIndex<=o&&e.nodeIndex+e.childCount>o)throw new Error("Illegal State: childCount of node leads outside of parent, at index "+e.nodeIndex+"!")}}function Kr(t,e,n,r){var o=Jr(t.root,t.renderer,t,e,n);return to(o,t.component,r),eo(o),o}function Wr(t,e,n){var r=Jr(t,t.renderer,null,null,e);return to(r,n,n),eo(r),r}function $r(t,e,n,r){var o,i=e.element.componentRendererType;return o=i?t.root.rendererFactory.createRenderer(r,i):t.root.renderer,Jr(t.root,o,t,e.element.componentProvider,n)}function Jr(t,e,n,r,o){var i=new Array(o.nodes.length),s=o.outputCount?new Array(o.outputCount):null;return{def:o,parent:n,viewContainerParent:null,parentNodeDef:r,context:null,component:null,nodes:i,state:13,root:t,renderer:e,oldValues:new Array(o.bindingCount),disposables:s,initIndex:-1}}function to(t,e,n){t.component=e,t.context=n}function eo(t){var e;_n(t)&&(e=Xe(t.parent,t.parentNodeDef.parent.nodeIndex).renderElement);for(var n=t.def,r=t.nodes,o=0;o0&&Fn(t,e,0,n)&&(d=!0),p>1&&Fn(t,e,1,r)&&(d=!0),p>2&&Fn(t,e,2,o)&&(d=!0),p>3&&Fn(t,e,3,i)&&(d=!0),p>4&&Fn(t,e,4,s)&&(d=!0),p>5&&Fn(t,e,5,a)&&(d=!0),p>6&&Fn(t,e,6,l)&&(d=!0),p>7&&Fn(t,e,7,u)&&(d=!0),p>8&&Fn(t,e,8,c)&&(d=!0),p>9&&Fn(t,e,9,h)&&(d=!0),d}(t,e,n,r,o,i,s,a,l,u,c,h);case 2:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=!1,d=e.bindings,f=d.length;if(f>0&&un(t,e,0,n)&&(p=!0),f>1&&un(t,e,1,r)&&(p=!0),f>2&&un(t,e,2,o)&&(p=!0),f>3&&un(t,e,3,i)&&(p=!0),f>4&&un(t,e,4,s)&&(p=!0),f>5&&un(t,e,5,a)&&(p=!0),f>6&&un(t,e,6,l)&&(p=!0),f>7&&un(t,e,7,u)&&(p=!0),f>8&&un(t,e,8,c)&&(p=!0),f>9&&un(t,e,9,h)&&(p=!0),p){var m=e.text.prefix;f>0&&(m+=Xr(n,d[0])),f>1&&(m+=Xr(r,d[1])),f>2&&(m+=Xr(o,d[2])),f>3&&(m+=Xr(i,d[3])),f>4&&(m+=Xr(s,d[4])),f>5&&(m+=Xr(a,d[5])),f>6&&(m+=Xr(l,d[6])),f>7&&(m+=Xr(u,d[7])),f>8&&(m+=Xr(c,d[8])),f>9&&(m+=Xr(h,d[9]));var y=qe(t,e.nodeIndex).renderText;t.renderer.setValue(y,m)}return p}(t,e,n,r,o,i,s,a,l,u,c,h);case 16384:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=Ge(t,e.nodeIndex),d=p.instance,f=!1,m=void 0,y=e.bindings.length;return y>0&&ln(t,e,0,n)&&(f=!0,m=Rr(t,p,e,0,n,m)),y>1&&ln(t,e,1,r)&&(f=!0,m=Rr(t,p,e,1,r,m)),y>2&&ln(t,e,2,o)&&(f=!0,m=Rr(t,p,e,2,o,m)),y>3&&ln(t,e,3,i)&&(f=!0,m=Rr(t,p,e,3,i,m)),y>4&&ln(t,e,4,s)&&(f=!0,m=Rr(t,p,e,4,s,m)),y>5&&ln(t,e,5,a)&&(f=!0,m=Rr(t,p,e,5,a,m)),y>6&&ln(t,e,6,l)&&(f=!0,m=Rr(t,p,e,6,l,m)),y>7&&ln(t,e,7,u)&&(f=!0,m=Rr(t,p,e,7,u,m)),y>8&&ln(t,e,8,c)&&(f=!0,m=Rr(t,p,e,8,c,m)),y>9&&ln(t,e,9,h)&&(f=!0,m=Rr(t,p,e,9,h,m)),m&&d.ngOnChanges(m),65536&e.flags&&Ye(t,256,e.nodeIndex)&&d.ngOnInit(),262144&e.flags&&d.ngDoCheck(),f}(t,e,n,r,o,i,s,a,l,u,c,h);case 32:case 64:case 128:return function(t,e,n,r,o,i,s,a,l,u,c,h){var p=e.bindings,d=!1,f=p.length;if(f>0&&un(t,e,0,n)&&(d=!0),f>1&&un(t,e,1,r)&&(d=!0),f>2&&un(t,e,2,o)&&(d=!0),f>3&&un(t,e,3,i)&&(d=!0),f>4&&un(t,e,4,s)&&(d=!0),f>5&&un(t,e,5,a)&&(d=!0),f>6&&un(t,e,6,l)&&(d=!0),f>7&&un(t,e,7,u)&&(d=!0),f>8&&un(t,e,8,c)&&(d=!0),f>9&&un(t,e,9,h)&&(d=!0),d){var m=Ze(t,e.nodeIndex),y=void 0;switch(201347067&e.flags){case 32:y=new Array(p.length),f>0&&(y[0]=n),f>1&&(y[1]=r),f>2&&(y[2]=o),f>3&&(y[3]=i),f>4&&(y[4]=s),f>5&&(y[5]=a),f>6&&(y[6]=l),f>7&&(y[7]=u),f>8&&(y[8]=c),f>9&&(y[9]=h);break;case 64:y={},f>0&&(y[p[0].name]=n),f>1&&(y[p[1].name]=r),f>2&&(y[p[2].name]=o),f>3&&(y[p[3].name]=i),f>4&&(y[p[4].name]=s),f>5&&(y[p[5].name]=a),f>6&&(y[p[6].name]=l),f>7&&(y[p[7].name]=u),f>8&&(y[p[8].name]=c),f>9&&(y[p[9].name]=h);break;case 128:var _=n;switch(f){case 1:y=_.transform(n);break;case 2:y=_.transform(r);break;case 3:y=_.transform(r,o);break;case 4:y=_.transform(r,o,i);break;case 5:y=_.transform(r,o,i,s);break;case 6:y=_.transform(r,o,i,s,a);break;case 7:y=_.transform(r,o,i,s,a,l);break;case 8:y=_.transform(r,o,i,s,a,l,u);break;case 9:y=_.transform(r,o,i,s,a,l,u,c);break;case 10:y=_.transform(r,o,i,s,a,l,u,c,h)}}m.value=y}return d}(t,e,n,r,o,i,s,a,l,u,c,h);default:throw"unreachable"}}(t,e,r,o,i,s,a,l,u,c,h,p):function(t,e,n){switch(201347067&e.flags){case 1:return function(t,e,n){for(var r=!1,o=0;o0&&cn(t,e,0,n),p>1&&cn(t,e,1,r),p>2&&cn(t,e,2,o),p>3&&cn(t,e,3,i),p>4&&cn(t,e,4,s),p>5&&cn(t,e,5,a),p>6&&cn(t,e,6,l),p>7&&cn(t,e,7,u),p>8&&cn(t,e,8,c),p>9&&cn(t,e,9,h)}(t,e,r,o,i,s,a,l,u,c,h,p):function(t,e,n){for(var r=0;r0){var r=t.slice(0,n),o=r.toLowerCase(),i=t.slice(n+1).trim();e.maybeSetNormalizedName(r,o),e.headers.has(o)?e.headers.get(o).push(i):e.headers.set(o,[i])}})}:function(){e.headers=new Map,Object.keys(t).forEach(function(n){var r=t[n],o=n.toLowerCase();"string"==typeof r&&(r=[r]),r.length>0&&(e.headers.set(o,r),e.maybeSetNormalizedName(n,o))})}:this.headers=new Map}return t.prototype.has=function(t){return this.init(),this.headers.has(t.toLowerCase())},t.prototype.get=function(t){this.init();var e=this.headers.get(t.toLowerCase());return e&&e.length>0?e[0]:null},t.prototype.keys=function(){return this.init(),Array.from(this.normalizedNames.values())},t.prototype.getAll=function(t){return this.init(),this.headers.get(t.toLowerCase())||null},t.prototype.append=function(t,e){return this.clone({name:t,value:e,op:"a"})},t.prototype.set=function(t,e){return this.clone({name:t,value:e,op:"s"})},t.prototype.delete=function(t,e){return this.clone({name:t,value:e,op:"d"})},t.prototype.maybeSetNormalizedName=function(t,e){this.normalizedNames.has(e)||this.normalizedNames.set(e,t)},t.prototype.init=function(){var e=this;this.lazyInit&&(this.lazyInit instanceof t?this.copyFrom(this.lazyInit):this.lazyInit(),this.lazyInit=null,this.lazyUpdate&&(this.lazyUpdate.forEach(function(t){return e.applyUpdate(t)}),this.lazyUpdate=null))},t.prototype.copyFrom=function(t){var e=this;t.init(),Array.from(t.headers.keys()).forEach(function(n){e.headers.set(n,t.headers.get(n)),e.normalizedNames.set(n,t.normalizedNames.get(n))})},t.prototype.clone=function(e){var n=new t;return n.lazyInit=this.lazyInit&&this.lazyInit instanceof t?this.lazyInit:this,n.lazyUpdate=(this.lazyUpdate||[]).concat([e]),n},t.prototype.applyUpdate=function(t){var e=t.name.toLowerCase();switch(t.op){case"a":case"s":var n=t.value;if("string"==typeof n&&(n=[n]),0===n.length)return;this.maybeSetNormalizedName(t.name,e);var r=("a"===t.op?this.headers.get(e):void 0)||[];r.push.apply(r,n),this.headers.set(e,r);break;case"d":var o=t.value;if(o){var i=this.headers.get(e);if(!i)return;0===(i=i.filter(function(t){return-1===o.indexOf(t)})).length?(this.headers.delete(e),this.normalizedNames.delete(e)):this.headers.set(e,i)}else this.headers.delete(e),this.normalizedNames.delete(e)}},t.prototype.forEach=function(t){var e=this;this.init(),Array.from(this.normalizedNames.keys()).forEach(function(n){return t(e.normalizedNames.get(n),e.headers.get(n))})},t}(),L=function(){function t(){}return t.prototype.encodeKey=function(t){return B(t)},t.prototype.encodeValue=function(t){return B(t)},t.prototype.decodeKey=function(t){return decodeURIComponent(t)},t.prototype.decodeValue=function(t){return decodeURIComponent(t)},t}();function B(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/gi,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%2B/gi,"+").replace(/%3D/gi,"=").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}var H=function(){function t(t){void 0===t&&(t={});var e,n,r,o=this;if(this.updates=null,this.cloneFrom=null,this.encoder=t.encoder||new L,t.fromString){if(t.fromObject)throw new Error("Cannot specify both fromString and fromObject.");this.map=(e=t.fromString,n=this.encoder,r=new Map,e.length>0&&e.split("&").forEach(function(t){var e=t.indexOf("="),o=-1==e?[n.decodeKey(t),""]:[n.decodeKey(t.slice(0,e)),n.decodeValue(t.slice(e+1))],i=o[0],s=o[1],a=r.get(i)||[];a.push(s),r.set(i,a)}),r)}else t.fromObject?(this.map=new Map,Object.keys(t.fromObject).forEach(function(e){var n=t.fromObject[e];o.map.set(e,Array.isArray(n)?n:[n])})):this.map=null}return t.prototype.has=function(t){return this.init(),this.map.has(t)},t.prototype.get=function(t){this.init();var e=this.map.get(t);return e?e[0]:null},t.prototype.getAll=function(t){return this.init(),this.map.get(t)||null},t.prototype.keys=function(){return this.init(),Array.from(this.map.keys())},t.prototype.append=function(t,e){return this.clone({param:t,value:e,op:"a"})},t.prototype.set=function(t,e){return this.clone({param:t,value:e,op:"s"})},t.prototype.delete=function(t,e){return this.clone({param:t,value:e,op:"d"})},t.prototype.toString=function(){var t=this;return this.init(),this.keys().map(function(e){var n=t.encoder.encodeKey(e);return t.map.get(e).map(function(e){return n+"="+t.encoder.encodeValue(e)}).join("&")}).join("&")},t.prototype.clone=function(e){var n=new t({encoder:this.encoder});return n.cloneFrom=this.cloneFrom||this,n.updates=(this.updates||[]).concat([e]),n},t.prototype.init=function(){var t=this;null===this.map&&(this.map=new Map),null!==this.cloneFrom&&(this.cloneFrom.init(),this.cloneFrom.keys().forEach(function(e){return t.map.set(e,t.cloneFrom.map.get(e))}),this.updates.forEach(function(e){switch(e.op){case"a":case"s":var n=("a"===e.op?t.map.get(e.param):void 0)||[];n.push(e.value),t.map.set(e.param,n);break;case"d":if(void 0===e.value){t.map.delete(e.param);break}var r=t.map.get(e.param)||[],o=r.indexOf(e.value);-1!==o&&r.splice(o,1),r.length>0?t.map.set(e.param,r):t.map.delete(e.param)}}),this.cloneFrom=null)},t}();function z(t){return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer}function U(t){return"undefined"!=typeof Blob&&t instanceof Blob}function Y(t){return"undefined"!=typeof FormData&&t instanceof FormData}var q=function(){function t(t,e,n,r){var o;if(this.url=e,this.body=null,this.reportProgress=!1,this.withCredentials=!1,this.responseType="json",this.method=t.toUpperCase(),function(t){switch(t){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"JSONP":return!1;default:return!0}}(this.method)||r?(this.body=void 0!==n?n:null,o=r):o=n,o&&(this.reportProgress=!!o.reportProgress,this.withCredentials=!!o.withCredentials,o.responseType&&(this.responseType=o.responseType),o.headers&&(this.headers=o.headers),o.params&&(this.params=o.params)),this.headers||(this.headers=new F),this.params){var i=this.params.toString();if(0===i.length)this.urlWithParams=e;else{var s=e.indexOf("?");this.urlWithParams=e+(-1===s?"?":s=200&&this.status<300}}(),Z=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;return n.type=X.ResponseHeader,n}return Object(c.b)(e,t),e.prototype.clone=function(t){return void 0===t&&(t={}),new e({headers:t.headers||this.headers,status:void 0!==t.status?t.status:this.status,statusText:t.statusText||this.statusText,url:t.url||this.url||void 0})},e}(G),Q=function(t){function e(e){void 0===e&&(e={});var n=t.call(this,e)||this;return n.type=X.Response,n.body=void 0!==e.body?e.body:null,n}return Object(c.b)(e,t),e.prototype.clone=function(t){return void 0===t&&(t={}),new e({body:void 0!==t.body?t.body:this.body,headers:t.headers||this.headers,status:void 0!==t.status?t.status:this.status,statusText:t.statusText||this.statusText,url:t.url||this.url||void 0})},e}(G),K=function(t){function e(e){var n=t.call(this,e,0,"Unknown Error")||this;return n.name="HttpErrorResponse",n.ok=!1,n.message=n.status>=200&&n.status<300?"Http failure during parsing for "+(e.url||"(unknown url)"):"Http failure response for "+(e.url||"(unknown url)")+": "+e.status+" "+e.statusText,n.error=e.error||null,n}return Object(c.b)(e,t),e}(G);function W(t,e){return{body:e,headers:t.headers,observe:t.observe,params:t.params,reportProgress:t.reportProgress,responseType:t.responseType,withCredentials:t.withCredentials}}var $=function(){function t(t){this.handler=t}return t.prototype.request=function(t,e,n){var r,o=this;if(void 0===n&&(n={}),t instanceof q)r=t;else{var i;i=n.headers instanceof F?n.headers:new F(n.headers);var s=void 0;n.params&&(s=n.params instanceof H?n.params:new H({fromObject:n.params})),r=new q(t,e,void 0!==n.body?n.body:null,{headers:i,params:s,reportProgress:n.reportProgress,responseType:n.responseType||"json",withCredentials:n.withCredentials})}var a=(function(t,e){return function(t,e){return Object(u.a)(t,e,1)}(t,e)(this)}).call(l(r),function(t){return o.handler.handle(t)});if(t instanceof q||"events"===n.observe)return a;var c=(function(t,e){return p(t,e)(this)}).call(a,function(t){return t instanceof Q});switch(n.observe||"body"){case"body":switch(r.responseType){case"arraybuffer":return _.call(c,function(t){if(null!==t.body&&!(t.body instanceof ArrayBuffer))throw new Error("Response is not an ArrayBuffer.");return t.body});case"blob":return _.call(c,function(t){if(null!==t.body&&!(t.body instanceof Blob))throw new Error("Response is not a Blob.");return t.body});case"text":return _.call(c,function(t){if(null!==t.body&&"string"!=typeof t.body)throw new Error("Response is not a string.");return t.body});case"json":default:return _.call(c,function(t){return t.body})}case"response":return c;default:throw new Error("Unreachable: unhandled observe type "+n.observe+"}")}},t.prototype.delete=function(t,e){return void 0===e&&(e={}),this.request("DELETE",t,e)},t.prototype.get=function(t,e){return void 0===e&&(e={}),this.request("GET",t,e)},t.prototype.head=function(t,e){return void 0===e&&(e={}),this.request("HEAD",t,e)},t.prototype.jsonp=function(t,e){return this.request("JSONP",t,{params:(new H).append(e,"JSONP_CALLBACK"),observe:"body",responseType:"json"})},t.prototype.options=function(t,e){return void 0===e&&(e={}),this.request("OPTIONS",t,e)},t.prototype.patch=function(t,e,n){return void 0===n&&(n={}),this.request("PATCH",t,W(n,e))},t.prototype.post=function(t,e,n){return void 0===n&&(n={}),this.request("POST",t,W(n,e))},t.prototype.put=function(t,e,n){return void 0===n&&(n={}),this.request("PUT",t,W(n,e))},t}(),J=function(){function t(t,e){this.next=t,this.interceptor=e}return t.prototype.handle=function(t){return this.interceptor.intercept(t,this.next)},t}(),tt=new o.n("HTTP_INTERCEPTORS"),et=function(){function t(){}return t.prototype.intercept=function(t,e){return e.handle(t)},t}(),nt=/^\)\]\}',?\n/,rt=function(){},ot=function(){function t(){}return t.prototype.build=function(){return new XMLHttpRequest},t}(),it=function(){function t(t){this.xhrFactory=t}return t.prototype.handle=function(t){var e=this;if("JSONP"===t.method)throw new Error("Attempted to construct Jsonp request without JsonpClientModule installed.");return new j.a(function(n){var r=e.xhrFactory.build();if(r.open(t.method,t.urlWithParams),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach(function(t,e){return r.setRequestHeader(t,e.join(","))}),t.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),!t.headers.has("Content-Type")){var o=t.detectContentTypeHeader();null!==o&&r.setRequestHeader("Content-Type",o)}if(t.responseType){var i=t.responseType.toLowerCase();r.responseType="json"!==i?i:"text"}var s=t.serializeBody(),a=null,l=function(){if(null!==a)return a;var e=1223===r.status?204:r.status,n=r.statusText||"OK",o=new F(r.getAllResponseHeaders()),i=function(t){return"responseURL"in t&&t.responseURL?t.responseURL:/^X-Request-URL:/m.test(t.getAllResponseHeaders())?t.getResponseHeader("X-Request-URL"):null}(r)||t.url;return a=new Z({headers:o,status:e,statusText:n,url:i})},u=function(){var e=l(),o=e.headers,i=e.status,s=e.statusText,a=e.url,u=null;204!==i&&(u="undefined"==typeof r.response?r.responseText:r.response),0===i&&(i=u?200:0);var c=i>=200&&i<300;if("json"===t.responseType&&"string"==typeof u){var h=u;u=u.replace(nt,"");try{u=""!==u?JSON.parse(u):null}catch(t){u=h,c&&(c=!1,u={error:t,text:u})}}c?(n.next(new Q({body:u,headers:o,status:i,statusText:s,url:a||void 0})),n.complete()):n.error(new K({error:u,headers:o,status:i,statusText:s,url:a||void 0}))},c=function(t){var e=new K({error:t,status:r.status||0,statusText:r.statusText||"Unknown Error"});n.error(e)},h=!1,p=function(e){h||(n.next(l()),h=!0);var o={type:X.DownloadProgress,loaded:e.loaded};e.lengthComputable&&(o.total=e.total),"text"===t.responseType&&r.responseText&&(o.partialText=r.responseText),n.next(o)},d=function(t){var e={type:X.UploadProgress,loaded:t.loaded};t.lengthComputable&&(e.total=t.total),n.next(e)};return r.addEventListener("load",u),r.addEventListener("error",c),t.reportProgress&&(r.addEventListener("progress",p),null!==s&&r.upload&&r.upload.addEventListener("progress",d)),r.send(s),n.next({type:X.Sent}),function(){r.removeEventListener("error",c),r.removeEventListener("load",u),t.reportProgress&&(r.removeEventListener("progress",p),null!==s&&r.upload&&r.upload.removeEventListener("progress",d)),r.abort()}})},t}(),st=new o.n("XSRF_COOKIE_NAME"),at=new o.n("XSRF_HEADER_NAME"),lt=function(){},ut=function(){function t(t,e,n){this.doc=t,this.platform=e,this.cookieName=n,this.lastCookieString="",this.lastToken=null,this.parseCount=0}return t.prototype.getToken=function(){if("server"===this.platform)return null;var t=this.doc.cookie||"";return t!==this.lastCookieString&&(this.parseCount++,this.lastToken=O(t,this.cookieName),this.lastCookieString=t),this.lastToken},t}(),ct=function(){function t(t,e){this.tokenService=t,this.headerName=e}return t.prototype.intercept=function(t,e){var n=t.url.toLowerCase();if("GET"===t.method||"HEAD"===t.method||n.startsWith("http://")||n.startsWith("https://"))return e.handle(t);var r=this.tokenService.getToken();return null===r||t.headers.has(this.headerName)||(t=t.clone({headers:t.headers.set(this.headerName,r)})),e.handle(t)},t}(),ht=function(){function t(t,e){this.backend=t,this.injector=e,this.chain=null}return t.prototype.handle=function(t){if(null===this.chain){var e=this.injector.get(tt,[]);this.chain=e.reduceRight(function(t,e){return new J(t,e)},this.backend)}return this.chain.handle(t)},t}(),pt=function(){function t(){}return t.disable=function(){return{ngModule:t,providers:[{provide:ct,useClass:et}]}},t.withOptions=function(e){return void 0===e&&(e={}),{ngModule:t,providers:[e.cookieName?{provide:st,useValue:e.cookieName}:[],e.headerName?{provide:at,useValue:e.headerName}:[]]}},t}(),dt=function(){};j.a.prototype.map=_;var ft=function(){function t(t){this.http=t}return t.prototype.setSecurityHeaders=function(e){t.securityHeaders=e},t.prototype.getTorrentData=function(){return this.http.get("http://"+location.hostname+":8880/ktorrentdata")},t.prototype.getTorrents=function(){return this.getTorrentData().map(function(t){return t.torrents.map(function(t){return s.fromJson(t)})})},t.prototype.startTorrent=function(e){this.http.post("http://"+location.host+"/ktorrentaction",{type:"start",hash:e},{headers:t.securityHeaders}).subscribe()},t.prototype.stopTorrent=function(e){this.http.post("http://"+location.host+"/ktorrentaction",{type:"stop",hash:e},{headers:t.securityHeaders}).subscribe()},t.prototype.removeTorrent=function(e){this.http.post("http://"+location.host+"/ktorrentaction",{type:"remove",hash:e},{headers:t.securityHeaders}).subscribe()},t.prototype.startFromMagnetLink=function(e){this.http.post("http://"+location.host+"/ktorrentaction",{type:"magnet",magnet:e},{headers:t.securityHeaders}).subscribe()},t}(),mt=new o.n("cdk-dir-doc"),yt=function(){return function(t){this.value="ltr",this.change=new o.l,t&&(this.value=(t.body?t.body.dir:null)||(t.documentElement?t.documentElement.dir:null)||"ltr")}}(),_t=function(){};function gt(t){return null!=t&&""+t!="false"}var vt=n("g5jc"),bt=null;function wt(){return bt}var Et,Ct={class:"className",innerHtml:"innerHTML",readonly:"readOnly",tabindex:"tabIndex"},xt={"\b":"Backspace","\t":"Tab","\x7f":"Delete","\x1b":"Escape",Del:"Delete",Esc:"Escape",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Menu:"ContextMenu",Scroll:"ScrollLock",Win:"OS"},St={A:"1",B:"2",C:"3",D:"4",E:"5",F:"6",G:"7",H:"8",I:"9",J:"*",K:"+",M:"-",N:".",O:"/","`":"0","\x90":"NumLock"};o.Z.Node&&(Et=o.Z.Node.prototype.contains||function(t){return!!(16&this.compareDocumentPosition(t))});var Tt,Ot=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e.prototype.parse=function(t){throw new Error("parse not implemented")},e.makeCurrent=function(){var t;t=new e,bt||(bt=t)},e.prototype.hasProperty=function(t,e){return e in t},e.prototype.setProperty=function(t,e,n){t[e]=n},e.prototype.getProperty=function(t,e){return t[e]},e.prototype.invoke=function(t,e,n){var r;(r=t)[e].apply(r,n)},e.prototype.logError=function(t){window.console&&(console.error?console.error(t):console.log(t))},e.prototype.log=function(t){window.console&&window.console.log&&window.console.log(t)},e.prototype.logGroup=function(t){window.console&&window.console.group&&window.console.group(t)},e.prototype.logGroupEnd=function(){window.console&&window.console.groupEnd&&window.console.groupEnd()},Object.defineProperty(e.prototype,"attrToPropMap",{get:function(){return Ct},enumerable:!0,configurable:!0}),e.prototype.contains=function(t,e){return Et.call(t,e)},e.prototype.querySelector=function(t,e){return t.querySelector(e)},e.prototype.querySelectorAll=function(t,e){return t.querySelectorAll(e)},e.prototype.on=function(t,e,n){t.addEventListener(e,n,!1)},e.prototype.onAndCancel=function(t,e,n){return t.addEventListener(e,n,!1),function(){t.removeEventListener(e,n,!1)}},e.prototype.dispatchEvent=function(t,e){t.dispatchEvent(e)},e.prototype.createMouseEvent=function(t){var e=this.getDefaultDocument().createEvent("MouseEvent");return e.initEvent(t,!0,!0),e},e.prototype.createEvent=function(t){var e=this.getDefaultDocument().createEvent("Event");return e.initEvent(t,!0,!0),e},e.prototype.preventDefault=function(t){t.preventDefault(),t.returnValue=!1},e.prototype.isPrevented=function(t){return t.defaultPrevented||null!=t.returnValue&&!t.returnValue},e.prototype.getInnerHTML=function(t){return t.innerHTML},e.prototype.getTemplateContent=function(t){return"content"in t&&this.isTemplateElement(t)?t.content:null},e.prototype.getOuterHTML=function(t){return t.outerHTML},e.prototype.nodeName=function(t){return t.nodeName},e.prototype.nodeValue=function(t){return t.nodeValue},e.prototype.type=function(t){return t.type},e.prototype.content=function(t){return this.hasProperty(t,"content")?t.content:t},e.prototype.firstChild=function(t){return t.firstChild},e.prototype.nextSibling=function(t){return t.nextSibling},e.prototype.parentElement=function(t){return t.parentNode},e.prototype.childNodes=function(t){return t.childNodes},e.prototype.childNodesAsList=function(t){for(var e=t.childNodes,n=new Array(e.length),r=0;r0},e.prototype.tagName=function(t){return t.tagName},e.prototype.attributeMap=function(t){for(var e=new Map,n=t.attributes,r=0;r0;a||(a=t[s]=[]);var u=ue(e)?Zone.root:Zone.current;if(0===a.length)a.push({zone:u,handler:i});else{for(var c=!1,h=0;h-1},e}(zt),ye=["alt","control","meta","shift"],_e={alt:function(t){return t.altKey},control:function(t){return t.ctrlKey},meta:function(t){return t.metaKey},shift:function(t){return t.shiftKey}},ge=function(t){function e(e){return t.call(this,e)||this}return Object(c.b)(e,t),e.prototype.supports=function(t){return null!=e.parseEventName(t)},e.prototype.addEventListener=function(t,n,r){var o=e.parseEventName(n),i=e.eventCallback(o.fullKey,r,this.manager.getZone());return this.manager.getZone().runOutsideAngular(function(){return wt().onAndCancel(t,o.domEventName,i)})},e.parseEventName=function(t){var n=t.toLowerCase().split("."),r=n.shift();if(0===n.length||"keydown"!==r&&"keyup"!==r)return null;var o=e._normalizeKey(n.pop()),i="";if(ye.forEach(function(t){var e=n.indexOf(t);e>-1&&(n.splice(e,1),i+=t+".")}),i+=o,0!=n.length||0===o.length)return null;var s={};return s.domEventName=r,s.fullKey=i,s},e.getEventFullKey=function(t){var e="",n=wt().getEventKey(t);return" "===(n=n.toLowerCase())?n="space":"."===n&&(n="dot"),ye.forEach(function(r){r!=n&&(0,_e[r])(t)&&(e+=r+".")}),e+=n},e.eventCallback=function(t,n,r){return function(o){e.getEventFullKey(o)===t&&r.runGuarded(function(){return n(o)})}},e._normalizeKey=function(t){switch(t){case"esc":return"escape";default:return t}},e}(zt),ve=function(){function t(t,e){this.defaultDoc=t,this.DOM=e;var n=this.DOM.createHtmlDocument();if(this.inertBodyElement=n.body,null==this.inertBodyElement){var r=this.DOM.createElement("html",n);this.inertBodyElement=this.DOM.createElement("body",n),this.DOM.appendChild(r,this.inertBodyElement),this.DOM.appendChild(n,r)}this.DOM.setInnerHTML(this.inertBodyElement,''),!this.inertBodyElement.querySelector||this.inertBodyElement.querySelector("svg")?(this.DOM.setInnerHTML(this.inertBodyElement,'

'),this.getInertBodyElement=this.inertBodyElement.querySelector&&this.inertBodyElement.querySelector("svg img")&&function(){try{return!!window.DOMParser}catch(t){return!1}}()?this.getInertBodyElement_DOMParser:this.getInertBodyElement_InertDocument):this.getInertBodyElement=this.getInertBodyElement_XHR}return t.prototype.getInertBodyElement_XHR=function(t){t=""+t+"";try{t=encodeURI(t)}catch(t){return null}var e=new XMLHttpRequest;e.responseType="document",e.open("GET","data:text/html;charset=utf-8,"+t,!1),e.send(null);var n=e.response.body;return n.removeChild(n.firstChild),n},t.prototype.getInertBodyElement_DOMParser=function(t){t=""+t+"";try{var e=(new window.DOMParser).parseFromString(t,"text/html").body;return e.removeChild(e.firstChild),e}catch(t){return null}},t.prototype.getInertBodyElement_InertDocument=function(t){var e=this.DOM.createElement("template");return"content"in e?(this.DOM.setInnerHTML(e,t),e):(this.DOM.setInnerHTML(this.inertBodyElement,t),this.defaultDoc.documentMode&&this.stripCustomNsAttrs(this.inertBodyElement),this.inertBodyElement)},t.prototype.stripCustomNsAttrs=function(t){var e=this;this.DOM.attributeMap(t).forEach(function(n,r){"xmlns:ns1"!==r&&0!==r.indexOf("ns1:")||e.DOM.removeAttribute(t,r)});for(var n=0,r=this.DOM.childNodesAsList(t);n")):this.sanitizedSomething=!0},t.prototype.endElement=function(t){var e=this.DOM.nodeName(t).toLowerCase();Pe.hasOwnProperty(e)&&!Te.hasOwnProperty(e)&&(this.buf.push(""))},t.prototype.chars=function(t){this.buf.push(Me(t))},t.prototype.checkClobberedElement=function(t,e){if(e&&this.DOM.contains(t,e))throw new Error("Failed to sanitize html because the element is clobbered: "+this.DOM.getOuterHTML(t));return e},t}(),je=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,Ve=/([^\#-~ |!])/g;function Me(t){return t.replace(/&/g,"&").replace(je,function(t){return"&#"+(1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320)+65536)+";"}).replace(Ve,function(t){return"&#"+t.charCodeAt(0)+";"}).replace(//g,">")}var Fe=new RegExp("^([-,.\"'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?|(?:repeating-)?(?:linear|radial)-gradient|(?:calc|attr))\\([-0-9.%, #a-zA-Z]+\\))$","g"),Le=/^url\(([^)]+)\)$/,Be=function(){},He=function(t){function e(e){var n=t.call(this)||this;return n._doc=e,n}return Object(c.b)(e,t),e.prototype.sanitize=function(t,e){if(null==e)return null;switch(t){case o.C.NONE:return e;case o.C.HTML:return e instanceof Ue?e.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(e,"HTML"),function(t,e){var n=wt(),r=null;try{Se=Se||new ve(t,n);var i=e?String(e):"";r=Se.getInertBodyElement(i);var s=5,a=i;do{if(0===s)throw new Error("Failed to sanitize html because the input is unstable");s--,i=a,a=n.getInnerHTML(r),r=Se.getInertBodyElement(i)}while(i!==a);var l=new Ne,u=l.sanitizeChildren(n.getTemplateContent(r)||r);return Object(o.O)()&&l.sanitizedSomething&&n.log("WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss)."),u}finally{if(r)for(var c=n.getTemplateContent(r)||r,h=0,p=n.childNodesAsList(c);h=0},t.prototype.isFocusable=function(t){return function(t){return!function(t){return function(t){return"input"==t.nodeName.toLowerCase()}(t)&&"hidden"==t.type}(t)&&(function(t){var e=t.nodeName.toLowerCase();return"input"===e||"select"===e||"button"===e||"textarea"===e}(t)||function(t){return function(t){return"a"==t.nodeName.toLowerCase()}(t)&&t.hasAttribute("href")}(t)||t.hasAttribute("contenteditable")||In(t))}(t)&&!this.isDisabled(t)&&this.isVisible(t)},t}();function In(t){if(!t.hasAttribute("tabindex")||void 0===t.tabIndex)return!1;var e=t.getAttribute("tabindex");return"-32768"!=e&&!(!e||isNaN(parseInt(e,10)))}function Rn(t){if(!In(t))return null;var e=parseInt(t.getAttribute("tabindex")||"",10);return isNaN(e)?-1:e}var Nn=function(){function t(t,e,n,r,o){void 0===o&&(o=!1),this._element=t,this._checker=e,this._ngZone=n,this._document=r,this._enabled=!0,o||this.attachAnchors()}return Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(t){this._enabled=t,this._startAnchor&&this._endAnchor&&(this._startAnchor.tabIndex=this._endAnchor.tabIndex=this._enabled?0:-1)},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){this._startAnchor&&this._startAnchor.parentNode&&this._startAnchor.parentNode.removeChild(this._startAnchor),this._endAnchor&&this._endAnchor.parentNode&&this._endAnchor.parentNode.removeChild(this._endAnchor),this._startAnchor=this._endAnchor=null},t.prototype.attachAnchors=function(){var t=this;this._startAnchor||(this._startAnchor=this._createAnchor()),this._endAnchor||(this._endAnchor=this._createAnchor()),this._ngZone.runOutsideAngular(function(){t._startAnchor.addEventListener("focus",function(){t.focusLastTabbableElement()}),t._endAnchor.addEventListener("focus",function(){t.focusFirstTabbableElement()}),t._element.parentNode&&(t._element.parentNode.insertBefore(t._startAnchor,t._element),t._element.parentNode.insertBefore(t._endAnchor,t._element.nextSibling))})},t.prototype.focusInitialElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusInitialElement())})})},t.prototype.focusFirstTabbableElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusFirstTabbableElement())})})},t.prototype.focusLastTabbableElementWhenReady=function(){var t=this;return new Promise(function(e){t._executeOnStable(function(){return e(t.focusLastTabbableElement())})})},t.prototype._getRegionBoundary=function(t){for(var e=this._element.querySelectorAll("[cdk-focus-region-"+t+"], [cdkFocusRegion"+t+"], [cdk-focus-"+t+"]"),n=0;n=0;n--){var r=e[n].nodeType===this._document.ELEMENT_NODE?this._getLastTabbableElement(e[n]):null;if(r)return r}return null},t.prototype._createAnchor=function(){var t=this._document.createElement("div");return t.tabIndex=this._enabled?0:-1,t.classList.add("cdk-visually-hidden"),t.classList.add("cdk-focus-trap-anchor"),t},t.prototype._executeOnStable=function(t){this._ngZone.isStable?t():this._ngZone.onStable.asObservable().pipe(xn(1)).subscribe(t)},t}(),jn=function(){function t(t,e,n){this._checker=t,this._ngZone=e,this._document=n}return t.prototype.create=function(t,e){return void 0===e&&(e=!1),new Nn(t,this._checker,this._ngZone,this._document,e)},t}();function Vn(t,e){return(t.getAttribute(e)||"").match(/\S+/g)||[]}var Mn=0,Fn=new Map,Ln=null,Bn=function(){function t(t){this._document=t}return t.prototype.describe=function(t,e){this._canBeDescribed(t,e)&&(Fn.has(e)||this._createMessageElement(e),this._isElementDescribedByMessage(t,e)||this._addMessageReference(t,e))},t.prototype.removeDescription=function(t,e){if(this._canBeDescribed(t,e)){this._isElementDescribedByMessage(t,e)&&this._removeMessageReference(t,e);var n=Fn.get(e);n&&0===n.referenceCount&&this._deleteMessageElement(e),Ln&&0===Ln.childNodes.length&&this._deleteMessagesContainer()}},t.prototype.ngOnDestroy=function(){for(var t=this._document.querySelectorAll("[cdk-describedby-host]"),e=0;e=0?this.period=Number(n)<1?1:Number(n):Object(or.a)(n)&&(r=n),Object(or.a)(r)||(r=Pn),this.scheduler=r,this.dueTime=(i=e)instanceof Date&&!isNaN(+i)?+e-this.scheduler.now():e}return Object(c.b)(e,t),e.create=function(t,n,r){return void 0===t&&(t=0),new e(t,n,r)},e.dispatch=function(t){var e=t.index,n=t.period,r=t.subscriber;if(r.next(e),!r.closed){if(-1===n)return r.complete();t.index=e+1,this.schedule(t,n)}},e.prototype._subscribe=function(t){return this.scheduler.schedule(e.dispatch,this.dueTime,{index:0,period:this.period,subscriber:t})},e}(j.a).create;function sr(t,e){return void 0===e&&(e=Pn),n=function(){return ir(t,e)},function(t){return t.lift(new er(n))};var n}var ar=n("/nXB"),lr=function(){function t(t,e){this._ngZone=t,this._platform=e,this._scrolled=new vt.a,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map}return t.prototype.register=function(t){var e=this,n=t.elementScrolled().subscribe(function(){return e._scrolled.next(t)});this.scrollContainers.set(t,n)},t.prototype.deregister=function(t){var e=this.scrollContainers.get(t);e&&(e.unsubscribe(),this.scrollContainers.delete(t))},t.prototype.scrolled=function(t){var e=this;return void 0===t&&(t=20),this._platform.isBrowser?j.a.create(function(n){e._globalSubscription||e._addGlobalListener();var r=t>0?e._scrolled.pipe(sr(t)).subscribe(n):e._scrolled.subscribe(n);return e._scrolledCount++,function(){r.unsubscribe(),e._scrolledCount--,e._scrolledCount||e._removeGlobalListener()}}):l()},t.prototype.ngOnDestroy=function(){var t=this;this._removeGlobalListener(),this.scrollContainers.forEach(function(e,n){return t.deregister(n)})},t.prototype.ancestorScrolled=function(t,e){var n=this.getAncestorScrollContainers(t);return this.scrolled(e).pipe(p(function(t){return!t||n.indexOf(t)>-1}))},t.prototype.getAncestorScrollContainers=function(t){var e=this,n=[];return this.scrollContainers.forEach(function(r,o){e._scrollableContainsElement(o,t)&&n.push(o)}),n},t.prototype._scrollableContainsElement=function(t,e){var n=e.nativeElement,r=t.getElementRef().nativeElement;do{if(n==r)return!0}while(n=n.parentElement);return!1},t.prototype._addGlobalListener=function(){var t=this;this._globalSubscription=this._ngZone.runOutsideAngular(function(){return $n(window.document,"scroll").subscribe(function(){return t._scrolled.next()})})},t.prototype._removeGlobalListener=function(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)},t}();function ur(t,e,n){return t||new lr(e,n)}var cr=function(){function t(t,e){var n=this;this._platform=t,this._change=t.isBrowser?e.runOutsideAngular(function(){return Object(ar.a)($n(window,"resize"),$n(window,"orientationchange"))}):l(),this._invalidateCache=this.change().subscribe(function(){return n._updateViewportSize()})}return t.prototype.ngOnDestroy=function(){this._invalidateCache.unsubscribe()},t.prototype.getViewportSize=function(){this._viewportSize||this._updateViewportSize();var t={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),t},t.prototype.getViewportRect=function(){var t=this.getViewportScrollPosition(),e=this.getViewportSize(),n=e.width,r=e.height;return{top:t.top,left:t.left,bottom:t.top+r,right:t.left+n,height:r,width:n}},t.prototype.getViewportScrollPosition=function(){if(!this._platform.isBrowser)return{top:0,left:0};var t=document.documentElement.getBoundingClientRect();return{top:-t.top||document.body.scrollTop||window.scrollY||document.documentElement.scrollTop||0,left:-t.left||document.body.scrollLeft||window.scrollX||document.documentElement.scrollLeft||0}},t.prototype.change=function(t){return void 0===t&&(t=20),t>0?this._change.pipe(sr(t)):this._change},t.prototype._updateViewportSize=function(){this._viewportSize=this._platform.isBrowser?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0}},t}();function hr(t,e,n){return t||new cr(e,n)}var pr=function(){};function dr(){throw Error("Host already has a portal attached")}var fr=function(){function t(){}return t.prototype.attach=function(t){return null==t&&function(){throw Error("Attempting to attach a portal to a null PortalOutlet")}(),t.hasAttached()&&dr(),this._attachedHost=t,t.attach(this)},t.prototype.detach=function(){var t=this._attachedHost;null==t?function(){throw Error("Attempting to detach a portal that is not attached to a host")}():(this._attachedHost=null,t.detach())},Object.defineProperty(t.prototype,"isAttached",{get:function(){return null!=this._attachedHost},enumerable:!0,configurable:!0}),t.prototype.setAttachedHost=function(t){this._attachedHost=t},t}(),mr=function(t){function e(e,n,r){var o=t.call(this)||this;return o.component=e,o.viewContainerRef=n,o.injector=r,o}return Object(c.b)(e,t),e}(fr),yr=function(t){function e(e,n,r){var o=t.call(this)||this;return o.templateRef=e,o.viewContainerRef=n,o.context=r,o}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"origin",{get:function(){return this.templateRef.elementRef},enumerable:!0,configurable:!0}),e.prototype.attach=function(e,n){return void 0===n&&(n=this.context),this.context=n,t.prototype.attach.call(this,e)},e.prototype.detach=function(){return this.context=void 0,t.prototype.detach.call(this)},e}(fr),_r=function(){function t(){this._isDisposed=!1}return t.prototype.hasAttached=function(){return!!this._attachedPortal},t.prototype.attach=function(t){return t||function(){throw Error("Must provide a portal to attach")}(),this.hasAttached()&&dr(),this._isDisposed&&function(){throw Error("This PortalOutlet has already been disposed")}(),t instanceof mr?(this._attachedPortal=t,this.attachComponentPortal(t)):t instanceof yr?(this._attachedPortal=t,this.attachTemplatePortal(t)):void function(){throw Error("Attempting to attach an unknown Portal type. BasePortalOutlet accepts either a ComponentPortal or a TemplatePortal.")}()},t.prototype.detach=function(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()},t.prototype.dispose=function(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0},t.prototype.setDisposeFn=function(t){this._disposeFn=t},t.prototype._invokeDisposeFn=function(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)},t}(),gr=function(t){function e(e,n,r,o){var i=t.call(this)||this;return i.outletElement=e,i._componentFactoryResolver=n,i._appRef=r,i._defaultInjector=o,i}return Object(c.b)(e,t),e.prototype.attachComponentPortal=function(t){var e,n=this,r=this._componentFactoryResolver.resolveComponentFactory(t.component);return t.viewContainerRef?(e=t.viewContainerRef.createComponent(r,t.viewContainerRef.length,t.injector||t.viewContainerRef.parentInjector),this.setDisposeFn(function(){return e.destroy()})):(e=r.create(t.injector||this._defaultInjector),this._appRef.attachView(e.hostView),this.setDisposeFn(function(){n._appRef.detachView(e.hostView),e.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(e)),e},e.prototype.attachTemplatePortal=function(t){var e=this,n=t.viewContainerRef,r=n.createEmbeddedView(t.templateRef,t.context);return r.detectChanges(),r.rootNodes.forEach(function(t){return e.outletElement.appendChild(t)}),this.setDisposeFn(function(){var t=n.indexOf(r);-1!==t&&n.remove(t)}),r},e.prototype.dispose=function(){t.prototype.dispose.call(this),null!=this.outletElement.parentNode&&this.outletElement.parentNode.removeChild(this.outletElement)},e.prototype._getComponentRootNode=function(t){return t.hostView.rootNodes[0]},e}(_r),vr=function(t){function e(e,n){var r=t.call(this)||this;return r._componentFactoryResolver=e,r._viewContainerRef=n,r._isInitialized=!1,r.attached=new o.l,r}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"_deprecatedPortal",{get:function(){return this.portal},set:function(t){this.portal=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_deprecatedPortalHost",{get:function(){return this.portal},set:function(t){this.portal=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"portal",{get:function(){return this._attachedPortal},set:function(e){(!this.hasAttached()||e||this._isInitialized)&&(this.hasAttached()&&t.prototype.detach.call(this),e&&t.prototype.attach.call(this,e),this._attachedPortal=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"attachedRef",{get:function(){return this._attachedRef},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){this._isInitialized=!0},e.prototype.ngOnDestroy=function(){t.prototype.dispose.call(this),this._attachedPortal=null,this._attachedRef=null},e.prototype.attachComponentPortal=function(e){e.setAttachedHost(this);var n=null!=e.viewContainerRef?e.viewContainerRef:this._viewContainerRef,r=this._componentFactoryResolver.resolveComponentFactory(e.component),o=n.createComponent(r,n.length,e.injector||n.parentInjector);return t.prototype.setDisposeFn.call(this,function(){return o.destroy()}),this._attachedPortal=e,this._attachedRef=o,this.attached.emit(o),o},e.prototype.attachTemplatePortal=function(e){var n=this;e.setAttachedHost(this);var r=this._viewContainerRef.createEmbeddedView(e.templateRef,e.context);return t.prototype.setDisposeFn.call(this,function(){return n._viewContainerRef.clear()}),this._attachedPortal=e,this._attachedRef=r,this.attached.emit(r),r},e}(_r),br=function(){},wr=function(){function t(t,e){this._parentInjector=t,this._customTokens=e}return t.prototype.get=function(t,e){var n=this._customTokens.get(t);return"undefined"!=typeof n?n:this._parentInjector.get(t,e)},t}(),Er=function(){function t(){}return t.prototype.enable=function(){},t.prototype.disable=function(){},t.prototype.attach=function(){},t}(),Cr=function(){return function(t){var e=this;this.scrollStrategy=new Er,this.panelClass="",this.hasBackdrop=!1,this.backdropClass="cdk-overlay-dark-backdrop",this.direction="ltr",t&&Object.keys(t).filter(function(e){return"undefined"!=typeof t[e]}).forEach(function(n){return e[n]=t[n]})}}();function xr(){return Error("Scroll strategy has already been attached.")}var Sr=function(){function t(t,e,n,r){var o=this;this._scrollDispatcher=t,this._ngZone=e,this._viewportRuler=n,this._config=r,this._scrollSubscription=null,this._detach=function(){o.disable(),o._overlayRef.hasAttached()&&o._ngZone.run(function(){return o._overlayRef.detach()})}}return t.prototype.attach=function(t){if(this._overlayRef)throw xr();this._overlayRef=t},t.prototype.enable=function(){var t=this;if(!this._scrollSubscription){var e=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=e.subscribe(function(){var e=t._viewportRuler.getViewportScrollPosition().top;Math.abs(e-t._initialScrollPosition)>t._config.threshold?t._detach():t._overlayRef.updatePosition()})):this._scrollSubscription=e.subscribe(this._detach)}},t.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},t}(),Tr=function(){function t(t,e){this._viewportRuler=t,this._previousHTMLStyles={top:"",left:""},this._isEnabled=!1,this._document=e}return t.prototype.attach=function(){},t.prototype.enable=function(){if(this._canBeEnabled()){var t=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=t.style.left||"",this._previousHTMLStyles.top=t.style.top||"",t.style.left=-this._previousScrollPosition.left+"px",t.style.top=-this._previousScrollPosition.top+"px",t.classList.add("cdk-global-scrollblock"),this._isEnabled=!0}},t.prototype.disable=function(){if(this._isEnabled){var t=this._document.documentElement,e=this._document.body,n=t.style.scrollBehavior||"",r=e.style.scrollBehavior||"";this._isEnabled=!1,t.style.left=this._previousHTMLStyles.left,t.style.top=this._previousHTMLStyles.top,t.classList.remove("cdk-global-scrollblock"),t.style.scrollBehavior=e.style.scrollBehavior="auto",window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),t.style.scrollBehavior=n,e.style.scrollBehavior=r}},t.prototype._canBeEnabled=function(){if(this._document.documentElement.classList.contains("cdk-global-scrollblock")||this._isEnabled)return!1;var t=this._document.body,e=this._viewportRuler.getViewportSize();return t.scrollHeight>e.height||t.scrollWidth>e.width},t}();function Or(t,e){return e.some(function(e){return t.bottome.bottom||t.righte.right})}function kr(t,e){return e.some(function(e){return t.tope.bottom||t.lefte.right})}var Ar=function(){function t(t,e,n,r){this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=n,this._config=r,this._scrollSubscription=null}return t.prototype.attach=function(t){if(this._overlayRef)throw xr();this._overlayRef=t},t.prototype.enable=function(){var t=this;this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(function(){if(t._overlayRef.updatePosition(),t._config&&t._config.autoClose){var e=t._overlayRef.overlayElement.getBoundingClientRect(),n=t._viewportRuler.getViewportSize(),r=n.width,o=n.height;Or(e,[{width:r,height:o,bottom:o,right:r,top:0,left:0}])&&(t.disable(),t._ngZone.run(function(){return t._overlayRef.detach()}))}}))},t.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},t}(),Pr=function(){return function(t,e,n,r){var o=this;this._scrollDispatcher=t,this._viewportRuler=e,this._ngZone=n,this.noop=function(){return new Er},this.close=function(t){return new Sr(o._scrollDispatcher,o._ngZone,o._viewportRuler,t)},this.block=function(){return new Tr(o._viewportRuler,o._document)},this.reposition=function(t){return new Ar(o._scrollDispatcher,o._viewportRuler,o._ngZone,t)},this._document=r}}(),Dr=function(){function t(t,e,n,r,o,i){this._portalOutlet=t,this._pane=e,this._config=n,this._ngZone=r,this._keyboardDispatcher=o,this._document=i,this._backdropElement=null,this._backdropClick=new vt.a,this._attachments=new vt.a,this._detachments=new vt.a,this._keydownEvents=new vt.a,n.scrollStrategy&&n.scrollStrategy.attach(this)}return Object.defineProperty(t.prototype,"overlayElement",{get:function(){return this._pane},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"backdropElement",{get:function(){return this._backdropElement},enumerable:!0,configurable:!0}),t.prototype.attach=function(t){var e=this,n=this._portalOutlet.attach(t);return this._config.positionStrategy&&this._config.positionStrategy.attach(this),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._config.scrollStrategy&&this._config.scrollStrategy.enable(),this._ngZone.onStable.asObservable().pipe(xn(1)).subscribe(function(){e.hasAttached()&&e.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&(Array.isArray(this._config.panelClass)?this._config.panelClass.forEach(function(t){return e._pane.classList.add(t)}):this._pane.classList.add(this._config.panelClass)),this._attachments.next(),this._keyboardDispatcher.add(this),n},t.prototype.detach=function(){if(this.hasAttached()){this.detachBackdrop(),this._togglePointerEvents(!1),this._config.positionStrategy&&this._config.positionStrategy.detach&&this._config.positionStrategy.detach(),this._config.scrollStrategy&&this._config.scrollStrategy.disable();var t=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),t}},t.prototype.dispose=function(){var t=this.hasAttached();this._config.positionStrategy&&this._config.positionStrategy.dispose(),this._config.scrollStrategy&&this._config.scrollStrategy.disable(),this.detachBackdrop(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),t&&this._detachments.next(),this._detachments.complete()},t.prototype.hasAttached=function(){return this._portalOutlet.hasAttached()},t.prototype.backdropClick=function(){return this._backdropClick.asObservable()},t.prototype.attachments=function(){return this._attachments.asObservable()},t.prototype.detachments=function(){return this._detachments.asObservable()},t.prototype.keydownEvents=function(){return this._keydownEvents.asObservable()},t.prototype.getConfig=function(){return this._config},t.prototype.updatePosition=function(){this._config.positionStrategy&&this._config.positionStrategy.apply()},t.prototype.updateSize=function(t){this._config=Object(c.a)({},this._config,t),this._updateElementSize()},t.prototype.setDirection=function(t){this._config=Object(c.a)({},this._config,{direction:t}),this._updateElementDirection()},t.prototype._updateElementDirection=function(){this._pane.setAttribute("dir",this._config.direction)},t.prototype._updateElementSize=function(){(this._config.width||0===this._config.width)&&(this._pane.style.width=Ir(this._config.width)),(this._config.height||0===this._config.height)&&(this._pane.style.height=Ir(this._config.height)),(this._config.minWidth||0===this._config.minWidth)&&(this._pane.style.minWidth=Ir(this._config.minWidth)),(this._config.minHeight||0===this._config.minHeight)&&(this._pane.style.minHeight=Ir(this._config.minHeight)),(this._config.maxWidth||0===this._config.maxWidth)&&(this._pane.style.maxWidth=Ir(this._config.maxWidth)),(this._config.maxHeight||0===this._config.maxHeight)&&(this._pane.style.maxHeight=Ir(this._config.maxHeight))},t.prototype._togglePointerEvents=function(t){this._pane.style.pointerEvents=t?"auto":"none"},t.prototype._attachBackdrop=function(){var t=this;this._backdropElement=this._document.createElement("div"),this._backdropElement.classList.add("cdk-overlay-backdrop"),this._config.backdropClass&&this._backdropElement.classList.add(this._config.backdropClass),this._pane.parentElement.insertBefore(this._backdropElement,this._pane),this._backdropElement.addEventListener("click",function(e){return t._backdropClick.next(e)}),"undefined"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(function(){requestAnimationFrame(function(){t._backdropElement&&t._backdropElement.classList.add("cdk-overlay-backdrop-showing")})}):this._backdropElement.classList.add("cdk-overlay-backdrop-showing")},t.prototype._updateStackingOrder=function(){this._pane.nextSibling&&this._pane.parentNode.appendChild(this._pane)},t.prototype.detachBackdrop=function(){var t=this,e=this._backdropElement;if(e){var n=function(){e&&e.parentNode&&e.parentNode.removeChild(e),t._backdropElement==e&&(t._backdropElement=null)};e.classList.remove("cdk-overlay-backdrop-showing"),this._config.backdropClass&&e.classList.remove(this._config.backdropClass),e.addEventListener("transitionend",n),e.style.pointerEvents="none",this._ngZone.runOutsideAngular(function(){setTimeout(n,500)})}},t}();function Ir(t){return"string"==typeof t?t:t+"px"}var Rr=function(){function t(t,e,n,r,o){this._connectedTo=n,this._viewportRuler=r,this._document=o,this._dir="ltr",this._offsetX=0,this._offsetY=0,this.scrollables=[],this._resizeSubscription=On.a.EMPTY,this._preferredPositions=[],this._applied=!1,this._positionLocked=!1,this._onPositionChange=new vt.a,this._origin=this._connectedTo.nativeElement,this.withFallbackPosition(t,e)}return Object.defineProperty(t.prototype,"_isRtl",{get:function(){return"rtl"===this._dir},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onPositionChange",{get:function(){return this._onPositionChange.asObservable()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"positions",{get:function(){return this._preferredPositions},enumerable:!0,configurable:!0}),t.prototype.attach=function(t){var e=this;this._pane=t.overlayElement,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(function(){return e.apply()})},t.prototype.dispose=function(){this._applied=!1,this._resizeSubscription.unsubscribe(),this._onPositionChange.complete()},t.prototype.detach=function(){this._applied=!1,this._resizeSubscription.unsubscribe()},t.prototype.apply=function(){if(this._applied&&this._positionLocked&&this._lastConnectedPosition)this.recalculateLastPosition();else{this._applied=!0;for(var t,e,n=this._pane,r=this._origin.getBoundingClientRect(),o=n.getBoundingClientRect(),i=this._viewportRuler.getViewportSize(),s=0,a=this._preferredPositions;s-1&&this._attachedOverlays.splice(e,1),0===this._attachedOverlays.length&&this._unsubscribeFromKeydownEvents()},t.prototype._subscribeToKeydownEvents=function(){var t=this,e=$n(this._document.body,"keydown",!0);this._keydownEventSubscription=e.pipe(p(function(){return!!t._attachedOverlays.length})).subscribe(function(e){t._selectOverlayFromEvent(e)._keydownEvents.next(e)})},t.prototype._unsubscribeFromKeydownEvents=function(){this._keydownEventSubscription&&(this._keydownEventSubscription.unsubscribe(),this._keydownEventSubscription=null)},t.prototype._selectOverlayFromEvent=function(t){return this._attachedOverlays.find(function(e){return e.overlayElement===t.target||e.overlayElement.contains(t.target)})||this._attachedOverlays[this._attachedOverlays.length-1]},t}();function Mr(t,e){return t||new Vr(e)}var Fr=function(){function t(t){this._document=t}return t.prototype.ngOnDestroy=function(){this._containerElement&&this._containerElement.parentNode&&this._containerElement.parentNode.removeChild(this._containerElement)},t.prototype.getContainerElement=function(){return this._containerElement||this._createContainer(),this._containerElement},t.prototype._createContainer=function(){var t=this._document.createElement("div");t.classList.add("cdk-overlay-container"),this._document.body.appendChild(t),this._containerElement=t},t}();function Lr(t,e){return t||new Fr(e)}var Br=0,Hr=function(){function t(t,e,n,r,o,i,s,a,l){this.scrollStrategies=t,this._overlayContainer=e,this._componentFactoryResolver=n,this._positionBuilder=r,this._keyboardDispatcher=o,this._appRef=i,this._injector=s,this._ngZone=a,this._document=l}return t.prototype.create=function(t){var e=this._createPaneElement(),n=this._createPortalOutlet(e);return new Dr(n,e,new Cr(t),this._ngZone,this._keyboardDispatcher,this._document)},t.prototype.position=function(){return this._positionBuilder},t.prototype._createPaneElement=function(){var t=this._document.createElement("div");return t.id="cdk-overlay-"+Br++,t.classList.add("cdk-overlay-pane"),this._overlayContainer.getContainerElement().appendChild(t),t},t.prototype._createPortalOutlet=function(t){return new gr(t,this._componentFactoryResolver,this._appRef,this._injector)},t}(),zr=new o.n("cdk-connected-overlay-scroll-strategy");function Ur(t){return function(){return t.scrollStrategies.reposition()}}var Yr=function(){},qr=function(){function t(t,e,n){this.kind=t,this.value=e,this.error=n,this.hasValue="N"===t}return t.prototype.observe=function(t){switch(this.kind){case"N":return t.next&&t.next(this.value);case"E":return t.error&&t.error(this.error);case"C":return t.complete&&t.complete()}},t.prototype.do=function(t,e,n){switch(this.kind){case"N":return t&&t(this.value);case"E":return e&&e(this.error);case"C":return n&&n()}},t.prototype.accept=function(t,e,n){return t&&"function"==typeof t.next?this.observe(t):this.do(t,e,n)},t.prototype.toObservable=function(){switch(this.kind){case"N":return j.a.of(this.value);case"E":return j.a.throw(this.error);case"C":return j.a.empty()}throw new Error("unexpected notification kind value")},t.createNext=function(e){return"undefined"!=typeof e?new t("N",e):t.undefinedValueNotification},t.createError=function(e){return new t("E",void 0,e)},t.createComplete=function(){return t.completeNotification},t.completeNotification=new t("C"),t.undefinedValueNotification=new t("N",void 0),t}(),Xr=function(t){function e(e,n){t.call(this),this.sources=e,this.resultSelector=n}return Object(c.b)(e,t),e.create=function(){for(var t=[],n=0;nt?{max:{max:t,actual:e.value}}:null}},t.required=function(t){return eo(t.value)?{required:!0}:null},t.requiredTrue=function(t){return!0===t.value?null:{required:!0}},t.email=function(t){return no.test(t.value)?null:{email:!0}},t.minLength=function(t){return function(e){if(eo(e.value))return null;var n=e.value?e.value.length:0;return nt?{maxlength:{requiredLength:t,actualLength:n}}:null}},t.pattern=function(e){return e?("string"==typeof e?(r="","^"!==e.charAt(0)&&(r+="^"),r+=e,"$"!==e.charAt(e.length-1)&&(r+="$"),n=new RegExp(r)):(r=e.toString(),n=e),function(t){if(eo(t.value))return null;var e=t.value;return n.test(e)?null:{pattern:{requiredPattern:r,actualValue:e}}}):t.nullValidator;var n,r},t.nullValidator=function(t){return null},t.compose=function(t){if(!t)return null;var e=t.filter(oo);return 0==e.length?null:function(t){return so(function(t,n){return e.map(function(e){return e(t)})}(t))}},t.composeAsync=function(t){if(!t)return null;var e=t.filter(oo);return 0==e.length?null:function(t){var n=function(t,n){return e.map(function(e){return e(t)})}(t).map(io);return _.call(Zr(n),so)}},t}();function oo(t){return null!=t}function io(t){var e=Object(o._3)(t)?$r(t):t;if(!Object(o._2)(e))throw new Error("Expected validator to return Promise or Observable.");return e}function so(t){var e=t.reduce(function(t,e){return null!=e?Object(c.a)({},t,e):t},{});return 0===Object.keys(e).length?null:e}var ao=new o.n("NgValueAccessor"),lo=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"checked",t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),uo=new o.n("CompositionEventMode"),co=function(){function t(t,e,n){var r;this._renderer=t,this._elementRef=e,this._compositionMode=n,this.onChange=function(t){},this.onTouched=function(){},this._composing=!1,null==this._compositionMode&&(this._compositionMode=(r=wt()?wt().getUserAgent():"",!/android (\d+)/.test(r.toLowerCase())))}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=t},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._handleInput=function(t){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(t)},t.prototype._compositionStart=function(){this._composing=!0},t.prototype._compositionEnd=function(t){this._composing=!1,this._compositionMode&&this.onChange(t)},t}();function ho(t){return t.validate?function(e){return t.validate(e)}:t}function po(t){return t.validate?function(e){return t.validate(e)}:t}var fo=function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==t?"":t)},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}();function mo(){throw new Error("unimplemented")}var yo=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._parent=null,e.name=null,e.valueAccessor=null,e._rawValidators=[],e._rawAsyncValidators=[],e}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"validator",{get:function(){return mo()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return mo()},enumerable:!0,configurable:!0}),e}(Jr),_o=function(){function t(){this._accessors=[]}return t.prototype.add=function(t,e){this._accessors.push([t,e])},t.prototype.remove=function(t){for(var e=this._accessors.length-1;e>=0;--e)if(this._accessors[e][1]===t)return void this._accessors.splice(e,1)},t.prototype.select=function(t){var e=this;this._accessors.forEach(function(n){e._isSameGroup(n,t)&&n[1]!==t&&n[1].fireUncheck(t.value)})},t.prototype._isSameGroup=function(t,e){return!!t[0].control&&t[0]._parent===e._control._parent&&t[1].name===e.name},t}(),go=function(){function t(t,e,n,r){this._renderer=t,this._elementRef=e,this._registry=n,this._injector=r,this.onChange=function(){},this.onTouched=function(){}}return t.prototype.ngOnInit=function(){this._control=this._injector.get(yo),this._checkName(),this._registry.add(this._control,this)},t.prototype.ngOnDestroy=function(){this._registry.remove(this)},t.prototype.writeValue=function(t){this._state=t===this.value,this._renderer.setProperty(this._elementRef.nativeElement,"checked",this._state)},t.prototype.registerOnChange=function(t){var e=this;this._fn=t,this.onChange=function(){t(e.value),e._registry.select(e)}},t.prototype.fireUncheck=function(t){this.writeValue(t)},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._checkName=function(){this.name&&this.formControlName&&this.name!==this.formControlName&&this._throwNameError(),!this.name&&this.formControlName&&(this.name=this.formControlName)},t.prototype._throwNameError=function(){throw new Error('\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: \n ')},t}();function vo(t,e){return e.path.concat([t])}function bo(t,e){t||xo(e,"Cannot find control with"),e.valueAccessor||xo(e,"No value accessor for form control with"),t.validator=ro.compose([t.validator,e.validator]),t.asyncValidator=ro.composeAsync([t.asyncValidator,e.asyncValidator]),e.valueAccessor.writeValue(t.value),function(t,e){e.valueAccessor.registerOnChange(function(n){t._pendingValue=n,t._pendingChange=!0,t._pendingDirty=!0,"change"===t.updateOn&&wo(t,e)})}(t,e),function(t,e){t.registerOnChange(function(t,n){e.valueAccessor.writeValue(t),n&&e.viewToModelUpdate(t)})}(t,e),function(t,e){e.valueAccessor.registerOnTouched(function(){t._pendingTouched=!0,"blur"===t.updateOn&&t._pendingChange&&wo(t,e),"submit"!==t.updateOn&&t.markAsTouched()})}(t,e),e.valueAccessor.setDisabledState&&t.registerOnDisabledChange(function(t){e.valueAccessor.setDisabledState(t)}),e._rawValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})}),e._rawAsyncValidators.forEach(function(e){e.registerOnValidatorChange&&e.registerOnValidatorChange(function(){return t.updateValueAndValidity()})})}function wo(t,e){e.viewToModelUpdate(t._pendingValue),t._pendingDirty&&t.markAsDirty(),t.setValue(t._pendingValue,{emitModelToViewChange:!1}),t._pendingChange=!1}function Eo(t,e){null==t&&xo(e,"Cannot find control with"),t.validator=ro.compose([t.validator,e.validator]),t.asyncValidator=ro.composeAsync([t.asyncValidator,e.asyncValidator])}function Co(t){return xo(t,"There is no FormControl instance attached to form control element with")}function xo(t,e){var n;throw n=t.path.length>1?"path: '"+t.path.join(" -> ")+"'":t.path[0]?"name: '"+t.path+"'":"unspecified name attribute",new Error(e+" "+n)}function So(t){return null!=t?ro.compose(t.map(ho)):null}function To(t){return null!=t?ro.composeAsync(t.map(po)):null}var Oo=[lo,function(){function t(t,e){this._renderer=t,this._elementRef=e,this.onChange=function(t){},this.onTouched=function(){}}return t.prototype.writeValue=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"value",parseFloat(t))},t.prototype.registerOnChange=function(t){this.onChange=function(e){t(""==e?null:parseFloat(e))}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t}(),fo,function(){function t(t,e){this._renderer=t,this._elementRef=e,this._optionMap=new Map,this._idCounter=0,this.onChange=function(t){},this.onTouched=function(){},this._compareWith=o._4}return Object.defineProperty(t.prototype,"compareWith",{set:function(t){if("function"!=typeof t)throw new Error("compareWith must be a function, but received "+JSON.stringify(t));this._compareWith=t},enumerable:!0,configurable:!0}),t.prototype.writeValue=function(t){this.value=t;var e=this._getOptionId(t);null==e&&this._renderer.setProperty(this._elementRef.nativeElement,"selectedIndex",-1);var n=function(t,e){return null==t?""+e:(e&&"object"==typeof e&&(e="Object"),(t+": "+e).slice(0,50))}(e,t);this._renderer.setProperty(this._elementRef.nativeElement,"value",n)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){e.value=e._getOptionValue(n),t(e.value)}},t.prototype.registerOnTouched=function(t){this.onTouched=t},t.prototype.setDisabledState=function(t){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",t)},t.prototype._registerOption=function(){return(this._idCounter++).toString()},t.prototype._getOptionId=function(t){for(var e=0,n=Array.from(this._optionMap.keys());e-1)}}else e=function(t,e){t._setSelected(!1)};this._optionMap.forEach(e)},t.prototype.registerOnChange=function(t){var e=this;this.onChange=function(n){var r=[];if(n.hasOwnProperty("selectedOptions"))for(var o=n.selectedOptions,i=0;i-1&&t.splice(n,1)}var Po=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e.prototype.ngOnInit=function(){this._checkParentType(),this.formDirective.addFormGroup(this)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeFormGroup(this)},Object.defineProperty(e.prototype,"control",{get:function(){return this.formDirective.getFormGroup(this)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return vo(this.name,this._parent)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return So(this._validators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return To(this._asyncValidators)},enumerable:!0,configurable:!0}),e.prototype._checkParentType=function(){},e}(to),Do=function(t){function e(e){return t.call(this,e)||this}return Object(c.b)(e,t),e}(function(){function t(t){this._cd=t}return Object.defineProperty(t.prototype,"ngClassUntouched",{get:function(){return!!this._cd.control&&this._cd.control.untouched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassTouched",{get:function(){return!!this._cd.control&&this._cd.control.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPristine",{get:function(){return!!this._cd.control&&this._cd.control.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassDirty",{get:function(){return!!this._cd.control&&this._cd.control.dirty},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassValid",{get:function(){return!!this._cd.control&&this._cd.control.valid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassInvalid",{get:function(){return!!this._cd.control&&this._cd.control.invalid},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"ngClassPending",{get:function(){return!!this._cd.control&&this._cd.control.pending},enumerable:!0,configurable:!0}),t}());function Io(t){var e=No(t)?t.validators:t;return Array.isArray(e)?So(e):e||null}function Ro(t,e){var n=No(e)?e.asyncValidators:t;return Array.isArray(n)?To(n):n||null}function No(t){return null!=t&&!Array.isArray(t)&&"object"==typeof t}var jo=function(){function t(t,e){this.validator=t,this.asyncValidator=e,this._onCollectionChange=function(){},this.pristine=!0,this.touched=!1,this._onDisabledChange=[]}return Object.defineProperty(t.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"valid",{get:function(){return"VALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invalid",{get:function(){return"INVALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pending",{get:function(){return"PENDING"==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"disabled",{get:function(){return"DISABLED"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"enabled",{get:function(){return"DISABLED"!==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dirty",{get:function(){return!this.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"untouched",{get:function(){return!this.touched},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updateOn",{get:function(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"},enumerable:!0,configurable:!0}),t.prototype.setValidators=function(t){this.validator=Io(t)},t.prototype.setAsyncValidators=function(t){this.asyncValidator=Ro(t)},t.prototype.clearValidators=function(){this.validator=null},t.prototype.clearAsyncValidators=function(){this.asyncValidator=null},t.prototype.markAsTouched=function(t){void 0===t&&(t={}),this.touched=!0,this._parent&&!t.onlySelf&&this._parent.markAsTouched(t)},t.prototype.markAsUntouched=function(t){void 0===t&&(t={}),this.touched=!1,this._pendingTouched=!1,this._forEachChild(function(t){t.markAsUntouched({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype.markAsDirty=function(t){void 0===t&&(t={}),this.pristine=!1,this._parent&&!t.onlySelf&&this._parent.markAsDirty(t)},t.prototype.markAsPristine=function(t){void 0===t&&(t={}),this.pristine=!0,this._pendingDirty=!1,this._forEachChild(function(t){t.markAsPristine({onlySelf:!0})}),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype.markAsPending=function(t){void 0===t&&(t={}),this.status="PENDING",this._parent&&!t.onlySelf&&this._parent.markAsPending(t)},t.prototype.disable=function(t){void 0===t&&(t={}),this.status="DISABLED",this.errors=null,this._forEachChild(function(e){e.disable(Object(c.a)({},t,{onlySelf:!0}))}),this._updateValue(),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!0)})},t.prototype.enable=function(t){void 0===t&&(t={}),this.status="VALID",this._forEachChild(function(e){e.enable(Object(c.a)({},t,{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent}),this._updateAncestors(t),this._onDisabledChange.forEach(function(t){return t(!1)})},t.prototype._updateAncestors=function(t){this._parent&&!t.onlySelf&&(this._parent.updateValueAndValidity(t),this._parent._updatePristine(),this._parent._updateTouched())},t.prototype.setParent=function(t){this._parent=t},t.prototype.updateValueAndValidity=function(t){void 0===t&&(t={}),this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),"VALID"!==this.status&&"PENDING"!==this.status||this._runAsyncValidator(t.emitEvent)),!1!==t.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!t.onlySelf&&this._parent.updateValueAndValidity(t)},t.prototype._updateTreeValidity=function(t){void 0===t&&(t={emitEvent:!0}),this._forEachChild(function(e){return e._updateTreeValidity(t)}),this.updateValueAndValidity({onlySelf:!0,emitEvent:t.emitEvent})},t.prototype._setInitialStatus=function(){this.status=this._allControlsDisabled()?"DISABLED":"VALID"},t.prototype._runValidator=function(){return this.validator?this.validator(this):null},t.prototype._runAsyncValidator=function(t){var e=this;if(this.asyncValidator){this.status="PENDING";var n=io(this.asyncValidator(this));this._asyncValidationSubscription=n.subscribe(function(n){return e.setErrors(n,{emitEvent:t})})}},t.prototype._cancelExistingSubscription=function(){this._asyncValidationSubscription&&this._asyncValidationSubscription.unsubscribe()},t.prototype.setErrors=function(t,e){void 0===e&&(e={}),this.errors=t,this._updateControlsErrors(!1!==e.emitEvent)},t.prototype.get=function(t){return function(t,e,n){return null==e?null:(e instanceof Array||(e=e.split(".")),e instanceof Array&&0===e.length?null:e.reduce(function(t,e){return t instanceof Mo?t.controls[e]||null:t instanceof Fo&&t.at(e)||null},t))}(this,t)},t.prototype.getError=function(t,e){var n=e?this.get(e):this;return n&&n.errors?n.errors[t]:null},t.prototype.hasError=function(t,e){return!!this.getError(t,e)},Object.defineProperty(t.prototype,"root",{get:function(){for(var t=this;t._parent;)t=t._parent;return t},enumerable:!0,configurable:!0}),t.prototype._updateControlsErrors=function(t){this.status=this._calculateStatus(),t&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(t)},t.prototype._initObservables=function(){this.valueChanges=new o.l,this.statusChanges=new o.l},t.prototype._calculateStatus=function(){return this._allControlsDisabled()?"DISABLED":this.errors?"INVALID":this._anyControlsHaveStatus("PENDING")?"PENDING":this._anyControlsHaveStatus("INVALID")?"INVALID":"VALID"},t.prototype._anyControlsHaveStatus=function(t){return this._anyControls(function(e){return e.status===t})},t.prototype._anyControlsDirty=function(){return this._anyControls(function(t){return t.dirty})},t.prototype._anyControlsTouched=function(){return this._anyControls(function(t){return t.touched})},t.prototype._updatePristine=function(t){void 0===t&&(t={}),this.pristine=!this._anyControlsDirty(),this._parent&&!t.onlySelf&&this._parent._updatePristine(t)},t.prototype._updateTouched=function(t){void 0===t&&(t={}),this.touched=this._anyControlsTouched(),this._parent&&!t.onlySelf&&this._parent._updateTouched(t)},t.prototype._isBoxedValue=function(t){return"object"==typeof t&&null!==t&&2===Object.keys(t).length&&"value"in t&&"disabled"in t},t.prototype._registerOnCollectionChange=function(t){this._onCollectionChange=t},t.prototype._setUpdateStrategy=function(t){No(t)&&null!=t.updateOn&&(this._updateOn=t.updateOn)},t}(),Vo=function(t){function e(e,n,r){void 0===e&&(e=null);var o=t.call(this,Io(n),Ro(r,n))||this;return o._onChange=[],o._applyFormState(e),o._setUpdateStrategy(n),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o._initObservables(),o}return Object(c.b)(e,t),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this.value=this._pendingValue=t,this._onChange.length&&!1!==e.emitModelToViewChange&&this._onChange.forEach(function(t){return t(n.value,!1!==e.emitViewToModelChange)}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){void 0===e&&(e={}),this.setValue(t,e)},e.prototype.reset=function(t,e){void 0===t&&(t=null),void 0===e&&(e={}),this._applyFormState(t),this.markAsPristine(e),this.markAsUntouched(e),this.setValue(this.value,e),this._pendingChange=!1},e.prototype._updateValue=function(){},e.prototype._anyControls=function(t){return!1},e.prototype._allControlsDisabled=function(){return this.disabled},e.prototype.registerOnChange=function(t){this._onChange.push(t)},e.prototype._clearChangeFns=function(){this._onChange=[],this._onDisabledChange=[],this._onCollectionChange=function(){}},e.prototype.registerOnDisabledChange=function(t){this._onDisabledChange.push(t)},e.prototype._forEachChild=function(t){},e.prototype._syncPendingControls=function(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))},e.prototype._applyFormState=function(t){this._isBoxedValue(t)?(this.value=this._pendingValue=t.value,t.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=t},e}(jo),Mo=function(t){function e(e,n,r){var o=t.call(this,Io(n),Ro(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return Object(c.b)(e,t),e.prototype.registerControl=function(t,e){return this.controls[t]?this.controls[t]:(this.controls[t]=e,e.setParent(this),e._registerOnCollectionChange(this._onCollectionChange),e)},e.prototype.addControl=function(t,e){this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.removeControl=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),delete this.controls[t],e&&this.registerControl(t,e),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.contains=function(t){return this.controls.hasOwnProperty(t)&&this.controls[t].enabled},e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),Object.keys(t).forEach(function(r){n._throwIfControlMissing(r),n.controls[r].setValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),Object.keys(t).forEach(function(r){n.controls[r]&&n.controls[r].patchValue(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t={}),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this._reduceChildren({},function(t,e,n){return t[n]=e instanceof Vo?e.value:e.getRawValue(),t})},e.prototype._syncPendingControls=function(){var t=this._reduceChildren(!1,function(t,e){return!!e._syncPendingControls()||t});return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!Object.keys(this.controls).length)throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.controls[t])throw new Error("Cannot find form control with name: "+t+".")},e.prototype._forEachChild=function(t){var e=this;Object.keys(this.controls).forEach(function(n){return t(e.controls[n],n)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){e.setParent(t),e._registerOnCollectionChange(t._onCollectionChange)})},e.prototype._updateValue=function(){this.value=this._reduceValue()},e.prototype._anyControls=function(t){var e=this,n=!1;return this._forEachChild(function(r,o){n=n||e.contains(o)&&t(r)}),n},e.prototype._reduceValue=function(){var t=this;return this._reduceChildren({},function(e,n,r){return(n.enabled||t.disabled)&&(e[r]=n.value),e})},e.prototype._reduceChildren=function(t,e){var n=t;return this._forEachChild(function(t,r){n=e(n,t,r)}),n},e.prototype._allControlsDisabled=function(){for(var t=0,e=Object.keys(this.controls);t0||this.disabled},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control with name: '"+n+"'.")})},e}(jo),Fo=function(t){function e(e,n,r){var o=t.call(this,Io(n),Ro(r,n))||this;return o.controls=e,o._initObservables(),o._setUpdateStrategy(n),o._setUpControls(),o.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),o}return Object(c.b)(e,t),e.prototype.at=function(t){return this.controls[t]},e.prototype.push=function(t){this.controls.push(t),this._registerControl(t),this.updateValueAndValidity(),this._onCollectionChange()},e.prototype.insert=function(t,e){this.controls.splice(t,0,e),this._registerControl(e),this.updateValueAndValidity()},e.prototype.removeAt=function(t){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),this.updateValueAndValidity()},e.prototype.setControl=function(t,e){this.controls[t]&&this.controls[t]._registerOnCollectionChange(function(){}),this.controls.splice(t,1),e&&(this.controls.splice(t,0,e),this._registerControl(e)),this.updateValueAndValidity(),this._onCollectionChange()},Object.defineProperty(e.prototype,"length",{get:function(){return this.controls.length},enumerable:!0,configurable:!0}),e.prototype.setValue=function(t,e){var n=this;void 0===e&&(e={}),this._checkAllValuesPresent(t),t.forEach(function(t,r){n._throwIfControlMissing(r),n.at(r).setValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.patchValue=function(t,e){var n=this;void 0===e&&(e={}),t.forEach(function(t,r){n.at(r)&&n.at(r).patchValue(t,{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e)},e.prototype.reset=function(t,e){void 0===t&&(t=[]),void 0===e&&(e={}),this._forEachChild(function(n,r){n.reset(t[r],{onlySelf:!0,emitEvent:e.emitEvent})}),this.updateValueAndValidity(e),this._updatePristine(e),this._updateTouched(e)},e.prototype.getRawValue=function(){return this.controls.map(function(t){return t instanceof Vo?t.value:t.getRawValue()})},e.prototype._syncPendingControls=function(){var t=this.controls.reduce(function(t,e){return!!e._syncPendingControls()||t},!1);return t&&this.updateValueAndValidity({onlySelf:!0}),t},e.prototype._throwIfControlMissing=function(t){if(!this.controls.length)throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.at(t))throw new Error("Cannot find form control at index "+t)},e.prototype._forEachChild=function(t){this.controls.forEach(function(e,n){t(e,n)})},e.prototype._updateValue=function(){var t=this;this.value=this.controls.filter(function(e){return e.enabled||t.disabled}).map(function(t){return t.value})},e.prototype._anyControls=function(t){return this.controls.some(function(e){return e.enabled&&t(e)})},e.prototype._setUpControls=function(){var t=this;this._forEachChild(function(e){return t._registerControl(e)})},e.prototype._checkAllValuesPresent=function(t){this._forEachChild(function(e,n){if(void 0===t[n])throw new Error("Must supply a value for form control at index: "+n+".")})},e.prototype._allControlsDisabled=function(){for(var t=0,e=this.controls;t0||this.disabled},e.prototype._registerControl=function(t){t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange)},e}(jo),Lo=Promise.resolve(null),Bo=function(t){function e(e,n){var r=t.call(this)||this;return r.submitted=!1,r._directives=[],r.ngSubmit=new o.l,r.form=new Mo({},So(e),To(n)),r}return Object(c.b)(e,t),e.prototype.ngAfterViewInit=function(){this._setUpdateStrategy()},Object.defineProperty(e.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"controls",{get:function(){return this.form.controls},enumerable:!0,configurable:!0}),e.prototype.addControl=function(t){var e=this;Lo.then(function(){var n=e._findContainer(t.path);t.control=n.registerControl(t.name,t.control),bo(t.control,t),t.control.updateValueAndValidity({emitEvent:!1}),e._directives.push(t)})},e.prototype.getControl=function(t){return this.form.get(t.path)},e.prototype.removeControl=function(t){var e=this;Lo.then(function(){var n=e._findContainer(t.path);n&&n.removeControl(t.name),Ao(e._directives,t)})},e.prototype.addFormGroup=function(t){var e=this;Lo.then(function(){var n=e._findContainer(t.path),r=new Mo({});Eo(r,t),n.registerControl(t.name,r),r.updateValueAndValidity({emitEvent:!1})})},e.prototype.removeFormGroup=function(t){var e=this;Lo.then(function(){var n=e._findContainer(t.path);n&&n.removeControl(t.name)})},e.prototype.getFormGroup=function(t){return this.form.get(t.path)},e.prototype.updateModel=function(t,e){var n=this;Lo.then(function(){n.form.get(t.path).setValue(e)})},e.prototype.setValue=function(t){this.control.setValue(t)},e.prototype.onSubmit=function(t){return this.submitted=!0,ko(this.form,this._directives),this.ngSubmit.emit(t),!1},e.prototype.onReset=function(){this.resetForm()},e.prototype.resetForm=function(t){void 0===t&&(t=void 0),this.form.reset(t),this.submitted=!1},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)},e.prototype._findContainer=function(t){return t.pop(),t.length?this.form.get(t):this.form},e}(to),Ho='\n

\n \n
\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });',zo='\n
\n
\n \n
\n
\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });',Uo='\n
\n
\n \n
\n
',Yo=function(){function t(){}return t.modelParentException=function(){throw new Error('\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup\'s partner directive "formControlName" instead. Example:\n\n '+Ho+'\n\n Or, if you\'d like to avoid registering this form control, indicate that it\'s standalone in ngModelOptions:\n\n Example:\n\n \n
\n \n \n
\n ')},t.formGroupNameException=function(){throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n "+zo+"\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n "+Uo)},t.missingNameException=function(){throw new Error('If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as \'standalone\' in ngModelOptions.\n\n Example 1: \n Example 2: ')},t.modelGroupParentException=function(){throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n "+zo+"\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n "+Uo)},t}(),qo=function(t){function e(e,n,r){var o=t.call(this)||this;return o._parent=e,o._validators=n,o._asyncValidators=r,o}return Object(c.b)(e,t),e.prototype._checkParentType=function(){this._parent instanceof e||this._parent instanceof Bo||Yo.modelGroupParentException()},e}(Po),Xo=Promise.resolve(null),Go=function(t){function e(e,n,r,i){var s=t.call(this)||this;return s.control=new Vo,s._registered=!1,s.update=new o.l,s._parent=e,s._rawValidators=n||[],s._rawAsyncValidators=r||[],s.valueAccessor=function(t,e){if(!e)return null;var n=void 0,r=void 0,o=void 0;return e.forEach(function(e){var i;e.constructor===co?n=e:(i=e,Oo.some(function(t){return i.constructor===t})?(r&&xo(t,"More than one built-in value accessor matches form control with"),r=e):(o&&xo(t,"More than one custom value accessor matches form control with"),o=e))}),o||r||n||(xo(t,"No valid value accessor for form control with"),null)}(s,i),s}return Object(c.b)(e,t),e.prototype.ngOnChanges=function(t){this._checkForErrors(),this._registered||this._setUpControl(),"isDisabled"in t&&this._updateDisabled(t),function(t,e){if(!t.hasOwnProperty("model"))return!1;var n=t.model;return!!n.isFirstChange()||!Object(o._4)(e,n.currentValue)}(t,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)},e.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeControl(this)},Object.defineProperty(e.prototype,"path",{get:function(){return this._parent?vo(this.name,this._parent):[this.name]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"validator",{get:function(){return So(this._rawValidators)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"asyncValidator",{get:function(){return To(this._rawAsyncValidators)},enumerable:!0,configurable:!0}),e.prototype.viewToModelUpdate=function(t){this.viewModel=t,this.update.emit(t)},e.prototype._setUpControl=function(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0},e.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)},e.prototype._isStandalone=function(){return!this._parent||!(!this.options||!this.options.standalone)},e.prototype._setUpStandalone=function(){bo(this.control,this),this.control.updateValueAndValidity({emitEvent:!1})},e.prototype._checkForErrors=function(){this._isStandalone()||this._checkParentType(),this._checkName()},e.prototype._checkParentType=function(){!(this._parent instanceof qo)&&this._parent instanceof Po?Yo.formGroupNameException():this._parent instanceof qo||this._parent instanceof Bo||Yo.modelParentException()},e.prototype._checkName=function(){this.options&&this.options.name&&(this.name=this.options.name),this._isStandalone()||this.name||Yo.missingNameException()},e.prototype._updateValue=function(t){var e=this;Xo.then(function(){e.control.setValue(t,{emitViewToModelChange:!1})})},e.prototype._updateDisabled=function(t){var e=this,n=t.isDisabled.currentValue,r=""===n||n&&"false"!==n;Xo.then(function(){r&&!e.control.disabled?e.control.disable():!r&&e.control.disabled&&e.control.enable()})},e}(yo),Zo=function(){function t(){}return t.controlParentException=function(){throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n "+Ho)},t.ngModelGroupException=function(){throw new Error('formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a "form" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n '+zo+"\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n "+Uo)},t.missingFormException=function(){throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n "+Ho)},t.groupParentException=function(){throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n "+zo)},t.arrayParentException=function(){throw new Error('formArrayName must be used with a parent formGroup directive. You\'ll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n \n
\n
\n
\n \n
\n
\n
\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl(\'SF\')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });')},t.disabledAttrWarning=function(){console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n ")},t}(),Qo=function(t){function e(e,n){var r=t.call(this)||this;return r._validators=e,r._asyncValidators=n,r.submitted=!1,r.directives=[],r.form=null,r.ngSubmit=new o.l,r}return Object(c.b)(e,t),e.prototype.ngOnChanges=function(t){this._checkFormPresent(),t.hasOwnProperty("form")&&(this._updateValidators(),this._updateDomValue(),this._updateRegistrations())},Object.defineProperty(e.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),e.prototype.addControl=function(t){var e=this.form.get(t.path);return bo(e,t),e.updateValueAndValidity({emitEvent:!1}),this.directives.push(t),e},e.prototype.getControl=function(t){return this.form.get(t.path)},e.prototype.removeControl=function(t){Ao(this.directives,t)},e.prototype.addFormGroup=function(t){var e=this.form.get(t.path);Eo(e,t),e.updateValueAndValidity({emitEvent:!1})},e.prototype.removeFormGroup=function(t){},e.prototype.getFormGroup=function(t){return this.form.get(t.path)},e.prototype.addFormArray=function(t){var e=this.form.get(t.path);Eo(e,t),e.updateValueAndValidity({emitEvent:!1})},e.prototype.removeFormArray=function(t){},e.prototype.getFormArray=function(t){return this.form.get(t.path)},e.prototype.updateModel=function(t,e){this.form.get(t.path).setValue(e)},e.prototype.onSubmit=function(t){return this.submitted=!0,ko(this.form,this.directives),this.ngSubmit.emit(t),!1},e.prototype.onReset=function(){this.resetForm()},e.prototype.resetForm=function(t){void 0===t&&(t=void 0),this.form.reset(t),this.submitted=!1},e.prototype._updateDomValue=function(){var t=this;this.directives.forEach(function(e){var n=t.form.get(e.path);e.control!==n&&(function(t,e){e.valueAccessor.registerOnChange(function(){return Co(e)}),e.valueAccessor.registerOnTouched(function(){return Co(e)}),e._rawValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(null)}),e._rawAsyncValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(null)}),t&&t._clearChangeFns()}(e.control,e),n&&bo(n,e),e.control=n)}),this.form._updateTreeValidity({emitEvent:!1})},e.prototype._updateRegistrations=function(){var t=this;this.form._registerOnCollectionChange(function(){return t._updateDomValue()}),this._oldForm&&this._oldForm._registerOnCollectionChange(function(){}),this._oldForm=this.form},e.prototype._updateValidators=function(){var t=So(this._validators);this.form.validator=ro.compose([this.form.validator,t]);var e=To(this._asyncValidators);this.form.asyncValidator=ro.composeAsync([this.form.asyncValidator,e])},e.prototype._checkFormPresent=function(){this.form||Zo.missingFormException()},e}(to),Ko=function(){},Wo=function(){},$o=n("TILf"),Jo=n("N4j0"),ti=n("cQXm"),ei=n("etqZ"),ni=function(t){function e(e,n){if(t.call(this),this.scheduler=n,null==e)throw new Error("iterator cannot be null.");this.iterator=ii(e)}return Object(c.b)(e,t),e.create=function(t,n){return new e(t,n)},e.dispatch=function(t){var e=t.index,n=t.iterator,r=t.subscriber;if(t.hasError)r.error(t.error);else{var o=n.next();o.done?r.complete():(r.next(o.value),t.index=e+1,r.closed?"function"==typeof n.return&&n.return():this.schedule(t))}},e.prototype._subscribe=function(t){var n=this.iterator,r=this.scheduler;if(r)return r.schedule(e.dispatch,0,{index:0,iterator:n,subscriber:t});for(;;){var o=n.next();if(o.done){t.complete();break}if(t.next(o.value),t.closed){"function"==typeof n.return&&n.return();break}}},e}(j.a),ri=function(){function t(t,e,n){void 0===e&&(e=0),void 0===n&&(n=t.length),this.str=t,this.idx=e,this.len=n}return t.prototype[ei.a]=function(){return this},t.prototype.next=function(){return this.idxsi?si:o:o}()),this.arr=t,this.idx=e,this.len=n}return t.prototype[ei.a]=function(){return this},t.prototype.next=function(){return this.idx=t.length?r.complete():(r.next(e[n]),t.index=n+1,this.schedule(t)))},e.prototype._subscribe=function(t){var n=this.arrayLike,r=this.scheduler,o=n.length;if(r)return r.schedule(e.dispatch,0,{arrayLike:n,index:0,length:o,subscriber:t});for(var i=0;i1?new a.a(t,n):new Cn.a(n),e)}}var fi=function(){},mi="*";function yi(t,e){return void 0===e&&(e=null),{type:2,steps:t,options:e}}function _i(t){return{type:6,styles:t,offset:null}}function gi(t){Promise.resolve(null).then(t)}var vi=function(){function t(){this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this.parentPlayer=null,this.totalTime=0}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.onStart=function(t){this._onStartFns.push(t)},t.prototype.onDone=function(t){this._onDoneFns.push(t)},t.prototype.onDestroy=function(t){this._onDestroyFns.push(t)},t.prototype.hasStarted=function(){return this._started},t.prototype.init=function(){},t.prototype.play=function(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0},t.prototype.triggerMicrotask=function(){var t=this;gi(function(){return t._onFinish()})},t.prototype._onStart=function(){this._onStartFns.forEach(function(t){return t()}),this._onStartFns=[]},t.prototype.pause=function(){},t.prototype.restart=function(){},t.prototype.finish=function(){this._onFinish()},t.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(function(t){return t()}),this._onDestroyFns=[])},t.prototype.reset=function(){},t.prototype.setPosition=function(t){},t.prototype.getPosition=function(){return 0},t.prototype.triggerCallback=function(t){var e="start"==t?this._onStartFns:this._onDoneFns;e.forEach(function(t){return t()}),e.length=0},t}(),bi=function(){function t(t){var e=this;this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=t;var n=0,r=0,o=0,i=this.players.length;0==i?gi(function(){return e._onFinish()}):this.players.forEach(function(t){t.onDone(function(){++n==i&&e._onFinish()}),t.onDestroy(function(){++r==i&&e._onDestroy()}),t.onStart(function(){++o==i&&e._onStart()})}),this.totalTime=this.players.reduce(function(t,e){return Math.max(t,e.totalTime)},0)}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.init=function(){this.players.forEach(function(t){return t.init()})},t.prototype.onStart=function(t){this._onStartFns.push(t)},t.prototype._onStart=function(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(function(t){return t()}),this._onStartFns=[])},t.prototype.onDone=function(t){this._onDoneFns.push(t)},t.prototype.onDestroy=function(t){this._onDestroyFns.push(t)},t.prototype.hasStarted=function(){return this._started},t.prototype.play=function(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(function(t){return t.play()})},t.prototype.pause=function(){this.players.forEach(function(t){return t.pause()})},t.prototype.restart=function(){this.players.forEach(function(t){return t.restart()})},t.prototype.finish=function(){this._onFinish(),this.players.forEach(function(t){return t.finish()})},t.prototype.destroy=function(){this._onDestroy()},t.prototype._onDestroy=function(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(function(t){return t.destroy()}),this._onDestroyFns.forEach(function(t){return t()}),this._onDestroyFns=[])},t.prototype.reset=function(){this.players.forEach(function(t){return t.reset()}),this._destroyed=!1,this._finished=!1,this._started=!1},t.prototype.setPosition=function(t){var e=t*this.totalTime;this.players.forEach(function(t){var n=t.totalTime?Math.min(1,e/t.totalTime):1;t.setPosition(n)})},t.prototype.getPosition=function(){var t=0;return this.players.forEach(function(e){var n=e.getPosition();t=Math.min(n,t)}),t},t.prototype.beforeDestroy=function(){this.players.forEach(function(t){t.beforeDestroy&&t.beforeDestroy()})},t.prototype.triggerCallback=function(t){var e="start"==t?this._onStartFns:this._onDoneFns;e.forEach(function(t){return t()}),e.length=0},t}(),wi="!",Ei=function(){};function Ci(t){return Error("A hint was already declared for 'align=\""+t+"\"'.")}var xi=0,Si=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o._elementRef=e,o._changeDetectorRef=n,o._showAlwaysAnimate=!1,o._subscriptAnimationState="",o._hintLabel="",o._hintLabelId="mat-hint-"+xi++,o._labelOptions=r||{},o.floatLabel=o._labelOptions.float||"auto",o}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"dividerColor",{get:function(){return this.color},set:function(t){this.color=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hideRequiredMarker",{get:function(){return this._hideRequiredMarker},set:function(t){this._hideRequiredMarker=gt(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_shouldAlwaysFloat",{get:function(){return"always"===this._floatLabel&&!this._showAlwaysAnimate},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_canLabelFloat",{get:function(){return"never"!==this._floatLabel},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hintLabel",{get:function(){return this._hintLabel},set:function(t){this._hintLabel=t,this._processHints()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"floatPlaceholder",{get:function(){return this._floatLabel},set:function(t){this.floatLabel=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"floatLabel",{get:function(){return this._floatLabel},set:function(t){t!==this._floatLabel&&(this._floatLabel=t||this._labelOptions.float||"auto",this._changeDetectorRef.markForCheck())},enumerable:!0,configurable:!0}),e.prototype.ngAfterContentInit=function(){var t=this;this._validateControlChild(),this._control.controlType&&this._elementRef.nativeElement.classList.add("mat-form-field-type-"+this._control.controlType),this._control.stateChanges.pipe(di(null)).subscribe(function(){t._validatePlaceholders(),t._syncDescribedByIds(),t._changeDetectorRef.markForCheck()});var e=this._control.ngControl;e&&e.valueChanges&&e.valueChanges.subscribe(function(){t._changeDetectorRef.markForCheck()}),this._hintChildren.changes.pipe(di(null)).subscribe(function(){t._processHints(),t._changeDetectorRef.markForCheck()}),this._errorChildren.changes.pipe(di(null)).subscribe(function(){t._syncDescribedByIds(),t._changeDetectorRef.markForCheck()})},e.prototype.ngAfterContentChecked=function(){this._validateControlChild()},e.prototype.ngAfterViewInit=function(){this._subscriptAnimationState="enter",this._changeDetectorRef.detectChanges()},e.prototype._shouldForward=function(t){var e=this._control?this._control.ngControl:null;return e&&e[t]},e.prototype._hasPlaceholder=function(){return!(!this._control.placeholder&&!this._placeholderChild)},e.prototype._hasLabel=function(){return!!this._labelChild},e.prototype._shouldLabelFloat=function(){return this._canLabelFloat&&(this._control.shouldLabelFloat||this._control.shouldPlaceholderFloat||this._shouldAlwaysFloat)},e.prototype._hideControlPlaceholder=function(){return!this._hasLabel()||!this._shouldLabelFloat()},e.prototype._hasFloatingLabel=function(){return this._hasLabel()||this._hasPlaceholder()},e.prototype._getDisplayedMessages=function(){return this._errorChildren&&this._errorChildren.length>0&&this._control.errorState?"error":"hint"},e.prototype._animateAndLockLabel=function(){var t=this;this._hasFloatingLabel()&&this._canLabelFloat&&(this._showAlwaysAnimate=!0,this._floatLabel="always",$n(this._label.nativeElement,"transitionend").pipe(xn(1)).subscribe(function(){t._showAlwaysAnimate=!1}),this._changeDetectorRef.markForCheck())},e.prototype._validatePlaceholders=function(){if(this._control.placeholder&&this._placeholderChild)throw Error("Placeholder attribute and child element were both specified.")},e.prototype._processHints=function(){this._validateHints(),this._syncDescribedByIds()},e.prototype._validateHints=function(){var t,e,n=this;this._hintChildren&&this._hintChildren.forEach(function(r){if("start"===r.align){if(t||n.hintLabel)throw Ci("start");t=r}else if("end"===r.align){if(e)throw Ci("end");e=r}})},e.prototype._syncDescribedByIds=function(){if(this._control){var t=[];if("hint"===this._getDisplayedMessages()){var e=this._hintChildren?this._hintChildren.find(function(t){return"start"===t.align}):null,n=this._hintChildren?this._hintChildren.find(function(t){return"end"===t.align}):null;e?t.push(e.id):this._hintLabel&&t.push(this._hintLabelId),n&&t.push(n.id)}else this._errorChildren&&(t=this._errorChildren.map(function(t){return t.id}));this._control.setDescribedByIds(t)}},e.prototype._validateControlChild=function(){if(!this._control)throw Error("mat-form-field must contain a MatFormFieldControl.")},e}(hn(function(t){this._elementRef=t},"primary")),Ti=function(){},Oi=function(t){function e(e){t.call(this),this.observableFactory=e}return Object(c.b)(e,t),e.create=function(t){return new e(t)},e.prototype._subscribe=function(t){return new ki(t,this.observableFactory)},e}(j.a),ki=function(t){function e(e,n){t.call(this,e),this.factory=n,this.tryDefer()}return Object(c.b)(e,t),e.prototype.tryDefer=function(){try{this._callFactory()}catch(t){this._error(t)}},e.prototype._callFactory=function(){var t=this.factory();t&&this.add(Object(tr.a)(this,t))},e}(Jn.a),Ai=Oi.create,Pi="accent",Di="primary",Ii=["mat-button","mat-flat-button","mat-icon-button","mat-raised-button","mat-stroked-button","mat-mini-fab","mat-fab"],Ri=function(t){function e(e,n,r){var o=t.call(this,e)||this;o._platform=n,o._focusMonitor=r,o._isRoundButton=o._hasHostAttributes("mat-fab","mat-mini-fab"),o._isIconButton=o._hasHostAttributes("mat-icon-button");for(var i=0,s=Ii;i-1&&(this.openDialogs.splice(e,1),this.openDialogs.length||(this._ariaHiddenElements.forEach(function(t,e){t?e.setAttribute("aria-hidden",t):e.removeAttribute("aria-hidden")}),this._ariaHiddenElements.clear(),this._afterAllClosed.next()))},t.prototype._hideNonDialogContentFromAssistiveTechnology=function(){var t=this._overlayContainer.getContainerElement();if(t.parentElement)for(var e=t.parentElement.children,n=e.length-1;n>-1;n--){var r=e[n];r===t||"SCRIPT"===r.nodeName||"STYLE"===r.nodeName||r.hasAttribute("aria-live")||(this._ariaHiddenElements.set(r,r.getAttribute("aria-hidden")),r.setAttribute("aria-hidden","true"))}},t}(),qi=0,Xi=function(){function t(t,e,n){this.dialogRef=t,this._elementRef=e,this._dialog=n,this.ariaLabel="Close dialog"}return t.prototype.ngOnInit=function(){this.dialogRef||(this.dialogRef=Ki(this._elementRef,this._dialog.openDialogs))},t.prototype.ngOnChanges=function(t){var e=t._matDialogClose||t._matDialogCloseResult;e&&(this.dialogResult=e.currentValue)},t}(),Gi=function(){function t(t,e,n){this._dialogRef=t,this._elementRef=e,this._dialog=n,this.id="mat-dialog-title-"+qi++}return t.prototype.ngOnInit=function(){var t=this;this._dialogRef||(this._dialogRef=Ki(this._elementRef,this._dialog.openDialogs)),this._dialogRef&&Promise.resolve().then(function(){var e=t._dialogRef._containerInstance;e&&!e._ariaLabelledBy&&(e._ariaLabelledBy=t.id)})},t}(),Zi=function(){},Qi=function(){};function Ki(t,e){for(var n=t.nativeElement.parentElement;n&&!n.classList.contains("mat-dialog-container");)n=n.parentElement;return n?e.find(function(t){return t.id===n.id}):null}var Wi=function(){},$i=function(){function t(t){this.notifier=t}return t.prototype.call=function(t,e){return e.subscribe(new Ji(t,this.notifier))},t}(),Ji=function(t){function e(e,n){t.call(this,e),this.notifier=n,this.add(Object(tr.a)(this,n))}return Object(c.b)(e,t),e.prototype.notifyNext=function(t,e,n,r,o){this.complete()},e.prototype.notifyComplete=function(){},e}(Jn.a),ts=["button","checkbox","file","hidden","image","radio","range","reset","submit"],es=0,ns=function(t){function e(e,n,r,o,i,s,a){var l=t.call(this,s,o,i,r)||this;return l._elementRef=e,l._platform=n,l.ngControl=r,l._uid="mat-input-"+es++,l._isServer=!1,l.focused=!1,l.stateChanges=new vt.a,l.controlType="mat-input",l._disabled=!1,l.placeholder="",l._required=!1,l._type="text",l._readonly=!1,l._neverEmptyInputTypes=["date","datetime","datetime-local","month","time","week"].filter(function(t){return on().has(t)}),l._inputValueAccessor=a||l._elementRef.nativeElement,l._previousNativeValue=l.value,l.id=l.id,n.IOS&&e.nativeElement.addEventListener("keyup",function(t){var e=t.target;e.value||e.selectionStart||e.selectionEnd||(e.setSelectionRange(1,1),e.setSelectionRange(0,0))}),l._isServer=!l._platform.isBrowser,l}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"disabled",{get:function(){return this.ngControl&&null!==this.ngControl.disabled?this.ngControl.disabled:this._disabled},set:function(t){this._disabled=gt(t),this.focused&&(this.focused=!1,this.stateChanges.next())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},set:function(t){this._id=t||this._uid},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"required",{get:function(){return this._required},set:function(t){this._required=gt(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(t){this._type=t||"text",this._validateType(),!this._isTextarea()&&on().has(this._type)&&(this._elementRef.nativeElement.type=this._type)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._inputValueAccessor.value},set:function(t){t!==this.value&&(this._inputValueAccessor.value=t,this.stateChanges.next())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readonly",{get:function(){return this._readonly},set:function(t){this._readonly=gt(t)},enumerable:!0,configurable:!0}),e.prototype.ngOnChanges=function(){this.stateChanges.next()},e.prototype.ngOnDestroy=function(){this.stateChanges.complete()},e.prototype.ngDoCheck=function(){this.ngControl&&this.updateErrorState(),this._dirtyCheckNativeValue()},e.prototype.focus=function(){this._elementRef.nativeElement.focus()},e.prototype._focusChanged=function(t){t===this.focused||this.readonly||(this.focused=t,this.stateChanges.next())},e.prototype._onInput=function(){},e.prototype._dirtyCheckNativeValue=function(){var t=this.value;this._previousNativeValue!==t&&(this._previousNativeValue=t,this.stateChanges.next())},e.prototype._validateType=function(){if(ts.indexOf(this._type)>-1)throw Error('Input type "'+this._type+"\" isn't supported by matInput.")},e.prototype._isNeverEmpty=function(){return this._neverEmptyInputTypes.indexOf(this._type)>-1},e.prototype._isBadInput=function(){var t=this._elementRef.nativeElement.validity;return t&&t.badInput},e.prototype._isTextarea=function(){var t=this._elementRef.nativeElement,e=this._platform.isBrowser?t.nodeName:t.name;return!!e&&"textarea"===e.toLowerCase()},Object.defineProperty(e.prototype,"empty",{get:function(){return!this._isNeverEmpty()&&!this._elementRef.nativeElement.value&&!this._isBadInput()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shouldLabelFloat",{get:function(){return this.focused||!this.empty},enumerable:!0,configurable:!0}),e.prototype.setDescribedByIds=function(t){this._ariaDescribedby=t.join(" ")},e.prototype.onContainerClick=function(){this.focus()},e}(function(t){return function(t){function e(){for(var e=[],n=0;n0&&!this._renderChangeSubscription&&this._observeRenderChanges()},t.prototype.ngOnDestroy=function(){this._rowPlaceholder.viewContainer.clear(),this._headerRowPlaceholder.viewContainer.clear(),this._onDestroy.next(),this._onDestroy.complete(),this.dataSource instanceof ji&&this.dataSource.disconnect(this)},t.prototype.renderRows=function(){var t=this,e=this._dataDiffer.diff(this._data);if(e){var n=this._rowPlaceholder.viewContainer;e.forEachOperation(function(e,r,o){if(null==e.previousIndex)t._insertRow(e.item,o);else if(null==o)n.remove(r);else{var i=n.get(r);n.move(i,o)}}),this._updateRowIndexContext(),e.forEachIdentityChange(function(t){n.get(t.currentIndex).context.$implicit=t.item})}},t.prototype.setHeaderRowDef=function(t){this._headerRowDef=t,this._headerRowDefChanged=!0},t.prototype.addColumnDef=function(t){this._customColumnDefs.add(t)},t.prototype.removeColumnDef=function(t){this._customColumnDefs.delete(t)},t.prototype.addRowDef=function(t){this._customRowDefs.add(t)},t.prototype.removeRowDef=function(t){this._customRowDefs.delete(t)},t.prototype._cacheColumnDefs=function(){var t=this;this._columnDefsByName.clear();var e=this._contentColumnDefs?this._contentColumnDefs.toArray():[];this._customColumnDefs.forEach(function(t){return e.push(t)}),e.forEach(function(e){if(t._columnDefsByName.has(e.name))throw Error('Duplicate column definition name provided: "'+e.name+'".');t._columnDefsByName.set(e.name,e)})},t.prototype._cacheRowDefs=function(){var t=this;this._rowDefs=this._contentRowDefs?this._contentRowDefs.toArray():[],this._customRowDefs.forEach(function(e){return t._rowDefs.push(e)});var e=this._rowDefs.filter(function(t){return!t.when});if(e.length>1)throw Error("There can only be one default row without a when predicate function.");this._defaultRowDef=e[0]},t.prototype._renderUpdatedColumns=function(){var t=this;this._rowDefs.forEach(function(e){e.getColumnsDiff()&&(t._dataDiffer.diff([]),t._rowPlaceholder.viewContainer.clear(),t.renderRows())}),this._headerRowDef&&this._headerRowDef.getColumnsDiff()&&this._renderHeaderRow()},t.prototype._switchDataSource=function(t){this._data=[],this.dataSource instanceof ji&&this.dataSource.disconnect(this),this._renderChangeSubscription&&(this._renderChangeSubscription.unsubscribe(),this._renderChangeSubscription=null),t||(this._dataDiffer&&this._dataDiffer.diff([]),this._rowPlaceholder.viewContainer.clear()),this._dataSource=t},t.prototype._observeRenderChanges=function(){var t,e=this;if(this.dataSource){var n;if(this.dataSource.connect instanceof Function?n=this.dataSource.connect(this):this.dataSource instanceof j.a?n=this.dataSource:Array.isArray(this.dataSource)&&(n=l(this.dataSource)),void 0===n)throw Error("Provided data source did not match an array, Observable, or DataSource");this._renderChangeSubscription=n.pipe((t=this._onDestroy,function(e){return e.lift(new $i(t))})).subscribe(function(t){e._data=t,e.renderRows()})}},t.prototype._renderHeaderRow=function(){this._headerRowPlaceholder.viewContainer.length>0&&this._headerRowPlaceholder.viewContainer.clear();var t=this._getHeaderCellTemplatesForRow(this._headerRowDef);t.length&&(this._headerRowPlaceholder.viewContainer.createEmbeddedView(this._headerRowDef.template,{cells:t}),t.forEach(function(t){ds.mostRecentCellOutlet&&ds.mostRecentCellOutlet._viewContainer.createEmbeddedView(t.template,{})}),this._changeDetectorRef.markForCheck())},t.prototype._getRowDef=function(t,e){if(1==this._rowDefs.length)return this._rowDefs[0];var n=this._rowDefs.find(function(n){return n.when&&n.when(e,t)})||this._defaultRowDef;if(!n)throw Error("Could not find a matching row definition for the provided row data.");return n},t.prototype._insertRow=function(t,e){var n=this._getRowDef(t,e),r={$implicit:t};this._rowPlaceholder.viewContainer.createEmbeddedView(n.template,r,e),this._getCellTemplatesForRow(n).forEach(function(t){ds.mostRecentCellOutlet&&ds.mostRecentCellOutlet._viewContainer.createEmbeddedView(t.template,r)}),this._changeDetectorRef.markForCheck()},t.prototype._updateRowIndexContext=function(){for(var t=this._rowPlaceholder.viewContainer,e=0,n=t.length;e=r.length&&(o=0),r[o]},e.prototype.ngOnChanges=function(){this._stateChanges.next()},e.prototype.ngOnDestroy=function(){this._stateChanges.complete()},e}(cn(function(){})),Cs=function(){return function(){this.changes=new vt.a,this.sortButtonLabel=function(t){return"Change sorting for "+t},this.sortDescriptionLabel=function(t,e){return"Sorted by "+t+" "+("asc"==e?"ascending":"descending")}}}();function xs(t){return t||new Cs}var Ss=function(t){function e(e,n,r,o){var i=t.call(this)||this;if(i._intl=e,i._sort=r,i._cdkColumnDef=o,i._showIndicatorHint=!1,i._arrowDirection="",i._disableViewStateAnimation=!1,i.arrowPosition="after",!r)throw Error("MatSortHeader must be placed within a parent element with the MatSort directive.");return i._rerenderSubscription=Object(ar.a)(r.sortChange,r._stateChanges,e.changes).subscribe(function(){i._isSorted()&&i._updateArrowDirection(),!i._isSorted()&&i._viewState&&"active"===i._viewState.toState&&(i._disableViewStateAnimation=!1,i._setAnimationTransitionState({fromState:"active",toState:i._arrowDirection})),n.markForCheck()}),i}return Object(c.b)(e,t),Object.defineProperty(e.prototype,"disableClear",{get:function(){return this._disableClear},set:function(t){this._disableClear=gt(t)},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){!this.id&&this._cdkColumnDef&&(this.id=this._cdkColumnDef.name),this._updateArrowDirection(),this._setAnimationTransitionState({toState:this._isSorted()?"active":this._arrowDirection}),this._sort.register(this)},e.prototype.ngOnDestroy=function(){this._sort.deregister(this),this._rerenderSubscription.unsubscribe()},e.prototype._setIndicatorHintVisible=function(t){this._isDisabled()&&t||(this._showIndicatorHint=t,this._isSorted()||(this._updateArrowDirection(),this._setAnimationTransitionState(this._showIndicatorHint?{fromState:this._arrowDirection,toState:"hint"}:{fromState:"hint",toState:this._arrowDirection})))},e.prototype._setAnimationTransitionState=function(t){this._viewState=t,this._disableViewStateAnimation&&(this._viewState={toState:t.toState})},e.prototype._handleClick=function(){if(!this._isDisabled()){this._sort.sort(this),"hint"!==this._viewState.toState&&"active"!==this._viewState.toState||(this._disableViewStateAnimation=!0);var t=this._isSorted()?{fromState:this._arrowDirection,toState:"active"}:{fromState:"active",toState:this._arrowDirection};this._setAnimationTransitionState(t),this._showIndicatorHint=!1}},e.prototype._isSorted=function(){return this._sort.active==this.id&&("asc"===this._sort.direction||"desc"===this._sort.direction)},e.prototype._getArrowDirectionState=function(){return(this._isSorted()?"active-":"")+this._arrowDirection},e.prototype._getArrowViewState=function(){var t=this._viewState.fromState;return(t?t+"-to-":"")+this._viewState.toState},e.prototype._updateArrowDirection=function(){this._arrowDirection=this._isSorted()?this._sort.direction:this.start||this._sort.start},e.prototype._isDisabled=function(){return this._sort.disabled||this.disabled},e}(cn(function(){})),Ts=function(){},Os=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(bs),ks=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(fs),As=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(ms),Ps=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(ys),Ds=function(t){function e(e,n){var r=t.call(this,e,n)||this;return n.nativeElement.classList.add("mat-column-"+e.cssClassFriendlyName),r}return Object(c.b)(e,t),e}(function(t,e){e.nativeElement.classList.add("cdk-column-"+t.cssClassFriendlyName)}),Is=function(t){function e(e,n){var r=t.call(this,e,n)||this;return n.nativeElement.classList.add("mat-column-"+e.cssClassFriendlyName),r}return Object(c.b)(e,t),e}(function(t,e){e.nativeElement.classList.add("cdk-column-"+t.cssClassFriendlyName)}),Rs=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(hs),Ns=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(ps),js=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(function(){}),Vs=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e}(function(){}),Ms=function(){},Fs=function(t){function e(e,n,r){var o=t.call(this,e)||this;return o._platform=n,o._document=r,o}return Object(c.b)(e,t),e.prototype.ngAfterViewInit=function(){var t=this;Object(o.O)()&&this._platform.isBrowser&&(this._checkToolbarMixedModes(),this._toolbarRows.changes.subscribe(function(){return t._checkToolbarMixedModes()}))},e.prototype._checkToolbarMixedModes=function(){var t=this;this._toolbarRows.length&&[].slice.call(this._elementRef.nativeElement.childNodes).filter(function(t){return!(t.classList&&t.classList.contains("mat-toolbar-row"))}).filter(function(e){return e.nodeType!==(t._document?t._document.COMMENT_NODE:8)}).some(function(t){return t.textContent.trim()})&&function(){throw Error("MatToolbar: Attempting to combine different toolbar modes. Either specify multiple `` elements explicitly or just place content inside of a `` for a single row.")}()},e}(hn(function(t){this._elementRef=t})),Ls=function(){},Bs=function(){function t(t,e){this.dialog=t,this.torrentsService=e,this.title="app"}return t.prototype.openMagnet=function(){var t=this;this.dialog.open(Hs,{height:"220px",width:"450px"}).afterClosed().subscribe(function(e){e&&t.torrentsService.startFromMagnetLink(e)})},t}(),Hs=function(){function t(t){this.renderer=t}return t.prototype.submit=function(t){13===t.keyCode&&document.getElementById("start").click()},t}(),zs=o.W({encapsulation:2,styles:[".mat-dialog-container{box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12);display:block;padding:24px;border-radius:2px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%}@media screen and (-ms-high-contrast:active){.mat-dialog-container{outline:solid 1px}}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:12px 0;display:flex;flex-wrap:wrap;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button+.mat-button,.mat-dialog-actions .mat-button+.mat-raised-button,.mat-dialog-actions .mat-raised-button+.mat-button,.mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-button+.mat-raised-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:0;margin-right:8px}"],data:{animation:[{type:7,name:"slideDialog",definitions:[{type:0,name:"enter",styles:{type:6,styles:{transform:"none",opacity:1},offset:null},options:void 0},{type:0,name:"void",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0) scale(0.9)",opacity:0},offset:null},options:void 0},{type:0,name:"exit",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0)",opacity:0},offset:null},options:void 0},{type:1,expr:"* => *",animation:{type:4,styles:null,timings:"400ms cubic-bezier(0.25, 0.8, 0.25, 1)"},options:null}],options:{}}]}});function Us(t){return o._16(0,[(t()(),o.T(0,null,null,0))],null,null)}function Ys(t){return o._16(0,[o._13(402653184,1,{_portalOutlet:0}),(t()(),o.T(16777216,null,null,1,null,Us)),o.X(2,212992,[[1,4]],0,vr,[o.h,o.H],{portal:[0,"portal"]},null)],function(t,e){t(e,2,0,"")},null)}var qs=o.U("mat-dialog-container",Mi,function(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"mat-dialog-container",[["class","mat-dialog-container"],["tabindex","-1"]],[[1,"id",0],[1,"role",0],[1,"aria-labelledby",0],[1,"aria-label",0],[1,"aria-describedby",0],[40,"@slideDialog",0]],[["component","@slideDialog.start"],["component","@slideDialog.done"]],function(t,e,n){var r=!0;return"component:@slideDialog.start"===e&&(r=!1!==o._9(t,1)._onAnimationStart(n)&&r),"component:@slideDialog.done"===e&&(r=!1!==o._9(t,1)._onAnimationDone(n)&&r),r},Ys,zs)),o.X(1,49152,null,0,Mi,[o.i,jn,o.f,[2,N]],null,null)],null,function(t,e){t(e,0,0,o._9(e,1)._id,null==o._9(e,1)._config?null:o._9(e,1)._config.role,null!=o._9(e,1)._config&&o._9(e,1)._config.ariaLabel?null:o._9(e,1)._ariaLabelledBy,null==o._9(e,1)._config?null:o._9(e,1)._config.ariaLabel,(null==o._9(e,1)._config?null:o._9(e,1)._config.ariaDescribedBy)||null,o._9(e,1)._state)})},{},{},[]),Xs=o.W({encapsulation:2,styles:[".mat-toolbar-row,.mat-toolbar-single-row{display:flex;box-sizing:border-box;padding:0 16px;width:100%;flex-direction:row;align-items:center;white-space:nowrap}.mat-toolbar-multiple-rows{display:flex;box-sizing:border-box;flex-direction:column;width:100%}.mat-toolbar-multiple-rows{min-height:64px}.mat-toolbar-row,.mat-toolbar-single-row{height:64px}@media (max-width:599px){.mat-toolbar-multiple-rows{min-height:56px}.mat-toolbar-row,.mat-toolbar-single-row{height:56px}}"],data:{}});function Gs(t){return o._16(2,[o._8(null,0),o._8(null,1)],null,null)}var Zs=o.W({encapsulation:2,styles:[".mat-button,.mat-flat-button,.mat-icon-button,.mat-stroked-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px}.mat-button[disabled],.mat-flat-button[disabled],.mat-icon-button[disabled],.mat-stroked-button[disabled]{cursor:default}.mat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-button.cdk-program-focused .mat-button-focus-overlay,.mat-flat-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-flat-button.cdk-program-focused .mat-button-focus-overlay,.mat-icon-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-icon-button.cdk-program-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-stroked-button.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-button::-moz-focus-inner,.mat-flat-button::-moz-focus-inner,.mat-icon-button::-moz-focus-inner,.mat-stroked-button::-moz-focus-inner{border:0}.mat-button .mat-button-focus-overlay,.mat-icon-button .mat-button-focus-overlay{transition:none;opacity:0}.mat-button:hover .mat-button-focus-overlay,.mat-stroked-button:hover .mat-button-focus-overlay{opacity:1}.mat-raised-button{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1)}.mat-raised-button[disabled]{cursor:default}.mat-raised-button.cdk-keyboard-focused .mat-button-focus-overlay,.mat-raised-button.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-raised-button::-moz-focus-inner{border:0}.mat-raised-button:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-raised-button:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-raised-button[disabled]{box-shadow:none}.mat-stroked-button{border:1px solid currentColor;padding:0 15px;line-height:34px}.mat-stroked-button:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-flat-button:not([class*=mat-elevation-z]){box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:56px;height:56px;padding:0;flex-shrink:0}.mat-fab[disabled]{cursor:default}.mat-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-fab.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-fab::-moz-focus-inner{border:0}.mat-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-fab[disabled]{box-shadow:none}.mat-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-fab .mat-button-wrapper{padding:16px 0;display:inline-block;line-height:24px}.mat-mini-fab{box-sizing:border-box;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;outline:0;border:none;-webkit-tap-highlight-color:transparent;display:inline-block;white-space:nowrap;text-decoration:none;vertical-align:baseline;text-align:center;margin:0;min-width:88px;line-height:36px;padding:0 16px;border-radius:2px;transform:translate3d(0,0,0);transition:background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);min-width:0;border-radius:50%;width:40px;height:40px;padding:0;flex-shrink:0}.mat-mini-fab[disabled]{cursor:default}.mat-mini-fab.cdk-keyboard-focused .mat-button-focus-overlay,.mat-mini-fab.cdk-program-focused .mat-button-focus-overlay{opacity:1}.mat-mini-fab::-moz-focus-inner{border:0}.mat-mini-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-mini-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-mini-fab[disabled]{box-shadow:none}.mat-mini-fab:not([class*=mat-elevation-z]){box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-mini-fab:not([disabled]):active:not([class*=mat-elevation-z]){box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-mini-fab .mat-button-wrapper{padding:8px 0;display:inline-block;line-height:24px}.mat-icon-button{padding:0;min-width:0;width:40px;height:40px;flex-shrink:0;line-height:40px;border-radius:50%}.mat-icon-button .mat-icon,.mat-icon-button i{line-height:24px}.mat-button,.mat-fab,.mat-icon-button,.mat-mini-fab,.mat-raised-button{color:currentColor}.mat-button .mat-button-wrapper>*,.mat-fab .mat-button-wrapper>*,.mat-icon-button .mat-button-wrapper>*,.mat-mini-fab .mat-button-wrapper>*,.mat-raised-button .mat-button-wrapper>*{vertical-align:middle}.mat-button-focus-overlay,.mat-button-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-button-focus-overlay{background-color:rgba(0,0,0,.12);border-radius:inherit;opacity:0;transition:opacity .2s cubic-bezier(.35,0,.25,1),background-color .2s cubic-bezier(.35,0,.25,1)}@media screen and (-ms-high-contrast:active){.mat-button-focus-overlay{background-color:rgba(255,255,255,.5)}}.mat-button-ripple-round{border-radius:50%;z-index:1}@media screen and (-ms-high-contrast:active){.mat-button,.mat-fab,.mat-flat-button,.mat-icon-button,.mat-mini-fab,.mat-raised-button{outline:solid 1px}}"],data:{}});function Qs(t){return o._16(2,[o._13(402653184,1,{ripple:0}),(t()(),o.Y(1,0,null,null,1,"span",[["class","mat-button-wrapper"]],null,null,null,null,null)),o._8(null,0),(t()(),o.Y(3,0,null,null,1,"div",[["class","mat-button-ripple mat-ripple"],["matRipple",""]],[[2,"mat-button-ripple-round",null],[2,"mat-ripple-unbounded",null]],null,null,null,null)),o.X(4,212992,[[1,4]],0,vn,[o.i,o.u,en,[2,gn]],{centered:[0,"centered"],disabled:[1,"disabled"],trigger:[2,"trigger"]},null),(t()(),o.Y(5,0,null,null,0,"div",[["class","mat-button-focus-overlay"]],null,null,null,null,null))],function(t,e){var n=e.component;t(e,4,0,n._isIconButton,n._isRippleDisabled(),n._getHostElement())},function(t,e){var n=e.component;t(e,3,0,n._isRoundButton||n._isIconButton,o._9(e,4).unbounded)})}var Ks=o.W({encapsulation:2,styles:[".mat-sort-header-container{display:flex;cursor:pointer}.mat-sort-header-disabled .mat-sort-header-container{cursor:default}.mat-sort-header-position-before{flex-direction:row-reverse}.mat-sort-header-button{border:none;background:0 0;display:flex;align-items:center;padding:0;cursor:inherit;outline:0;font:inherit;color:currentColor}.mat-sort-header-arrow{height:12px;width:12px;min-width:12px;margin:0 0 0 6px;position:relative;display:flex}.mat-sort-header-position-before .mat-sort-header-arrow{margin:0 6px 0 0}.mat-sort-header-stem{background:currentColor;height:10px;width:2px;margin:auto;display:flex;align-items:center}.mat-sort-header-indicator{width:100%;height:2px;display:flex;align-items:center;position:absolute;top:0;left:0}.mat-sort-header-pointer-middle{margin:auto;height:2px;width:2px;background:currentColor;transform:rotate(45deg)}.mat-sort-header-pointer-left,.mat-sort-header-pointer-right{background:currentColor;width:6px;height:2px;position:absolute;top:0}.mat-sort-header-pointer-left{transform-origin:right;left:0}.mat-sort-header-pointer-right{transform-origin:left;right:0}"],data:{animation:[{type:7,name:"indicator",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"translateY(0px)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"translateY(10px)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"leftPointer",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"rotate(-45deg)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"rotate(45deg)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"rightPointer",definitions:[{type:0,name:"active-asc, asc",styles:{type:6,styles:{transform:"rotate(45deg)"},offset:null},options:void 0},{type:0,name:"active-desc, desc",styles:{type:6,styles:{transform:"rotate(-45deg)"},offset:null},options:void 0},{type:1,expr:"active-asc <=> active-desc",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"arrowOpacity",definitions:[{type:0,name:"desc-to-active, asc-to-active, active",styles:{type:6,styles:{opacity:1},offset:null},options:void 0},{type:0,name:"desc-to-hint, asc-to-hint, hint",styles:{type:6,styles:{opacity:.54},offset:null},options:void 0},{type:0,name:"hint-to-desc, active-to-desc, desc, hint-to-asc, active-to-asc, asc",styles:{type:6,styles:{opacity:0},offset:null},options:void 0},{type:1,expr:"* => asc, * => desc, * => active, * => hint",animation:{type:4,styles:null,timings:"0ms"},options:null},{type:1,expr:"* <=> *",animation:{type:4,styles:null,timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null}],options:{}},{type:7,name:"arrowPosition",definitions:[{type:1,expr:"* => desc-to-hint, * => desc-to-active",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(-25%)"},offset:null},{type:6,styles:{transform:"translateY(0)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => hint-to-desc, * => active-to-desc",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(0)"},offset:null},{type:6,styles:{transform:"translateY(25%)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => asc-to-hint, * => asc-to-active",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(25%)"},offset:null},{type:6,styles:{transform:"translateY(0)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:1,expr:"* => hint-to-asc, * => active-to-asc",animation:{type:4,styles:{type:5,steps:[{type:6,styles:{transform:"translateY(0)"},offset:null},{type:6,styles:{transform:"translateY(-25%)"},offset:null}]},timings:"225ms cubic-bezier(0.4,0.0,0.2,1)"},options:null},{type:0,name:"desc-to-hint, asc-to-hint, hint, desc-to-active, asc-to-active, active",styles:{type:6,styles:{transform:"translateY(0)"},offset:null},options:void 0},{type:0,name:"hint-to-desc, active-to-desc, desc",styles:{type:6,styles:{transform:"translateY(-25%)"},offset:null},options:void 0},{type:0,name:"hint-to-asc, active-to-asc, asc",styles:{type:6,styles:{transform:"translateY(25%)"},offset:null},options:void 0}],options:{}},{type:7,name:"allowChildren",definitions:[{type:1,expr:"* <=> *",animation:[{type:11,selector:"@*",animation:{type:9,options:null},options:{optional:!0}}],options:null}],options:{}}]}});function Ws(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"span",[["class","cdk-visually-hidden"]],null,null,null,null,null)),(t()(),o._15(1,null,["\xa0",""]))],null,function(t,e){var n=e.component;t(e,1,0,n._intl.sortDescriptionLabel(n.id,n._sort.direction))})}function $s(t){return o._16(2,[(t()(),o.Y(0,0,null,null,8,"div",[["class","mat-sort-header-container"]],[[2,"mat-sort-header-sorted",null],[2,"mat-sort-header-position-before",null]],null,null,null,null)),(t()(),o.Y(1,0,null,null,1,"button",[["class","mat-sort-header-button"],["type","button"]],[[1,"disabled",0],[1,"aria-label",0]],[[null,"focus"],[null,"blur"]],function(t,e,n){var r=!0,o=t.component;return"focus"===e&&(r=!1!==o._setIndicatorHintVisible(!0)&&r),"blur"===e&&(r=!1!==o._setIndicatorHintVisible(!1)&&r),r},null,null)),o._8(null,0),(t()(),o.Y(3,0,null,null,5,"div",[["class","mat-sort-header-arrow"]],[[24,"@arrowOpacity",0],[24,"@arrowPosition",0],[24,"@allowChildren",0]],[[null,"@arrowPosition.start"],[null,"@arrowPosition.done"]],function(t,e,n){var r=!0,o=t.component;return"@arrowPosition.start"===e&&(r=0!=(o._disableViewStateAnimation=!0)&&r),"@arrowPosition.done"===e&&(r=0!=(o._disableViewStateAnimation=!1)&&r),r},null,null)),(t()(),o.Y(4,0,null,null,0,"div",[["class","mat-sort-header-stem"]],null,null,null,null,null)),(t()(),o.Y(5,0,null,null,3,"div",[["class","mat-sort-header-indicator"]],[[24,"@indicator",0]],null,null,null,null)),(t()(),o.Y(6,0,null,null,0,"div",[["class","mat-sort-header-pointer-left"]],[[24,"@leftPointer",0]],null,null,null,null)),(t()(),o.Y(7,0,null,null,0,"div",[["class","mat-sort-header-pointer-right"]],[[24,"@rightPointer",0]],null,null,null,null)),(t()(),o.Y(8,0,null,null,0,"div",[["class","mat-sort-header-pointer-middle"]],null,null,null,null,null)),(t()(),o.T(16777216,null,null,1,null,Ws)),o.X(10,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null)],function(t,e){t(e,10,0,e.component._isSorted())},function(t,e){var n=e.component;t(e,0,0,n._isSorted(),"before"==n.arrowPosition),t(e,1,0,n._isDisabled()||null,n._intl.sortButtonLabel(n.id)),t(e,3,0,n._getArrowViewState(),n._getArrowViewState(),n._getArrowDirectionState()),t(e,5,0,n._getArrowDirectionState()),t(e,6,0,n._getArrowDirectionState()),t(e,7,0,n._getArrowDirectionState())})}var Js=o.W({encapsulation:2,styles:[".mat-table{display:block}.mat-header-row{min-height:56px}.mat-row{min-height:48px}.mat-header-row,.mat-row{display:flex;border-bottom-width:1px;border-bottom-style:solid;align-items:center;padding:0 24px;box-sizing:border-box}.mat-header-row::after,.mat-row::after{display:inline-block;min-height:inherit;content:''}.mat-cell,.mat-header-cell{flex:1;overflow:hidden;word-wrap:break-word}"],data:{}});function ta(t){return o._16(2,[o._13(402653184,1,{_rowPlaceholder:0}),o._13(402653184,2,{_headerRowPlaceholder:0}),(t()(),o.Y(2,16777216,null,null,1,null,null,null,null,null,null,null)),o.X(3,16384,[[2,4]],0,vs,[o.H],null,null),(t()(),o.Y(4,16777216,null,null,1,null,null,null,null,null,null,null)),o.X(5,16384,[[1,4]],0,gs,[o.H],null,null)],null,null)}var ea=o.W({encapsulation:2,styles:[],data:{}});function na(t){return o._16(2,[(t()(),o.Y(0,16777216,null,null,1,null,null,null,null,null,null,null)),o.X(1,16384,null,0,ds,[o.H],null,null)],null,null)}var ra=o.W({encapsulation:2,styles:[],data:{}});function oa(t){return o._16(2,[(t()(),o.Y(0,16777216,null,null,1,null,null,null,null,null,null,null)),o.X(1,16384,null,0,ds,[o.H],null,null)],null,null)}j.a.prototype.startWith=function(){for(var t=[],e=0;e0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},e}(Jn.a);function aa(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),function(t,e,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"number"==typeof e&&(n=e,e=null),function(r){return r.lift(new ia(t,e,n))}}(t,e,n)(this)}j.a.prototype.flatMapTo=aa,j.a.prototype.mergeMapTo=aa,j.a.timer=ir;var la=function(){function t(t){this.torrentsService=t,this.securityToken="",this.displayedColumns=["actions","name","infoHash","status","timeAdded","bytesDownloaded","bytesUploaded","totalBytes","totalBytesToDownload","downloadRate","uploadRate","numPeers"]}return t.prototype.ngOnInit=function(){var e=this;j.a.timer(0,t.REFRESH_RATE).mergeMapTo(this.torrentsService.getTorrents()).subscribe(function(t){return e.torrents=t});var n=document.cookie.split("; ").map(function(t){return t.split("=")}).filter(function(t){return"token"===t[0]})[0][1]||"";this.torrentsService.setSecurityHeaders((new F).set("Session-Token",n))},t.prototype.status=function(t){return r[t.status]},t.prototype.humanReadable=function(t,e){return void 0===e&&(e=["","k","M","G","T"]),t<900?this.fixed(t)+e[0]:e.length>1?this.humanReadable(t/1e3,e.slice(1)):this.fixed(t)+e[0]},t.prototype.fixed=function(t){return Math.round(100*t)/100},t.prototype.startTorrent=function(t){this.torrentsService.startTorrent(t)},t.prototype.pauseTorrent=function(t){this.torrentsService.stopTorrent(t)},t.prototype.removeTorrent=function(t){this.torrentsService.removeTorrent(t)},t.REFRESH_RATE=8e3,t}(),ua=o.W({encapsulation:0,styles:[[".mat-column-actions[_ngcontent-%COMP%]{-webkit-box-flex:10;-ms-flex:10 5 10px;flex:10 5 10px}.mat-column-actions[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{min-width:30px;padding:0}.mat-column-name[_ngcontent-%COMP%]{-webkit-box-flex:40;-ms-flex:40 10 60px;flex:40 10 60px}.mat-column-infoHash[_ngcontent-%COMP%]{-webkit-box-flex:20;-ms-flex:20 10 50px;flex:20 10 50px}.mat-column-status[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 50px;flex:5 10 50px}.mat-column-bytesDownloaded[_ngcontent-%COMP%], .mat-column-bytesUploaded[_ngcontent-%COMP%], .mat-column-bytesUploded[_ngcontent-%COMP%], .mat-column-timeAdded[_ngcontent-%COMP%], .mat-column-totalBytes[_ngcontent-%COMP%], .mat-column-totalBytesToDownload[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 20px;flex:5 10 20px}.mat-column-downloadRate[_ngcontent-%COMP%], .mat-column-numPeers[_ngcontent-%COMP%], .mat-column-seeders[_ngcontent-%COMP%], .mat-column-seedersTotal[_ngcontent-%COMP%], .mat-column-uploadRate[_ngcontent-%COMP%]{-webkit-box-flex:5;-ms-flex:5 10 10px;flex:5 10 10px}"]],data:{}});function ca(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Actions"]))],null,null)}function ha(t){return o._16(0,[(t()(),o.Y(0,0,null,null,20,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(-1,null,["\n \t"])),(t()(),o.Y(3,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.startTorrent(t.context.$implicit.infoHash)&&r),r},Qs,Zs)),o.X(4,180224,null,0,Ri,[o.i,en,qn],null,null),(t()(),o._15(-1,0,["\n \t\t"])),(t()(),o.Y(6,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),o._15(-1,null,["play_arrow"])),(t()(),o._15(-1,null,["\n \t"])),(t()(),o.Y(9,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.pauseTorrent(t.context.$implicit.infoHash)&&r),r},Qs,Zs)),o.X(10,180224,null,0,Ri,[o.i,en,qn],null,null),(t()(),o._15(-1,0,["\n \t\t"])),(t()(),o.Y(12,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),o._15(-1,null,["stop"])),(t()(),o._15(-1,null,["\n \t"])),(t()(),o.Y(15,0,null,null,4,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.removeTorrent(t.context.$implicit.infoHash)&&r),r},Qs,Zs)),o.X(16,180224,null,0,Ri,[o.i,en,qn],null,null),(t()(),o._15(-1,0,["\n \t\t"])),(t()(),o.Y(18,0,null,0,1,"i",[["class","material-icons"]],null,null,null,null,null)),(t()(),o._15(-1,null,["delete"])),(t()(),o._15(-1,null,["\n\t "]))],null,function(t,e){t(e,3,0,o._9(e,4).disabled||null),t(e,9,0,o._9(e,10).disabled||null),t(e,15,0,o._9(e,16).disabled||null)})}function pa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,3,"mat-header-cell",[["class","mat-header-cell"],["mat-sort-header",""],["role","columnheader"]],[[2,"mat-sort-header-disabled",null]],[[null,"click"],[null,"mouseenter"],[null,"longpress"],[null,"mouseleave"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==o._9(t,1)._handleClick()&&r),"mouseenter"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!0)&&r),"longpress"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!0)&&r),"mouseleave"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!1)&&r),r},$s,Ks)),o.X(1,245760,null,0,Ss,[Cs,o.f,[2,Es],[2,ys]],{id:[0,"id"]},null),o.X(2,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,0,["Name"]))],function(t,e){t(e,1,0,"")},function(t,e){t(e,0,0,o._9(e,1)._isDisabled())})}function da(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,["",""]))],null,function(t,e){t(e,2,0,e.context.$implicit.name)})}function fa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Info Hash"]))],null,null)}function ma(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" ",""]))],null,function(t,e){t(e,2,0,e.context.$implicit.infoHash)})}function ya(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Status"]))],null,null)}function _a(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.status(e.context.$implicit))})}function ga(t){return o._16(0,[(t()(),o.Y(0,0,null,null,3,"mat-header-cell",[["class","mat-header-cell"],["mat-sort-header",""],["role","columnheader"]],[[2,"mat-sort-header-disabled",null]],[[null,"click"],[null,"mouseenter"],[null,"longpress"],[null,"mouseleave"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==o._9(t,1)._handleClick()&&r),"mouseenter"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!0)&&r),"longpress"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!0)&&r),"mouseleave"===e&&(r=!1!==o._9(t,1)._setIndicatorHintVisible(!1)&&r),r},$s,Ks)),o.X(1,245760,null,0,Ss,[Cs,o.f,[2,Es],[2,ys]],{id:[0,"id"]},null),o.X(2,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,0,["Time Added"]))],function(t,e){t(e,1,0,"")},function(t,e){t(e,0,0,o._9(e,1)._isDisabled())})}function va(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.context.$implicit.timeAdded)})}function ba(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Bytes Downloaded"]))],null,null)}function wa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.bytesDownloaded))})}function Ea(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Bytes Uploaded"]))],null,null)}function Ca(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.bytesUploaded))})}function xa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Total Bytes"]))],null,null)}function Sa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.totalBytes))})}function Ta(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Done"]))],null,null)}function Oa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,["","%"]))],null,function(t,e){t(e,2,0,e.component.fixed(e.context.$implicit.percentDone))})}function ka(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Download Rate"]))],null,null)}function Aa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,["","B/s"]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.downloadRate))})}function Pa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Upload Rate"]))],null,null)}function Da(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,["","B/s"]))],null,function(t,e){t(e,2,0,e.component.humanReadable(e.context.$implicit.uploadRate))})}function Ia(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-header-cell",[["class","mat-header-cell"],["role","columnheader"]],null,null,null,null,null)),o.X(1,16384,null,0,Ds,[ys,o.i],null,null),(t()(),o._15(-1,null,["Peers"]))],null,null)}function Ra(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,"mat-cell",[["class","mat-cell"],["role","gridcell"]],null,null,null,null,null)),o.X(1,16384,null,0,Is,[ys,o.i],null,null),(t()(),o._15(2,null,[" "," "]))],null,function(t,e){t(e,2,0,e.context.$implicit.numPeers)})}function Na(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"mat-header-row",[["class","mat-header-row"],["role","row"]],null,null,null,na,ea)),o.X(1,49152,null,0,js,[],null,null)],null,null)}function ja(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"mat-row",[["class","mat-row"],["role","row"]],null,null,null,oa,ra)),o.X(1,49152,null,0,Vs,[],null,null)],null,null)}function Va(t){return o._16(0,[o._13(402653184,1,{sort:0}),(t()(),o.Y(1,0,null,null,197,"div",[["class","torrent-list mat-elevation-z8"]],null,null,null,null,null)),(t()(),o._15(-1,null,["\n "])),(t()(),o.Y(3,0,null,null,194,"mat-table",[["class","mat-table"],["matSort",""]],null,null,null,ta,Js)),o.X(4,671744,[[1,4]],0,Es,[],null,null),o.X(5,2342912,[["table",4]],3,Os,[o.p,o.f,o.i,[8,null]],{dataSource:[0,"dataSource"]},null),o._13(603979776,2,{_contentColumnDefs:1}),o._13(603979776,3,{_contentRowDefs:1}),o._13(335544320,4,{_headerRowDef:0}),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(10,0,null,null,13,null,null,null,null,null,null,null)),o.X(11,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,5,{cell:0}),o._13(335544320,6,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ca)),o.X(17,16384,null,0,As,[o.E],null,null),o._11(2048,[[6,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ha)),o.X(21,16384,null,0,ks,[o.E],null,null),o._11(2048,[[5,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(25,0,null,null,13,null,null,null,null,null,null,null)),o.X(26,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,7,{cell:0}),o._13(335544320,8,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,pa)),o.X(32,16384,null,0,As,[o.E],null,null),o._11(2048,[[8,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,da)),o.X(36,16384,null,0,ks,[o.E],null,null),o._11(2048,[[7,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(40,0,null,null,13,null,null,null,null,null,null,null)),o.X(41,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,9,{cell:0}),o._13(335544320,10,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,fa)),o.X(47,16384,null,0,As,[o.E],null,null),o._11(2048,[[10,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ma)),o.X(51,16384,null,0,ks,[o.E],null,null),o._11(2048,[[9,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(55,0,null,null,13,null,null,null,null,null,null,null)),o.X(56,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,11,{cell:0}),o._13(335544320,12,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ya)),o.X(62,16384,null,0,As,[o.E],null,null),o._11(2048,[[12,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,_a)),o.X(66,16384,null,0,ks,[o.E],null,null),o._11(2048,[[11,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(70,0,null,null,13,null,null,null,null,null,null,null)),o.X(71,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,13,{cell:0}),o._13(335544320,14,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ga)),o.X(77,16384,null,0,As,[o.E],null,null),o._11(2048,[[14,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,va)),o.X(81,16384,null,0,ks,[o.E],null,null),o._11(2048,[[13,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(85,0,null,null,13,null,null,null,null,null,null,null)),o.X(86,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,15,{cell:0}),o._13(335544320,16,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ba)),o.X(92,16384,null,0,As,[o.E],null,null),o._11(2048,[[16,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,wa)),o.X(96,16384,null,0,ks,[o.E],null,null),o._11(2048,[[15,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(100,0,null,null,13,null,null,null,null,null,null,null)),o.X(101,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,17,{cell:0}),o._13(335544320,18,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Ea)),o.X(107,16384,null,0,As,[o.E],null,null),o._11(2048,[[18,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Ca)),o.X(111,16384,null,0,ks,[o.E],null,null),o._11(2048,[[17,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(115,0,null,null,13,null,null,null,null,null,null,null)),o.X(116,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,19,{cell:0}),o._13(335544320,20,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,xa)),o.X(122,16384,null,0,As,[o.E],null,null),o._11(2048,[[20,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Sa)),o.X(126,16384,null,0,ks,[o.E],null,null),o._11(2048,[[19,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(130,0,null,null,13,null,null,null,null,null,null,null)),o.X(131,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,21,{cell:0}),o._13(335544320,22,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Ta)),o.X(137,16384,null,0,As,[o.E],null,null),o._11(2048,[[22,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Oa)),o.X(141,16384,null,0,ks,[o.E],null,null),o._11(2048,[[21,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(145,0,null,null,13,null,null,null,null,null,null,null)),o.X(146,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,23,{cell:0}),o._13(335544320,24,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ka)),o.X(152,16384,null,0,As,[o.E],null,null),o._11(2048,[[24,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Aa)),o.X(156,16384,null,0,ks,[o.E],null,null),o._11(2048,[[23,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(160,0,null,null,13,null,null,null,null,null,null,null)),o.X(161,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,25,{cell:0}),o._13(335544320,26,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Pa)),o.X(167,16384,null,0,As,[o.E],null,null),o._11(2048,[[26,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Da)),o.X(171,16384,null,0,ks,[o.E],null,null),o._11(2048,[[25,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.Y(175,0,null,null,13,null,null,null,null,null,null,null)),o.X(176,16384,null,2,Ps,[],{name:[0,"name"]},null),o._13(335544320,27,{cell:0}),o._13(335544320,28,{headerCell:0}),o._11(2048,[[2,4]],ys,null,[Ps]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Ia)),o.X(182,16384,null,0,As,[o.E],null,null),o._11(2048,[[28,4]],ms,null,[As]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,Ra)),o.X(186,16384,null,0,ks,[o.E],null,null),o._11(2048,[[27,4]],fs,null,[ks]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n\n "])),(t()(),o.T(0,null,null,2,null,Na)),o.X(191,540672,null,0,Rs,[o.E,o.p],{columns:[0,"columns"]},null),o._11(2048,[[4,4]],hs,null,[Rs]),(t()(),o._15(-1,null,["\n "])),(t()(),o.T(0,null,null,2,null,ja)),o.X(195,540672,null,0,Ns,[o.E,o.p],{columns:[0,"columns"]},null),o._11(2048,[[3,4]],ps,null,[Ns]),(t()(),o._15(-1,null,["\n "])),(t()(),o._15(-1,null,["\n"]))],function(t,e){var n=e.component;t(e,5,0,n.torrents),t(e,11,0,"actions"),t(e,26,0,"name"),t(e,41,0,"infoHash"),t(e,56,0,"status"),t(e,71,0,"timeAdded"),t(e,86,0,"bytesDownloaded"),t(e,101,0,"bytesUploaded"),t(e,116,0,"totalBytes"),t(e,131,0,"totalBytesToDownload"),t(e,146,0,"downloadRate"),t(e,161,0,"uploadRate"),t(e,176,0,"numPeers"),t(e,191,0,n.displayedColumns),t(e,195,0,n.displayedColumns)},null)}var Ma=o.W({encapsulation:2,styles:[".mat-form-field{display:inline-block;position:relative;text-align:left}[dir=rtl] .mat-form-field{text-align:right}.mat-form-field-wrapper{position:relative}.mat-form-field-flex{display:inline-flex;align-items:baseline;width:100%}.mat-form-field-prefix,.mat-form-field-suffix{white-space:nowrap;flex:none}.mat-form-field-prefix .mat-icon,.mat-form-field-suffix .mat-icon{width:1em}.mat-form-field-prefix .mat-icon-button,.mat-form-field-suffix .mat-icon-button{font:inherit;vertical-align:baseline}.mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-suffix .mat-icon-button .mat-icon{font-size:inherit}.mat-form-field-infix{display:block;position:relative;flex:auto;min-width:0;width:180px}.mat-form-field-label-wrapper{position:absolute;left:0;box-sizing:content-box;width:100%;height:100%;overflow:hidden;pointer-events:none}.mat-form-field-label{position:absolute;left:0;font:inherit;pointer-events:none;width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;transform:perspective(100px);-ms-transform:none;transform-origin:0 0;transition:transform .4s cubic-bezier(.25,.8,.25,1),color .4s cubic-bezier(.25,.8,.25,1),width .4s cubic-bezier(.25,.8,.25,1);display:none}[dir=rtl] .mat-form-field-label{transform-origin:100% 0;left:auto;right:0}.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label,.mat-form-field-empty.mat-form-field-label{display:block}.mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:none}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{display:block;transition:none}.mat-input-server:focus+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder,.mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder{display:none}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder,.mat-form-field-can-float .mat-input-server[placeholder]:not(:placeholder-shown)+.mat-form-field-placeholder-wrapper .mat-form-field-placeholder{display:block}.mat-form-field-label:not(.mat-form-field-empty){transition:none}.mat-form-field-underline{position:absolute;height:1px;width:100%}.mat-form-field-disabled .mat-form-field-underline{background-position:0;background-color:transparent}.mat-form-field-underline .mat-form-field-ripple{position:absolute;top:0;left:0;width:100%;height:2px;transform-origin:50%;transform:scaleX(.5);visibility:hidden;opacity:0;transition:background-color .3s cubic-bezier(.55,0,.55,.2)}.mat-form-field-invalid:not(.mat-focused) .mat-form-field-underline .mat-form-field-ripple{height:1px}.mat-focused .mat-form-field-underline .mat-form-field-ripple,.mat-form-field-invalid .mat-form-field-underline .mat-form-field-ripple{visibility:visible;opacity:1;transform:scaleX(1);transition:transform .3s cubic-bezier(.25,.8,.25,1),opacity .1s cubic-bezier(.25,.8,.25,1),background-color .3s cubic-bezier(.25,.8,.25,1)}.mat-form-field-subscript-wrapper{position:absolute;width:100%;overflow:hidden}.mat-form-field-label-wrapper .mat-icon,.mat-form-field-subscript-wrapper .mat-icon{width:1em;height:1em;font-size:inherit;vertical-align:baseline}.mat-form-field-hint-wrapper{display:flex}.mat-form-field-hint-spacer{flex:1 0 1em}.mat-error{display:block}",".mat-input-element{font:inherit;background:0 0;color:currentColor;border:none;outline:0;padding:0;margin:0;width:100%;max-width:100%;vertical-align:bottom;text-align:inherit}.mat-input-element:-moz-ui-invalid{box-shadow:none}.mat-input-element::-ms-clear,.mat-input-element::-ms-reveal{display:none}.mat-input-element[type=date]::after,.mat-input-element[type=datetime-local]::after,.mat-input-element[type=datetime]::after,.mat-input-element[type=month]::after,.mat-input-element[type=time]::after,.mat-input-element[type=week]::after{content:' ';white-space:pre;width:1px}.mat-input-element::placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element::-moz-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element::-webkit-input-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-input-element:-ms-input-placeholder{transition:color .4s .133s cubic-bezier(.25,.8,.25,1)}.mat-form-field-hide-placeholder .mat-input-element::placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element::-moz-placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element::-webkit-input-placeholder{color:transparent!important;transition:none}.mat-form-field-hide-placeholder .mat-input-element:-ms-input-placeholder{color:transparent!important;transition:none}textarea.mat-input-element{resize:vertical;overflow:auto}textarea.mat-autosize{resize:none}"],data:{animation:[{type:7,name:"transitionMessages",definitions:[{type:0,name:"enter",styles:{type:6,styles:{opacity:1,transform:"translateY(0%)"},offset:null},options:void 0},{type:1,expr:"void => enter",animation:[{type:6,styles:{opacity:0,transform:"translateY(-100%)"},offset:null},{type:4,styles:null,timings:"300ms cubic-bezier(0.55, 0, 0.55, 0.2)"}],options:null}],options:{}}]}});function Fa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"div",[["class","mat-input-prefix mat-form-field-prefix"]],null,null,null,null,null)),o._8(null,0)],null,null)}function La(t){return o._16(0,[(t()(),o.Y(0,0,null,null,2,null,null,null,null,null,null,null)),o._8(null,2),(t()(),o._15(2,null,["",""]))],null,function(t,e){t(e,2,0,e.component._control.placeholder)})}function Ba(t){return o._16(0,[o._8(null,3),(t()(),o.T(0,null,null,0))],null,null)}function Ha(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"span",[["aria-hidden","true"],["class","mat-placeholder-required mat-form-field-required-marker"]],null,null,null,null,null)),(t()(),o._15(-1,null,["\xa0*"]))],null,null)}function za(t){return o._16(0,[(t()(),o.Y(0,0,[[4,0],["label",1]],null,7,"label",[["class","mat-form-field-label mat-input-placeholder mat-form-field-placeholder"]],[[1,"for",0],[1,"aria-owns",0],[2,"mat-empty",null],[2,"mat-form-field-empty",null],[2,"mat-accent",null],[2,"mat-warn",null]],null,null,null,null)),o.X(1,16384,null,0,D,[],{ngSwitch:[0,"ngSwitch"]},null),(t()(),o.T(16777216,null,null,1,null,La)),o.X(3,278528,null,0,I,[o.H,o.E,D],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),o.T(16777216,null,null,1,null,Ba)),o.X(5,278528,null,0,I,[o.H,o.E,D],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),o.T(16777216,null,null,1,null,Ha)),o.X(7,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null)],function(t,e){var n=e.component;t(e,1,0,n._hasLabel()),t(e,3,0,!1),t(e,5,0,!0),t(e,7,0,!n.hideRequiredMarker&&n._control.required&&!n._control.disabled)},function(t,e){var n=e.component;t(e,0,0,n._control.id,n._control.id,n._control.empty&&!n._shouldAlwaysFloat,n._control.empty&&!n._shouldAlwaysFloat,"accent"==n.color,"warn"==n.color)})}function Ua(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"div",[["class","mat-input-suffix mat-form-field-suffix"]],null,null,null,null,null)),o._8(null,4)],null,null)}function Ya(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"div",[],[[24,"@transitionMessages",0]],null,null,null,null)),o._8(null,5)],null,function(t,e){t(e,0,0,e.component._subscriptAnimationState)})}function qa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"div",[["class","mat-hint"]],[[8,"id",0]],null,null,null,null)),(t()(),o._15(1,null,["",""]))],null,function(t,e){var n=e.component;t(e,0,0,n._hintLabelId),t(e,1,0,n.hintLabel)})}function Xa(t){return o._16(0,[(t()(),o.Y(0,0,null,null,5,"div",[["class","mat-input-hint-wrapper mat-form-field-hint-wrapper"]],[[24,"@transitionMessages",0]],null,null,null,null)),(t()(),o.T(16777216,null,null,1,null,qa)),o.X(2,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null),o._8(null,6),(t()(),o.Y(4,0,null,null,0,"div",[["class","mat-input-hint-spacer mat-form-field-hint-spacer"]],null,null,null,null,null)),o._8(null,7)],function(t,e){t(e,2,0,e.component.hintLabel)},function(t,e){t(e,0,0,e.component._subscriptAnimationState)})}function Ga(t){return o._16(2,[o._13(402653184,1,{underlineRef:0}),o._13(402653184,2,{_connectionContainerRef:0}),o._13(402653184,3,{_inputContainerRef:0}),o._13(671088640,4,{_label:0}),(t()(),o.Y(4,0,null,null,18,"div",[["class","mat-input-wrapper mat-form-field-wrapper"]],null,null,null,null,null)),(t()(),o.Y(5,0,[[2,0],["connectionContainer",1]],null,9,"div",[["class","mat-input-flex mat-form-field-flex"]],null,[[null,"click"]],function(t,e,n){var r=!0,o=t.component;return"click"===e&&(r=!1!==(o._control.onContainerClick&&o._control.onContainerClick(n))&&r),r},null,null)),(t()(),o.T(16777216,null,null,1,null,Fa)),o.X(7,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null),(t()(),o.Y(8,0,[[3,0],["inputContainer",1]],null,4,"div",[["class","mat-input-infix mat-form-field-infix"]],null,null,null,null,null)),o._8(null,1),(t()(),o.Y(10,0,null,null,2,"span",[["class","mat-form-field-label-wrapper mat-input-placeholder-wrapper mat-form-field-placeholder-wrapper"]],null,null,null,null,null)),(t()(),o.T(16777216,null,null,1,null,za)),o.X(12,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null),(t()(),o.T(16777216,null,null,1,null,Ua)),o.X(14,16384,null,0,k,[o.H,o.E],{ngIf:[0,"ngIf"]},null),(t()(),o.Y(15,0,[[1,0],["underline",1]],null,1,"div",[["class","mat-input-underline mat-form-field-underline"]],null,null,null,null,null)),(t()(),o.Y(16,0,null,null,0,"span",[["class","mat-input-ripple mat-form-field-ripple"]],[[2,"mat-accent",null],[2,"mat-warn",null]],null,null,null,null)),(t()(),o.Y(17,0,null,null,5,"div",[["class","mat-input-subscript-wrapper mat-form-field-subscript-wrapper"]],null,null,null,null,null)),o.X(18,16384,null,0,D,[],{ngSwitch:[0,"ngSwitch"]},null),(t()(),o.T(16777216,null,null,1,null,Ya)),o.X(20,278528,null,0,I,[o.H,o.E,D],{ngSwitchCase:[0,"ngSwitchCase"]},null),(t()(),o.T(16777216,null,null,1,null,Xa)),o.X(22,278528,null,0,I,[o.H,o.E,D],{ngSwitchCase:[0,"ngSwitchCase"]},null)],function(t,e){var n=e.component;t(e,7,0,n._prefixChildren.length),t(e,12,0,n._hasFloatingLabel()),t(e,14,0,n._suffixChildren.length),t(e,18,0,n._getDisplayedMessages()),t(e,20,0,"error"),t(e,22,0,"hint")},function(t,e){var n=e.component;t(e,16,0,"accent"==n.color,"warn"==n.color)})}var Za=o.W({encapsulation:0,styles:[[""]],data:{}});function Qa(t){return o._16(0,[(t()(),o._15(-1,null,["\n"])),(t()(),o.Y(1,0,null,null,6,"mat-toolbar",[["class","mat-toolbar"]],[[2,"mat-toolbar-multiple-rows",null],[2,"mat-toolbar-single-row",null]],null,null,Gs,Xs)),o.X(2,4243456,null,1,Fs,[o.i,en,N],null,null),o._13(603979776,1,{_toolbarRows:1}),(t()(),o._15(-1,0,["\n "])),(t()(),o.Y(5,0,null,0,1,"span",[],null,null,null,null,null)),(t()(),o._15(-1,null,["KTorrent HTML interface"])),(t()(),o._15(-1,0,["\n"])),(t()(),o._15(-1,null,["\n\n"])),(t()(),o.Y(9,0,null,null,2,"button",[["mat-button",""]],[[8,"disabled",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==t.component.openMagnet()&&r),r},Qs,Zs)),o.X(10,180224,null,0,Ri,[o.i,en,qn],null,null),(t()(),o._15(-1,0,["Magnet link"])),(t()(),o._15(-1,null,["\n\n"])),(t()(),o.Y(13,0,null,null,1,"app-torrent-list",[],null,null,null,Va,ua)),o.X(14,114688,null,0,la,[ft],null,null),(t()(),o._15(-1,null,["\n\n"]))],function(t,e){t(e,14,0)},function(t,e){t(e,1,0,o._9(e,2)._toolbarRows.length,!o._9(e,2)._toolbarRows.length),t(e,9,0,o._9(e,10).disabled||null)})}var Ka=o.U("app-root",Bs,function(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"app-root",[],null,null,null,Qa,Za)),o.X(1,49152,null,0,Bs,[Yi,ft],null,null)],null,null)},{},{},[]),Wa=o.W({encapsulation:0,styles:["mat-form-field[_ngcontent-%COMP%] {\n width: 100%;\n}"],data:{}});function $a(t){return o._16(0,[(t()(),o.Y(0,0,null,null,43,"div",[],null,[[null,"keydown"]],function(t,e,n){var r=!0;return"keydown"===e&&(r=!1!==t.component.submit(n)&&r),r},null,null)),(t()(),o._15(-1,null,["\n\t"])),(t()(),o.Y(2,0,null,null,2,"h2",[["class","mat-dialog-title"],["mat-dialog-title",""]],[[8,"id",0]],null,null,null,null)),o.X(3,81920,null,0,Gi,[[2,Li],o.i,Yi],null,null),(t()(),o._15(-1,null,["New torrent from magnet link"])),(t()(),o._15(-1,null,["\n\t"])),(t()(),o.Y(6,0,null,null,2,"mat-dialog-content",[["class","mat-dialog-content"]],null,null,null,null,null)),o.X(7,16384,null,0,Zi,[],null,null),(t()(),o._15(-1,null,["Enter magnet link"])),(t()(),o._15(-1,null,["\n\t"])),(t()(),o.Y(10,0,null,null,18,"mat-form-field",[["class","mat-input-container mat-form-field"]],[[2,"mat-input-invalid",null],[2,"mat-form-field-invalid",null],[2,"mat-form-field-can-float",null],[2,"mat-form-field-should-float",null],[2,"mat-form-field-hide-placeholder",null],[2,"mat-form-field-disabled",null],[2,"mat-focused",null],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],null,null,Ga,Ma)),o.X(11,7389184,null,7,Si,[o.i,o.f,[2,wn]],null,null),o._13(335544320,1,{_control:0}),o._13(335544320,2,{_placeholderChild:0}),o._13(335544320,3,{_labelChild:0}),o._13(603979776,4,{_errorChildren:1}),o._13(603979776,5,{_hintChildren:1}),o._13(603979776,6,{_prefixChildren:1}),o._13(603979776,7,{_suffixChildren:1}),(t()(),o._15(-1,1,["\n\t\t"])),(t()(),o.Y(20,0,null,1,7,"input",[["class","mat-input-element mat-form-field-autofill-control"],["matInput",""],["placeholder","Magnet link"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null],[2,"mat-input-server",null],[1,"id",0],[8,"placeholder",0],[8,"disabled",0],[8,"required",0],[8,"readOnly",0],[1,"aria-describedby",0],[1,"aria-invalid",0],[1,"aria-required",0]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"focus"]],function(t,e,n){var r=!0,i=t.component;return"input"===e&&(r=!1!==o._9(t,21)._handleInput(n.target.value)&&r),"blur"===e&&(r=!1!==o._9(t,21).onTouched()&&r),"compositionstart"===e&&(r=!1!==o._9(t,21)._compositionStart()&&r),"compositionend"===e&&(r=!1!==o._9(t,21)._compositionEnd(n.target.value)&&r),"blur"===e&&(r=!1!==o._9(t,26)._focusChanged(!1)&&r),"focus"===e&&(r=!1!==o._9(t,26)._focusChanged(!0)&&r),"input"===e&&(r=!1!==o._9(t,26)._onInput()&&r),"ngModelChange"===e&&(r=!1!==(i.magnet=n)&&r),r},null,null)),o.X(21,16384,null,0,co,[o.y,o.i,[2,uo]],null,null),o._11(1024,null,ao,function(t){return[t]},[co]),o.X(23,671744,null,0,Go,[[8,null],[8,null],[8,null],[2,ao]],{model:[0,"model"]},{update:"ngModelChange"}),o._11(2048,null,yo,null,[Go]),o.X(25,16384,null,0,Do,[yo],null,null),o.X(26,933888,null,0,ns,[o.i,en,[2,yo],[2,Bo],[2,Qo],pn,[8,null]],{placeholder:[0,"placeholder"]},null),o._11(2048,[[1,4]],Ei,null,[ns]),(t()(),o._15(-1,1,["\n\t"])),(t()(),o._15(-1,null,["\n\t"])),(t()(),o.Y(30,0,null,null,12,"mat-dialog-actions",[["class","mat-dialog-actions"]],null,null,null,null,null)),o.X(31,16384,null,0,Qi,[],null,null),(t()(),o._15(-1,null,["\n\t "])),(t()(),o.Y(33,0,null,null,3,"button",[["id","start"],["mat-button",""],["type","button"]],[[8,"disabled",0],[1,"aria-label",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==o._9(t,35).dialogRef.close(o._9(t,35).dialogResult)&&r),r},Qs,Zs)),o.X(34,180224,null,0,Ri,[o.i,en,qn],null,null),o.X(35,606208,null,0,Xi,[[2,Li],o.i,Yi],{dialogResult:[0,"dialogResult"]},null),(t()(),o._15(-1,0,["Start torrent"])),(t()(),o._15(-1,null,["\n\t "])),(t()(),o.Y(38,0,null,null,3,"button",[["mat-button",""],["type","button"]],[[8,"disabled",0],[1,"aria-label",0]],[[null,"click"]],function(t,e,n){var r=!0;return"click"===e&&(r=!1!==o._9(t,40).dialogRef.close(o._9(t,40).dialogResult)&&r),r},Qs,Zs)),o.X(39,180224,null,0,Ri,[o.i,en,qn],null,null),o.X(40,606208,null,0,Xi,[[2,Li],o.i,Yi],{dialogResult:[0,"dialogResult"]},null),(t()(),o._15(-1,0,["Cancel"])),(t()(),o._15(-1,null,["\n\t"])),(t()(),o._15(-1,null,["\n"])),(t()(),o._15(-1,null,["\n"]))],function(t,e){var n=e.component;t(e,3,0),t(e,23,0,n.magnet),t(e,26,0,"Magnet link"),t(e,35,0,n.magnet),t(e,40,0,!1)},function(t,e){t(e,2,0,o._9(e,3).id),t(e,10,1,[o._9(e,11)._control.errorState,o._9(e,11)._control.errorState,o._9(e,11)._canLabelFloat,o._9(e,11)._shouldLabelFloat(),o._9(e,11)._hideControlPlaceholder(),o._9(e,11)._control.disabled,o._9(e,11)._control.focused,o._9(e,11)._shouldForward("untouched"),o._9(e,11)._shouldForward("touched"),o._9(e,11)._shouldForward("pristine"),o._9(e,11)._shouldForward("dirty"),o._9(e,11)._shouldForward("valid"),o._9(e,11)._shouldForward("invalid"),o._9(e,11)._shouldForward("pending")]),t(e,20,1,[o._9(e,25).ngClassUntouched,o._9(e,25).ngClassTouched,o._9(e,25).ngClassPristine,o._9(e,25).ngClassDirty,o._9(e,25).ngClassValid,o._9(e,25).ngClassInvalid,o._9(e,25).ngClassPending,o._9(e,26)._isServer,o._9(e,26).id,o._9(e,26).placeholder,o._9(e,26).disabled,o._9(e,26).required,o._9(e,26).readonly,o._9(e,26)._ariaDescribedby||null,o._9(e,26).errorState,o._9(e,26).required.toString()]),t(e,33,0,o._9(e,34).disabled||null,o._9(e,35).ariaLabel),t(e,38,0,o._9(e,39).disabled||null,o._9(e,40).ariaLabel)})}var Ja=o.U("app-magnet-dialog",Hs,function(t){return o._16(0,[(t()(),o.Y(0,0,null,null,1,"app-magnet-dialog",[],null,null,null,$a,Wa)),o.X(1,49152,null,0,Hs,[o.y],null,null)],null,null)},{},{},[]);function tl(t){switch(t.length){case 0:return new vi;case 1:return t[0];default:return new bi(t)}}function el(t,e,n,r,o,i){void 0===o&&(o={}),void 0===i&&(i={});var s=[],a=[],l=-1,u=null;if(r.forEach(function(t){var n=t.offset,r=n==l,c=r&&u||{};Object.keys(t).forEach(function(n){var r=n,a=t[n];if("offset"!==n)switch(r=e.normalizePropertyName(r,s),a){case wi:a=o[n];break;case mi:a=i[n];break;default:a=e.normalizeStyleValue(n,r,a,s)}c[r]=a}),r||a.push(c),u=c,l=n}),s.length)throw new Error("Unable to animate due to the following errors:\n - "+s.join("\n - "));return a}function nl(t,e,n,r){switch(e){case"start":t.onStart(function(){return r(n&&rl(n,"start",t.totalTime))});break;case"done":t.onDone(function(){return r(n&&rl(n,"done",t.totalTime))});break;case"destroy":t.onDestroy(function(){return r(n&&rl(n,"destroy",t.totalTime))})}}function rl(t,e,n){var r=ol(t.element,t.triggerName,t.fromState,t.toState,e||t.phaseName,void 0==n?t.totalTime:n),o=t._data;return null!=o&&(r._data=o),r}function ol(t,e,n,r,o,i){return void 0===o&&(o=""),void 0===i&&(i=0),{element:t,triggerName:e,fromState:n,toState:r,phaseName:o,totalTime:i}}function il(t,e,n){var r;return t instanceof Map?(r=t.get(e))||t.set(e,r=n):(r=t[e])||(r=t[e]=n),r}function sl(t){var e=t.indexOf(":");return[t.substring(1,e),t.substr(e+1)]}var al=function(t,e){return!1},ll=function(t,e){return!1},ul=function(t,e,n){return[]};if("undefined"!=typeof Element){if(al=function(t,e){return t.contains(e)},Element.prototype.matches)ll=function(t,e){return t.matches(e)};else{var cl=Element.prototype,hl=cl.matchesSelector||cl.mozMatchesSelector||cl.msMatchesSelector||cl.oMatchesSelector||cl.webkitMatchesSelector;hl&&(ll=function(t,e){return hl.apply(t,[e])})}ul=function(t,e,n){var r=[];if(n)r.push.apply(r,t.querySelectorAll(e));else{var o=t.querySelector(e);o&&r.push(o)}return r}}var pl=null,dl=!1;function fl(t){pl||(pl=ml()||{},dl=!!pl.style&&"WebkitAppearance"in pl.style);var e=!0;return pl.style&&!function(t){return"ebkit"==t.substring(1,6)}(t)&&!(e=t in pl.style)&&dl&&(e="Webkit"+t.charAt(0).toUpperCase()+t.substr(1)in pl.style),e}function ml(){return"undefined"!=typeof document?document.body:null}var yl=ll,_l=al,gl=ul,vl=function(){function t(){}return t.prototype.validateStyleProperty=function(t){return fl(t)},t.prototype.matchesElement=function(t,e){return yl(t,e)},t.prototype.containsElement=function(t,e){return _l(t,e)},t.prototype.query=function(t,e,n){return gl(t,e,n)},t.prototype.computeStyle=function(t,e,n){return n||""},t.prototype.animate=function(t,e,n,r,o,i){return void 0===i&&(i=[]),new vi},t}(),bl=function(){function t(){}return t.NOOP=new vl,t}(),wl=1e3;function El(t){if("number"==typeof t)return t;var e=t.match(/^(-?[\.\d]+)(m?s)/);return!e||e.length<2?0:Cl(parseFloat(e[1]),e[2])}function Cl(t,e){switch(e){case"s":return t*wl;default:return t}}function xl(t,e,n){return t.hasOwnProperty("duration")?t:function(t,e,n){var r,o=0,i="";if("string"==typeof t){var s=t.match(/^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i);if(null===s)return e.push('The provided timing value "'+t+'" is invalid.'),{duration:0,delay:0,easing:""};r=Cl(parseFloat(s[1]),s[2]);var a=s[3];null!=a&&(o=Cl(Math.floor(parseFloat(a)),s[4]));var l=s[5];l&&(i=l)}else r=t;if(!n){var u=!1,c=e.length;r<0&&(e.push("Duration values below 0 are not allowed for this animation step."),u=!0),o<0&&(e.push("Delay values below 0 are not allowed for this animation step."),u=!0),u&&e.splice(c,0,'The provided timing value "'+t+'" is invalid.')}return{duration:r,delay:o,easing:i}}(t,e,n)}function Sl(t,e){return void 0===e&&(e={}),Object.keys(t).forEach(function(n){e[n]=t[n]}),e}function Tl(t,e,n){if(void 0===n&&(n={}),e)for(var r in t)n[r]=t[r];else Sl(t,n);return n}function Ol(t,e){t.style&&Object.keys(e).forEach(function(n){var r=jl(n);t.style[r]=e[n]})}function kl(t,e){t.style&&Object.keys(e).forEach(function(e){var n=jl(e);t.style[n]=""})}function Al(t){return Array.isArray(t)?1==t.length?t[0]:yi(t):t}var Pl=new RegExp("{{\\s*(.+?)\\s*}}","g");function Dl(t){var e=[];if("string"==typeof t){for(var n=t.toString(),r=void 0;r=Pl.exec(n);)e.push(r[1]);Pl.lastIndex=0}return e}function Il(t,e,n){var r=t.toString(),o=r.replace(Pl,function(t,r){var o=e[r];return e.hasOwnProperty(r)||(n.push("Please provide a value for the animation param "+r),o=""),o.toString()});return o==r?t:o}function Rl(t){for(var e=[],n=t.next();!n.done;)e.push(n.value),n=t.next();return e}var Nl=/-+([a-z0-9])/g;function jl(t){return t.replace(Nl,function(){for(var t=[],e=0;e *";case":leave":return"* => void";case":increment":return function(t,e){return parseFloat(e)>parseFloat(t)};case":decrement":return function(t,e){return parseFloat(e) *"}}(t,n);if("function"==typeof r)return void e.push(r);t=r}var o=t.match(/^(\*|[-\w]+)\s*()\s*(\*|[-\w]+)$/);if(null==o||o.length<4)return n.push('The provided transition expression "'+t+'" is not supported'),e;var i=o[1],s=o[2],a=o[3];e.push(Bl(i,a)),"<"!=s[0]||i==Ml&&a==Ml||e.push(Bl(a,i))}(t,o,r)}):o.push(n),o),animation:i,queryCount:e.queryCount,depCount:e.depCount,options:Xl(t.options)}},t.prototype.visitSequence=function(t,e){var n=this;return{type:2,steps:t.steps.map(function(t){return Vl(n,t,e)}),options:Xl(t.options)}},t.prototype.visitGroup=function(t,e){var n=this,r=e.currentTime,o=0,i=t.steps.map(function(t){e.currentTime=r;var i=Vl(n,t,e);return o=Math.max(o,e.currentTime),i});return e.currentTime=o,{type:3,steps:i,options:Xl(t.options)}},t.prototype.visitAnimate=function(t,e){var n,r=function(t,e){var n=null;if(t.hasOwnProperty("duration"))n=t;else if("number"==typeof t)return Gl(xl(t,e).duration,0,"");var r=t;if(r.split(/\s+/).some(function(t){return"{"==t.charAt(0)&&"{"==t.charAt(1)})){var o=Gl(0,0,"");return o.dynamic=!0,o.strValue=r,o}return Gl((n=n||xl(r,e)).duration,n.delay,n.easing)}(t.timings,e.errors);e.currentAnimateTimings=r;var o=t.styles?t.styles:_i({});if(5==o.type)n=this.visitKeyframes(o,e);else{var i=t.styles,s=!1;if(!i){s=!0;var a={};r.easing&&(a.easing=r.easing),i=_i(a)}e.currentTime+=r.duration+r.delay;var l=this.visitStyle(i,e);l.isEmptyStep=s,n=l}return e.currentAnimateTimings=null,{type:4,timings:r,style:n,options:null}},t.prototype.visitStyle=function(t,e){var n=this._makeStyleAst(t,e);return this._validateStyleAst(n,e),n},t.prototype._makeStyleAst=function(t,e){var n=[];Array.isArray(t.styles)?t.styles.forEach(function(t){"string"==typeof t?t==mi?n.push(t):e.errors.push("The provided style string value "+t+" is not allowed."):n.push(t)}):n.push(t.styles);var r=!1,o=null;return n.forEach(function(t){if(ql(t)){var e=t,n=e.easing;if(n&&(o=n,delete e.easing),!r)for(var i in e)if(e[i].toString().indexOf("{{")>=0){r=!0;break}}}),{type:6,styles:n,easing:o,offset:t.offset,containsDynamicStyles:r,options:null}},t.prototype._validateStyleAst=function(t,e){var n=this,r=e.currentAnimateTimings,o=e.currentTime,i=e.currentTime;r&&i>0&&(i-=r.duration+r.delay),t.styles.forEach(function(t){"string"!=typeof t&&Object.keys(t).forEach(function(r){if(n._driver.validateStyleProperty(r)){var s,a,l,u=e.collectedStyles[e.currentQuerySelector],c=u[r],h=!0;c&&(i!=o&&i>=c.startTime&&o<=c.endTime&&(e.errors.push('The CSS property "'+r+'" that exists between the times of "'+c.startTime+'ms" and "'+c.endTime+'ms" is also being animated in a parallel animation between the times of "'+i+'ms" and "'+o+'ms"'),h=!1),i=c.startTime),h&&(u[r]={startTime:i,endTime:o}),e.options&&(s=e.errors,a=e.options.params||{},(l=Dl(t[r])).length&&l.forEach(function(t){a.hasOwnProperty(t)||s.push("Unable to resolve the local animation param "+t+" in the given list of values")}))}else e.errors.push('The provided animation property "'+r+'" is not a supported CSS property for animations')})})},t.prototype.visitKeyframes=function(t,e){var n=this,r={type:5,styles:[],options:null};if(!e.currentAnimateTimings)return e.errors.push("keyframes() must be placed inside of a call to animate()"),r;var o=0,i=[],s=!1,a=!1,l=0,u=t.steps.map(function(t){var r=n._makeStyleAst(t,e),u=null!=r.offset?r.offset:function(t){if("string"==typeof t)return null;var e=null;if(Array.isArray(t))t.forEach(function(t){if(ql(t)&&t.hasOwnProperty("offset")){var n=t;e=parseFloat(n.offset),delete n.offset}});else if(ql(t)&&t.hasOwnProperty("offset")){var n=t;e=parseFloat(n.offset),delete n.offset}return e}(r.styles),c=0;return null!=u&&(o++,c=r.offset=u),a=a||c<0||c>1,s=s||c0&&o0?o==p?1:h*o:i[o],a=s*m;e.currentTime=d+f.delay+a,f.duration=a,n._validateStyleAst(t,e),t.offset=s,r.styles.push(t)}),r},t.prototype.visitReference=function(t,e){return{type:8,animation:Vl(this,Al(t.animation),e),options:Xl(t.options)}},t.prototype.visitAnimateChild=function(t,e){return e.depCount++,{type:9,options:Xl(t.options)}},t.prototype.visitAnimateRef=function(t,e){return{type:10,animation:this.visitReference(t.animation,e),options:Xl(t.options)}},t.prototype.visitQuery=function(t,e){var n=e.currentQuerySelector,r=t.options||{};e.queryCount++,e.currentQuery=t;var o=function(t){var e=!!t.split(/\s*,\s*/).find(function(t){return":self"==t});return e&&(t=t.replace(Hl,"")),[t=t.replace(/@\*/g,".ng-trigger").replace(/@\w+/g,function(t){return".ng-trigger-"+t.substr(1)}).replace(/:animating/g,".ng-animating"),e]}(t.selector),i=o[0],s=o[1];e.currentQuerySelector=n.length?n+" "+i:i,il(e.collectedStyles,e.currentQuerySelector,{});var a=Vl(this,Al(t.animation),e);return e.currentQuery=null,e.currentQuerySelector=n,{type:11,selector:i,limit:r.limit||0,optional:!!r.optional,includeSelf:s,animation:a,originalSelector:t.selector,options:Xl(t.options)}},t.prototype.visitStagger=function(t,e){e.currentQuery||e.errors.push("stagger() can only be used inside of query()");var n="full"===t.timings?{duration:0,delay:0,easing:"full"}:xl(t.timings,e.errors,!0);return{type:12,animation:Vl(this,Al(t.animation),e),timings:n,options:null}},t}(),Yl=function(t){this.errors=t,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null};function ql(t){return!Array.isArray(t)&&"object"==typeof t}function Xl(t){var e;return t?(t=Sl(t)).params&&(t.params=(e=t.params)?Sl(e):null):t={},t}function Gl(t,e,n){return{duration:t,delay:e,easing:n}}function Zl(t,e,n,r,o,i,s,a){return void 0===s&&(s=null),void 0===a&&(a=!1),{type:1,element:t,keyframes:e,preStyleProps:n,postStyleProps:r,duration:o,delay:i,totalTime:o+i,easing:s,subTimeline:a}}var Ql=function(){function t(){this._map=new Map}return t.prototype.consume=function(t){var e=this._map.get(t);return e?this._map.delete(t):e=[],e},t.prototype.append=function(t,e){var n=this._map.get(t);n||this._map.set(t,n=[]),n.push.apply(n,e)},t.prototype.has=function(t){return this._map.has(t)},t.prototype.clear=function(){this._map.clear()},t}(),Kl=new RegExp(":enter","g"),Wl=new RegExp(":leave","g");function $l(t,e,n,r,o,i,s,a,l,u){return void 0===i&&(i={}),void 0===s&&(s={}),void 0===u&&(u=[]),(new Jl).buildKeyframes(t,e,n,r,o,i,s,a,l,u)}var Jl=function(){function t(){}return t.prototype.buildKeyframes=function(t,e,n,r,o,i,s,a,l,u){void 0===u&&(u=[]),l=l||new Ql;var c=new eu(t,e,l,r,o,u,[]);c.options=a,c.currentTimeline.setStyles([i],null,c.errors,a),Vl(this,n,c);var h=c.timelines.filter(function(t){return t.containsAnimation()});if(h.length&&Object.keys(s).length){var p=h[h.length-1];p.allowOnlyTimelineStyles()||p.setStyles([s],null,c.errors,a)}return h.length?h.map(function(t){return t.buildKeyframes()}):[Zl(e,[],[],[],0,0,"",!1)]},t.prototype.visitTrigger=function(t,e){},t.prototype.visitState=function(t,e){},t.prototype.visitTransition=function(t,e){},t.prototype.visitAnimateChild=function(t,e){var n=e.subInstructions.consume(e.element);if(n){var r=e.createSubContext(t.options),o=e.currentTimeline.currentTime,i=this._visitSubInstructions(n,r,r.options);o!=i&&e.transformIntoNewTimeline(i)}e.previousNode=t},t.prototype.visitAnimateRef=function(t,e){var n=e.createSubContext(t.options);n.transformIntoNewTimeline(),this.visitReference(t.animation,n),e.transformIntoNewTimeline(n.currentTimeline.currentTime),e.previousNode=t},t.prototype._visitSubInstructions=function(t,e,n){var r=e.currentTimeline.currentTime,o=null!=n.duration?El(n.duration):null,i=null!=n.delay?El(n.delay):null;return 0!==o&&t.forEach(function(t){var n=e.appendInstructionToTimeline(t,o,i);r=Math.max(r,n.duration+n.delay)}),r},t.prototype.visitReference=function(t,e){e.updateOptions(t.options,!0),Vl(this,t.animation,e),e.previousNode=t},t.prototype.visitSequence=function(t,e){var n=this,r=e.subContextCount,o=e,i=t.options;if(i&&(i.params||i.delay)&&((o=e.createSubContext(i)).transformIntoNewTimeline(),null!=i.delay)){6==o.previousNode.type&&(o.currentTimeline.snapshotCurrentStyles(),o.previousNode=tu);var s=El(i.delay);o.delayNextStep(s)}t.steps.length&&(t.steps.forEach(function(t){return Vl(n,t,o)}),o.currentTimeline.applyStylesToKeyframe(),o.subContextCount>r&&o.transformIntoNewTimeline()),e.previousNode=t},t.prototype.visitGroup=function(t,e){var n=this,r=[],o=e.currentTimeline.currentTime,i=t.options&&t.options.delay?El(t.options.delay):0;t.steps.forEach(function(s){var a=e.createSubContext(t.options);i&&a.delayNextStep(i),Vl(n,s,a),o=Math.max(o,a.currentTimeline.currentTime),r.push(a.currentTimeline)}),r.forEach(function(t){return e.currentTimeline.mergeTimelineCollectedStyles(t)}),e.transformIntoNewTimeline(o),e.previousNode=t},t.prototype._visitTiming=function(t,e){if(t.dynamic){var n=t.strValue;return xl(e.params?Il(n,e.params,e.errors):n,e.errors)}return{duration:t.duration,delay:t.delay,easing:t.easing}},t.prototype.visitAnimate=function(t,e){var n=e.currentAnimateTimings=this._visitTiming(t.timings,e),r=e.currentTimeline;n.delay&&(e.incrementTime(n.delay),r.snapshotCurrentStyles());var o=t.style;5==o.type?this.visitKeyframes(o,e):(e.incrementTime(n.duration),this.visitStyle(o,e),r.applyStylesToKeyframe()),e.currentAnimateTimings=null,e.previousNode=t},t.prototype.visitStyle=function(t,e){var n=e.currentTimeline,r=e.currentAnimateTimings;!r&&n.getCurrentStyleProperties().length&&n.forwardFrame();var o=r&&r.easing||t.easing;t.isEmptyStep?n.applyEmptyStep(o):n.setStyles(t.styles,o,e.errors,e.options),e.previousNode=t},t.prototype.visitKeyframes=function(t,e){var n=e.currentAnimateTimings,r=e.currentTimeline.duration,o=n.duration,i=e.createSubContext().currentTimeline;i.easing=n.easing,t.styles.forEach(function(t){i.forwardTime((t.offset||0)*o),i.setStyles(t.styles,t.easing,e.errors,e.options),i.applyStylesToKeyframe()}),e.currentTimeline.mergeTimelineCollectedStyles(i),e.transformIntoNewTimeline(r+o),e.previousNode=t},t.prototype.visitQuery=function(t,e){var n=this,r=e.currentTimeline.currentTime,o=t.options||{},i=o.delay?El(o.delay):0;i&&(6===e.previousNode.type||0==r&&e.currentTimeline.getCurrentStyleProperties().length)&&(e.currentTimeline.snapshotCurrentStyles(),e.previousNode=tu);var s=r,a=e.invokeQuery(t.selector,t.originalSelector,t.limit,t.includeSelf,!!o.optional,e.errors);e.currentQueryTotal=a.length;var l=null;a.forEach(function(r,o){e.currentQueryIndex=o;var a=e.createSubContext(t.options,r);i&&a.delayNextStep(i),r===e.element&&(l=a.currentTimeline),Vl(n,t.animation,a),a.currentTimeline.applyStylesToKeyframe(),s=Math.max(s,a.currentTimeline.currentTime)}),e.currentQueryIndex=0,e.currentQueryTotal=0,e.transformIntoNewTimeline(s),l&&(e.currentTimeline.mergeTimelineCollectedStyles(l),e.currentTimeline.snapshotCurrentStyles()),e.previousNode=t},t.prototype.visitStagger=function(t,e){var n=e.parentContext,r=e.currentTimeline,o=t.timings,i=Math.abs(o.duration),s=i*(e.currentQueryTotal-1),a=i*e.currentQueryIndex;switch(o.duration<0?"reverse":o.easing){case"reverse":a=s-a;break;case"full":a=n.currentStaggerTime}var l=e.currentTimeline;a&&l.delayNextStep(a);var u=l.currentTime;Vl(this,t.animation,e),e.previousNode=t,n.currentStaggerTime=r.currentTime-u+(r.startTime-n.currentTimeline.startTime)},t}(),tu={},eu=function(){function t(t,e,n,r,o,i,s,a){this._driver=t,this.element=e,this.subInstructions=n,this._enterClassName=r,this._leaveClassName=o,this.errors=i,this.timelines=s,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=tu,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=a||new nu(this._driver,e,0),s.push(this.currentTimeline)}return Object.defineProperty(t.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),t.prototype.updateOptions=function(t,e){var n=this;if(t){var r=t,o=this.options;null!=r.duration&&(o.duration=El(r.duration)),null!=r.delay&&(o.delay=El(r.delay));var i=r.params;if(i){var s=o.params;s||(s=this.options.params={}),Object.keys(i).forEach(function(t){e&&s.hasOwnProperty(t)||(s[t]=Il(i[t],s,n.errors))})}}},t.prototype._copyOptions=function(){var t={};if(this.options){var e=this.options.params;if(e){var n=t.params={};Object.keys(e).forEach(function(t){n[t]=e[t]})}}return t},t.prototype.createSubContext=function(e,n,r){void 0===e&&(e=null);var o=n||this.element,i=new t(this._driver,o,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(o,r||0));return i.previousNode=this.previousNode,i.currentAnimateTimings=this.currentAnimateTimings,i.options=this._copyOptions(),i.updateOptions(e),i.currentQueryIndex=this.currentQueryIndex,i.currentQueryTotal=this.currentQueryTotal,i.parentContext=this,this.subContextCount++,i},t.prototype.transformIntoNewTimeline=function(t){return this.previousNode=tu,this.currentTimeline=this.currentTimeline.fork(this.element,t),this.timelines.push(this.currentTimeline),this.currentTimeline},t.prototype.appendInstructionToTimeline=function(t,e,n){var r={duration:null!=e?e:t.duration,delay:this.currentTimeline.currentTime+(null!=n?n:0)+t.delay,easing:""},o=new ru(this._driver,t.element,t.keyframes,t.preStyleProps,t.postStyleProps,r,t.stretchStartingKeyframe);return this.timelines.push(o),r},t.prototype.incrementTime=function(t){this.currentTimeline.forwardTime(this.currentTimeline.duration+t)},t.prototype.delayNextStep=function(t){t>0&&this.currentTimeline.delayNextStep(t)},t.prototype.invokeQuery=function(t,e,n,r,o,i){var s=[];if(r&&s.push(this.element),t.length>0){t=(t=t.replace(Kl,"."+this._enterClassName)).replace(Wl,"."+this._leaveClassName);var a=this._driver.query(this.element,t,1!=n);0!==n&&(a=n<0?a.slice(a.length+n,a.length):a.slice(0,n)),s.push.apply(s,a)}return o||0!=s.length||i.push('`query("'+e+'")` returned zero elements. (Use `query("'+e+'", { optional: true })` if you wish to allow this.)'),s},t}(),nu=function(){function t(t,e,n,r){this._driver=t,this.element=e,this.startTime=n,this._elementTimelineStylesLookup=r,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(e),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(e,this._localTimelineStyles)),this._loadKeyframe()}return t.prototype.containsAnimation=function(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}},t.prototype.getCurrentStyleProperties=function(){return Object.keys(this._currentKeyframe)},Object.defineProperty(t.prototype,"currentTime",{get:function(){return this.startTime+this.duration},enumerable:!0,configurable:!0}),t.prototype.delayNextStep=function(t){var e=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||e?(this.forwardTime(this.currentTime+t),e&&this.snapshotCurrentStyles()):this.startTime+=t},t.prototype.fork=function(e,n){return this.applyStylesToKeyframe(),new t(this._driver,e,n||this.currentTime,this._elementTimelineStylesLookup)},t.prototype._loadKeyframe=function(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))},t.prototype.forwardFrame=function(){this.duration+=1,this._loadKeyframe()},t.prototype.forwardTime=function(t){this.applyStylesToKeyframe(),this.duration=t,this._loadKeyframe()},t.prototype._updateStyle=function(t,e){this._localTimelineStyles[t]=e,this._globalTimelineStyles[t]=e,this._styleSummary[t]={time:this.currentTime,value:e}},t.prototype.allowOnlyTimelineStyles=function(){return this._currentEmptyStepKeyframe!==this._currentKeyframe},t.prototype.applyEmptyStep=function(t){var e=this;t&&(this._previousKeyframe.easing=t),Object.keys(this._globalTimelineStyles).forEach(function(t){e._backFill[t]=e._globalTimelineStyles[t]||mi,e._currentKeyframe[t]=mi}),this._currentEmptyStepKeyframe=this._currentKeyframe},t.prototype.setStyles=function(t,e,n,r){var o=this;e&&(this._previousKeyframe.easing=e);var i=r&&r.params||{},s=function(t,e){var n,r={};return t.forEach(function(t){"*"===t?(n=n||Object.keys(e)).forEach(function(t){r[t]=mi}):Tl(t,!1,r)}),r}(t,this._globalTimelineStyles);Object.keys(s).forEach(function(t){var e=Il(s[t],i,n);o._pendingStyles[t]=e,o._localTimelineStyles.hasOwnProperty(t)||(o._backFill[t]=o._globalTimelineStyles.hasOwnProperty(t)?o._globalTimelineStyles[t]:mi),o._updateStyle(t,e)})},t.prototype.applyStylesToKeyframe=function(){var t=this,e=this._pendingStyles,n=Object.keys(e);0!=n.length&&(this._pendingStyles={},n.forEach(function(n){t._currentKeyframe[n]=e[n]}),Object.keys(this._localTimelineStyles).forEach(function(e){t._currentKeyframe.hasOwnProperty(e)||(t._currentKeyframe[e]=t._localTimelineStyles[e])}))},t.prototype.snapshotCurrentStyles=function(){var t=this;Object.keys(this._localTimelineStyles).forEach(function(e){var n=t._localTimelineStyles[e];t._pendingStyles[e]=n,t._updateStyle(e,n)})},t.prototype.getFinalKeyframe=function(){return this._keyframes.get(this.duration)},Object.defineProperty(t.prototype,"properties",{get:function(){var t=[];for(var e in this._currentKeyframe)t.push(e);return t},enumerable:!0,configurable:!0}),t.prototype.mergeTimelineCollectedStyles=function(t){var e=this;Object.keys(t._styleSummary).forEach(function(n){var r=e._styleSummary[n],o=t._styleSummary[n];(!r||o.time>r.time)&&e._updateStyle(n,o.value)})},t.prototype.buildKeyframes=function(){var t=this;this.applyStylesToKeyframe();var e=new Set,n=new Set,r=1===this._keyframes.size&&0===this.duration,o=[];this._keyframes.forEach(function(i,s){var a=Tl(i,!0);Object.keys(a).forEach(function(t){var r=a[t];r==wi?e.add(t):r==mi&&n.add(t)}),r||(a.offset=s/t.duration),o.push(a)});var i=e.size?Rl(e.values()):[],s=n.size?Rl(n.values()):[];if(r){var a=o[0],l=Sl(a);a.offset=0,l.offset=1,o=[a,l]}return Zl(this.element,o,i,s,this.duration,this.startTime,this.easing,!1)},t}(),ru=function(t){function e(e,n,r,o,i,s,a){void 0===a&&(a=!1);var l=t.call(this,e,n,s.delay)||this;return l.element=n,l.keyframes=r,l.preStyleProps=o,l.postStyleProps=i,l._stretchStartingKeyframe=a,l.timings={duration:s.duration,delay:s.delay,easing:s.easing},l}return Object(c.b)(e,t),e.prototype.containsAnimation=function(){return this.keyframes.length>1},e.prototype.buildKeyframes=function(){var t=this.keyframes,e=this.timings,n=e.delay,r=e.duration,o=e.easing;if(this._stretchStartingKeyframe&&n){var i=[],s=r+n,a=n/s,l=Tl(t[0],!1);l.offset=0,i.push(l);var u=Tl(t[0],!1);u.offset=ou(a),i.push(u);for(var c=t.length-1,h=1;h<=c;h++){var p=Tl(t[h],!1);p.offset=ou((n+p.offset*r)/s),i.push(p)}r=s,n=0,o="",t=i}return Zl(this.element,t,this.preStyleProps,this.postStyleProps,r,n,o,!0)},e}(nu);function ou(t,e){void 0===e&&(e=3);var n=Math.pow(10,e-1);return Math.round(t*n)/n}var iu=function(){},su=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(c.b)(e,t),e.prototype.normalizePropertyName=function(t,e){return jl(t)},e.prototype.normalizeStyleValue=function(t,e,n,r){var o="",i=n.toString().trim();if(au[e]&&0!==n&&"0"!==n)if("number"==typeof n)o="px";else{var s=n.match(/^[+-]?[\d\.]+([a-z]*)$/);s&&0==s[1].length&&r.push("Please provide a CSS unit value for "+t+":"+n)}return i+o},e}(iu),au=function(t){var e={};return"width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective".split(",").forEach(function(t){return e[t]=!0}),e}();function lu(t,e,n,r,o,i,s,a,l,u,c,h){return{type:0,element:t,triggerName:e,isRemovalTransition:o,fromState:n,fromStyles:i,toState:r,toStyles:s,timelines:a,queriedElements:l,preStyleProps:u,postStyleProps:c,errors:h}}var uu={},cu=function(){function t(t,e,n){this._triggerName=t,this.ast=e,this._stateStyles=n}return t.prototype.match=function(t,e){return function(t,e,n){return t.some(function(t){return t(e,n)})}(this.ast.matchers,t,e)},t.prototype.buildStyles=function(t,e,n){var r=this._stateStyles["*"],o=this._stateStyles[t],i=r?r.buildStyles(e,n):{};return o?o.buildStyles(e,n):i},t.prototype.build=function(t,e,n,r,o,i,s,a,l){var u=[],h=this.ast.options&&this.ast.options.params||uu,p=this.buildStyles(n,s&&s.params||uu,u),d=a&&a.params||uu,f=this.buildStyles(r,d,u),m=new Set,y=new Map,_=new Map,g="void"===r,v={params:Object(c.a)({},h,d)},b=$l(t,e,this.ast.animation,o,i,p,f,v,l,u);if(u.length)return lu(e,this._triggerName,n,r,g,p,f,[],[],y,_,u);b.forEach(function(t){var n=t.element,r=il(y,n,{});t.preStyleProps.forEach(function(t){return r[t]=!0});var o=il(_,n,{});t.postStyleProps.forEach(function(t){return o[t]=!0}),n!==e&&m.add(n)});var w=Rl(m.values());return lu(e,this._triggerName,n,r,g,p,f,b,w,y,_)},t}(),hu=function(){function t(t,e){this.styles=t,this.defaultParams=e}return t.prototype.buildStyles=function(t,e){var n={},r=Sl(this.defaultParams);return Object.keys(t).forEach(function(e){var n=t[e];null!=n&&(r[e]=n)}),this.styles.styles.forEach(function(t){if("string"!=typeof t){var o=t;Object.keys(o).forEach(function(t){var i=o[t];i.length>1&&(i=Il(i,r,e)),n[t]=i})}}),n},t}(),pu=function(){function t(t,e){var n=this;this.name=t,this.ast=e,this.transitionFactories=[],this.states={},e.states.forEach(function(t){n.states[t.name]=new hu(t.style,t.options&&t.options.params||{})}),du(this.states,"true","1"),du(this.states,"false","0"),e.transitions.forEach(function(e){n.transitionFactories.push(new cu(t,e,n.states))}),this.fallbackTransition=new cu(t,{type:1,animation:{type:2,steps:[],options:null},matchers:[function(t,e){return!0}],options:null,queryCount:0,depCount:0},this.states)}return Object.defineProperty(t.prototype,"containsQueries",{get:function(){return this.ast.queryCount>0},enumerable:!0,configurable:!0}),t.prototype.matchTransition=function(t,e){return this.transitionFactories.find(function(n){return n.match(t,e)})||null},t.prototype.matchStyles=function(t,e,n){return this.fallbackTransition.buildStyles(t,e,n)},t}();function du(t,e,n){t.hasOwnProperty(e)?t.hasOwnProperty(n)||(t[n]=t[e]):t.hasOwnProperty(n)&&(t[e]=t[n])}var fu=new Ql,mu=function(){function t(t,e){this._driver=t,this._normalizer=e,this._animations={},this._playersById={},this.players=[]}return t.prototype.register=function(t,e){var n=[],r=zl(this._driver,e,n);if(n.length)throw new Error("Unable to build the animation due to the following errors: "+n.join("\n"));this._animations[t]=r},t.prototype._buildPlayer=function(t,e,n){var r=t.element,o=el(0,this._normalizer,0,t.keyframes,e,n);return this._driver.animate(r,o,t.duration,t.delay,t.easing,[])},t.prototype.create=function(t,e,n){var r=this;void 0===n&&(n={});var o,i=[],s=this._animations[t],a=new Map;if(s?(o=$l(this._driver,e,s,"ng-enter","ng-leave",{},{},n,fu,i)).forEach(function(t){var e=il(a,t.element,{});t.postStyleProps.forEach(function(t){return e[t]=null})}):(i.push("The requested animation doesn't exist or has already been destroyed"),o=[]),i.length)throw new Error("Unable to create the animation due to the following errors: "+i.join("\n"));a.forEach(function(t,e){Object.keys(t).forEach(function(n){t[n]=r._driver.computeStyle(e,n,mi)})});var l=tl(o.map(function(t){var e=a.get(t.element);return r._buildPlayer(t,{},e)}));return this._playersById[t]=l,l.onDestroy(function(){return r.destroy(t)}),this.players.push(l),l},t.prototype.destroy=function(t){var e=this._getPlayer(t);e.destroy(),delete this._playersById[t];var n=this.players.indexOf(e);n>=0&&this.players.splice(n,1)},t.prototype._getPlayer=function(t){var e=this._playersById[t];if(!e)throw new Error("Unable to find the timeline player referenced by "+t);return e},t.prototype.listen=function(t,e,n,r){var o=ol(e,"","","");return nl(this._getPlayer(t),n,o,r),function(){}},t.prototype.command=function(t,e,n,r){if("register"!=n)if("create"!=n){var o=this._getPlayer(t);switch(n){case"play":o.play();break;case"pause":o.pause();break;case"reset":o.reset();break;case"restart":o.restart();break;case"finish":o.finish();break;case"init":o.init();break;case"setPosition":o.setPosition(parseFloat(r[0]));break;case"destroy":this.destroy(t)}}else this.create(t,e,r[0]||{});else this.register(t,r[0])},t}(),yu=[],_u={namespaceId:"",setForRemoval:null,hasAnimation:!1,removedBeforeQueried:!1},gu={namespaceId:"",setForRemoval:null,hasAnimation:!1,removedBeforeQueried:!0},vu="__ng_removed",bu=function(){function t(t,e){void 0===e&&(e=""),this.namespaceId=e;var n=t&&t.hasOwnProperty("value");if(this.value=function(t){return null!=t?t:null}(n?t.value:t),n){var r=Sl(t);delete r.value,this.options=r}else this.options={};this.options.params||(this.options.params={})}return Object.defineProperty(t.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),t.prototype.absorbOptions=function(t){var e=t.params;if(e){var n=this.options.params;Object.keys(e).forEach(function(t){null==n[t]&&(n[t]=e[t])})}},t}(),wu=new bu("void"),Eu=new bu("DELETED"),Cu=function(){function t(t,e,n){this.id=t,this.hostElement=e,this._engine=n,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName="ng-tns-"+t,Du(e,this._hostClassName)}return t.prototype.listen=function(t,e,n,r){var o,i=this;if(!this._triggers.hasOwnProperty(e))throw new Error('Unable to listen on the animation trigger event "'+n+'" because the animation trigger "'+e+"\" doesn't exist!");if(null==n||0==n.length)throw new Error('Unable to listen on the animation trigger "'+e+'" because the provided event is undefined!');if("start"!=(o=n)&&"done"!=o)throw new Error('The provided animation trigger event "'+n+'" for the animation trigger "'+e+'" is not supported!');var s=il(this._elementListeners,t,[]),a={name:e,phase:n,callback:r};s.push(a);var l=il(this._engine.statesByElement,t,{});return l.hasOwnProperty(e)||(Du(t,"ng-trigger"),Du(t,"ng-trigger-"+e),l[e]=wu),function(){i._engine.afterFlush(function(){var t=s.indexOf(a);t>=0&&s.splice(t,1),i._triggers[e]||delete l[e]})}},t.prototype.register=function(t,e){return!this._triggers[t]&&(this._triggers[t]=e,!0)},t.prototype._getTrigger=function(t){var e=this._triggers[t];if(!e)throw new Error('The provided animation trigger "'+t+'" has not been registered!');return e},t.prototype.trigger=function(t,e,n,r){var o=this;void 0===r&&(r=!0);var i=this._getTrigger(e),s=new Su(this.id,e,t),a=this._engine.statesByElement.get(t);a||(Du(t,"ng-trigger"),Du(t,"ng-trigger-"+e),this._engine.statesByElement.set(t,a={}));var l=a[e],u=new bu(n,this.id);if(!(n&&n.hasOwnProperty("value"))&&l&&u.absorbOptions(l.options),a[e]=u,l){if(l===Eu)return s}else l=wu;if("void"===u.value||l.value!==u.value){var c=il(this._engine.playersByElement,t,[]);c.forEach(function(t){t.namespaceId==o.id&&t.triggerName==e&&t.queued&&t.destroy()});var h=i.matchTransition(l.value,u.value),p=!1;if(!h){if(!r)return;h=i.fallbackTransition,p=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:t,triggerName:e,transition:h,fromState:l,toState:u,player:s,isFallbackTransition:p}),p||(Du(t,"ng-animate-queued"),s.onStart(function(){Iu(t,"ng-animate-queued")})),s.onDone(function(){var e=o.players.indexOf(s);e>=0&&o.players.splice(e,1);var n=o._engine.playersByElement.get(t);if(n){var r=n.indexOf(s);r>=0&&n.splice(r,1)}}),this.players.push(s),c.push(s),s}if(!function(t,e){var n=Object.keys(t),r=Object.keys(e);if(n.length!=r.length)return!1;for(var o=0;o=0){for(var r=!1,o=n;o>=0;o--)if(this.driver.containsElement(this._namespaceList[o].hostElement,e)){this._namespaceList.splice(o+1,0,t),r=!0;break}r||this._namespaceList.splice(0,0,t)}else this._namespaceList.push(t);return this.namespacesByHostElement.set(e,t),t},t.prototype.register=function(t,e){var n=this._namespaceLookup[t];return n||(n=this.createNamespace(t,e)),n},t.prototype.registerTrigger=function(t,e,n){var r=this._namespaceLookup[t];r&&r.register(e,n)&&this.totalAnimations++},t.prototype.destroy=function(t,e){var n=this;if(t){var r=this._fetchNamespace(t);this.afterFlush(function(){n.namespacesByHostElement.delete(r.hostElement),delete n._namespaceLookup[t];var e=n._namespaceList.indexOf(r);e>=0&&n._namespaceList.splice(e,1)}),this.afterFlushAnimationsDone(function(){return r.destroy(e)})}},t.prototype._fetchNamespace=function(t){return this._namespaceLookup[t]},t.prototype.fetchNamespacesByElement=function(t){var e=new Set,n=this.statesByElement.get(t);if(n)for(var r=Object.keys(n),o=0;o=0;S--)this._namespaceList[S].drainQueuedTransitions(e).forEach(function(t){var e=t.player;C.push(e);var i=t.element;if(p&&n.driver.containsElement(p,i)){var c=w.get(i),h=m.get(i),d=n._buildInstruction(t,r,h,c);if(d.errors&&d.errors.length)x.push(d);else{if(t.isFallbackTransition)return e.onStart(function(){return kl(i,d.fromStyles)}),e.onDestroy(function(){return Ol(i,d.toStyles)}),void o.push(e);d.timelines.forEach(function(t){return t.stretchStartingKeyframe=!0}),r.append(i,d.timelines),s.push({instruction:d,player:e,element:i}),d.queriedElements.forEach(function(t){return il(a,t,[]).push(e)}),d.preStyleProps.forEach(function(t,e){var n=Object.keys(t);if(n.length){var r=l.get(e);r||l.set(e,r=new Set),n.forEach(function(t){return r.add(t)})}}),d.postStyleProps.forEach(function(t,e){var n=Object.keys(t),r=u.get(e);r||u.set(e,r=new Set),n.forEach(function(t){return r.add(t)})})}}else e.destroy()});if(x.length){var T=[];x.forEach(function(t){T.push("@"+t.triggerName+" has failed due to:\n"),t.errors.forEach(function(t){return T.push("- "+t+"\n")})}),C.forEach(function(t){return t.destroy()}),this.reportError(T)}var O=new Map,k=new Map;s.forEach(function(t){var e=t.element;r.has(e)&&(k.set(e,e),n._beforeAnimationBuild(t.player.namespaceId,t.instruction,O))}),o.forEach(function(t){var e=t.element;n._getPreviousPlayers(e,!1,t.namespaceId,t.triggerName,null).forEach(function(t){il(O,e,[]).push(t),t.destroy()})});var A=_.filter(function(t){return Nu(t,l,u)}),P=new Map;ku(P,this.driver,v,u,mi).forEach(function(t){Nu(t,l,u)&&A.push(t)});var D=new Map;f.forEach(function(t,e){ku(D,n.driver,new Set(t),l,wi)}),A.forEach(function(t){var e=P.get(t),n=D.get(t);P.set(t,Object(c.a)({},e,n))});var I=[],R=[],N={};s.forEach(function(t){var e=t.element,s=t.player,a=t.instruction;if(r.has(e)){if(h.has(e))return s.onDestroy(function(){return Ol(e,a.toStyles)}),void o.push(s);var l=N;if(k.size>1){for(var u=e,c=[];u=u.parentNode;){var p=k.get(u);if(p){l=p;break}c.push(u)}c.forEach(function(t){return k.set(t,l)})}var d=n._buildAnimation(s.namespaceId,a,O,i,D,P);if(s.setRealPlayer(d),l===N)I.push(s);else{var f=n.playersByElement.get(l);f&&f.length&&(s.parentPlayer=tl(f)),o.push(s)}}else kl(e,a.fromStyles),s.onDestroy(function(){return Ol(e,a.toStyles)}),R.push(s),h.has(e)&&o.push(s)}),R.forEach(function(t){var e=i.get(t.element);if(e&&e.length){var n=tl(e);t.setRealPlayer(n)}}),o.forEach(function(t){t.parentPlayer?t.syncPlayerEvents(t.parentPlayer):t.destroy()});for(var j=0;j<_.length;j++){var V,M=(V=_[j])[vu];if(Iu(V,"ng-leave"),!M||!M.hasAnimation){var F=[];if(a.size){var L=a.get(V);L&&L.length&&F.push.apply(F,L);for(var B=this.driver.query(V,".ng-animating",!0),H=0;H0?this.driver.animate(t.element,e,t.duration,t.delay,t.easing,n):new vi},t}(),Su=function(){function t(t,e,n){this.namespaceId=t,this.triggerName=e,this.element=n,this._player=new vi,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.queued=!0}return t.prototype.setRealPlayer=function(t){var e=this;this._containsRealPlayer||(this._player=t,Object.keys(this._queuedCallbacks).forEach(function(n){e._queuedCallbacks[n].forEach(function(e){return nl(t,n,void 0,e)})}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.queued=!1)},t.prototype.getRealPlayer=function(){return this._player},t.prototype.syncPlayerEvents=function(t){var e=this,n=this._player;n.triggerCallback&&t.onStart(function(){return n.triggerCallback("start")}),t.onDone(function(){return e.finish()}),t.onDestroy(function(){return e.destroy()})},t.prototype._queueEvent=function(t,e){il(this._queuedCallbacks,t,[]).push(e)},t.prototype.onDone=function(t){this.queued&&this._queueEvent("done",t),this._player.onDone(t)},t.prototype.onStart=function(t){this.queued&&this._queueEvent("start",t),this._player.onStart(t)},t.prototype.onDestroy=function(t){this.queued&&this._queueEvent("destroy",t),this._player.onDestroy(t)},t.prototype.init=function(){this._player.init()},t.prototype.hasStarted=function(){return!this.queued&&this._player.hasStarted()},t.prototype.play=function(){!this.queued&&this._player.play()},t.prototype.pause=function(){!this.queued&&this._player.pause()},t.prototype.restart=function(){!this.queued&&this._player.restart()},t.prototype.finish=function(){this._player.finish()},t.prototype.destroy=function(){this.destroyed=!0,this._player.destroy()},t.prototype.reset=function(){!this.queued&&this._player.reset()},t.prototype.setPosition=function(t){this.queued||this._player.setPosition(t)},t.prototype.getPosition=function(){return this.queued?0:this._player.getPosition()},Object.defineProperty(t.prototype,"totalTime",{get:function(){return this._player.totalTime},enumerable:!0,configurable:!0}),t.prototype.triggerCallback=function(t){var e=this._player;e.triggerCallback&&e.triggerCallback(t)},t}();function Tu(t){return t&&1===t.nodeType}function Ou(t,e){var n=t.style.display;return t.style.display=null!=e?e:"none",n}function ku(t,e,n,r,o){var i=[];n.forEach(function(t){return i.push(Ou(t))});var s=[];r.forEach(function(n,r){var i={};n.forEach(function(t){var n=i[t]=e.computeStyle(r,t,o);n&&0!=n.length||(r[vu]=gu,s.push(r))}),t.set(r,i)});var a=0;return n.forEach(function(t){return Ou(t,i[a++])}),s}function Au(t,e){var n=new Map;if(t.forEach(function(t){return n.set(t,[])}),0==e.length)return n;var r=new Set(e),o=new Map;return e.forEach(function(t){var e=function t(e){if(!e)return 1;var i=o.get(e);if(i)return i;var s=e.parentNode;return i=n.has(s)?s:r.has(s)?1:t(s),o.set(e,i),i}(t);1!==e&&n.get(e).push(t)}),n}var Pu="$$classes";function Du(t,e){if(t.classList)t.classList.add(e);else{var n=t[Pu];n||(n=t[Pu]={}),n[e]=!0}}function Iu(t,e){if(t.classList)t.classList.remove(e);else{var n=t[Pu];n&&delete n[e]}}function Ru(t,e,n){tl(n).onDone(function(){return t.processLeaveNode(e)})}function Nu(t,e,n){var r=n.get(t);if(!r)return!1;var o=e.get(t);return o?r.forEach(function(t){return o.add(t)}):e.set(t,r),n.delete(t),!0}var ju=function(){function t(t,e){var n=this;this._driver=t,this._triggerCache={},this.onRemovalComplete=function(t,e){},this._transitionEngine=new xu(t,e),this._timelineEngine=new mu(t,e),this._transitionEngine.onRemovalComplete=function(t,e){return n.onRemovalComplete(t,e)}}return t.prototype.registerTrigger=function(t,e,n,r,o){var i=t+"-"+r,s=this._triggerCache[i];if(!s){var a=[],l=zl(this._driver,o,a);if(a.length)throw new Error('The animation trigger "'+r+'" has failed to build due to the following errors:\n - '+a.join("\n - "));s=function(t,e){return new pu(t,e)}(r,l),this._triggerCache[i]=s}this._transitionEngine.registerTrigger(e,r,s)},t.prototype.register=function(t,e){this._transitionEngine.register(t,e)},t.prototype.destroy=function(t,e){this._transitionEngine.destroy(t,e)},t.prototype.onInsert=function(t,e,n,r){this._transitionEngine.insertNode(t,e,n,r)},t.prototype.onRemove=function(t,e,n){this._transitionEngine.removeNode(t,e,n)},t.prototype.disableAnimations=function(t,e){this._transitionEngine.markElementAsDisabled(t,e)},t.prototype.process=function(t,e,n,r){if("@"==n.charAt(0)){var o=sl(n);this._timelineEngine.command(o[0],e,o[1],r)}else this._transitionEngine.trigger(t,e,n,r)},t.prototype.listen=function(t,e,n,r,o){if("@"==n.charAt(0)){var i=sl(n);return this._timelineEngine.listen(i[0],e,i[1],o)}return this._transitionEngine.listen(t,e,n,r,o)},t.prototype.flush=function(t){void 0===t&&(t=-1),this._transitionEngine.flush(t)},Object.defineProperty(t.prototype,"players",{get:function(){return this._transitionEngine.players.concat(this._timelineEngine.players)},enumerable:!0,configurable:!0}),t.prototype.whenRenderingDone=function(){return this._transitionEngine.whenRenderingDone()},t}(),Vu=function(){function t(t,e,n,r){void 0===r&&(r=[]);var o=this;this.element=t,this.keyframes=e,this.options=n,this.previousPlayers=r,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.previousStyles={},this.currentSnapshot={},this._duration=n.duration,this._delay=n.delay||0,this.time=this._duration+this._delay,(0===this._duration||0===this._delay)&&r.forEach(function(t){var e=t.currentSnapshot;Object.keys(e).forEach(function(t){return o.previousStyles[t]=e[t]})})}return t.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(t){return t()}),this._onDoneFns=[])},t.prototype.init=function(){this._buildPlayer(),this._preparePlayerBeforeStart()},t.prototype._buildPlayer=function(){var t=this;if(!this._initialized){this._initialized=!0;var e=this.keyframes.map(function(t){return Tl(t,!1)}),n=Object.keys(this.previousStyles);if(n.length&&e.length){var r=e[0],o=[];if(n.forEach(function(e){r.hasOwnProperty(e)||o.push(e),r[e]=t.previousStyles[e]}),o.length)for(var i=this,s=function(){var t=e[a];o.forEach(function(e){t[e]=Mu(i.element,e)})},a=1;a=0&&t.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){color:rgba(0,0,0,.38)}.cdk-keyboard-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),.cdk-program-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),:not(.mat-calendar-body-disabled):hover>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){background-color:rgba(0,0,0,.04)}.mat-calendar-body-selected{background-color:#673ab7;color:#fff}.mat-calendar-body-disabled>.mat-calendar-body-selected{background-color:rgba(103,58,183,.4)}.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.38)}.mat-calendar-body-today.mat-calendar-body-selected{-webkit-box-shadow:inset 0 0 0 1px #fff;box-shadow:inset 0 0 0 1px #fff}.mat-calendar-body-disabled>.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.18)}.mat-datepicker-toggle-active{color:#673ab7}.mat-dialog-container{background:#fff;color:rgba(0,0,0,.87)}.mat-divider{border-top-color:rgba(0,0,0,.12)}.mat-divider-vertical{border-right-color:rgba(0,0,0,.12)}.mat-expansion-panel{background:#fff;color:rgba(0,0,0,.87)}.mat-action-row{border-top-color:rgba(0,0,0,.12)}.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-keyboard-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-program-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]):hover{background:rgba(0,0,0,.04)}.mat-expansion-panel-header-title{color:rgba(0,0,0,.87)}.mat-expansion-indicator::after,.mat-expansion-panel-header-description{color:rgba(0,0,0,.54)}.mat-expansion-panel-header[aria-disabled=true]{color:rgba(0,0,0,.26)}.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-description,.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-title{color:inherit}.mat-form-field-label,.mat-hint{color:rgba(0,0,0,.54)}.mat-focused .mat-form-field-label{color:#673ab7}.mat-focused .mat-form-field-label.mat-accent{color:#ffd740}.mat-focused .mat-form-field-label.mat-warn{color:#f44336}.mat-focused .mat-form-field-required-marker{color:#ffd740}.mat-form-field-underline{background-color:rgba(0,0,0,.42)}.mat-form-field-disabled .mat-form-field-underline{background-image:-webkit-gradient(linear,left top,right top,color-stop(0,rgba(0,0,0,.42)),color-stop(33%,rgba(0,0,0,.42)),color-stop(0,transparent));background-image:linear-gradient(to right,rgba(0,0,0,.42) 0,rgba(0,0,0,.42) 33%,transparent 0);background-size:4px 1px;background-repeat:repeat-x}.mat-form-field-ripple{background-color:#673ab7}.mat-form-field-ripple.mat-accent{background-color:#ffd740}.mat-form-field-ripple.mat-warn{background-color:#f44336}.mat-form-field-invalid .mat-form-field-label,.mat-form-field-invalid .mat-form-field-label .mat-form-field-required-marker,.mat-form-field-invalid .mat-form-field-label.mat-accent{color:#f44336}.mat-form-field-invalid .mat-form-field-ripple{background-color:#f44336}.mat-error{color:#f44336}.mat-icon.mat-primary{color:#673ab7}.mat-icon.mat-accent{color:#ffd740}.mat-icon.mat-warn{color:#f44336}.mat-input-element:disabled{color:rgba(0,0,0,.38)}.mat-input-element{caret-color:#673ab7}.mat-input-element::-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-moz-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-webkit-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element:-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-accent .mat-input-element{caret-color:#ffd740}.mat-form-field-invalid .mat-input-element,.mat-warn .mat-input-element{caret-color:#f44336}.mat-list .mat-list-item,.mat-list .mat-list-option,.mat-nav-list .mat-list-item,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-item,.mat-selection-list .mat-list-option{color:rgba(0,0,0,.87)}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:14px;font-weight:500;color:rgba(0,0,0,.54)}.mat-list-item-disabled{background-color:#eee}.mat-nav-list .mat-list-item{outline:0}.mat-nav-list .mat-list-item.mat-list-item-focus,.mat-nav-list .mat-list-item:hover{background:rgba(0,0,0,.04)}.mat-list-option{outline:0}.mat-list-option.mat-list-item-focus,.mat-list-option:hover{background:rgba(0,0,0,.04)}.mat-menu-panel{background:#fff}.mat-menu-item{background:0 0;color:rgba(0,0,0,.87)}.mat-menu-item[disabled]{color:rgba(0,0,0,.38)}.mat-menu-item .mat-icon:not([color]),.mat-menu-item-submenu-trigger::after{color:rgba(0,0,0,.54)}.mat-menu-item-highlighted:not([disabled]),.mat-menu-item.cdk-keyboard-focused:not([disabled]),.mat-menu-item.cdk-program-focused:not([disabled]),.mat-menu-item:hover:not([disabled]){background:rgba(0,0,0,.04)}.mat-paginator{background:#fff}.mat-paginator,.mat-paginator-page-size .mat-select-trigger{color:rgba(0,0,0,.54)}.mat-paginator-decrement,.mat-paginator-increment{border-top:2px solid rgba(0,0,0,.54);border-right:2px solid rgba(0,0,0,.54)}.mat-paginator-first,.mat-paginator-last{border-top:2px solid rgba(0,0,0,.54)}.mat-icon-button[disabled] .mat-paginator-decrement,.mat-icon-button[disabled] .mat-paginator-first,.mat-icon-button[disabled] .mat-paginator-increment,.mat-icon-button[disabled] .mat-paginator-last{border-color:rgba(0,0,0,.38)}.mat-progress-bar-background{fill:#d1c4e9}.mat-progress-bar-buffer{background-color:#d1c4e9}.mat-progress-bar-fill::after{background-color:#673ab7}.mat-progress-bar.mat-accent .mat-progress-bar-background{fill:#ffe57f}.mat-progress-bar.mat-accent .mat-progress-bar-buffer{background-color:#ffe57f}.mat-progress-bar.mat-accent .mat-progress-bar-fill::after{background-color:#ffd740}.mat-progress-bar.mat-warn .mat-progress-bar-background{fill:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-buffer{background-color:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-fill::after{background-color:#f44336}.mat-progress-spinner circle,.mat-spinner circle{stroke:#673ab7}.mat-progress-spinner.mat-accent circle,.mat-spinner.mat-accent circle{stroke:#ffd740}.mat-progress-spinner.mat-warn circle,.mat-spinner.mat-warn circle{stroke:#f44336}.mat-radio-outer-circle{border-color:rgba(0,0,0,.54)}.mat-radio-disabled .mat-radio-outer-circle{border-color:rgba(0,0,0,.38)}.mat-radio-disabled .mat-radio-inner-circle,.mat-radio-disabled .mat-radio-ripple .mat-ripple-element{background-color:rgba(0,0,0,.38)}.mat-radio-disabled .mat-radio-label-content{color:rgba(0,0,0,.38)}.mat-radio-button.mat-primary.mat-radio-checked .mat-radio-outer-circle{border-color:#673ab7}.mat-radio-button.mat-primary .mat-radio-inner-circle{background-color:#673ab7}.mat-radio-button.mat-primary .mat-radio-ripple .mat-ripple-element{background-color:rgba(103,58,183,.26)}.mat-radio-button.mat-accent.mat-radio-checked .mat-radio-outer-circle{border-color:#ffd740}.mat-radio-button.mat-accent .mat-radio-inner-circle{background-color:#ffd740}.mat-radio-button.mat-accent .mat-radio-ripple .mat-ripple-element{background-color:rgba(255,215,64,.26)}.mat-radio-button.mat-warn.mat-radio-checked .mat-radio-outer-circle{border-color:#f44336}.mat-radio-button.mat-warn .mat-radio-inner-circle{background-color:#f44336}.mat-radio-button.mat-warn .mat-radio-ripple .mat-ripple-element{background-color:rgba(244,67,54,.26)}.mat-select-content,.mat-select-panel-done-animating{background:#fff}.mat-select-value{color:rgba(0,0,0,.87)}.mat-select-placeholder{color:rgba(0,0,0,.42)}.mat-select-disabled .mat-select-value{color:rgba(0,0,0,.38)}.mat-select-arrow{color:rgba(0,0,0,.54)}.mat-select-panel .mat-option.mat-selected:not(.mat-option-multiple){background:rgba(0,0,0,.12)}.mat-form-field.mat-focused.mat-primary .mat-select-arrow{color:#673ab7}.mat-form-field.mat-focused.mat-accent .mat-select-arrow{color:#ffd740}.mat-form-field .mat-select.mat-select-invalid .mat-select-arrow,.mat-form-field.mat-focused.mat-warn .mat-select-arrow{color:#f44336}.mat-form-field .mat-select.mat-select-disabled .mat-select-arrow{color:rgba(0,0,0,.38)}.mat-drawer-container{background-color:#fafafa;color:rgba(0,0,0,.87)}.mat-drawer{background-color:#fff;color:rgba(0,0,0,.87)}.mat-drawer.mat-drawer-push{background-color:#fff}.mat-drawer-backdrop.mat-drawer-shown{background-color:rgba(0,0,0,.6)}.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#ffc107}.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(255,193,7,.5)}.mat-slide-toggle:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle .mat-ripple-element{background-color:rgba(255,193,7,.12)}.mat-slide-toggle.mat-primary.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#673ab7}.mat-slide-toggle.mat-primary.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(103,58,183,.5)}.mat-slide-toggle.mat-primary:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle.mat-primary .mat-ripple-element{background-color:rgba(103,58,183,.12)}.mat-slide-toggle.mat-warn.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#f44336}.mat-slide-toggle.mat-warn.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(244,67,54,.5)}.mat-slide-toggle.mat-warn:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle.mat-warn .mat-ripple-element{background-color:rgba(244,67,54,.12)}.mat-disabled .mat-slide-toggle-thumb{background-color:#bdbdbd}.mat-disabled .mat-slide-toggle-bar{background-color:rgba(0,0,0,.1)}.mat-slide-toggle-thumb{background-color:#fafafa}.mat-slide-toggle-bar{background-color:rgba(0,0,0,.38)}.mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-primary .mat-slider-thumb,.mat-primary .mat-slider-thumb-label,.mat-primary .mat-slider-track-fill{background-color:#673ab7}.mat-primary .mat-slider-thumb-label-text{color:#fff}.mat-accent .mat-slider-thumb,.mat-accent .mat-slider-thumb-label,.mat-accent .mat-slider-track-fill{background-color:#ffd740}.mat-accent .mat-slider-thumb-label-text{color:rgba(0,0,0,.87)}.mat-warn .mat-slider-thumb,.mat-warn .mat-slider-thumb-label,.mat-warn .mat-slider-track-fill{background-color:#f44336}.mat-warn .mat-slider-thumb-label-text{color:#fff}.mat-slider-focus-ring{background-color:rgba(255,215,64,.2)}.cdk-focused .mat-slider-track-background,.mat-slider:hover .mat-slider-track-background{background-color:rgba(0,0,0,.38)}.mat-slider-disabled .mat-slider-thumb,.mat-slider-disabled .mat-slider-track-background,.mat-slider-disabled .mat-slider-track-fill,.mat-slider-disabled:hover .mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-slider-min-value .mat-slider-focus-ring{background-color:rgba(0,0,0,.12)}.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb-label{background-color:rgba(0,0,0,.87)}.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb-label{background-color:rgba(0,0,0,.26)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing) .mat-slider-thumb{border-color:rgba(0,0,0,.26);background-color:transparent}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover .mat-slider-thumb{border-color:rgba(0,0,0,.38)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused.mat-slider-disabled .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover.mat-slider-disabled .mat-slider-thumb{border-color:rgba(0,0,0,.26)}.mat-slider-has-ticks .mat-slider-wrapper::after{border-color:rgba(0,0,0,.7)}.mat-slider-horizontal .mat-slider-ticks{background-image:repeating-linear-gradient(to right,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent);background-image:-moz-repeating-linear-gradient(.0001deg,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-slider-vertical .mat-slider-ticks{background-image:repeating-linear-gradient(to bottom,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-step-header.cdk-keyboard-focused,.mat-step-header.cdk-program-focused,.mat-step-header:hover{background-color:rgba(0,0,0,.04)}.mat-step-header .mat-step-label,.mat-step-header .mat-step-optional{color:rgba(0,0,0,.38)}.mat-step-header .mat-step-icon{background-color:#673ab7;color:#fff}.mat-step-header .mat-step-icon-not-touched{background-color:rgba(0,0,0,.38);color:#fff}.mat-step-header .mat-step-label.mat-step-label-active{color:rgba(0,0,0,.87)}.mat-stepper-horizontal,.mat-stepper-vertical{background-color:#fff}.mat-stepper-vertical-line::before{border-left-color:rgba(0,0,0,.12)}.mat-stepper-horizontal-line{border-top-color:rgba(0,0,0,.12)}.mat-tab-header,.mat-tab-nav-bar{border-bottom:1px solid rgba(0,0,0,.12)}.mat-tab-group-inverted-header .mat-tab-header,.mat-tab-group-inverted-header .mat-tab-nav-bar{border-top:1px solid rgba(0,0,0,.12);border-bottom:none}.mat-tab-label,.mat-tab-link{color:rgba(0,0,0,.87)}.mat-tab-label.mat-tab-disabled,.mat-tab-link.mat-tab-disabled{color:rgba(0,0,0,.38)}.mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.87)}.mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.38)}.mat-tab-group[class*=mat-background-] .mat-tab-header,.mat-tab-nav-bar[class*=mat-background-]{border-bottom:none;border-top:none}.mat-tab-group.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(209,196,233,.3)}.mat-tab-group.mat-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary .mat-ink-bar{background-color:#673ab7}.mat-tab-group.mat-primary.mat-background-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary.mat-background-primary .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-accent .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-accent .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,229,127,.3)}.mat-tab-group.mat-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent .mat-ink-bar{background-color:#ffd740}.mat-tab-group.mat-accent.mat-background-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent.mat-background-accent .mat-ink-bar{background-color:rgba(0,0,0,.87)}.mat-tab-group.mat-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-warn .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-warn .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn .mat-ink-bar{background-color:#f44336}.mat-tab-group.mat-warn.mat-background-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn.mat-background-warn .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-primary .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-primary .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(209,196,233,.3)}.mat-tab-group.mat-background-primary .mat-tab-header,.mat-tab-group.mat-background-primary .mat-tab-links,.mat-tab-nav-bar.mat-background-primary .mat-tab-header,.mat-tab-nav-bar.mat-background-primary .mat-tab-links{background-color:#673ab7}.mat-tab-group.mat-background-primary .mat-tab-label,.mat-tab-group.mat-background-primary .mat-tab-link,.mat-tab-nav-bar.mat-background-primary .mat-tab-label,.mat-tab-nav-bar.mat-background-primary .mat-tab-link{color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-primary .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-ripple-element,.mat-tab-nav-bar.mat-background-primary .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-tab-group.mat-background-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-accent .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-accent .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,229,127,.3)}.mat-tab-group.mat-background-accent .mat-tab-header,.mat-tab-group.mat-background-accent .mat-tab-links,.mat-tab-nav-bar.mat-background-accent .mat-tab-header,.mat-tab-nav-bar.mat-background-accent .mat-tab-links{background-color:#ffd740}.mat-tab-group.mat-background-accent .mat-tab-label,.mat-tab-group.mat-background-accent .mat-tab-link,.mat-tab-nav-bar.mat-background-accent .mat-tab-label,.mat-tab-nav-bar.mat-background-accent .mat-tab-link{color:rgba(0,0,0,.87)}.mat-tab-group.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-accent .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-link.mat-tab-disabled{color:rgba(0,0,0,.4)}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.87)}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.4)}.mat-tab-group.mat-background-accent .mat-ripple-element,.mat-tab-nav-bar.mat-background-accent .mat-ripple-element{background-color:rgba(0,0,0,.12)}.mat-tab-group.mat-background-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-warn .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-warn .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-background-warn .mat-tab-header,.mat-tab-group.mat-background-warn .mat-tab-links,.mat-tab-nav-bar.mat-background-warn .mat-tab-header,.mat-tab-nav-bar.mat-background-warn .mat-tab-links{background-color:#f44336}.mat-tab-group.mat-background-warn .mat-tab-label,.mat-tab-group.mat-background-warn .mat-tab-link,.mat-tab-nav-bar.mat-background-warn .mat-tab-label,.mat-tab-nav-bar.mat-background-warn .mat-tab-link{color:#fff}.mat-tab-group.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-warn .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-ripple-element,.mat-tab-nav-bar.mat-background-warn .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-toolbar{background:#f5f5f5;color:rgba(0,0,0,.87)}.mat-toolbar.mat-primary{background:#673ab7;color:#fff}.mat-toolbar.mat-accent{background:#ffd740;color:rgba(0,0,0,.87)}.mat-toolbar.mat-warn{background:#f44336;color:#fff}.mat-tooltip{background:rgba(97,97,97,.9)}.mat-snack-bar-container{background:#323232;color:#fff}.mat-simple-snackbar-action{line-height:1;font-family:inherit;font-size:inherit;font-weight:500;color:#ffd740} \ No newline at end of file Index: plugins/htmlinterface/html/styles.ef26c6a93b31d2372f33.bundle.css =================================================================== --- /dev/null +++ plugins/htmlinterface/html/styles.ef26c6a93b31d2372f33.bundle.css @@ -0,0 +1 @@ +.mat-elevation-z0{-webkit-box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12);box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.mat-elevation-z1{-webkit-box-shadow:0 2px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 3px 0 rgba(0,0,0,.12);box-shadow:0 2px 1px -1px rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 1px 3px 0 rgba(0,0,0,.12)}.mat-elevation-z2{-webkit-box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12);box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-elevation-z3{-webkit-box-shadow:0 3px 3px -2px rgba(0,0,0,.2),0 3px 4px 0 rgba(0,0,0,.14),0 1px 8px 0 rgba(0,0,0,.12);box-shadow:0 3px 3px -2px rgba(0,0,0,.2),0 3px 4px 0 rgba(0,0,0,.14),0 1px 8px 0 rgba(0,0,0,.12)}.mat-elevation-z4{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.mat-elevation-z5{-webkit-box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 5px 8px 0 rgba(0,0,0,.14),0 1px 14px 0 rgba(0,0,0,.12);box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 5px 8px 0 rgba(0,0,0,.14),0 1px 14px 0 rgba(0,0,0,.12)}.mat-elevation-z6{-webkit-box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12);box-shadow:0 3px 5px -1px rgba(0,0,0,.2),0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12)}.mat-elevation-z7{-webkit-box-shadow:0 4px 5px -2px rgba(0,0,0,.2),0 7px 10px 1px rgba(0,0,0,.14),0 2px 16px 1px rgba(0,0,0,.12);box-shadow:0 4px 5px -2px rgba(0,0,0,.2),0 7px 10px 1px rgba(0,0,0,.14),0 2px 16px 1px rgba(0,0,0,.12)}.mat-elevation-z8{-webkit-box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12);box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.mat-elevation-z9{-webkit-box-shadow:0 5px 6px -3px rgba(0,0,0,.2),0 9px 12px 1px rgba(0,0,0,.14),0 3px 16px 2px rgba(0,0,0,.12);box-shadow:0 5px 6px -3px rgba(0,0,0,.2),0 9px 12px 1px rgba(0,0,0,.14),0 3px 16px 2px rgba(0,0,0,.12)}.mat-elevation-z10{-webkit-box-shadow:0 6px 6px -3px rgba(0,0,0,.2),0 10px 14px 1px rgba(0,0,0,.14),0 4px 18px 3px rgba(0,0,0,.12);box-shadow:0 6px 6px -3px rgba(0,0,0,.2),0 10px 14px 1px rgba(0,0,0,.14),0 4px 18px 3px rgba(0,0,0,.12)}.mat-elevation-z11{-webkit-box-shadow:0 6px 7px -4px rgba(0,0,0,.2),0 11px 15px 1px rgba(0,0,0,.14),0 4px 20px 3px rgba(0,0,0,.12);box-shadow:0 6px 7px -4px rgba(0,0,0,.2),0 11px 15px 1px rgba(0,0,0,.14),0 4px 20px 3px rgba(0,0,0,.12)}.mat-elevation-z12{-webkit-box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12);box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 12px 17px 2px rgba(0,0,0,.14),0 5px 22px 4px rgba(0,0,0,.12)}.mat-elevation-z13{-webkit-box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 13px 19px 2px rgba(0,0,0,.14),0 5px 24px 4px rgba(0,0,0,.12);box-shadow:0 7px 8px -4px rgba(0,0,0,.2),0 13px 19px 2px rgba(0,0,0,.14),0 5px 24px 4px rgba(0,0,0,.12)}.mat-elevation-z14{-webkit-box-shadow:0 7px 9px -4px rgba(0,0,0,.2),0 14px 21px 2px rgba(0,0,0,.14),0 5px 26px 4px rgba(0,0,0,.12);box-shadow:0 7px 9px -4px rgba(0,0,0,.2),0 14px 21px 2px rgba(0,0,0,.14),0 5px 26px 4px rgba(0,0,0,.12)}.mat-elevation-z15{-webkit-box-shadow:0 8px 9px -5px rgba(0,0,0,.2),0 15px 22px 2px rgba(0,0,0,.14),0 6px 28px 5px rgba(0,0,0,.12);box-shadow:0 8px 9px -5px rgba(0,0,0,.2),0 15px 22px 2px rgba(0,0,0,.14),0 6px 28px 5px rgba(0,0,0,.12)}.mat-elevation-z16{-webkit-box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12);box-shadow:0 8px 10px -5px rgba(0,0,0,.2),0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12)}.mat-elevation-z17{-webkit-box-shadow:0 8px 11px -5px rgba(0,0,0,.2),0 17px 26px 2px rgba(0,0,0,.14),0 6px 32px 5px rgba(0,0,0,.12);box-shadow:0 8px 11px -5px rgba(0,0,0,.2),0 17px 26px 2px rgba(0,0,0,.14),0 6px 32px 5px rgba(0,0,0,.12)}.mat-elevation-z18{-webkit-box-shadow:0 9px 11px -5px rgba(0,0,0,.2),0 18px 28px 2px rgba(0,0,0,.14),0 7px 34px 6px rgba(0,0,0,.12);box-shadow:0 9px 11px -5px rgba(0,0,0,.2),0 18px 28px 2px rgba(0,0,0,.14),0 7px 34px 6px rgba(0,0,0,.12)}.mat-elevation-z19{-webkit-box-shadow:0 9px 12px -6px rgba(0,0,0,.2),0 19px 29px 2px rgba(0,0,0,.14),0 7px 36px 6px rgba(0,0,0,.12);box-shadow:0 9px 12px -6px rgba(0,0,0,.2),0 19px 29px 2px rgba(0,0,0,.14),0 7px 36px 6px rgba(0,0,0,.12)}.mat-elevation-z20{-webkit-box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 20px 31px 3px rgba(0,0,0,.14),0 8px 38px 7px rgba(0,0,0,.12);box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 20px 31px 3px rgba(0,0,0,.14),0 8px 38px 7px rgba(0,0,0,.12)}.mat-elevation-z21{-webkit-box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 21px 33px 3px rgba(0,0,0,.14),0 8px 40px 7px rgba(0,0,0,.12);box-shadow:0 10px 13px -6px rgba(0,0,0,.2),0 21px 33px 3px rgba(0,0,0,.14),0 8px 40px 7px rgba(0,0,0,.12)}.mat-elevation-z22{-webkit-box-shadow:0 10px 14px -6px rgba(0,0,0,.2),0 22px 35px 3px rgba(0,0,0,.14),0 8px 42px 7px rgba(0,0,0,.12);box-shadow:0 10px 14px -6px rgba(0,0,0,.2),0 22px 35px 3px rgba(0,0,0,.14),0 8px 42px 7px rgba(0,0,0,.12)}.mat-elevation-z23{-webkit-box-shadow:0 11px 14px -7px rgba(0,0,0,.2),0 23px 36px 3px rgba(0,0,0,.14),0 9px 44px 8px rgba(0,0,0,.12);box-shadow:0 11px 14px -7px rgba(0,0,0,.2),0 23px 36px 3px rgba(0,0,0,.14),0 9px 44px 8px rgba(0,0,0,.12)}.mat-elevation-z24{-webkit-box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12);box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12)}.mat-h1,.mat-headline,.mat-typography h1{font:400 24px/32px Roboto,"Helvetica Neue",sans-serif;margin:0 0 16px}.mat-h2,.mat-title,.mat-typography h2{font:500 20px/32px Roboto,"Helvetica Neue",sans-serif;margin:0 0 16px}.mat-h3,.mat-subheading-2,.mat-typography h3{font:400 16px/28px Roboto,"Helvetica Neue",sans-serif;margin:0 0 16px}.mat-h4,.mat-subheading-1,.mat-typography h4{font:400 15px/24px Roboto,"Helvetica Neue",sans-serif;margin:0 0 16px}.mat-h5,.mat-typography h5{font:400 11.62px/20px Roboto,"Helvetica Neue",sans-serif;margin:0 0 12px}.mat-h6,.mat-typography h6{font:400 9.38px/20px Roboto,"Helvetica Neue",sans-serif;margin:0 0 12px}.mat-body-2,.mat-body-strong{font:500 14px/24px Roboto,"Helvetica Neue",sans-serif}.mat-body,.mat-body-1,.mat-typography{font:400 14px/20px Roboto,"Helvetica Neue",sans-serif}.mat-body p,.mat-body-1 p,.mat-typography p{margin:0 0 12px}.mat-caption,.mat-small{font:400 12px/20px Roboto,"Helvetica Neue",sans-serif}.mat-display-4,.mat-typography .mat-display-4{font:300 112px/112px Roboto,"Helvetica Neue",sans-serif;margin:0 0 56px;letter-spacing:-.05em}.mat-display-3,.mat-typography .mat-display-3{font:400 56px/56px Roboto,"Helvetica Neue",sans-serif;margin:0 0 64px;letter-spacing:-.02em}.mat-display-2,.mat-typography .mat-display-2{font:400 45px/48px Roboto,"Helvetica Neue",sans-serif;margin:0 0 64px;letter-spacing:-.005em}.mat-display-1,.mat-typography .mat-display-1{font:400 34px/40px Roboto,"Helvetica Neue",sans-serif;margin:0 0 64px}.mat-button,.mat-fab,.mat-flat-button,.mat-icon-button,.mat-mini-fab,.mat-raised-button,.mat-stroked-button{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:14px;font-weight:500}.mat-button-toggle,.mat-card{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-card-title{font-size:24px;font-weight:400}.mat-card-content,.mat-card-header .mat-card-title,.mat-card-subtitle{font-size:14px}.mat-checkbox{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-checkbox-layout .mat-checkbox-label{line-height:24px}.mat-chip{font-size:13px;line-height:18px}.mat-chip .mat-chip-remove.mat-icon{font-size:18px}.mat-table{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-header-cell{font-size:12px;font-weight:500}.mat-cell{font-size:14px}.mat-calendar{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-calendar-body{font-size:13px}.mat-calendar-body-label,.mat-calendar-period-button{font-size:14px;font-weight:500}.mat-calendar-table-header th{font-size:11px;font-weight:400}.mat-dialog-title{font:500 20px/32px Roboto,"Helvetica Neue",sans-serif}.mat-expansion-panel-header{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:15px;font-weight:400}.mat-expansion-panel-content{font:400 14px/20px Roboto,"Helvetica Neue",sans-serif}.mat-form-field{font-size:inherit;font-weight:400;line-height:1.125;font-family:Roboto,"Helvetica Neue",sans-serif}.mat-form-field-wrapper{padding-bottom:1.25em}.mat-form-field-prefix .mat-icon,.mat-form-field-suffix .mat-icon{font-size:150%;line-height:1.125}.mat-form-field-prefix .mat-icon-button,.mat-form-field-suffix .mat-icon-button{height:1.5em;width:1.5em}.mat-form-field-prefix .mat-icon-button .mat-icon,.mat-form-field-suffix .mat-icon-button .mat-icon{height:1.125em;line-height:1.125}.mat-form-field-infix{padding:.4375em 0;border-top:.84375em solid transparent}.mat-form-field-can-float .mat-input-server:focus+.mat-form-field-label-wrapper .mat-form-field-label,.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.001px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.001px);-ms-transform:translateY(-1.28125em) scale(.75);width:133.33333%}.mat-form-field-can-float .mat-form-field-autofill-control:-webkit-autofill+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00101px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00101px);-ms-transform:translateY(-1.28124em) scale(.75);width:133.33334%}.mat-form-field-can-float .mat-input-server[label]:not(:label-shown)+.mat-form-field-label-wrapper .mat-form-field-label{-webkit-transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00102px);transform:translateY(-1.28125em) scale(.75) perspective(100px) translateZ(.00102px);-ms-transform:translateY(-1.28123em) scale(.75);width:133.33335%}.mat-form-field-label-wrapper{top:-.84375em;padding-top:.84375em}.mat-form-field-label{top:1.28125em}.mat-form-field-underline{bottom:1.25em}.mat-form-field-subscript-wrapper{font-size:75%;margin-top:.54167em;top:calc(100% - 1.66667em)}.mat-grid-tile-footer,.mat-grid-tile-header{font-size:14px}.mat-grid-tile-footer .mat-line,.mat-grid-tile-header .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-sizing:border-box;box-sizing:border-box}.mat-grid-tile-footer .mat-line:nth-child(n+2),.mat-grid-tile-header .mat-line:nth-child(n+2){font-size:12px}input.mat-input-element{margin-top:-.0625em}.mat-menu-item{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:16px;font-weight:400}.mat-paginator,.mat-paginator-page-size .mat-select-trigger{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:12px}.mat-radio-button,.mat-select{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-select-trigger{height:1.125em}.mat-slide-toggle-content{font:400 14px/20px Roboto,"Helvetica Neue",sans-serif}.mat-slider-thumb-label-text{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:12px;font-weight:500}.mat-stepper-horizontal,.mat-stepper-vertical{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-step-label{font-size:14px;font-weight:400}.mat-step-label-selected{font-size:14px;font-weight:500}.mat-tab-group{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-tab-label,.mat-tab-link{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:14px;font-weight:500}.mat-toolbar,.mat-toolbar h1,.mat-toolbar h2,.mat-toolbar h3,.mat-toolbar h4,.mat-toolbar h5,.mat-toolbar h6{font:500 20px/32px Roboto,"Helvetica Neue",sans-serif;margin:0}.mat-tooltip{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:10px;padding-top:6px;padding-bottom:6px}.mat-tooltip-handset{font-size:14px;padding-top:9px;padding-bottom:9px}.mat-list-item,.mat-list-option{font-family:Roboto,"Helvetica Neue",sans-serif}.mat-list .mat-list-item,.mat-nav-list .mat-list-item,.mat-selection-list .mat-list-item{font-size:16px}.mat-list .mat-list-item .mat-line,.mat-nav-list .mat-list-item .mat-line,.mat-selection-list .mat-list-item .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-sizing:border-box;box-sizing:border-box}.mat-list .mat-list-item .mat-line:nth-child(n+2),.mat-nav-list .mat-list-item .mat-line:nth-child(n+2),.mat-selection-list .mat-list-item .mat-line:nth-child(n+2){font-size:14px}.mat-list .mat-list-option,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-option{font-size:16px}.mat-list .mat-list-option .mat-line,.mat-nav-list .mat-list-option .mat-line,.mat-selection-list .mat-list-option .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-sizing:border-box;box-sizing:border-box}.mat-list .mat-list-option .mat-line:nth-child(n+2),.mat-nav-list .mat-list-option .mat-line:nth-child(n+2),.mat-selection-list .mat-list-option .mat-line:nth-child(n+2){font-size:14px}.mat-list[dense] .mat-list-item,.mat-nav-list[dense] .mat-list-item,.mat-selection-list[dense] .mat-list-item{font-size:12px}.mat-list[dense] .mat-list-item .mat-line,.mat-nav-list[dense] .mat-list-item .mat-line,.mat-selection-list[dense] .mat-list-item .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-sizing:border-box;box-sizing:border-box}.mat-list[dense] .mat-list-item .mat-line:nth-child(n+2),.mat-list[dense] .mat-list-option,.mat-nav-list[dense] .mat-list-item .mat-line:nth-child(n+2),.mat-nav-list[dense] .mat-list-option,.mat-selection-list[dense] .mat-list-item .mat-line:nth-child(n+2),.mat-selection-list[dense] .mat-list-option{font-size:12px}.mat-list[dense] .mat-list-option .mat-line,.mat-nav-list[dense] .mat-list-option .mat-line,.mat-selection-list[dense] .mat-list-option .mat-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;-webkit-box-sizing:border-box;box-sizing:border-box}.mat-list[dense] .mat-list-option .mat-line:nth-child(n+2),.mat-nav-list[dense] .mat-list-option .mat-line:nth-child(n+2),.mat-selection-list[dense] .mat-list-option .mat-line:nth-child(n+2){font-size:12px}.mat-list[dense] .mat-subheader,.mat-nav-list[dense] .mat-subheader,.mat-selection-list[dense] .mat-subheader{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:12px;font-weight:500}.mat-option{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:16px;color:rgba(0,0,0,.87)}.mat-optgroup-label{font:500 14px/24px Roboto,"Helvetica Neue",sans-serif;color:rgba(0,0,0,.54)}.mat-simple-snackbar{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:14px}.mat-ripple{overflow:hidden}@media screen and (-ms-high-contrast:active){.mat-ripple{display:none}}.mat-ripple.mat-ripple-unbounded{overflow:visible}.mat-ripple-element{position:absolute;border-radius:50%;pointer-events:none;-webkit-transition:opacity,-webkit-transform 0s cubic-bezier(0,0,.2,1);transition:opacity,-webkit-transform 0s cubic-bezier(0,0,.2,1);transition:opacity,transform 0s cubic-bezier(0,0,.2,1);transition:opacity,transform 0s cubic-bezier(0,0,.2,1),-webkit-transform 0s cubic-bezier(0,0,.2,1);-webkit-transform:scale(0);transform:scale(0)}.cdk-visually-hidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;outline:0;-webkit-appearance:none;-moz-appearance:none}.cdk-global-overlay-wrapper,.cdk-overlay-container{pointer-events:none;top:0;left:0;height:100%;width:100%}.cdk-overlay-container{position:fixed;z-index:1000}.cdk-overlay-container:empty{display:none}.cdk-global-overlay-wrapper{display:-webkit-box;display:-ms-flexbox;display:flex;position:absolute;z-index:1000}.cdk-overlay-pane{position:absolute;pointer-events:auto;-webkit-box-sizing:border-box;box-sizing:border-box;z-index:1000}.cdk-overlay-backdrop{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1000;pointer-events:auto;-webkit-tap-highlight-color:transparent;-webkit-transition:opacity .4s cubic-bezier(.25,.8,.25,1);transition:opacity .4s cubic-bezier(.25,.8,.25,1);opacity:0}.cdk-overlay-backdrop.cdk-overlay-backdrop-showing{opacity:1}.cdk-overlay-dark-backdrop{background:rgba(0,0,0,.288)}.cdk-overlay-transparent-backdrop,.cdk-overlay-transparent-backdrop.cdk-overlay-backdrop-showing{opacity:0}.cdk-global-scrollblock{position:fixed;width:100%;overflow-y:scroll}.mat-ripple-element{background-color:rgba(0,0,0,.1)}.mat-option:focus:not(.mat-option-disabled),.mat-option:hover:not(.mat-option-disabled){background:rgba(0,0,0,.04)}.mat-primary .mat-option.mat-selected:not(.mat-option-disabled){color:#673ab7}.mat-accent .mat-option.mat-selected:not(.mat-option-disabled){color:#ffd740}.mat-warn .mat-option.mat-selected:not(.mat-option-disabled){color:#f44336}.mat-option.mat-selected:not(.mat-option-multiple):not(.mat-option-disabled){background:rgba(0,0,0,.04)}.mat-option.mat-active{background:rgba(0,0,0,.04);color:rgba(0,0,0,.87)}.mat-option.mat-option-disabled{color:rgba(0,0,0,.38)}.mat-optgroup-disabled .mat-optgroup-label{color:rgba(0,0,0,.38)}.mat-pseudo-checkbox{color:rgba(0,0,0,.54)}.mat-pseudo-checkbox::after{color:#fafafa}.mat-accent .mat-pseudo-checkbox-checked,.mat-accent .mat-pseudo-checkbox-indeterminate,.mat-pseudo-checkbox-checked,.mat-pseudo-checkbox-indeterminate{background:#ffd740}.mat-primary .mat-pseudo-checkbox-checked,.mat-primary .mat-pseudo-checkbox-indeterminate{background:#673ab7}.mat-warn .mat-pseudo-checkbox-checked,.mat-warn .mat-pseudo-checkbox-indeterminate{background:#f44336}.mat-pseudo-checkbox-checked.mat-pseudo-checkbox-disabled,.mat-pseudo-checkbox-indeterminate.mat-pseudo-checkbox-disabled{background:#b0b0b0}.mat-app-background{background-color:#fafafa;color:rgba(0,0,0,.87)}.mat-theme-loaded-marker{display:none}.mat-autocomplete-panel{background:#fff;color:rgba(0,0,0,.87)}.mat-autocomplete-panel .mat-option.mat-selected:not(.mat-active):not(:hover){background:#fff}.mat-autocomplete-panel .mat-option.mat-selected:not(.mat-active):not(:hover):not(.mat-option-disabled){color:rgba(0,0,0,.87)}.mat-button,.mat-icon-button,.mat-stroked-button{background:0 0}.mat-button.mat-primary .mat-button-focus-overlay,.mat-icon-button.mat-primary .mat-button-focus-overlay,.mat-stroked-button.mat-primary .mat-button-focus-overlay{background-color:rgba(103,58,183,.12)}.mat-button.mat-accent .mat-button-focus-overlay,.mat-icon-button.mat-accent .mat-button-focus-overlay,.mat-stroked-button.mat-accent .mat-button-focus-overlay{background-color:rgba(255,215,64,.12)}.mat-button.mat-warn .mat-button-focus-overlay,.mat-icon-button.mat-warn .mat-button-focus-overlay,.mat-stroked-button.mat-warn .mat-button-focus-overlay{background-color:rgba(244,67,54,.12)}.mat-button[disabled] .mat-button-focus-overlay,.mat-icon-button[disabled] .mat-button-focus-overlay,.mat-stroked-button[disabled] .mat-button-focus-overlay{background-color:transparent}.mat-button.mat-primary,.mat-icon-button.mat-primary,.mat-stroked-button.mat-primary{color:#673ab7}.mat-button.mat-accent,.mat-icon-button.mat-accent,.mat-stroked-button.mat-accent{color:#ffd740}.mat-button.mat-warn,.mat-icon-button.mat-warn,.mat-stroked-button.mat-warn{color:#f44336}.mat-button.mat-accent[disabled],.mat-button.mat-primary[disabled],.mat-button.mat-warn[disabled],.mat-button[disabled][disabled],.mat-icon-button.mat-accent[disabled],.mat-icon-button.mat-primary[disabled],.mat-icon-button.mat-warn[disabled],.mat-icon-button[disabled][disabled],.mat-stroked-button.mat-accent[disabled],.mat-stroked-button.mat-primary[disabled],.mat-stroked-button.mat-warn[disabled],.mat-stroked-button[disabled][disabled]{color:rgba(0,0,0,.26)}.mat-fab,.mat-mini-fab,.mat-raised-button{color:rgba(0,0,0,.87);background-color:#fff}.mat-fab.mat-primary,.mat-mini-fab.mat-primary,.mat-raised-button.mat-primary{color:#fff;background-color:#673ab7}.mat-fab.mat-accent,.mat-mini-fab.mat-accent,.mat-raised-button.mat-accent{color:rgba(0,0,0,.87);background-color:#ffd740}.mat-fab.mat-warn,.mat-mini-fab.mat-warn,.mat-raised-button.mat-warn{color:#fff;background-color:#f44336}.mat-fab.mat-accent[disabled],.mat-fab.mat-primary[disabled],.mat-fab.mat-warn[disabled],.mat-fab[disabled][disabled],.mat-mini-fab.mat-accent[disabled],.mat-mini-fab.mat-primary[disabled],.mat-mini-fab.mat-warn[disabled],.mat-mini-fab[disabled][disabled],.mat-raised-button.mat-accent[disabled],.mat-raised-button.mat-primary[disabled],.mat-raised-button.mat-warn[disabled],.mat-raised-button[disabled][disabled]{color:rgba(0,0,0,.26);background-color:rgba(0,0,0,.12)}.mat-fab.mat-primary .mat-ripple-element,.mat-mini-fab.mat-primary .mat-ripple-element,.mat-raised-button.mat-primary .mat-ripple-element{background-color:rgba(255,255,255,.2)}.mat-fab.mat-accent .mat-ripple-element,.mat-mini-fab.mat-accent .mat-ripple-element,.mat-raised-button.mat-accent .mat-ripple-element{background-color:rgba(0,0,0,.2)}.mat-fab.mat-warn .mat-ripple-element,.mat-mini-fab.mat-warn .mat-ripple-element,.mat-raised-button.mat-warn .mat-ripple-element{background-color:rgba(255,255,255,.2)}.mat-button.mat-primary .mat-ripple-element{background-color:rgba(103,58,183,.1)}.mat-button.mat-accent .mat-ripple-element{background-color:rgba(255,215,64,.1)}.mat-button.mat-warn .mat-ripple-element{background-color:rgba(244,67,54,.1)}.mat-flat-button{color:rgba(0,0,0,.87);background-color:#fff}.mat-flat-button.mat-primary{color:#fff;background-color:#673ab7}.mat-flat-button.mat-accent{color:rgba(0,0,0,.87);background-color:#ffd740}.mat-flat-button.mat-warn{color:#fff;background-color:#f44336}.mat-flat-button.mat-accent[disabled],.mat-flat-button.mat-primary[disabled],.mat-flat-button.mat-warn[disabled],.mat-flat-button[disabled][disabled]{color:rgba(0,0,0,.26);background-color:rgba(0,0,0,.12)}.mat-flat-button.mat-primary .mat-ripple-element{background-color:rgba(255,255,255,.2)}.mat-flat-button.mat-accent .mat-ripple-element{background-color:rgba(0,0,0,.2)}.mat-flat-button.mat-warn .mat-ripple-element{background-color:rgba(255,255,255,.2)}.mat-icon-button.mat-primary .mat-ripple-element{background-color:rgba(103,58,183,.2)}.mat-icon-button.mat-accent .mat-ripple-element{background-color:rgba(255,215,64,.2)}.mat-icon-button.mat-warn .mat-ripple-element{background-color:rgba(244,67,54,.2)}.mat-button-toggle{color:rgba(0,0,0,.38)}.mat-button-toggle.cdk-focused .mat-button-toggle-focus-overlay{background-color:rgba(0,0,0,.12)}.mat-button-toggle-checked{background-color:#e0e0e0;color:rgba(0,0,0,.54)}.mat-button-toggle-disabled{background-color:#eee;color:rgba(0,0,0,.26)}.mat-button-toggle-disabled.mat-button-toggle-checked{background-color:#bdbdbd}.mat-card{background:#fff;color:rgba(0,0,0,.87)}.mat-card-subtitle{color:rgba(0,0,0,.54)}.mat-checkbox-frame{border-color:rgba(0,0,0,.54)}.mat-checkbox-checkmark{fill:#fafafa}.mat-checkbox-checkmark-path{stroke:#fafafa!important}.mat-checkbox-mixedmark{background-color:#fafafa}.mat-checkbox-checked.mat-primary .mat-checkbox-background,.mat-checkbox-indeterminate.mat-primary .mat-checkbox-background{background-color:#673ab7}.mat-checkbox-checked.mat-accent .mat-checkbox-background,.mat-checkbox-indeterminate.mat-accent .mat-checkbox-background{background-color:#ffd740}.mat-checkbox-checked.mat-warn .mat-checkbox-background,.mat-checkbox-indeterminate.mat-warn .mat-checkbox-background{background-color:#f44336}.mat-checkbox-disabled.mat-checkbox-checked .mat-checkbox-background,.mat-checkbox-disabled.mat-checkbox-indeterminate .mat-checkbox-background{background-color:#b0b0b0}.mat-checkbox-disabled:not(.mat-checkbox-checked) .mat-checkbox-frame{border-color:#b0b0b0}.mat-checkbox-disabled .mat-checkbox-label{color:#b0b0b0}.mat-checkbox:not(.mat-checkbox-disabled).mat-primary .mat-checkbox-ripple .mat-ripple-element{background-color:rgba(103,58,183,.26)}.mat-checkbox:not(.mat-checkbox-disabled).mat-accent .mat-checkbox-ripple .mat-ripple-element{background-color:rgba(255,215,64,.26)}.mat-checkbox:not(.mat-checkbox-disabled).mat-warn .mat-checkbox-ripple .mat-ripple-element{background-color:rgba(244,67,54,.26)}.mat-chip:not(.mat-basic-chip){background-color:#e0e0e0;color:rgba(0,0,0,.87)}.mat-chip:not(.mat-basic-chip) .mat-chip-remove{color:rgba(0,0,0,.87);opacity:.4}.mat-chip:not(.mat-basic-chip) .mat-chip-remove:hover{opacity:.54}.mat-chip.mat-chip-selected.mat-primary{background-color:#673ab7;color:#fff}.mat-chip.mat-chip-selected.mat-primary .mat-chip-remove{color:#fff;opacity:.4}.mat-chip.mat-chip-selected.mat-primary .mat-chip-remove:hover{opacity:.54}.mat-chip.mat-chip-selected.mat-warn{background-color:#f44336;color:#fff}.mat-chip.mat-chip-selected.mat-warn .mat-chip-remove{color:#fff;opacity:.4}.mat-chip.mat-chip-selected.mat-warn .mat-chip-remove:hover{opacity:.54}.mat-chip.mat-chip-selected.mat-accent{background-color:#ffd740;color:rgba(0,0,0,.87)}.mat-chip.mat-chip-selected.mat-accent .mat-chip-remove{color:rgba(0,0,0,.87);opacity:.4}.mat-chip.mat-chip-selected.mat-accent .mat-chip-remove:hover{opacity:.54}.mat-table{background:#fff}.mat-header-row,.mat-row{border-bottom-color:rgba(0,0,0,.12)}.mat-header-cell{color:rgba(0,0,0,.54)}.mat-cell{color:rgba(0,0,0,.87)}.mat-datepicker-content{background-color:#fff;color:rgba(0,0,0,.87)}.mat-calendar-arrow{border-top-color:rgba(0,0,0,.54)}.mat-calendar-next-button,.mat-calendar-previous-button{color:rgba(0,0,0,.54)}.mat-calendar-table-header{color:rgba(0,0,0,.38)}.mat-calendar-table-header-divider::after{background:rgba(0,0,0,.12)}.mat-calendar-body-label{color:rgba(0,0,0,.54)}.mat-calendar-body-cell-content{color:rgba(0,0,0,.87);border-color:transparent}.mat-calendar-body-disabled>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){color:rgba(0,0,0,.38)}.cdk-keyboard-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),.cdk-program-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),:not(.mat-calendar-body-disabled):hover>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){background-color:rgba(0,0,0,.04)}.mat-calendar-body-selected{background-color:#673ab7;color:#fff}.mat-calendar-body-disabled>.mat-calendar-body-selected{background-color:rgba(103,58,183,.4)}.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.38)}.mat-calendar-body-today.mat-calendar-body-selected{-webkit-box-shadow:inset 0 0 0 1px #fff;box-shadow:inset 0 0 0 1px #fff}.mat-calendar-body-disabled>.mat-calendar-body-today:not(.mat-calendar-body-selected){border-color:rgba(0,0,0,.18)}.mat-datepicker-toggle-active{color:#673ab7}.mat-dialog-container{background:#fff;color:rgba(0,0,0,.87)}.mat-divider{border-top-color:rgba(0,0,0,.12)}.mat-divider-vertical{border-right-color:rgba(0,0,0,.12)}.mat-expansion-panel{background:#fff;color:rgba(0,0,0,.87)}.mat-action-row{border-top-color:rgba(0,0,0,.12)}.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-keyboard-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]).cdk-program-focused,.mat-expansion-panel:not(.mat-expanded) .mat-expansion-panel-header:not([aria-disabled=true]):hover{background:rgba(0,0,0,.04)}.mat-expansion-panel-header-title{color:rgba(0,0,0,.87)}.mat-expansion-indicator::after,.mat-expansion-panel-header-description{color:rgba(0,0,0,.54)}.mat-expansion-panel-header[aria-disabled=true]{color:rgba(0,0,0,.26)}.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-description,.mat-expansion-panel-header[aria-disabled=true] .mat-expansion-panel-header-title{color:inherit}.mat-form-field-label,.mat-hint{color:rgba(0,0,0,.54)}.mat-focused .mat-form-field-label{color:#673ab7}.mat-focused .mat-form-field-label.mat-accent{color:#ffd740}.mat-focused .mat-form-field-label.mat-warn{color:#f44336}.mat-focused .mat-form-field-required-marker{color:#ffd740}.mat-form-field-underline{background-color:rgba(0,0,0,.42)}.mat-form-field-disabled .mat-form-field-underline{background-image:-webkit-gradient(linear,left top,right top,color-stop(0,rgba(0,0,0,.42)),color-stop(33%,rgba(0,0,0,.42)),color-stop(0,transparent));background-image:linear-gradient(to right,rgba(0,0,0,.42) 0,rgba(0,0,0,.42) 33%,transparent 0);background-size:4px 1px;background-repeat:repeat-x}.mat-form-field-ripple{background-color:#673ab7}.mat-form-field-ripple.mat-accent{background-color:#ffd740}.mat-form-field-ripple.mat-warn{background-color:#f44336}.mat-form-field-invalid .mat-form-field-label,.mat-form-field-invalid .mat-form-field-label .mat-form-field-required-marker,.mat-form-field-invalid .mat-form-field-label.mat-accent{color:#f44336}.mat-form-field-invalid .mat-form-field-ripple{background-color:#f44336}.mat-error{color:#f44336}.mat-icon.mat-primary{color:#673ab7}.mat-icon.mat-accent{color:#ffd740}.mat-icon.mat-warn{color:#f44336}.mat-input-element:disabled{color:rgba(0,0,0,.38)}.mat-input-element{caret-color:#673ab7}.mat-input-element::-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-moz-placeholder{color:rgba(0,0,0,.42)}.mat-input-element::-webkit-input-placeholder{color:rgba(0,0,0,.42)}.mat-input-element:-ms-input-placeholder{color:rgba(0,0,0,.42)}.mat-accent .mat-input-element{caret-color:#ffd740}.mat-form-field-invalid .mat-input-element,.mat-warn .mat-input-element{caret-color:#f44336}.mat-list .mat-list-item,.mat-list .mat-list-option,.mat-nav-list .mat-list-item,.mat-nav-list .mat-list-option,.mat-selection-list .mat-list-item,.mat-selection-list .mat-list-option{color:rgba(0,0,0,.87)}.mat-list .mat-subheader,.mat-nav-list .mat-subheader,.mat-selection-list .mat-subheader{font-family:Roboto,"Helvetica Neue",sans-serif;font-size:14px;font-weight:500;color:rgba(0,0,0,.54)}.mat-list-item-disabled{background-color:#eee}.mat-list-option.mat-list-item-focus,.mat-list-option:hover,.mat-nav-list .mat-list-item.mat-list-item-focus,.mat-nav-list .mat-list-item:hover{background:rgba(0,0,0,.04)}.mat-menu-panel{background:#fff}.mat-menu-item{background:0 0;color:rgba(0,0,0,.87)}.mat-menu-item[disabled]{color:rgba(0,0,0,.38)}.mat-menu-item .mat-icon:not([color]),.mat-menu-item-submenu-trigger::after{color:rgba(0,0,0,.54)}.mat-menu-item-highlighted:not([disabled]),.mat-menu-item.cdk-keyboard-focused:not([disabled]),.mat-menu-item.cdk-program-focused:not([disabled]),.mat-menu-item:hover:not([disabled]){background:rgba(0,0,0,.04)}.mat-paginator{background:#fff}.mat-paginator,.mat-paginator-page-size .mat-select-trigger{color:rgba(0,0,0,.54)}.mat-paginator-decrement,.mat-paginator-increment{border-top:2px solid rgba(0,0,0,.54);border-right:2px solid rgba(0,0,0,.54)}.mat-paginator-first,.mat-paginator-last{border-top:2px solid rgba(0,0,0,.54)}.mat-icon-button[disabled] .mat-paginator-decrement,.mat-icon-button[disabled] .mat-paginator-first,.mat-icon-button[disabled] .mat-paginator-increment,.mat-icon-button[disabled] .mat-paginator-last{border-color:rgba(0,0,0,.38)}.mat-progress-bar-background{fill:#d1c4e9}.mat-progress-bar-buffer{background-color:#d1c4e9}.mat-progress-bar-fill::after{background-color:#673ab7}.mat-progress-bar.mat-accent .mat-progress-bar-background{fill:#ffe57f}.mat-progress-bar.mat-accent .mat-progress-bar-buffer{background-color:#ffe57f}.mat-progress-bar.mat-accent .mat-progress-bar-fill::after{background-color:#ffd740}.mat-progress-bar.mat-warn .mat-progress-bar-background{fill:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-buffer{background-color:#ffcdd2}.mat-progress-bar.mat-warn .mat-progress-bar-fill::after{background-color:#f44336}.mat-progress-spinner circle,.mat-spinner circle{stroke:#673ab7}.mat-progress-spinner.mat-accent circle,.mat-spinner.mat-accent circle{stroke:#ffd740}.mat-progress-spinner.mat-warn circle,.mat-spinner.mat-warn circle{stroke:#f44336}.mat-radio-outer-circle{border-color:rgba(0,0,0,.54)}.mat-radio-disabled .mat-radio-outer-circle{border-color:rgba(0,0,0,.38)}.mat-radio-disabled .mat-radio-inner-circle,.mat-radio-disabled .mat-radio-ripple .mat-ripple-element{background-color:rgba(0,0,0,.38)}.mat-radio-disabled .mat-radio-label-content{color:rgba(0,0,0,.38)}.mat-radio-button.mat-primary.mat-radio-checked .mat-radio-outer-circle{border-color:#673ab7}.mat-radio-button.mat-primary .mat-radio-inner-circle{background-color:#673ab7}.mat-radio-button.mat-primary .mat-radio-ripple .mat-ripple-element{background-color:rgba(103,58,183,.26)}.mat-radio-button.mat-accent.mat-radio-checked .mat-radio-outer-circle{border-color:#ffd740}.mat-radio-button.mat-accent .mat-radio-inner-circle{background-color:#ffd740}.mat-radio-button.mat-accent .mat-radio-ripple .mat-ripple-element{background-color:rgba(255,215,64,.26)}.mat-radio-button.mat-warn.mat-radio-checked .mat-radio-outer-circle{border-color:#f44336}.mat-radio-button.mat-warn .mat-radio-inner-circle{background-color:#f44336}.mat-radio-button.mat-warn .mat-radio-ripple .mat-ripple-element{background-color:rgba(244,67,54,.26)}.mat-select-content,.mat-select-panel-done-animating{background:#fff}.mat-select-value{color:rgba(0,0,0,.87)}.mat-select-placeholder{color:rgba(0,0,0,.42)}.mat-select-disabled .mat-select-value{color:rgba(0,0,0,.38)}.mat-select-arrow{color:rgba(0,0,0,.54)}.mat-select-panel .mat-option.mat-selected:not(.mat-option-multiple){background:rgba(0,0,0,.12)}.mat-form-field.mat-focused.mat-primary .mat-select-arrow{color:#673ab7}.mat-form-field.mat-focused.mat-accent .mat-select-arrow{color:#ffd740}.mat-form-field .mat-select.mat-select-invalid .mat-select-arrow,.mat-form-field.mat-focused.mat-warn .mat-select-arrow{color:#f44336}.mat-form-field .mat-select.mat-select-disabled .mat-select-arrow{color:rgba(0,0,0,.38)}.mat-drawer-container{background-color:#fafafa;color:rgba(0,0,0,.87)}.mat-drawer{background-color:#fff;color:rgba(0,0,0,.87)}.mat-drawer.mat-drawer-push{background-color:#fff}.mat-drawer-backdrop.mat-drawer-shown{background-color:rgba(0,0,0,.6)}.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#ffc107}.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(255,193,7,.5)}.mat-slide-toggle:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle .mat-ripple-element{background-color:rgba(255,193,7,.12)}.mat-slide-toggle.mat-primary.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#673ab7}.mat-slide-toggle.mat-primary.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(103,58,183,.5)}.mat-slide-toggle.mat-primary:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle.mat-primary .mat-ripple-element{background-color:rgba(103,58,183,.12)}.mat-slide-toggle.mat-warn.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb{background-color:#f44336}.mat-slide-toggle.mat-warn.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar{background-color:rgba(244,67,54,.5)}.mat-slide-toggle.mat-warn:not(.mat-checked) .mat-ripple-element{background-color:rgba(0,0,0,.06)}.mat-slide-toggle.mat-warn .mat-ripple-element{background-color:rgba(244,67,54,.12)}.mat-disabled .mat-slide-toggle-thumb{background-color:#bdbdbd}.mat-disabled .mat-slide-toggle-bar{background-color:rgba(0,0,0,.1)}.mat-slide-toggle-thumb{background-color:#fafafa}.mat-slide-toggle-bar{background-color:rgba(0,0,0,.38)}.mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-primary .mat-slider-thumb,.mat-primary .mat-slider-thumb-label,.mat-primary .mat-slider-track-fill{background-color:#673ab7}.mat-primary .mat-slider-thumb-label-text{color:#fff}.mat-accent .mat-slider-thumb,.mat-accent .mat-slider-thumb-label,.mat-accent .mat-slider-track-fill{background-color:#ffd740}.mat-accent .mat-slider-thumb-label-text{color:rgba(0,0,0,.87)}.mat-warn .mat-slider-thumb,.mat-warn .mat-slider-thumb-label,.mat-warn .mat-slider-track-fill{background-color:#f44336}.mat-warn .mat-slider-thumb-label-text{color:#fff}.mat-slider-focus-ring{background-color:rgba(255,215,64,.2)}.cdk-focused .mat-slider-track-background,.mat-slider:hover .mat-slider-track-background{background-color:rgba(0,0,0,.38)}.mat-slider-disabled .mat-slider-thumb,.mat-slider-disabled .mat-slider-track-background,.mat-slider-disabled .mat-slider-track-fill,.mat-slider-disabled:hover .mat-slider-track-background{background-color:rgba(0,0,0,.26)}.mat-slider-min-value .mat-slider-focus-ring{background-color:rgba(0,0,0,.12)}.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing .mat-slider-thumb-label{background-color:rgba(0,0,0,.87)}.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb,.mat-slider-min-value.mat-slider-thumb-label-showing.cdk-focused .mat-slider-thumb-label{background-color:rgba(0,0,0,.26)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing) .mat-slider-thumb{border-color:rgba(0,0,0,.26);background-color:transparent}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover .mat-slider-thumb{border-color:rgba(0,0,0,.38)}.mat-slider-min-value:not(.mat-slider-thumb-label-showing).cdk-focused.mat-slider-disabled .mat-slider-thumb,.mat-slider-min-value:not(.mat-slider-thumb-label-showing):hover.mat-slider-disabled .mat-slider-thumb{border-color:rgba(0,0,0,.26)}.mat-slider-has-ticks .mat-slider-wrapper::after{border-color:rgba(0,0,0,.7)}.mat-slider-horizontal .mat-slider-ticks{background-image:repeating-linear-gradient(to right,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent);background-image:-moz-repeating-linear-gradient(.0001deg,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-slider-vertical .mat-slider-ticks{background-image:repeating-linear-gradient(to bottom,rgba(0,0,0,.7),rgba(0,0,0,.7) 2px,transparent 0,transparent)}.mat-step-header.cdk-keyboard-focused,.mat-step-header.cdk-program-focused,.mat-step-header:hover{background-color:rgba(0,0,0,.04)}.mat-step-header .mat-step-label,.mat-step-header .mat-step-optional{color:rgba(0,0,0,.38)}.mat-step-header .mat-step-icon{background-color:#673ab7;color:#fff}.mat-step-header .mat-step-icon-not-touched{background-color:rgba(0,0,0,.38);color:#fff}.mat-step-header .mat-step-label.mat-step-label-active{color:rgba(0,0,0,.87)}.mat-stepper-horizontal,.mat-stepper-vertical{background-color:#fff}.mat-stepper-vertical-line::before{border-left-color:rgba(0,0,0,.12)}.mat-stepper-horizontal-line{border-top-color:rgba(0,0,0,.12)}.mat-tab-header,.mat-tab-nav-bar{border-bottom:1px solid rgba(0,0,0,.12)}.mat-tab-group-inverted-header .mat-tab-header,.mat-tab-group-inverted-header .mat-tab-nav-bar{border-top:1px solid rgba(0,0,0,.12);border-bottom:none}.mat-tab-label,.mat-tab-link{color:rgba(0,0,0,.87)}.mat-tab-label.mat-tab-disabled,.mat-tab-link.mat-tab-disabled{color:rgba(0,0,0,.38)}.mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.87)}.mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.38)}.mat-tab-group[class*=mat-background-] .mat-tab-header,.mat-tab-nav-bar[class*=mat-background-]{border-bottom:none;border-top:none}.mat-tab-group.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-primary .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(209,196,233,.3)}.mat-tab-group.mat-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary .mat-ink-bar{background-color:#673ab7}.mat-tab-group.mat-primary.mat-background-primary .mat-ink-bar,.mat-tab-nav-bar.mat-primary.mat-background-primary .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-accent .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-accent .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,229,127,.3)}.mat-tab-group.mat-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent .mat-ink-bar{background-color:#ffd740}.mat-tab-group.mat-accent.mat-background-accent .mat-ink-bar,.mat-tab-nav-bar.mat-accent.mat-background-accent .mat-ink-bar{background-color:rgba(0,0,0,.87)}.mat-tab-group.mat-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-warn .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-warn .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn .mat-ink-bar{background-color:#f44336}.mat-tab-group.mat-warn.mat-background-warn .mat-ink-bar,.mat-tab-nav-bar.mat-warn.mat-background-warn .mat-ink-bar{background-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-primary .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-primary .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-primary .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(209,196,233,.3)}.mat-tab-group.mat-background-primary .mat-tab-header,.mat-tab-group.mat-background-primary .mat-tab-links,.mat-tab-nav-bar.mat-background-primary .mat-tab-header,.mat-tab-nav-bar.mat-background-primary .mat-tab-links{background-color:#673ab7}.mat-tab-group.mat-background-primary .mat-tab-label,.mat-tab-group.mat-background-primary .mat-tab-link,.mat-tab-nav-bar.mat-background-primary .mat-tab-label,.mat-tab-nav-bar.mat-background-primary .mat-tab-link{color:#fff}.mat-tab-group.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-primary .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-primary .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-primary .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-primary .mat-ripple-element,.mat-tab-nav-bar.mat-background-primary .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-tab-group.mat-background-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-accent .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-accent .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-accent .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,229,127,.3)}.mat-tab-group.mat-background-accent .mat-tab-header,.mat-tab-group.mat-background-accent .mat-tab-links,.mat-tab-nav-bar.mat-background-accent .mat-tab-header,.mat-tab-nav-bar.mat-background-accent .mat-tab-links{background-color:#ffd740}.mat-tab-group.mat-background-accent .mat-tab-label,.mat-tab-group.mat-background-accent .mat-tab-link,.mat-tab-nav-bar.mat-background-accent .mat-tab-label,.mat-tab-nav-bar.mat-background-accent .mat-tab-link{color:rgba(0,0,0,.87)}.mat-tab-group.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-accent .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-accent .mat-tab-link.mat-tab-disabled{color:rgba(0,0,0,.4)}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.87)}.mat-tab-group.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-accent .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(0,0,0,.4)}.mat-tab-group.mat-background-accent .mat-ripple-element,.mat-tab-nav-bar.mat-background-accent .mat-ripple-element{background-color:rgba(0,0,0,.12)}.mat-tab-group.mat-background-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-group.mat-background-warn .mat-tab-link:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-warn .mat-tab-label:not(.mat-tab-disabled):focus,.mat-tab-nav-bar.mat-background-warn .mat-tab-link:not(.mat-tab-disabled):focus{background-color:rgba(255,205,210,.3)}.mat-tab-group.mat-background-warn .mat-tab-header,.mat-tab-group.mat-background-warn .mat-tab-links,.mat-tab-nav-bar.mat-background-warn .mat-tab-header,.mat-tab-nav-bar.mat-background-warn .mat-tab-links{background-color:#f44336}.mat-tab-group.mat-background-warn .mat-tab-label,.mat-tab-group.mat-background-warn .mat-tab-link,.mat-tab-nav-bar.mat-background-warn .mat-tab-label,.mat-tab-nav-bar.mat-background-warn .mat-tab-link{color:#fff}.mat-tab-group.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-group.mat-background-warn .mat-tab-link.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-label.mat-tab-disabled,.mat-tab-nav-bar.mat-background-warn .mat-tab-link.mat-tab-disabled{color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-chevron{border-color:#fff}.mat-tab-group.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron,.mat-tab-nav-bar.mat-background-warn .mat-tab-header-pagination-disabled .mat-tab-header-pagination-chevron{border-color:rgba(255,255,255,.4)}.mat-tab-group.mat-background-warn .mat-ripple-element,.mat-tab-nav-bar.mat-background-warn .mat-ripple-element{background-color:rgba(255,255,255,.12)}.mat-toolbar{background:#f5f5f5;color:rgba(0,0,0,.87)}.mat-toolbar.mat-primary{background:#673ab7;color:#fff}.mat-toolbar.mat-accent{background:#ffd740;color:rgba(0,0,0,.87)}.mat-toolbar.mat-warn{background:#f44336;color:#fff}.mat-tooltip{background:rgba(97,97,97,.9)}.mat-snack-bar-container{background:#323232;color:#fff}.mat-simple-snackbar-action{line-height:1;font-family:inherit;font-size:inherit;font-weight:500;color:#ffd740} \ No newline at end of file Index: plugins/htmlinterface/htmlinterfacedialog.h =================================================================== --- plugins/htmlinterface/htmlinterfacedialog.h +++ /dev/null @@ -1,65 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Joris Guisson and Ivan Vasic * - * joris.guisson@gmail.com * - * ivasic@gmail.com * - * * - * Copyright (C) 2018 by Emmanuel Eytan * - * eje211@gmail.com * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * This program 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 General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - ***************************************************************************/ - - -#ifndef KTHTMLINTERFACEDIALOG_H -#define KTHTMLINTERFACEDIALOG_H - -#include -#include "ui_htmlinterfacewidget.h" - -namespace kt -{ - class HtmlInterfacePlugin; - class HtmlInterfaceModel; - - /** - Dialog to manipulate the download order. - */ - class HtmlInterfaceDialog : public QDialog, public Ui_HtmlInterfaceWidget - { - Q_OBJECT - public: - HtmlInterfaceDialog(HtmlInterfacePlugin* plugin, bt::TorrentInterface* tor, QWidget* parent); - ~HtmlInterfaceDialog(); - -// private slots: -// void commitHtmlInterface(); -// void moveUp(); -// void moveDown(); -// void moveTop(); -// void moveBottom(); -// void itemSelectionChanged(const QItemSelection& new_sel, const QItemSelection& old_sel); -// void customOrderEnableToggled(bool on); -// void search(const QString& text); -// -// private: -// bt::TorrentInterface* tor; -// HtmlInterfacePlugin* plugin; -// HtmlInterfaceModel* model; -// }; - -} - -#endif Index: plugins/htmlinterface/htmlinterfacedialog.cpp =================================================================== --- plugins/htmlinterface/htmlinterfacedialog.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 by Joris Guisson and Ivan Vasic * - * joris.guisson@gmail.com * - * ivasic@gmail.com * - * * - * Copyright (C) 2018 by Emmanuel Eytan * - * eje211@gmail.com * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * This program 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 General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the * - * Free Software Foundation, Inc., * - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * - ***************************************************************************/ - - -#include "htmlinterfacedialog.h" - -#include -#include - -#include - -#include -#include "htmlinterfaceplugin.h" - -namespace kt -{ - - HtmlInterfaceDialog::HtmlInterfaceDialog(HtmlInterfacePlugin* plugin, bt::TorrentInterface* tor, QWidget* parent) - : QDialog(parent), tor(tor), plugin(plugin) - { -// setupUi(this); -// connect(buttonBox, &QDialogButtonBox::accepted, this, &HtmlInterfaceDialog::accept); -// connect(buttonBox, &QDialogButtonBox::rejected, this, &HtmlInterfaceDialog::reject); -// connect(this, &HtmlInterfaceDialog::accepted, this, &HtmlInterfaceDialog::commitHtmlInterface); -// setWindowTitle(i18n("File Download Order")); -// m_top_label->setText(i18n("File download order for %1:", tor->getDisplayName())); -// -// HtmlInterfaceManager* dom = plugin->manager(tor); -// m_custom_order_enabled->setChecked(dom != 0); -// m_order->setEnabled(dom != 0); -// m_move_up->setEnabled(false); -// m_move_down->setEnabled(false); -// m_move_top->setEnabled(false); -// m_move_bottom->setEnabled(false); -// m_search_files->setEnabled(false); -// -// m_move_up->setIcon(QIcon::fromTheme(QStringLiteral("go-up"))); -// connect(m_move_up, &QPushButton::clicked, this, &HtmlInterfaceDialog::moveUp); -// m_move_down->setIcon(QIcon::fromTheme(QStringLiteral("go-down"))); -// connect(m_move_down, &QPushButton::clicked, this, &HtmlInterfaceDialog::moveDown); -// m_move_top->setIcon(QIcon::fromTheme(QStringLiteral("go-top"))); -// connect(m_move_top, &QPushButton::clicked, this, &HtmlInterfaceDialog::moveTop); -// m_move_bottom->setIcon(QIcon::fromTheme(QStringLiteral("go-bottom"))); -// connect(m_move_bottom, &QPushButton::clicked, this, &HtmlInterfaceDialog::moveBottom); -// -// m_order->setSelectionMode(QAbstractItemView::ContiguousSelection); -// m_order->setDragEnabled(true); -// m_order->setAcceptDrops(true); -// m_order->setDropIndicatorShown(true); -// m_order->setDragDropMode(QAbstractItemView::InternalMove); -// -// model = new HtmlInterfaceModel(tor, this); -// if (dom) -// model->initOrder(dom->downloadOrder()); -// m_order->setModel(model); -// -// QSize s = KSharedConfig::openConfig()->group("HtmlInterfaceDialog").readEntry("size", size()); -// resize(s); -// -// connect(m_order->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), -// this, SLOT(itemSelectionChanged(QItemSelection, QItemSelection))); -// connect(m_custom_order_enabled, &QCheckBox::toggled, this, &HtmlInterfaceDialog::customOrderEnableToggled); -// connect(m_search_files, &QLineEdit::textChanged, this, &HtmlInterfaceDialog::search); -// -// QMenu* sort_by_menu = new QMenu(m_sort_by); -// sort_by_menu->addAction(i18n("Name"), model, SLOT(sortByName())); -// sort_by_menu->addAction(i18n("Seasons and Episodes"), model, SLOT(sortBySeasonsAndEpisodes())); -// sort_by_menu->addAction(i18n("Album Track Order"), model, SLOT(sortByAlbumTrackOrder())); -// m_sort_by->setMenu(sort_by_menu); -// m_sort_by->setPopupMode(QToolButton::InstantPopup); -// m_sort_by->setEnabled(false); - } - - - HtmlInterfaceDialog::~HtmlInterfaceDialog() - { - KSharedConfig::openConfig()->group("HtmlInterfaceDialog").writeEntry("size", size()); - } - -// void HtmlInterfaceDialog::commitHtmlInterface() -// { -// if (m_custom_order_enabled->isChecked()) -// { -// HtmlInterfaceManager* dom = plugin->manager(tor); -// if (!dom) -// { -// dom = plugin->createManager(tor); -// connect(tor, &bt::TorrentInterface::chunkDownloaded, dom, &HtmlInterfaceManager::chunkDownloaded); -// } -// -// dom->setHtmlInterface(model->downloadOrder()); -// dom->save(); -// dom->update(); -// } -// else -// { -// HtmlInterfaceManager* dom = plugin->manager(tor); -// if (dom) -// { -// dom->disable(); -// plugin->destroyManager(tor); -// } -// } -// } -// -// void HtmlInterfaceDialog::moveUp() -// { -// QModelIndexList idx = m_order->selectionModel()->selectedRows(); -// model->moveUp(idx.front().row(), idx.count()); -// if (idx.front().row() > 0) -// { -// QItemSelection sel(model->index(idx.first().row() - 1), model->index(idx.last().row() - 1)); -// m_order->selectionModel()->select(sel, QItemSelectionModel::ClearAndSelect); -// } -// } -// -// void HtmlInterfaceDialog::moveTop() -// { -// QModelIndexList idx = m_order->selectionModel()->selectedRows(); -// model->moveTop(idx.front().row(), idx.count()); -// if (idx.front().row() > 0) -// { -// QItemSelection sel(model->index(0), model->index(idx.count() - 1)); -// m_order->selectionModel()->select(sel, QItemSelectionModel::ClearAndSelect); -// } -// } -// -// void HtmlInterfaceDialog::moveDown() -// { -// QModelIndexList idx = m_order->selectionModel()->selectedRows(); -// model->moveDown(idx.front().row(), idx.count()); -// if (idx.back().row() < (int)tor->getNumFiles() - 1) -// { -// QItemSelection sel(model->index(idx.first().row() + 1), model->index(idx.last().row() + 1)); -// m_order->selectionModel()->select(sel, QItemSelectionModel::ClearAndSelect); -// } -// } -// -// void HtmlInterfaceDialog::moveBottom() -// { -// QModelIndexList idx = m_order->selectionModel()->selectedRows(); -// model->moveBottom(idx.front().row(), idx.count()); -// if (idx.back().row() < (int)tor->getNumFiles() - 1) -// { -// QItemSelection sel(model->index(tor->getNumFiles() - idx.size()), model->index(tor->getNumFiles() - 1)); -// m_order->selectionModel()->select(sel, QItemSelectionModel::ClearAndSelect); -// } -// } -// -// void HtmlInterfaceDialog::itemSelectionChanged(const QItemSelection& new_sel, const QItemSelection& old_sel) -// { -// Q_UNUSED(old_sel); -// if (new_sel.empty()) -// { -// m_move_down->setEnabled(false); -// m_move_up->setEnabled(false); -// m_move_top->setEnabled(false); -// m_move_down->setEnabled(false); -// } -// else -// { -// bool up_ok = new_sel.front().topLeft().row() > 0; -// bool down_ok = new_sel.back().bottomRight().row() != (int)tor->getNumFiles() - 1; -// m_move_up->setEnabled(up_ok); -// m_move_top->setEnabled(up_ok); -// m_move_down->setEnabled(down_ok); -// m_move_bottom->setEnabled(down_ok); -// } -// } -// -// void HtmlInterfaceDialog::customOrderEnableToggled(bool on) -// { -// m_search_files->setEnabled(on); -// m_sort_by->setEnabled(on); -// if (!on) -// { -// m_move_down->setEnabled(false); -// m_move_up->setEnabled(false); -// m_move_top->setEnabled(false); -// m_move_down->setEnabled(false); -// } -// else -// { -// itemSelectionChanged(m_order->selectionModel()->selection(), QItemSelection()); -// } -// } -// -// void HtmlInterfaceDialog::search(const QString& text) -// { -// if (text.isEmpty()) -// { -// model->clearHighLights(); -// } -// else -// { -// QModelIndex idx = model->find(text); -// if (idx.isValid()) -// m_order->scrollTo(idx); -// } -// } -} Index: plugins/htmlinterface/htmlinterfaceplugin.h =================================================================== --- plugins/htmlinterface/htmlinterfaceplugin.h +++ plugins/htmlinterface/htmlinterfaceplugin.h @@ -47,27 +47,10 @@ void currentTorrentChanged(bt::TorrentInterface* tc) override; HtmlInterfacePlugin * instance; -// QString parentPart() const override {return QStringLiteral("torrentactivity");} -// -// /// Get the download order manager for a torrent (returns 0 if none exists) -// HtmlInterfaceManager* manager(bt::TorrentInterface* tc); -// -// /// Create a manager for a torrent -// HtmlInterfaceManager* createManager(bt::TorrentInterface* tc); -// -// /// Destroy a manager -// void destroyManager(bt::TorrentInterface* tc); -// -// private slots: -// void showHtmlInterfaceDialog(); -// void torrentAdded(bt::TorrentInterface* tc); -// void torrentRemoved(bt::TorrentInterface* tc); -// + private: QThread* thread; - WebServer * worker; -// QAction * download_order_action; -// bt::PtrMap managers; + WebServer * ws; }; } Index: plugins/htmlinterface/htmlinterfaceplugin.cpp =================================================================== --- plugins/htmlinterface/htmlinterfaceplugin.cpp +++ plugins/htmlinterface/htmlinterfaceplugin.cpp @@ -29,15 +29,9 @@ #include #include "htmlinterfaceplugin.h" -// #include -// #include #include #include -// #include #include -#include "mongoose.h" -// #include "htmlinterfacemanager.h" -// #include "htmlinterfacedialog.h" #include "webserver.h" @@ -53,11 +47,6 @@ { Q_UNUSED(args); qInfo("I've still been constructed!"); -// download_order_action = new QAction(QIcon::fromTheme(QStringLiteral("view-sort-ascending")), i18n("File Download Order"), this); -// connect(download_order_action, &QAction::triggered, this, &HtmlInterfacePlugin::showHtmlInterfaceDialog); -// actionCollection()->addAction(QStringLiteral("download_order"), download_order_action); -// setXMLFile(QStringLiteral("ktorrent_htmlinterfaceui.rc")); -// managers.setAutoDelete(true); } @@ -74,89 +63,19 @@ void HtmlInterfacePlugin::load() { qInfo("I've been loaded"); - HtmlInterfacePlugin::instance = this; - thread = new QThread; - worker = new WebServer(getCore()); - worker->moveToThread(thread); -// connect(worker, SIGNAL (error(QString)), this, SLOT (errorString(QString))); - connect(thread, SIGNAL (started()), worker, SLOT (process())); - connect(worker, SIGNAL (finished()), thread, SLOT (quit())); - connect(worker, SIGNAL (finished()), worker, SLOT (deleteLater())); - connect(thread, SIGNAL (finished()), thread, SLOT (deleteLater())); - thread->start(); -// TorrentActivityInterface* ta = getGUI()->getTorrentActivity(); -// ta->addViewListener(this); -// connect(getCore(), SIGNAL(torrentAdded(bt::TorrentInterface*)), this, SLOT(torrentAdded(bt::TorrentInterface*))); -// connect(getCore(), SIGNAL(torrentRemoved(bt::TorrentInterface*)), this, SLOT(torrentRemoved(bt::TorrentInterface*))); -// currentTorrentChanged(ta->getCurrentTorrent()); -// -// kt::QueueManager* qman = getCore()->getQueueManager(); -// for (kt::QueueManager::iterator i = qman->begin(); i != qman->end(); i++) -// torrentAdded(*i); + ws = new WebServer(getCore()); + ws->process(); } void HtmlInterfacePlugin::unload() { -// TorrentActivityInterface* ta = getGUI()->getTorrentActivity(); -// ta->removeViewListener(this); -// disconnect(getCore(), SIGNAL(torrentAdded(bt::TorrentInterface*)), this, SLOT(torrentAdded(bt::TorrentInterface*))); -// disconnect(getCore(), SIGNAL(torrentRemoved(bt::TorrentInterface*)), this, SLOT(torrentRemoved(bt::TorrentInterface*))); -// managers.clear(); + delete ws; } - -// void HtmlInterfacePlugin::showHtmlInterfaceDialog() -// { -// bt::TorrentInterface* tor = getGUI()->getTorrentActivity()->getCurrentTorrent(); -// if (!tor || !tor->getStats().multi_file_torrent) -// return; -// -// HtmlInterfaceDialog dlg(this, tor, getGUI()->getMainWindow()); -// dlg.exec(); -// } -// + void HtmlInterfacePlugin::currentTorrentChanged(bt::TorrentInterface* tc) { -// download_order_action->setEnabled(tc && tc->getStats().multi_file_torrent); } -// -// HtmlInterfaceManager* HtmlInterfacePlugin::manager(bt::TorrentInterface* tc) -// { -// return managers.find(tc);Aumyenne - -// } -// -// HtmlInterfaceManager* HtmlInterfacePlugin::createManager(bt::TorrentInterface* tc) -// { -// HtmlInterfaceManager* m = manager(tc); -// if (m) -// return m; -// -// m = new HtmlInterfaceManager(tc); -// managers.insert(tc, m); -// return m; -// } -// -// void HtmlInterfacePlugin::destroyManager(bt::TorrentInterface* tc) -// { -// managers.erase(tc); -// } -// -// void HtmlInterfacePlugin::torrentAdded(bt::TorrentInterface* tc) -// { -// if (bt::Exists(tc->getTorDir() + QStringLiteral("download_order"))) -// { -// HtmlInterfaceManager* m = createManager(tc); -// m->load(); -// m->update(); -// connect(tc, SIGNAL(chunkDownloaded(bt::TorrentInterface*, bt::Uint32)), -// m, SLOT(chunkDownloaded(bt::TorrentInterface*, bt::Uint32))); -// } -// } -// -// void HtmlInterfacePlugin::torrentRemoved(bt::TorrentInterface* tc) -// { -// managers.erase(tc); -// } + } Index: plugins/htmlinterface/htmlinterfacewidget.ui =================================================================== --- plugins/htmlinterface/htmlinterfacewidget.ui +++ /dev/null @@ -1,152 +0,0 @@ - - - DownloadOrderWidget - - - - 0 - 0 - 623 - 517 - - - - File Download Order - - - - - - File download order for: - - - - - - - Whether or not to enable a custom download order. - - - Custom file download order enabled - - - - - - - - - Qt::DefaultContextMenu - - - Sort By - - - Qt::ToolButtonTextBesideIcon - - - - - - - Search files - - - true - - - - - - - - - - - Order in which to download the files of a torrent. The file at the top will be downloaded first, followed by the second, then the third ... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - - Qt::Horizontal - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - m_custom_order_enabled - toggled(bool) - m_order - setEnabled(bool) - - - 141 - 33 - - - 166 - 113 - - - - - Index: plugins/htmlinterface/mongoose.h =================================================================== --- plugins/htmlinterface/mongoose.h +++ /dev/null @@ -1,6222 +0,0 @@ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_common.h" -#endif -/* - * Copyright (c) 2004-2013 Sergey Lyubka - * Copyright (c) 2013-2015 Cesanta Software Limited - * All rights reserved - * - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -#ifndef CS_MONGOOSE_SRC_COMMON_H_ -#define CS_MONGOOSE_SRC_COMMON_H_ - -#define MG_VERSION "6.11" - -/* Local tweaks, applied before any of Mongoose's own headers. */ -#ifdef MG_LOCALS -#include -#endif - -#endif /* CS_MONGOOSE_SRC_COMMON_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platform.h" -#endif -#ifndef CS_COMMON_PLATFORM_H_ -#define CS_COMMON_PLATFORM_H_ - -/* - * For the "custom" platform, includes and dependencies can be - * provided through mg_locals.h. - */ -#define CS_P_CUSTOM 0 -#define CS_P_UNIX 1 -#define CS_P_WINDOWS 2 -#define CS_P_ESP32 15 -#define CS_P_ESP8266 3 -#define CS_P_CC3100 6 -#define CS_P_CC3200 4 -#define CS_P_CC3220 17 -#define CS_P_MSP432 5 -#define CS_P_TM4C129 14 -#define CS_P_MBED 7 -#define CS_P_WINCE 8 -#define CS_P_NXP_LPC 13 -#define CS_P_NXP_KINETIS 9 -#define CS_P_NRF51 12 -#define CS_P_NRF52 10 -#define CS_P_PIC32 11 -#define CS_P_STM32 16 -/* Next id: 18 */ - -/* If not specified explicitly, we guess platform by defines. */ -#ifndef CS_PLATFORM - -#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__) -#define CS_PLATFORM CS_P_MSP432 -#elif defined(cc3200) || defined(TARGET_IS_CC3200) -#define CS_PLATFORM CS_P_CC3200 -#elif defined(cc3220) || defined(TARGET_IS_CC3220) -#define CS_PLATFORM CS_P_CC3220 -#elif defined(__unix__) || defined(__APPLE__) -#define CS_PLATFORM CS_P_UNIX -#elif defined(WINCE) -#define CS_PLATFORM CS_P_WINCE -#elif defined(_WIN32) -#define CS_PLATFORM CS_P_WINDOWS -#elif defined(__MBED__) -#define CS_PLATFORM CS_P_MBED -#elif defined(__USE_LPCOPEN) -#define CS_PLATFORM CS_P_NXP_LPC -#elif defined(FRDM_K64F) || defined(FREEDOM) -#define CS_PLATFORM CS_P_NXP_KINETIS -#elif defined(PIC32) -#define CS_PLATFORM CS_P_PIC32 -#elif defined(ESP_PLATFORM) -#define CS_PLATFORM CS_P_ESP32 -#elif defined(ICACHE_FLASH) -#define CS_PLATFORM CS_P_ESP8266 -#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \ - defined(TARGET_IS_TM4C129_RA2) -#define CS_PLATFORM CS_P_TM4C129 -#elif defined(STM32) -#define CS_PLATFORM CS_P_STM32 -#endif - -#ifndef CS_PLATFORM -#error "CS_PLATFORM is not specified and we couldn't guess it." -#endif - -#endif /* !defined(CS_PLATFORM) */ - -#define MG_NET_IF_SOCKET 1 -#define MG_NET_IF_SIMPLELINK 2 -#define MG_NET_IF_LWIP_LOW_LEVEL 3 -#define MG_NET_IF_PIC32 4 - -#define MG_SSL_IF_OPENSSL 1 -#define MG_SSL_IF_MBEDTLS 2 -#define MG_SSL_IF_SIMPLELINK 3 - -/* Amalgamated: #include "common/platforms/platform_unix.h" */ -/* Amalgamated: #include "common/platforms/platform_windows.h" */ -/* Amalgamated: #include "common/platforms/platform_esp32.h" */ -/* Amalgamated: #include "common/platforms/platform_esp8266.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3100.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3200.h" */ -/* Amalgamated: #include "common/platforms/platform_cc3220.h" */ -/* Amalgamated: #include "common/platforms/platform_mbed.h" */ -/* Amalgamated: #include "common/platforms/platform_nrf51.h" */ -/* Amalgamated: #include "common/platforms/platform_nrf52.h" */ -/* Amalgamated: #include "common/platforms/platform_wince.h" */ -/* Amalgamated: #include "common/platforms/platform_nxp_lpc.h" */ -/* Amalgamated: #include "common/platforms/platform_nxp_kinetis.h" */ -/* Amalgamated: #include "common/platforms/platform_pic32.h" */ -/* Amalgamated: #include "common/platforms/platform_stm32.h" */ - -/* Common stuff */ - -#if !defined(WEAK) -#if (defined(__GNUC__) || defined(__TI_COMPILER_VERSION__)) && !defined(_WIN32) -#define WEAK __attribute__((weak)) -#else -#define WEAK -#endif -#endif - -#ifdef __GNUC__ -#define NORETURN __attribute__((noreturn)) -#define NOINLINE __attribute__((noinline)) -#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) -#define NOINSTR __attribute__((no_instrument_function)) -#define DO_NOT_WARN_UNUSED __attribute__((unused)) -#else -#define NORETURN -#define NOINLINE -#define WARN_UNUSED_RESULT -#define NOINSTR -#define DO_NOT_WARN_UNUSED -#endif /* __GNUC__ */ - -#ifndef ARRAY_SIZE -#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) -#endif - -#endif /* CS_COMMON_PLATFORM_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_windows.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ -#if CS_PLATFORM == CS_P_WINDOWS - -/* - * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) - * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) - * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) - * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) - * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) - * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) - * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) - * MSVC++ 7.0 _MSC_VER == 1300 - * MSVC++ 6.0 _MSC_VER == 1200 - * MSVC++ 5.0 _MSC_VER == 1100 - */ -#ifdef _MSC_VER -#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ -#pragma warning(disable : 4204) /* missing c99 support */ -#endif - -#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS -#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 -#endif - -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */ -#endif - -#include -#include -#include -#include - -#if _MSC_VER < 1700 -typedef int bool; -#else -#include -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1800 -#define strdup _strdup -#endif - -#ifndef EINPROGRESS -#define EINPROGRESS WSAEINPROGRESS -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK WSAEWOULDBLOCK -#endif -#ifndef __func__ -#define STRX(x) #x -#define STR(x) STRX(x) -#define __func__ __FILE__ ":" STR(__LINE__) -#endif -#define snprintf _snprintf -#define vsnprintf _vsnprintf -#define to64(x) _atoi64(x) -#if !defined(__MINGW32__) && !defined(__MINGW64__) -#define popen(x, y) _popen((x), (y)) -#define pclose(x) _pclose(x) -#define fileno _fileno -#endif -#if defined(_MSC_VER) && _MSC_VER >= 1400 -#define fseeko(x, y, z) _fseeki64((x), (y), (z)) -#else -#define fseeko(x, y, z) fseek((x), (y), (z)) -#endif -#if defined(_MSC_VER) && _MSC_VER <= 1200 -typedef unsigned long uintptr_t; -typedef long intptr_t; -#endif -typedef int socklen_t; -#if _MSC_VER >= 1700 -#include -#else -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#endif -typedef SOCKET sock_t; -typedef uint32_t in_addr_t; -#ifndef UINT16_MAX -#define UINT16_MAX 65535 -#endif -#ifndef UINT32_MAX -#define UINT32_MAX 4294967295 -#endif -#ifndef pid_t -#define pid_t HANDLE -#endif -#define INT64_FMT "I64d" -#define INT64_X_FMT "I64x" -#define SIZE_T_FMT "Iu" -typedef struct _stati64 cs_stat_t; -#ifndef S_ISDIR -#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) -#endif -#ifndef S_ISREG -#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG) -#endif -#define DIRSEP '\\' -#define CS_DEFINE_DIRENT - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 1 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -unsigned int sleep(unsigned int seconds); - -/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */ -#define timegm _mkgmtime - -#define gmtime_r(a, b) \ - do { \ - *(b) = *gmtime(a); \ - } while (0) - -#endif /* CS_PLATFORM == CS_P_WINDOWS */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_unix.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ -#if CS_PLATFORM == CS_P_UNIX - -#ifndef _XOPEN_SOURCE -#define _XOPEN_SOURCE 600 -#endif - -/* wants this for C++ */ -#ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS -#endif - -/* C++ wants that for INT64_MAX */ -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS -#endif - -/* Enable fseeko() and ftello() functions */ -#ifndef _LARGEFILE_SOURCE -#define _LARGEFILE_SOURCE -#endif - -/* Enable 64-bit file offsets */ -#ifndef _FILE_OFFSET_BITS -#define _FILE_OFFSET_BITS 64 -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __APPLE__ -#include -#ifndef BYTE_ORDER -#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN -#define BIG_ENDIAN __DARWIN_BIG_ENDIAN -#define PDP_ENDIAN __DARWIN_PDP_ENDIAN -#define BYTE_ORDER __DARWIN_BYTE_ORDER -#endif -#endif - -/* - * osx correctly avoids defining strtoll when compiling in strict ansi mode. - * c++ 11 standard defines strtoll as well. - * We require strtoll, and if your embedded pre-c99 compiler lacks one, please - * implement a shim. - */ -#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \ - !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L) -long long strtoll(const char *, char **, int); -#endif - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "zu" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 - -#ifndef __cdecl -#define __cdecl -#endif - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#define closesocket(x) close(x) - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 1 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef MG_HOSTS_FILE_NAME -#define MG_HOSTS_FILE_NAME "/etc/hosts" -#endif - -#ifndef MG_RESOLV_CONF_FILE_NAME -#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf" -#endif - -#endif /* CS_PLATFORM == CS_P_UNIX */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_esp32.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ -#if CS_PLATFORM == CS_P_ESP32 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl -#define _FILE_OFFSET_BITS 32 - -#define MG_LWIP 1 - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#endif /* CS_PLATFORM == CS_P_ESP32 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_esp8266.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ -#if CS_PLATFORM == CS_P_ESP8266 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#if !defined(MGOS_VFS_DEFINE_DIRENT) -#define CS_DEFINE_DIRENT -#endif - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl -#define _FILE_OFFSET_BITS 32 - -#if !defined(RTOS_SDK) && !defined(__cplusplus) -#define fileno(x) -1 -#endif - -#define MG_LWIP 1 - -/* struct timeval is defined in sys/time.h. */ -#define LWIP_TIMEVAL_PRIVATE 0 - -#ifndef MG_NET_IF -#include -#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */ -#define MG_NET_IF MG_NET_IF_SOCKET -#else -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#endif -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#define inet_ntop(af, src, dst, size) \ - (((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \ - : NULL) -#define inet_pton(af, src, dst) \ - (((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0) - -#endif /* CS_PLATFORM == CS_P_ESP8266 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_cc3100.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ -#if CS_PLATFORM == CS_P_CC3100 - -#include -#include -#include -#include -#include -#include -#include - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* - * CC3100 SDK and STM32 SDK include headers w/out path, just like - * #include "simplelink.h". As result, we have to add all required directories - * into Makefile IPATH and do the same thing (include w/out path) - */ - -#include -#include -#undef timeval - -typedef int sock_t; -#define INVALID_SOCKET (-1) - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define SIZE_T_FMT "u" - -#define SOMAXCONN 8 - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); - -#endif /* CS_PLATFORM == CS_P_CC3100 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_cc3200.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ -#if CS_PLATFORM == CS_P_CC3200 - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* Only SPIFFS supports directories, SLFS does not. */ -#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING) -#define MG_ENABLE_DIRECTORY_LISTING 1 -#endif - -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#define fileno(x) -1 - -/* Some functions we implement for Mongoose. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __TI_COMPILER_VERSION__ -struct SlTimeval_t; -#define timeval SlTimeval_t -int gettimeofday(struct timeval *t, void *tz); -int settimeofday(const struct timeval *tv, const void *tz); - -int asprintf(char **strp, const char *fmt, ...); - -#endif - -/* TI's libc does not have stat & friends, add them. */ -#ifdef __TI_COMPILER_VERSION__ - -#include - -typedef unsigned int mode_t; -typedef size_t _off_t; -typedef long ssize_t; - -struct stat { - int st_ino; - mode_t st_mode; - int st_nlink; - time_t st_mtime; - off_t st_size; -}; - -int _stat(const char *pathname, struct stat *st); -int stat(const char *pathname, struct stat *st); - -#define __S_IFMT 0170000 - -#define __S_IFDIR 0040000 -#define __S_IFCHR 0020000 -#define __S_IFREG 0100000 - -#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) - -#define S_IFDIR __S_IFDIR -#define S_IFCHR __S_IFCHR -#define S_IFREG __S_IFREG -#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) -#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) - -/* 5.x series compilers don't have va_copy, 16.x do. */ -#if __TI_COMPILER_VERSION__ < 16000000 -#define va_copy(apc, ap) ((apc) = (ap)) -#endif - -#endif /* __TI_COMPILER_VERSION__ */ - -#ifdef CC3200_FS_SLFS -#define MG_FS_SLFS -#endif - -#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ - !defined(MG_ENABLE_FILESYSTEM) -#define MG_ENABLE_FILESYSTEM 1 -#define CS_DEFINE_DIRENT -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_msp432.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ -#if CS_PLATFORM == CS_P_MSP432 - -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MG_NET_IF MG_NET_IF_SIMPLELINK -#define MG_SSL_IF MG_SSL_IF_SIMPLELINK - -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ - -typedef int sock_t; -#define INVALID_SOCKET (-1) -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#define fileno(x) -1 - -/* Some functions we implement for Mongoose. */ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef __TI_COMPILER_VERSION__ -struct SlTimeval_t; -#define timeval SlTimeval_t -int gettimeofday(struct timeval *t, void *tz); -#endif - -/* TI's libc does not have stat & friends, add them. */ -#ifdef __TI_COMPILER_VERSION__ - -#include - -typedef unsigned int mode_t; -typedef size_t _off_t; -typedef long ssize_t; - -struct stat { - int st_ino; - mode_t st_mode; - int st_nlink; - time_t st_mtime; - off_t st_size; -}; - -int _stat(const char *pathname, struct stat *st); -#define stat(a, b) _stat(a, b) - -#define __S_IFMT 0170000 - -#define __S_IFDIR 0040000 -#define __S_IFCHR 0020000 -#define __S_IFREG 0100000 - -#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask)) - -#define S_IFDIR __S_IFDIR -#define S_IFCHR __S_IFCHR -#define S_IFREG __S_IFREG -#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR) -#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG) - -/* As of 5.2.7, TI compiler does not support va_copy() yet. */ -#define va_copy(apc, ap) ((apc) = (ap)) - -#endif /* __TI_COMPILER_VERSION__ */ - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \ - !defined(MG_ENABLE_FILESYSTEM) -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_MSP432 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_tm4c129.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ -#if CS_PLATFORM == CS_P_TM4C129 - -#include -#include -#include -#include -#include -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define __cdecl - -#ifndef MG_NET_IF -#include -#if LWIP_SOCKET -#define MG_NET_IF MG_NET_IF_SOCKET -#else -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#endif -#define MG_LWIP 1 -#elif MG_NET_IF == MG_NET_IF_SIMPLELINK -/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */ -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifdef __TI_COMPILER_VERSION__ -/* As of 5.2.8, TI compiler does not support va_copy() yet. */ -#define va_copy(apc, ap) ((apc) = (ap)) -#endif /* __TI_COMPILER_VERSION__ */ - -#ifdef __cplusplus -} -#endif - -#endif /* CS_PLATFORM == CS_P_TM4C129 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_mbed.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ -#if CS_PLATFORM == CS_P_MBED - -/* - * mbed.h contains C++ code (e.g. templates), thus, it should be processed - * only if included directly to startup file (ex: main.cpp) - */ -#ifdef __cplusplus -/* Amalgamated: #include "mbed.h" */ -#endif /* __cplusplus */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -typedef struct stat cs_stat_t; -#define DIRSEP '/' - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -/* - * mbed can be compiled with the ARM compiler which - * just doesn't come with a gettimeofday shim - * because it's a BSD API and ARM targets embedded - * non-unix platforms. - */ -#if defined(__ARMCC_VERSION) || defined(__ICCARM__) -#define _TIMEVAL_DEFINED -#define gettimeofday _gettimeofday - -/* copied from GCC on ARM; for some reason useconds are signed */ -typedef long suseconds_t; /* microseconds (signed) */ -struct timeval { - time_t tv_sec; /* seconds */ - suseconds_t tv_usec; /* and microseconds */ -}; - -#endif - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK - -#define MG_SIMPLELINK_NO_OSI 1 - -#include - -typedef int sock_t; -#define INVALID_SOCKET (-1) - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define INT64_X_FMT PRIx64 -#define SIZE_T_FMT "u" - -#define SOMAXCONN 8 - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); -int inet_aton(const char *cp, struct in_addr *inp); -in_addr_t inet_addr(const char *cp); - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ - -#endif /* CS_PLATFORM == CS_P_MBED */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nrf51.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ -#if CS_PLATFORM == CS_P_NRF51 - -#include -#include -#include -#include -#include -#include - -#define to64(x) strtoll(x, NULL, 10) - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#define MG_LWIP 1 -#define MG_ENABLE_IPV6 1 - -/* - * For ARM C Compiler, make lwip to export `struct timeval`; for other - * compilers, suppress it. - */ -#if !defined(__ARMCC_VERSION) -#define LWIP_TIMEVAL_PRIVATE 0 -#else -struct timeval; -int gettimeofday(struct timeval *tp, void *tzp); -#endif - -#define INT64_FMT PRId64 -#define SIZE_T_FMT "u" - -/* - * ARM C Compiler doesn't have strdup, so we provide it - */ -#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) - -#endif /* CS_PLATFORM == CS_P_NRF51 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nrf52.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ -#if CS_PLATFORM == CS_P_NRF52 - -#include -#include -#include -#include -#include -#include -#include -#include - -#define to64(x) strtoll(x, NULL, 10) - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL -#define MG_LWIP 1 -#define MG_ENABLE_IPV6 1 - -#if !defined(ENOSPC) -#define ENOSPC 28 /* No space left on device */ -#endif - -/* - * For ARM C Compiler, make lwip to export `struct timeval`; for other - * compilers, suppress it. - */ -#if !defined(__ARMCC_VERSION) -#define LWIP_TIMEVAL_PRIVATE 0 -#endif - -#define INT64_FMT PRId64 -#define SIZE_T_FMT "u" - -/* - * ARM C Compiler doesn't have strdup, so we provide it - */ -#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION) - -#endif /* CS_PLATFORM == CS_P_NRF52 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/cs_simplelink.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ - -#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK - -/* If simplelink.h is already included, all bets are off. */ -#if !defined(__SIMPLELINK_H__) - -#include - -#ifndef __TI_COMPILER_VERSION__ -#undef __CONCAT -#undef FD_CLR -#undef FD_ISSET -#undef FD_SET -#undef FD_SETSIZE -#undef FD_ZERO -#undef fd_set -#endif - -#if CS_PLATFORM == CS_P_CC3220 -#include -#include -#include -#include -#else -/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves - * and undef it. */ -#define PROVISIONING_API_H_ -#include -#undef PROVISIONING_API_H_ -#undef SL_INC_STD_BSD_API_NAMING - -#include -#include -#endif /* CS_PLATFORM == CS_P_CC3220 */ - -/* Now define only the subset of the BSD API that we use. - * Notably, close(), read() and write() are not defined. */ -#define AF_INET SL_AF_INET - -#define socklen_t SlSocklen_t -#define sockaddr SlSockAddr_t -#define sockaddr_in SlSockAddrIn_t -#define in_addr SlInAddr_t - -#define SOCK_STREAM SL_SOCK_STREAM -#define SOCK_DGRAM SL_SOCK_DGRAM - -#define htonl sl_Htonl -#define ntohl sl_Ntohl -#define htons sl_Htons -#define ntohs sl_Ntohs - -#ifndef EACCES -#define EACCES SL_EACCES -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT SL_EAFNOSUPPORT -#endif -#ifndef EAGAIN -#define EAGAIN SL_EAGAIN -#endif -#ifndef EBADF -#define EBADF SL_EBADF -#endif -#ifndef EINVAL -#define EINVAL SL_EINVAL -#endif -#ifndef ENOMEM -#define ENOMEM SL_ENOMEM -#endif -#ifndef EWOULDBLOCK -#define EWOULDBLOCK SL_EWOULDBLOCK -#endif - -#define SOMAXCONN 8 - -#ifdef __cplusplus -extern "C" { -#endif - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); -char *inet_ntoa(struct in_addr in); -int inet_pton(int af, const char *src, void *dst); - -struct mg_mgr; -struct mg_connection; - -typedef void (*mg_init_cb)(struct mg_mgr *mgr); -bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init); - -void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg); - -int sl_fs_init(void); - -void sl_restart_cb(struct mg_mgr *mgr); - -int sl_set_ssl_opts(int sock, struct mg_connection *nc); - -#ifdef __cplusplus -} -#endif - -#endif /* !defined(__SIMPLELINK_H__) */ - -/* Compatibility with older versions of SimpleLink */ -#if SL_MAJOR_VERSION_NUM < 2 - -#define SL_ERROR_BSD_EAGAIN SL_EAGAIN -#define SL_ERROR_BSD_EALREADY SL_EALREADY -#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT -#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR -#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY -#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM -#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \ - SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY -#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST -#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS -#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX -#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS -#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED -#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME -#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE -#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET -#define SL_SOCKET_FD_ZERO SL_FD_ZERO -#define SL_SOCKET_FD_SET SL_FD_SET -#define SL_SOCKET_FD_ISSET SL_FD_ISSET -#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION - -#define SL_FS_READ FS_MODE_OPEN_READ -#define SL_FS_WRITE FS_MODE_OPEN_WRITE - -#define SL_FI_FILE_SIZE(fi) ((fi).FileLen) -#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen) - -#define SlDeviceVersion_t SlVersionFull -#define sl_DeviceGet sl_DevGet -#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION -#define SL_LEN_TYPE _u8 -#define SL_OPT_TYPE _u8 - -#else /* SL_MAJOR_VERSION_NUM >= 2 */ - -#define FS_MODE_OPEN_CREATE(max_size, flag) \ - (SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size)) -#define SL_FI_FILE_SIZE(fi) ((fi).Len) -#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize) - -#define SL_LEN_TYPE _u16 -#define SL_OPT_TYPE _u16 - -#endif /* SL_MAJOR_VERSION_NUM < 2 */ - -int slfs_open(const unsigned char *fname, uint32_t flags); - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_wince.h" -#endif -#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ - -#if CS_PLATFORM == CS_P_WINCE - -/* - * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) - * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) - * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) - * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) - * MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) - * MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) - * MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003) - * MSVC++ 7.0 _MSC_VER == 1300 - * MSVC++ 6.0 _MSC_VER == 1200 - * MSVC++ 5.0 _MSC_VER == 1100 - */ -#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */ -#pragma warning(disable : 4204) /* missing c99 support */ - -#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS -#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 -#endif - -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif - -#include -#include -#include -#include -#include -#include - -#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */ - -#include -#include -#include - -#define strdup _strdup - -#ifndef EINPROGRESS -#define EINPROGRESS WSAEINPROGRESS -#endif - -#ifndef EWOULDBLOCK -#define EWOULDBLOCK WSAEWOULDBLOCK -#endif - -#ifndef EAGAIN -#define EAGAIN EWOULDBLOCK -#endif - -#ifndef __func__ -#define STRX(x) #x -#define STR(x) STRX(x) -#define __func__ __FILE__ ":" STR(__LINE__) -#endif - -#define snprintf _snprintf -#define fileno _fileno -#define vsnprintf _vsnprintf -#define sleep(x) Sleep((x) *1000) -#define to64(x) _atoi64(x) -#define rmdir _rmdir - -#if defined(_MSC_VER) && _MSC_VER >= 1400 -#define fseeko(x, y, z) _fseeki64((x), (y), (z)) -#else -#define fseeko(x, y, z) fseek((x), (y), (z)) -#endif - -typedef int socklen_t; - -#if _MSC_VER >= 1700 -#include -#else -typedef signed char int8_t; -typedef unsigned char uint8_t; -typedef int int32_t; -typedef unsigned int uint32_t; -typedef short int16_t; -typedef unsigned short uint16_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#endif - -typedef SOCKET sock_t; -typedef uint32_t in_addr_t; - -#ifndef UINT16_MAX -#define UINT16_MAX 65535 -#endif - -#ifndef UINT32_MAX -#define UINT32_MAX 4294967295 -#endif - -#ifndef pid_t -#define pid_t HANDLE -#endif - -#define INT64_FMT "I64d" -#define INT64_X_FMT "I64x" -/* TODO(alashkin): check if this is correct */ -#define SIZE_T_FMT "u" - -#define DIRSEP '\\' -#define CS_DEFINE_DIRENT - -#ifndef va_copy -#ifdef __va_copy -#define va_copy __va_copy -#else -#define va_copy(x, y) (x) = (y) -#endif -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 8192 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 4096 -#endif - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 40 -#endif - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#define abort() DebugBreak(); - -#ifndef BUFSIZ -#define BUFSIZ 4096 -#endif -/* - * Explicitly disabling MG_ENABLE_THREADS for WinCE - * because they are enabled for _WIN32 by default - */ -#ifndef MG_ENABLE_THREADS -#define MG_ENABLE_THREADS 0 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -typedef struct _stati64 { - uint32_t st_mtime; - uint32_t st_size; - uint32_t st_mode; -} cs_stat_t; - -/* - * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers - * use #ifdefs to avoid conflicts - */ - -#ifndef ENOENT -#define ENOENT ERROR_PATH_NOT_FOUND -#endif - -#ifndef EACCES -#define EACCES ERROR_ACCESS_DENIED -#endif - -#ifndef ENOMEM -#define ENOMEM ERROR_NOT_ENOUGH_MEMORY -#endif - -#ifndef _UINTPTR_T_DEFINED -typedef unsigned int *uintptr_t; -#endif - -#define _S_IFREG 2 -#define _S_IFDIR 4 - -#ifndef S_ISDIR -#define S_ISDIR(x) (((x) &_S_IFDIR) != 0) -#endif - -#ifndef S_ISREG -#define S_ISREG(x) (((x) &_S_IFREG) != 0) -#endif - -int open(const char *filename, int oflag, int pmode); -int _wstati64(const wchar_t *path, cs_stat_t *st); -const char *strerror(); - -#endif /* CS_PLATFORM == CS_P_WINCE */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nxp_lpc.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ - -#if CS_PLATFORM == CS_P_NXP_LPC - -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define INT64_FMT "lld" -#define INT64_X_FMT "llx" -#define __cdecl - -#define MG_LWIP 1 - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL - -/* - * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and - *Redlib. - * See https://community.nxp.com/message/630860 for more details. - * - * Redlib is the default and lacks certain things, so we provide them. - */ -#ifdef __REDLIB_INTERFACE_VERSION__ - -/* Let LWIP define timeval for us. */ -#define LWIP_TIMEVAL_PRIVATE 1 - -#define va_copy(d, s) __builtin_va_copy(d, s) - -#define CS_ENABLE_TO64 1 -#define to64(x) cs_to64(x) - -#define CS_ENABLE_STRDUP 1 - -#else - -#include -#define LWIP_TIMEVAL_PRIVATE 0 -#define to64(x) strtoll(x, NULL, 10) - -#endif - -#endif /* CS_PLATFORM == CS_P_NXP_LPC */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_nxp_kinetis.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ - -#if CS_PLATFORM == CS_P_NXP_KINETIS - -#include -#include -#include -#include - -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT "lld" -#define INT64_X_FMT "llx" -#define __cdecl - -#define MG_LWIP 1 - -#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL - -/* struct timeval is defined in sys/time.h. */ -#define LWIP_TIMEVAL_PRIVATE 0 - -#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_pic32.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ - -#if CS_PLATFORM == CS_P_PIC32 - -#define MG_NET_IF MG_NET_IF_PIC32 - -#include -#include -#include -#include - -#include -#include - -#include - -typedef TCP_SOCKET sock_t; -#define to64(x) strtoll(x, NULL, 10) - -#define SIZE_T_FMT "lu" -#define INT64_FMT "lld" - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -char *inet_ntoa(struct in_addr in); - -#endif /* CS_PLATFORM == CS_P_PIC32 */ - -#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/platform_stm32.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ -#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ -#if CS_PLATFORM == CS_P_STM32 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#define to64(x) strtoll(x, NULL, 10) -#define INT64_FMT PRId64 -#define SIZE_T_FMT "u" -typedef struct stat cs_stat_t; -#define DIRSEP '/' - -#ifndef CS_ENABLE_STDIO -#define CS_ENABLE_STDIO 1 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 1 -#endif - -#endif /* CS_PLATFORM == CS_P_STM32 */ -#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ -#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ - -#ifndef MG_LWIP -#define MG_LWIP 0 -#endif - -#if MG_LWIP - -/* - * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER - * already defined, so in order to avoid warnings in lwip, we have to undefine - * it. - * - * TODO: Check if in the future versions of nRF5 SDK that changes. - * Current version of nRF51 SDK: 0.8.0 - * nRF5 SDK: 0.9.0 - */ -#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 -#undef BYTE_ORDER -#endif - -#include -#include -#include -#include -#include -#include - -#ifndef LWIP_PROVIDE_ERRNO -#include -#endif - -#if LWIP_SOCKET -#include -#else -/* We really need the definitions from sockets.h. */ -#undef LWIP_SOCKET -#define LWIP_SOCKET 1 -#include -#undef LWIP_SOCKET -#define LWIP_SOCKET 0 -#endif - -#define INVALID_SOCKET (-1) -#define SOMAXCONN 10 -typedef int sock_t; - -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -struct mg_mgr; -struct mg_connection; -uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr); -void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, - int interval, int count); -#endif - -/* For older version of LWIP */ -#ifndef ipX_2_ip -#define ipX_2_ip(x) (x) -#endif - -#endif /* MG_LWIP */ - -#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_md5.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_MD5_H_ -#define CS_COMMON_MD5_H_ - -/* Amalgamated: #include "common/platform.h" */ - -#ifndef CS_DISABLE_MD5 -#define CS_DISABLE_MD5 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef struct { - uint32_t buf[4]; - uint32_t bits[2]; - unsigned char in[64]; -} cs_md5_ctx; - -void cs_md5_init(cs_md5_ctx *c); -void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len); -void cs_md5_final(unsigned char *md, cs_md5_ctx *c); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_MD5_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_sha1.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_SHA1_H_ -#define CS_COMMON_SHA1_H_ - -#ifndef CS_DISABLE_SHA1 -#define CS_DISABLE_SHA1 0 -#endif - -#if !CS_DISABLE_SHA1 - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -typedef struct { - uint32_t state[5]; - uint32_t count[2]; - unsigned char buffer[64]; -} cs_sha1_ctx; - -void cs_sha1_init(cs_sha1_ctx *); -void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len); -void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *); -void cs_hmac_sha1(const unsigned char *key, size_t key_len, - const unsigned char *text, size_t text_len, - unsigned char out[20]); -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_DISABLE_SHA1 */ - -#endif /* CS_COMMON_SHA1_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_time.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_CS_TIME_H_ -#define CS_COMMON_CS_TIME_H_ - -#include - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Sub-second granularity time(). */ -double cs_time(void); - -/* - * Similar to (non-standard) timegm, converts broken-down time into the number - * of seconds since Unix Epoch. - */ -double cs_timegm(const struct tm *tm); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_CS_TIME_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/mg_str.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_MG_STR_H_ -#define CS_COMMON_MG_STR_H_ - -#include - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Describes chunk of memory */ -struct mg_str { - const char *p; /* Memory chunk pointer */ - size_t len; /* Memory chunk length */ -}; - -/* - * Helper function for creating mg_str struct from plain C string. - * `NULL` is allowed and becomes `{NULL, 0}`. - */ -struct mg_str mg_mk_str(const char *s); - -/* - * Like `mg_mk_str`, but takes string length explicitly. - */ -struct mg_str mg_mk_str_n(const char *s, size_t len); - -/* Macro for initializing mg_str. */ -#define MG_MK_STR(str_literal) \ - { str_literal, sizeof(str_literal) - 1 } -#define MG_NULL_STR \ - { NULL, 0 } - -/* - * Cross-platform version of `strcmp()` where where first string is - * specified by `struct mg_str`. - */ -int mg_vcmp(const struct mg_str *str2, const char *str1); - -/* - * Cross-platform version of `strncasecmp()` where first string is - * specified by `struct mg_str`. - */ -int mg_vcasecmp(const struct mg_str *str2, const char *str1); - -/* Creates a copy of s (heap-allocated). */ -struct mg_str mg_strdup(const struct mg_str s); - -/* - * Creates a copy of s (heap-allocated). - * Resulting string is NUL-terminated (but NUL is not included in len). - */ -struct mg_str mg_strdup_nul(const struct mg_str s); - -/* - * Locates character in a string. - */ -const char *mg_strchr(const struct mg_str s, int c); - -/* - * Compare two `mg_str`s; return value is the same as `strcmp`. - */ -int mg_strcmp(const struct mg_str str1, const struct mg_str str2); - -/* - * Like `mg_strcmp`, but compares at most `n` characters. - */ -int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n); - -/* - * Finds the first occurrence of a substring `needle` in the `haystack`. - */ -const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle); - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_MG_STR_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/mbuf.h" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - */ - -/* - * === Memory Buffers - * - * Mbufs are mutable/growing memory buffers, like C++ strings. - * Mbuf can append data to the end of a buffer or insert data into arbitrary - * position in the middle of a buffer. The buffer grows automatically when - * needed. - */ - -#ifndef CS_COMMON_MBUF_H_ -#define CS_COMMON_MBUF_H_ - -#include -/* Amalgamated: #include "common/platform.h" */ - -#if defined(__cplusplus) -extern "C" { -#endif - -#ifndef MBUF_SIZE_MULTIPLIER -#define MBUF_SIZE_MULTIPLIER 1.5 -#endif - -/* Memory buffer descriptor */ -struct mbuf { - char *buf; /* Buffer pointer */ - size_t len; /* Data length. Data is located between offset 0 and len. */ - size_t size; /* Buffer size allocated by realloc(1). Must be >= len */ -}; - -/* - * Initialises an Mbuf. - * `initial_capacity` specifies the initial capacity of the mbuf. - */ -void mbuf_init(struct mbuf *, size_t initial_capacity); - -/* Frees the space allocated for the mbuffer and resets the mbuf structure. */ -void mbuf_free(struct mbuf *); - -/* - * Appends data to the Mbuf. - * - * Returns the number of bytes appended or 0 if out of memory. - */ -size_t mbuf_append(struct mbuf *, const void *data, size_t data_size); - -/* - * Inserts data at a specified offset in the Mbuf. - * - * Existing data will be shifted forwards and the buffer will - * be grown if necessary. - * Returns the number of bytes inserted. - */ -size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t); - -/* Removes `data_size` bytes from the beginning of the buffer. */ -void mbuf_remove(struct mbuf *, size_t data_size); - -/* - * Resizes an Mbuf. - * - * If `new_size` is smaller than buffer's `len`, the - * resize is not performed. - */ -void mbuf_resize(struct mbuf *, size_t new_size); - -/* Shrinks an Mbuf by resizing its `size` to `len`. */ -void mbuf_trim(struct mbuf *); - -#if defined(__cplusplus) -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_MBUF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_base64.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_CS_BASE64_H_ -#define CS_COMMON_CS_BASE64_H_ - -#ifndef DISABLE_BASE64 -#define DISABLE_BASE64 0 -#endif - -#if !DISABLE_BASE64 - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*cs_base64_putc_t)(char, void *); - -struct cs_base64_ctx { - /* cannot call it putc because it's a macro on some environments */ - cs_base64_putc_t b64_putc; - unsigned char chunk[3]; - int chunk_size; - void *user_data; -}; - -void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc, - void *user_data); -void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len); -void cs_base64_finish(struct cs_base64_ctx *ctx); - -void cs_base64_encode(const unsigned char *src, int src_len, char *dst); -void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len); -int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len); - -#ifdef __cplusplus -} -#endif - -#endif /* DISABLE_BASE64 */ - -#endif /* CS_COMMON_CS_BASE64_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/str_util.h" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_STR_UTIL_H_ -#define CS_COMMON_STR_UTIL_H_ - -#include -#include - -/* Amalgamated: #include "common/mg_str.h" */ -/* Amalgamated: #include "common/platform.h" */ - -#ifndef CS_ENABLE_STRDUP -#define CS_ENABLE_STRDUP 0 -#endif - -#ifndef CS_ENABLE_TO64 -#define CS_ENABLE_TO64 0 -#endif - -/* - * Expands to a string representation of its argument: e.g. - * `CS_STRINGIFY_LIT(5) expands to "5"` - */ -#define CS_STRINGIFY_LIT(x) #x - -/* - * Expands to a string representation of its argument, which is allowed - * to be a macro: e.g. - * - * #define FOO 123 - * CS_STRINGIFY_MACRO(FOO) - * - * expands to 123. - */ -#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x) - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * Equivalent of standard `strnlen()`. - */ -size_t c_strnlen(const char *s, size_t maxlen); - -/* - * Equivalent of standard `snprintf()`. - */ -int c_snprintf(char *buf, size_t buf_size, const char *format, ...); - -/* - * Equivalent of standard `vsnprintf()`. - */ -int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap); - -/* - * Find the first occurrence of find in s, where the search is limited to the - * first slen characters of s. - */ -const char *c_strnstr(const char *s, const char *find, size_t slen); - -/* - * Stringify binary data. Output buffer size must be 2 * size_of_input + 1 - * because each byte of input takes 2 bytes in string representation - * plus 1 byte for the terminating \0 character. - */ -void cs_to_hex(char *to, const unsigned char *p, size_t len); - -/* - * Convert stringified binary data back to binary. - * Does the reverse of `cs_to_hex()`. - */ -void cs_from_hex(char *to, const char *p, size_t len); - -#if CS_ENABLE_STRDUP -/* - * Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1. - */ -char *strdup(const char *src); -#endif - -#if CS_ENABLE_TO64 -#include -/* - * Simple string -> int64 conversion routine. - */ -int64_t cs_to64(const char *s); -#endif - -/* - * Cross-platform version of `strncasecmp()`. - */ -int mg_ncasecmp(const char *s1, const char *s2, size_t len); - -/* - * Cross-platform version of `strcasecmp()`. - */ -int mg_casecmp(const char *s1, const char *s2); - -/* - * Prints message to the buffer. If the buffer is large enough to hold the - * message, it returns buffer. If buffer is to small, it allocates a large - * enough buffer on heap and returns allocated buffer. - * This is a supposed use case: - * - * ```c - * char buf[5], *p = buf; - * mg_avprintf(&p, sizeof(buf), "%s", "hi there"); - * use_p_somehow(p); - * if (p != buf) { - * free(p); - * } - * ``` - * - * The purpose of this is to avoid malloc-ing if generated strings are small. - */ -int mg_asprintf(char **buf, size_t size, const char *fmt, ...); - -/* Same as mg_asprintf, but takes varargs list. */ -int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap); - -/* - * A helper function for traversing a comma separated list of values. - * It returns a list pointer shifted to the next value or NULL if the end - * of the list found. - * The value is stored in a val vector. If the value has a form "x=y", then - * eq_val vector is initialised to point to the "y" part, and val vector length - * is adjusted to point only to "x". - * If the list is just a comma separated list of entries, like "aa,bb,cc" then - * `eq_val` will contain zero-length string. - * - * The purpose of this function is to parse comma separated string without - * any copying/memory allocation. - */ -const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, - struct mg_str *eq_val); - -/* - * Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`. - */ -struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, - struct mg_str *eq_val); - -/* - * Matches 0-terminated string (mg_match_prefix) or string with given length - * mg_match_prefix_n against a glob pattern. Glob syntax: - * ``` - * - * matches zero or more characters until a slash character / - * - ** matches zero or more characters - * - ? Matches exactly one character which is not a slash / - * - | or , divides alternative patterns - * - any other character matches itself - * ``` - * Match is case-insensitive. Return number of bytes matched. - * Examples: - * ``` - * mg_match_prefix("a*f", len, "abcdefgh") == 6 - * mg_match_prefix("a*f", len, "abcdexgh") == 0 - * mg_match_prefix("a*f|de*,xy", len, "defgh") == 5 - * mg_match_prefix("?*", len, "abc") == 3 - * mg_match_prefix("?*", len, "") == 0 - * ``` - */ -size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str); - -/* - * Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`. - */ -size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str); - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_STR_UTIL_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/queue.h" -#endif -/* clang-format off */ -/*- - * Copyright (c) 1991, 1993 - * 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. - * 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. - * - * @(#)queue.h 8.5 (Berkeley) 8/20/94 - * $FreeBSD$ - */ - -#ifndef _SYS_QUEUE_H_ -#define _SYS_QUEUE_H_ - -/* - * This file defines four types of data structures: singly-linked lists, - * singly-linked tail queues, lists and tail queues. - * - * A singly-linked list is headed by a single forward pointer. The elements - * are singly linked for minimum space and pointer manipulation overhead at - * the expense of O(n) removal for arbitrary elements. New elements can be - * added to the list after an existing element or at the head of the list. - * Elements being removed from the head of the list should use the explicit - * macro for this purpose for optimum efficiency. A singly-linked list may - * only be traversed in the forward direction. Singly-linked lists are ideal - * for applications with large datasets and few or no removals or for - * implementing a LIFO queue. - * - * A singly-linked tail queue is headed by a pair of pointers, one to the - * head of the list and the other to the tail of the list. The elements are - * singly linked for minimum space and pointer manipulation overhead at the - * expense of O(n) removal for arbitrary elements. New elements can be added - * to the list after an existing element, at the head of the list, or at the - * end of the list. Elements being removed from the head of the tail queue - * should use the explicit macro for this purpose for optimum efficiency. - * A singly-linked tail queue may only be traversed in the forward direction. - * Singly-linked tail queues are ideal for applications with large datasets - * and few or no removals or for implementing a FIFO queue. - * - * A list is headed by a single forward pointer (or an array of forward - * pointers for a hash table header). The elements are doubly linked - * so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before - * or after an existing element or at the head of the list. A list - * may be traversed in either direction. - * - * A tail queue is headed by a pair of pointers, one to the head of the - * list and the other to the tail of the list. The elements are doubly - * linked so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before or - * after an existing element, at the head of the list, or at the end of - * the list. A tail queue may be traversed in either direction. - * - * For details on the use of these macros, see the queue(3) manual page. - * - * - * SLIST LIST STAILQ TAILQ - * _HEAD + + + + - * _CLASS_HEAD + + + + - * _HEAD_INITIALIZER + + + + - * _ENTRY + + + + - * _CLASS_ENTRY + + + + - * _INIT + + + + - * _EMPTY + + + + - * _FIRST + + + + - * _NEXT + + + + - * _PREV - + - + - * _LAST - - + + - * _FOREACH + + + + - * _FOREACH_FROM + + + + - * _FOREACH_SAFE + + + + - * _FOREACH_FROM_SAFE + + + + - * _FOREACH_REVERSE - - - + - * _FOREACH_REVERSE_FROM - - - + - * _FOREACH_REVERSE_SAFE - - - + - * _FOREACH_REVERSE_FROM_SAFE - - - + - * _INSERT_HEAD + + + + - * _INSERT_BEFORE - + - + - * _INSERT_AFTER + + + + - * _INSERT_TAIL - - + + - * _CONCAT - - + + - * _REMOVE_AFTER + - + - - * _REMOVE_HEAD + - + - - * _REMOVE + + + + - * _SWAP + + + + - * - */ -#ifdef QUEUE_MACRO_DEBUG -/* Store the last 2 places the queue element or head was altered */ -struct qm_trace { - unsigned long lastline; - unsigned long prevline; - const char *lastfile; - const char *prevfile; -}; - -#define TRACEBUF struct qm_trace trace; -#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } , -#define TRASHIT(x) do {(x) = (void *)-1;} while (0) -#define QMD_SAVELINK(name, link) void **name = (void *)&(link) - -#define QMD_TRACE_HEAD(head) do { \ - (head)->trace.prevline = (head)->trace.lastline; \ - (head)->trace.prevfile = (head)->trace.lastfile; \ - (head)->trace.lastline = __LINE__; \ - (head)->trace.lastfile = __FILE__; \ -} while (0) - -#define QMD_TRACE_ELEM(elem) do { \ - (elem)->trace.prevline = (elem)->trace.lastline; \ - (elem)->trace.prevfile = (elem)->trace.lastfile; \ - (elem)->trace.lastline = __LINE__; \ - (elem)->trace.lastfile = __FILE__; \ -} while (0) - -#else -#define QMD_TRACE_ELEM(elem) -#define QMD_TRACE_HEAD(head) -#define QMD_SAVELINK(name, link) -#define TRACEBUF -#define TRACEBUF_INITIALIZER -#define TRASHIT(x) -#endif /* QUEUE_MACRO_DEBUG */ - -#ifdef __cplusplus -/* - * In C++ there can be structure lists and class lists: - */ -#define QUEUE_TYPEOF(type) type -#else -#define QUEUE_TYPEOF(type) struct type -#endif - -/* - * Singly-linked List declarations. - */ -#define SLIST_HEAD(name, type) \ -struct name { \ - struct type *slh_first; /* first element */ \ -} - -#define SLIST_CLASS_HEAD(name, type) \ -struct name { \ - class type *slh_first; /* first element */ \ -} - -#define SLIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define SLIST_ENTRY(type) \ -struct { \ - struct type *sle_next; /* next element */ \ -} - -#define SLIST_CLASS_ENTRY(type) \ -struct { \ - class type *sle_next; /* next element */ \ -} - -/* - * Singly-linked List functions. - */ -#define SLIST_EMPTY(head) ((head)->slh_first == NULL) - -#define SLIST_FIRST(head) ((head)->slh_first) - -#define SLIST_FOREACH(var, head, field) \ - for ((var) = SLIST_FIRST((head)); \ - (var); \ - (var) = SLIST_NEXT((var), field)) - -#define SLIST_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ - (var); \ - (var) = SLIST_NEXT((var), field)) - -#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = SLIST_FIRST((head)); \ - (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \ - (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ - for ((varp) = &SLIST_FIRST((head)); \ - ((var) = *(varp)) != NULL; \ - (varp) = &SLIST_NEXT((var), field)) - -#define SLIST_INIT(head) do { \ - SLIST_FIRST((head)) = NULL; \ -} while (0) - -#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ - SLIST_NEXT((slistelm), field) = (elm); \ -} while (0) - -#define SLIST_INSERT_HEAD(head, elm, field) do { \ - SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ - SLIST_FIRST((head)) = (elm); \ -} while (0) - -#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) - -#define SLIST_REMOVE(head, elm, type, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.sle_next); \ - if (SLIST_FIRST((head)) == (elm)) { \ - SLIST_REMOVE_HEAD((head), field); \ - } \ - else { \ - QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \ - while (SLIST_NEXT(curelm, field) != (elm)) \ - curelm = SLIST_NEXT(curelm, field); \ - SLIST_REMOVE_AFTER(curelm, field); \ - } \ - TRASHIT(*oldnext); \ -} while (0) - -#define SLIST_REMOVE_AFTER(elm, field) do { \ - SLIST_NEXT(elm, field) = \ - SLIST_NEXT(SLIST_NEXT(elm, field), field); \ -} while (0) - -#define SLIST_REMOVE_HEAD(head, field) do { \ - SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ -} while (0) - -#define SLIST_SWAP(head1, head2, type) do { \ - QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \ - SLIST_FIRST(head1) = SLIST_FIRST(head2); \ - SLIST_FIRST(head2) = swap_first; \ -} while (0) - -/* - * Singly-linked Tail queue declarations. - */ -#define STAILQ_HEAD(name, type) \ -struct name { \ - struct type *stqh_first;/* first element */ \ - struct type **stqh_last;/* addr of last next element */ \ -} - -#define STAILQ_CLASS_HEAD(name, type) \ -struct name { \ - class type *stqh_first; /* first element */ \ - class type **stqh_last; /* addr of last next element */ \ -} - -#define STAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).stqh_first } - -#define STAILQ_ENTRY(type) \ -struct { \ - struct type *stqe_next; /* next element */ \ -} - -#define STAILQ_CLASS_ENTRY(type) \ -struct { \ - class type *stqe_next; /* next element */ \ -} - -/* - * Singly-linked Tail queue functions. - */ -#define STAILQ_CONCAT(head1, head2) do { \ - if (!STAILQ_EMPTY((head2))) { \ - *(head1)->stqh_last = (head2)->stqh_first; \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_INIT((head2)); \ - } \ -} while (0) - -#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) - -#define STAILQ_FIRST(head) ((head)->stqh_first) - -#define STAILQ_FOREACH(var, head, field) \ - for((var) = STAILQ_FIRST((head)); \ - (var); \ - (var) = STAILQ_NEXT((var), field)) - -#define STAILQ_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ - (var); \ - (var) = STAILQ_NEXT((var), field)) - -#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = STAILQ_FIRST((head)); \ - (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \ - (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define STAILQ_INIT(head) do { \ - STAILQ_FIRST((head)) = NULL; \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_NEXT((tqelm), field) = (elm); \ -} while (0) - -#define STAILQ_INSERT_HEAD(head, elm, field) do { \ - if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ - STAILQ_FIRST((head)) = (elm); \ -} while (0) - -#define STAILQ_INSERT_TAIL(head, elm, field) do { \ - STAILQ_NEXT((elm), field) = NULL; \ - *(head)->stqh_last = (elm); \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ -} while (0) - -#define STAILQ_LAST(head, type, field) \ - (STAILQ_EMPTY((head)) ? NULL : \ - __containerof((head)->stqh_last, \ - QUEUE_TYPEOF(type), field.stqe_next)) - -#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) - -#define STAILQ_REMOVE(head, elm, type, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \ - if (STAILQ_FIRST((head)) == (elm)) { \ - STAILQ_REMOVE_HEAD((head), field); \ - } \ - else { \ - QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \ - while (STAILQ_NEXT(curelm, field) != (elm)) \ - curelm = STAILQ_NEXT(curelm, field); \ - STAILQ_REMOVE_AFTER(head, curelm, field); \ - } \ - TRASHIT(*oldnext); \ -} while (0) - -#define STAILQ_REMOVE_AFTER(head, elm, field) do { \ - if ((STAILQ_NEXT(elm, field) = \ - STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \ - (head)->stqh_last = &STAILQ_NEXT((elm), field); \ -} while (0) - -#define STAILQ_REMOVE_HEAD(head, field) do { \ - if ((STAILQ_FIRST((head)) = \ - STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ - (head)->stqh_last = &STAILQ_FIRST((head)); \ -} while (0) - -#define STAILQ_SWAP(head1, head2, type) do { \ - QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \ - QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \ - STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \ - (head1)->stqh_last = (head2)->stqh_last; \ - STAILQ_FIRST(head2) = swap_first; \ - (head2)->stqh_last = swap_last; \ - if (STAILQ_EMPTY(head1)) \ - (head1)->stqh_last = &STAILQ_FIRST(head1); \ - if (STAILQ_EMPTY(head2)) \ - (head2)->stqh_last = &STAILQ_FIRST(head2); \ -} while (0) - - -/* - * List declarations. - */ -#define LIST_HEAD(name, type) \ -struct name { \ - struct type *lh_first; /* first element */ \ -} - -#define LIST_CLASS_HEAD(name, type) \ -struct name { \ - class type *lh_first; /* first element */ \ -} - -#define LIST_HEAD_INITIALIZER(head) \ - { NULL } - -#define LIST_ENTRY(type) \ -struct { \ - struct type *le_next; /* next element */ \ - struct type **le_prev; /* address of previous next element */ \ -} - -#define LIST_CLASS_ENTRY(type) \ -struct { \ - class type *le_next; /* next element */ \ - class type **le_prev; /* address of previous next element */ \ -} - -/* - * List functions. - */ - -#if (defined(_KERNEL) && defined(INVARIANTS)) -#define QMD_LIST_CHECK_HEAD(head, field) do { \ - if (LIST_FIRST((head)) != NULL && \ - LIST_FIRST((head))->field.le_prev != \ - &LIST_FIRST((head))) \ - panic("Bad list head %p first->prev != head", (head)); \ -} while (0) - -#define QMD_LIST_CHECK_NEXT(elm, field) do { \ - if (LIST_NEXT((elm), field) != NULL && \ - LIST_NEXT((elm), field)->field.le_prev != \ - &((elm)->field.le_next)) \ - panic("Bad link elm %p next->prev != elm", (elm)); \ -} while (0) - -#define QMD_LIST_CHECK_PREV(elm, field) do { \ - if (*(elm)->field.le_prev != (elm)) \ - panic("Bad link elm %p prev->next != elm", (elm)); \ -} while (0) -#else -#define QMD_LIST_CHECK_HEAD(head, field) -#define QMD_LIST_CHECK_NEXT(elm, field) -#define QMD_LIST_CHECK_PREV(elm, field) -#endif /* (_KERNEL && INVARIANTS) */ - -#define LIST_EMPTY(head) ((head)->lh_first == NULL) - -#define LIST_FIRST(head) ((head)->lh_first) - -#define LIST_FOREACH(var, head, field) \ - for ((var) = LIST_FIRST((head)); \ - (var); \ - (var) = LIST_NEXT((var), field)) - -#define LIST_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ - (var); \ - (var) = LIST_NEXT((var), field)) - -#define LIST_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = LIST_FIRST((head)); \ - (var) && ((tvar) = LIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : LIST_FIRST((head))); \ - (var) && ((tvar) = LIST_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define LIST_INIT(head) do { \ - LIST_FIRST((head)) = NULL; \ -} while (0) - -#define LIST_INSERT_AFTER(listelm, elm, field) do { \ - QMD_LIST_CHECK_NEXT(listelm, field); \ - if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ - LIST_NEXT((listelm), field)->field.le_prev = \ - &LIST_NEXT((elm), field); \ - LIST_NEXT((listelm), field) = (elm); \ - (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ -} while (0) - -#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ - QMD_LIST_CHECK_PREV(listelm, field); \ - (elm)->field.le_prev = (listelm)->field.le_prev; \ - LIST_NEXT((elm), field) = (listelm); \ - *(listelm)->field.le_prev = (elm); \ - (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ -} while (0) - -#define LIST_INSERT_HEAD(head, elm, field) do { \ - QMD_LIST_CHECK_HEAD((head), field); \ - if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ - LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ - LIST_FIRST((head)) = (elm); \ - (elm)->field.le_prev = &LIST_FIRST((head)); \ -} while (0) - -#define LIST_NEXT(elm, field) ((elm)->field.le_next) - -#define LIST_PREV(elm, head, type, field) \ - ((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \ - __containerof((elm)->field.le_prev, \ - QUEUE_TYPEOF(type), field.le_next)) - -#define LIST_REMOVE(elm, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.le_next); \ - QMD_SAVELINK(oldprev, (elm)->field.le_prev); \ - QMD_LIST_CHECK_NEXT(elm, field); \ - QMD_LIST_CHECK_PREV(elm, field); \ - if (LIST_NEXT((elm), field) != NULL) \ - LIST_NEXT((elm), field)->field.le_prev = \ - (elm)->field.le_prev; \ - *(elm)->field.le_prev = LIST_NEXT((elm), field); \ - TRASHIT(*oldnext); \ - TRASHIT(*oldprev); \ -} while (0) - -#define LIST_SWAP(head1, head2, type, field) do { \ - QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \ - LIST_FIRST((head1)) = LIST_FIRST((head2)); \ - LIST_FIRST((head2)) = swap_tmp; \ - if ((swap_tmp = LIST_FIRST((head1))) != NULL) \ - swap_tmp->field.le_prev = &LIST_FIRST((head1)); \ - if ((swap_tmp = LIST_FIRST((head2))) != NULL) \ - swap_tmp->field.le_prev = &LIST_FIRST((head2)); \ -} while (0) - -/* - * Tail queue declarations. - */ -#define TAILQ_HEAD(name, type) \ -struct name { \ - struct type *tqh_first; /* first element */ \ - struct type **tqh_last; /* addr of last next element */ \ - TRACEBUF \ -} - -#define TAILQ_CLASS_HEAD(name, type) \ -struct name { \ - class type *tqh_first; /* first element */ \ - class type **tqh_last; /* addr of last next element */ \ - TRACEBUF \ -} - -#define TAILQ_HEAD_INITIALIZER(head) \ - { NULL, &(head).tqh_first, TRACEBUF_INITIALIZER } - -#define TAILQ_ENTRY(type) \ -struct { \ - struct type *tqe_next; /* next element */ \ - struct type **tqe_prev; /* address of previous next element */ \ - TRACEBUF \ -} - -#define TAILQ_CLASS_ENTRY(type) \ -struct { \ - class type *tqe_next; /* next element */ \ - class type **tqe_prev; /* address of previous next element */ \ - TRACEBUF \ -} - -/* - * Tail queue functions. - */ -#if (defined(_KERNEL) && defined(INVARIANTS)) -#define QMD_TAILQ_CHECK_HEAD(head, field) do { \ - if (!TAILQ_EMPTY(head) && \ - TAILQ_FIRST((head))->field.tqe_prev != \ - &TAILQ_FIRST((head))) \ - panic("Bad tailq head %p first->prev != head", (head)); \ -} while (0) - -#define QMD_TAILQ_CHECK_TAIL(head, field) do { \ - if (*(head)->tqh_last != NULL) \ - panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \ -} while (0) - -#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \ - if (TAILQ_NEXT((elm), field) != NULL && \ - TAILQ_NEXT((elm), field)->field.tqe_prev != \ - &((elm)->field.tqe_next)) \ - panic("Bad link elm %p next->prev != elm", (elm)); \ -} while (0) - -#define QMD_TAILQ_CHECK_PREV(elm, field) do { \ - if (*(elm)->field.tqe_prev != (elm)) \ - panic("Bad link elm %p prev->next != elm", (elm)); \ -} while (0) -#else -#define QMD_TAILQ_CHECK_HEAD(head, field) -#define QMD_TAILQ_CHECK_TAIL(head, headname) -#define QMD_TAILQ_CHECK_NEXT(elm, field) -#define QMD_TAILQ_CHECK_PREV(elm, field) -#endif /* (_KERNEL && INVARIANTS) */ - -#define TAILQ_CONCAT(head1, head2, field) do { \ - if (!TAILQ_EMPTY(head2)) { \ - *(head1)->tqh_last = (head2)->tqh_first; \ - (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ - (head1)->tqh_last = (head2)->tqh_last; \ - TAILQ_INIT((head2)); \ - QMD_TRACE_HEAD(head1); \ - QMD_TRACE_HEAD(head2); \ - } \ -} while (0) - -#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) - -#define TAILQ_FIRST(head) ((head)->tqh_first) - -#define TAILQ_FOREACH(var, head, field) \ - for ((var) = TAILQ_FIRST((head)); \ - (var); \ - (var) = TAILQ_NEXT((var), field)) - -#define TAILQ_FOREACH_FROM(var, head, field) \ - for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ - (var); \ - (var) = TAILQ_NEXT((var), field)) - -#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ - for ((var) = TAILQ_FIRST((head)); \ - (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \ - for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \ - (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ - for ((var) = TAILQ_LAST((head), headname); \ - (var); \ - (var) = TAILQ_PREV((var), headname, field)) - -#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \ - for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ - (var); \ - (var) = TAILQ_PREV((var), headname, field)) - -#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ - for ((var) = TAILQ_LAST((head), headname); \ - (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ - (var) = (tvar)) - -#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \ - for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \ - (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ - (var) = (tvar)) - -#define TAILQ_INIT(head) do { \ - TAILQ_FIRST((head)) = NULL; \ - (head)->tqh_last = &TAILQ_FIRST((head)); \ - QMD_TRACE_HEAD(head); \ -} while (0) - -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ - QMD_TAILQ_CHECK_NEXT(listelm, field); \ - if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else { \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_HEAD(head); \ - } \ - TAILQ_NEXT((listelm), field) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ - QMD_TRACE_ELEM(&(elm)->field); \ - QMD_TRACE_ELEM(&(listelm)->field); \ -} while (0) - -#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ - QMD_TAILQ_CHECK_PREV(listelm, field); \ - (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ - TAILQ_NEXT((elm), field) = (listelm); \ - *(listelm)->field.tqe_prev = (elm); \ - (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_ELEM(&(elm)->field); \ - QMD_TRACE_ELEM(&(listelm)->field); \ -} while (0) - -#define TAILQ_INSERT_HEAD(head, elm, field) do { \ - QMD_TAILQ_CHECK_HEAD(head, field); \ - if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ - TAILQ_FIRST((head))->field.tqe_prev = \ - &TAILQ_NEXT((elm), field); \ - else \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - TAILQ_FIRST((head)) = (elm); \ - (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ - QMD_TRACE_HEAD(head); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_INSERT_TAIL(head, elm, field) do { \ - QMD_TAILQ_CHECK_TAIL(head, field); \ - TAILQ_NEXT((elm), field) = NULL; \ - (elm)->field.tqe_prev = (head)->tqh_last; \ - *(head)->tqh_last = (elm); \ - (head)->tqh_last = &TAILQ_NEXT((elm), field); \ - QMD_TRACE_HEAD(head); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_LAST(head, headname) \ - (*(((struct headname *)((head)->tqh_last))->tqh_last)) - -#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) - -#define TAILQ_PREV(elm, headname, field) \ - (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) - -#define TAILQ_REMOVE(head, elm, field) do { \ - QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \ - QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \ - QMD_TAILQ_CHECK_NEXT(elm, field); \ - QMD_TAILQ_CHECK_PREV(elm, field); \ - if ((TAILQ_NEXT((elm), field)) != NULL) \ - TAILQ_NEXT((elm), field)->field.tqe_prev = \ - (elm)->field.tqe_prev; \ - else { \ - (head)->tqh_last = (elm)->field.tqe_prev; \ - QMD_TRACE_HEAD(head); \ - } \ - *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ - TRASHIT(*oldnext); \ - TRASHIT(*oldprev); \ - QMD_TRACE_ELEM(&(elm)->field); \ -} while (0) - -#define TAILQ_SWAP(head1, head2, type, field) do { \ - QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \ - QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \ - (head1)->tqh_first = (head2)->tqh_first; \ - (head1)->tqh_last = (head2)->tqh_last; \ - (head2)->tqh_first = swap_first; \ - (head2)->tqh_last = swap_last; \ - if ((swap_first = (head1)->tqh_first) != NULL) \ - swap_first->field.tqe_prev = &(head1)->tqh_first; \ - else \ - (head1)->tqh_last = &(head1)->tqh_first; \ - if ((swap_first = (head2)->tqh_first) != NULL) \ - swap_first->field.tqe_prev = &(head2)->tqh_first; \ - else \ - (head2)->tqh_last = &(head2)->tqh_first; \ -} while (0) - -#endif /* !_SYS_QUEUE_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_features.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_FEATURES_H_ -#define CS_MONGOOSE_SRC_FEATURES_H_ - -#ifndef MG_DISABLE_HTTP_DIGEST_AUTH -#define MG_DISABLE_HTTP_DIGEST_AUTH 0 -#endif - -#ifndef MG_DISABLE_HTTP_KEEP_ALIVE -#define MG_DISABLE_HTTP_KEEP_ALIVE 0 -#endif - -#ifndef MG_DISABLE_PFS -#define MG_DISABLE_PFS 0 -#endif - -#ifndef MG_DISABLE_WS_RANDOM_MASK -#define MG_DISABLE_WS_RANDOM_MASK 0 -#endif - -#ifndef MG_ENABLE_ASYNC_RESOLVER -#define MG_ENABLE_ASYNC_RESOLVER 1 -#endif - -#ifndef MG_ENABLE_BROADCAST -#define MG_ENABLE_BROADCAST 0 -#endif - -#ifndef MG_ENABLE_COAP -#define MG_ENABLE_COAP 0 -#endif - -#ifndef MG_ENABLE_DEBUG -#define MG_ENABLE_DEBUG 0 -#endif - -#ifndef MG_ENABLE_DIRECTORY_LISTING -#define MG_ENABLE_DIRECTORY_LISTING 0 -#endif - -#ifndef MG_ENABLE_DNS -#define MG_ENABLE_DNS 1 -#endif - -#ifndef MG_ENABLE_DNS_SERVER -#define MG_ENABLE_DNS_SERVER 0 -#endif - -#ifndef MG_ENABLE_FAKE_DAVLOCK -#define MG_ENABLE_FAKE_DAVLOCK 0 -#endif - -#ifndef MG_ENABLE_FILESYSTEM -#define MG_ENABLE_FILESYSTEM 0 -#endif - -#ifndef MG_ENABLE_GETADDRINFO -#define MG_ENABLE_GETADDRINFO 0 -#endif - -#ifndef MG_ENABLE_HEXDUMP -#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO -#endif - -#ifndef MG_ENABLE_HTTP -#define MG_ENABLE_HTTP 1 -#endif - -#ifndef MG_ENABLE_HTTP_CGI -#define MG_ENABLE_HTTP_CGI 0 -#endif - -#ifndef MG_ENABLE_HTTP_SSI -#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM -#endif - -#ifndef MG_ENABLE_HTTP_SSI_EXEC -#define MG_ENABLE_HTTP_SSI_EXEC 0 -#endif - -#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART -#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0 -#endif - -#ifndef MG_ENABLE_HTTP_WEBDAV -#define MG_ENABLE_HTTP_WEBDAV 0 -#endif - -#ifndef MG_ENABLE_HTTP_WEBSOCKET -#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP -#endif - -#ifndef MG_ENABLE_IPV6 -#define MG_ENABLE_IPV6 0 -#endif - -#ifndef MG_ENABLE_MQTT -#define MG_ENABLE_MQTT 1 -#endif - -#ifndef MG_ENABLE_SOCKS -#define MG_ENABLE_SOCKS 0 -#endif - -#ifndef MG_ENABLE_MQTT_BROKER -#define MG_ENABLE_MQTT_BROKER 0 -#endif - -#ifndef MG_ENABLE_SSL -#define MG_ENABLE_SSL 0 -#endif - -#ifndef MG_ENABLE_SYNC_RESOLVER -#define MG_ENABLE_SYNC_RESOLVER 0 -#endif - -#ifndef MG_ENABLE_STDIO -#define MG_ENABLE_STDIO CS_ENABLE_STDIO -#endif - -#ifndef MG_NET_IF -#define MG_NET_IF MG_NET_IF_SOCKET -#endif - -#ifndef MG_SSL_IF -#define MG_SSL_IF MG_SSL_IF_OPENSSL -#endif - -#ifndef MG_ENABLE_THREADS /* ifdef-ok */ -#ifdef _WIN32 -#define MG_ENABLE_THREADS 1 -#else -#define MG_ENABLE_THREADS 0 -#endif -#endif - -#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG) -#define CS_ENABLE_DEBUG 1 -#endif - -/* MQTT broker requires MQTT */ -#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT -#undef MG_ENABLE_MQTT -#define MG_ENABLE_MQTT 1 -#endif - -#ifndef MG_ENABLE_HTTP_URL_REWRITES -#define MG_ENABLE_HTTP_URL_REWRITES \ - (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX) -#endif - -#ifndef MG_ENABLE_SNTP -#define MG_ENABLE_SNTP 0 -#endif - -#ifndef MG_ENABLE_EXTRA_ERRORS_DESC -#define MG_ENABLE_EXTRA_ERRORS_DESC 0 -#endif - -#ifndef MG_ENABLE_CALLBACK_USERDATA -#define MG_ENABLE_CALLBACK_USERDATA 0 -#endif - -#if MG_ENABLE_CALLBACK_USERDATA -#define MG_UD_ARG(ud) , ud -#define MG_CB(cb, ud) cb, ud -#else -#define MG_UD_ARG(ud) -#define MG_CB(cb, ud) cb -#endif - -#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_NET_IF_H_ -#define CS_MONGOOSE_SRC_NET_IF_H_ - -/* Amalgamated: #include "common/platform.h" */ - -/* - * Internal async networking core interface. - * Consists of calls made by the core, which should not block, - * and callbacks back into the core ("..._cb"). - * Callbacks may (will) cause methods to be invoked from within, - * but methods are not allowed to invoke callbacks inline. - * - * Implementation must ensure that only one callback is invoked at any time. - */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_MAIN_IFACE 0 - -struct mg_mgr; -struct mg_connection; -union socket_address; - -struct mg_iface_vtable; - -struct mg_iface { - struct mg_mgr *mgr; - void *data; /* Implementation-specific data */ - const struct mg_iface_vtable *vtable; -}; - -struct mg_iface_vtable { - void (*init)(struct mg_iface *iface); - void (*free)(struct mg_iface *iface); - void (*add_conn)(struct mg_connection *nc); - void (*remove_conn)(struct mg_connection *nc); - time_t (*poll)(struct mg_iface *iface, int timeout_ms); - - /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */ - int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa); - /* Request that a "listening" UDP socket be created. */ - int (*listen_udp)(struct mg_connection *nc, union socket_address *sa); - - /* Request that a TCP connection is made to the specified address. */ - void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa); - /* Open a UDP socket. Doesn't actually connect anything. */ - void (*connect_udp)(struct mg_connection *nc); - - /* Send functions for TCP and UDP. Sent data is copied before return. */ - void (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len); - void (*udp_send)(struct mg_connection *nc, const void *buf, size_t len); - - void (*recved)(struct mg_connection *nc, size_t len); - - /* Perform interface-related connection initialization. Return 1 on ok. */ - int (*create_conn)(struct mg_connection *nc); - /* Perform interface-related cleanup on connection before destruction. */ - void (*destroy_conn)(struct mg_connection *nc); - - /* Associate a socket to a connection. */ - void (*sock_set)(struct mg_connection *nc, sock_t sock); - - /* Put connection's address into *sa, local (remote = 0) or remote. */ - void (*get_conn_addr)(struct mg_connection *nc, int remote, - union socket_address *sa); -}; - -extern const struct mg_iface_vtable *mg_ifaces[]; -extern int mg_num_ifaces; - -/* Creates a new interface instance. */ -struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, - struct mg_mgr *mgr); - -/* - * Find an interface with a given implementation. The search is started from - * interface `from`, exclusive. Returns NULL if none is found. - */ -struct mg_iface *mg_find_iface(struct mg_mgr *mgr, - const struct mg_iface_vtable *vtable, - struct mg_iface *from); -/* - * Deliver a new TCP connection. Returns NULL in case on error (unable to - * create connection, in which case interface state should be discarded. - * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered - * when mg_if_accept_tcp_cb is invoked. - */ -struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc); -void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, - size_t sa_len); - -/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */ -void mg_if_connect_cb(struct mg_connection *nc, int err); -/* Callback that reports that data has been put on the wire. */ -void mg_if_sent_cb(struct mg_connection *nc, int num_sent); -/* - * Receive callback. - * if `own` is true, buf must be heap-allocated and ownership is transferred - * to the core. - * Core will acknowledge consumption by calling iface::recved. - */ -void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own); -/* - * Receive callback. - * buf must be heap-allocated and ownership is transferred to the core. - * Core will acknowledge consumption by calling iface::recved. - */ -void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, - union socket_address *sa, size_t sa_len); - -/* void mg_if_close_conn(struct mg_connection *nc); */ - -/* Deliver a POLL event to the connection. */ -void mg_if_poll(struct mg_connection *nc, time_t now); - -/* Deliver a TIMER event to the connection. */ -void mg_if_timer(struct mg_connection *c, double now); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_ssl_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SSL_IF_H_ -#define CS_MONGOOSE_SRC_SSL_IF_H_ - -#if MG_ENABLE_SSL - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -struct mg_ssl_if_ctx; -struct mg_connection; - -void mg_ssl_if_init(); - -enum mg_ssl_if_result { - MG_SSL_OK = 0, - MG_SSL_WANT_READ = -1, - MG_SSL_WANT_WRITE = -2, - MG_SSL_ERROR = -3, -}; - -struct mg_ssl_if_conn_params { - const char *cert; - const char *key; - const char *ca_cert; - const char *server_name; - const char *cipher_suites; - const char *psk_identity; - const char *psk_key; -}; - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg); -enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, - struct mg_connection *lc); -void mg_ssl_if_conn_close_notify(struct mg_connection *nc); -void mg_ssl_if_conn_free(struct mg_connection *nc); - -enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc); -int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size); -int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_SSL */ - -#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === Core API: TCP/UDP/SSL - * - * NOTE: Mongoose manager is single threaded. It does not protect - * its data structures by mutexes, therefore all functions that are dealing - * with a particular event manager should be called from the same thread, - * with exception of the `mg_broadcast()` function. It is fine to have different - * event managers handled by different threads. - */ - -#ifndef CS_MONGOOSE_SRC_NET_H_ -#define CS_MONGOOSE_SRC_NET_H_ - -/* Amalgamated: #include "mg_common.h" */ -/* Amalgamated: #include "mg_net_if.h" */ -/* Amalgamated: #include "common/mbuf.h" */ - -#ifndef MG_VPRINTF_BUFFER_SIZE -#define MG_VPRINTF_BUFFER_SIZE 100 -#endif - -#ifdef MG_USE_READ_WRITE -#define MG_RECV_FUNC(s, b, l, f) read(s, b, l) -#define MG_SEND_FUNC(s, b, l, f) write(s, b, l) -#else -#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f) -#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f) -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -union socket_address { - struct sockaddr sa; - struct sockaddr_in sin; -#if MG_ENABLE_IPV6 - struct sockaddr_in6 sin6; -#else - struct sockaddr sin6; -#endif -}; - -struct mg_connection; - -/* - * Callback function (event handler) prototype. Must be defined by the user. - * Mongoose calls the event handler, passing the events defined below. - */ -typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)); - -/* Events. Meaning of event parameter (evp) is given in the comment. */ -#define MG_EV_POLL 0 /* Sent to each connection on each mg_mgr_poll() call */ -#define MG_EV_ACCEPT 1 /* New connection accepted. union socket_address * */ -#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int * */ -#define MG_EV_RECV 3 /* Data has been received. int *num_bytes */ -#define MG_EV_SEND 4 /* Data has been written to a socket. int *num_bytes */ -#define MG_EV_CLOSE 5 /* Connection is closed. NULL */ -#define MG_EV_TIMER 6 /* now >= conn->ev_timer_time. double * */ - -/* - * Mongoose event manager. - */ -struct mg_mgr { - struct mg_connection *active_connections; -#if MG_ENABLE_HEXDUMP - const char *hexdump_file; /* Debug hexdump file path */ -#endif -#if MG_ENABLE_BROADCAST - sock_t ctl[2]; /* Socketpair for mg_broadcast() */ -#endif - void *user_data; /* User data */ - int num_ifaces; - struct mg_iface **ifaces; /* network interfaces */ - const char *nameserver; /* DNS server to use */ -}; - -/* - * Mongoose connection. - */ -struct mg_connection { - struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */ - struct mg_connection *listener; /* Set only for accept()-ed connections */ - struct mg_mgr *mgr; /* Pointer to containing manager */ - - sock_t sock; /* Socket to the remote peer */ - int err; - union socket_address sa; /* Remote peer address */ - size_t recv_mbuf_limit; /* Max size of recv buffer */ - struct mbuf recv_mbuf; /* Received data */ - struct mbuf send_mbuf; /* Data scheduled for sending */ - time_t last_io_time; /* Timestamp of the last socket IO */ - double ev_timer_time; /* Timestamp of the future MG_EV_TIMER */ -#if MG_ENABLE_SSL - void *ssl_if_data; /* SSL library data. */ -#endif - mg_event_handler_t proto_handler; /* Protocol-specific event handler */ - void *proto_data; /* Protocol-specific data */ - void (*proto_data_destructor)(void *proto_data); - mg_event_handler_t handler; /* Event handler function */ - void *user_data; /* User-specific data */ - union { - void *v; - /* - * the C standard is fussy about fitting function pointers into - * void pointers, since some archs might have fat pointers for functions. - */ - mg_event_handler_t f; - } priv_1; - void *priv_2; - void *mgr_data; /* Implementation-specific event manager's data. */ - struct mg_iface *iface; - unsigned long flags; -/* Flags set by Mongoose */ -#define MG_F_LISTENING (1 << 0) /* This connection is listening */ -#define MG_F_UDP (1 << 1) /* This connection is UDP */ -#define MG_F_RESOLVING (1 << 2) /* Waiting for async resolver */ -#define MG_F_CONNECTING (1 << 3) /* connect() call in progress */ -#define MG_F_SSL (1 << 4) /* SSL is enabled on the connection */ -#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */ -#define MG_F_WANT_READ (1 << 6) /* SSL specific */ -#define MG_F_WANT_WRITE (1 << 7) /* SSL specific */ -#define MG_F_IS_WEBSOCKET (1 << 8) /* Websocket specific */ - -/* Flags that are settable by user */ -#define MG_F_SEND_AND_CLOSE (1 << 10) /* Push remaining data and close */ -#define MG_F_CLOSE_IMMEDIATELY (1 << 11) /* Disconnect */ -#define MG_F_WEBSOCKET_NO_DEFRAG (1 << 12) /* Websocket specific */ -#define MG_F_DELETE_CHUNK (1 << 13) /* HTTP specific */ -#define MG_F_ENABLE_BROADCAST (1 << 14) /* Allow broadcast address usage */ - -#define MG_F_USER_1 (1 << 20) /* Flags left for application */ -#define MG_F_USER_2 (1 << 21) -#define MG_F_USER_3 (1 << 22) -#define MG_F_USER_4 (1 << 23) -#define MG_F_USER_5 (1 << 24) -#define MG_F_USER_6 (1 << 25) -}; - -/* - * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal. - * `mgr->user_data` field will be initialised with a `user_data` parameter. - * That is an arbitrary pointer, where the user code can associate some data - * with the particular Mongoose manager. For example, a C++ wrapper class - * could be written in which case `user_data` can hold a pointer to the - * class instance. - */ -void mg_mgr_init(struct mg_mgr *mgr, void *user_data); - -/* - * Optional parameters to `mg_mgr_init_opt()`. - * - * If `main_iface` is not NULL, it will be used as the main interface in the - * default interface set. The pointer will be free'd by `mg_mgr_free`. - * Otherwise, the main interface will be autodetected based on the current - * platform. - * - * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be - * used. - * This is an advanced option, as it requires you to construct a full interface - * set, including special networking interfaces required by some optional - * features such as TCP tunneling. Memory backing `ifaces` and each of the - * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`. - */ -struct mg_mgr_init_opts { - const struct mg_iface_vtable *main_iface; - int num_ifaces; - const struct mg_iface_vtable **ifaces; - const char *nameserver; -}; - -/* - * Like `mg_mgr_init` but with more options. - * - * Notably, this allows you to create a manger and choose - * dynamically which networking interface implementation to use. - */ -void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data, - struct mg_mgr_init_opts opts); - -/* - * De-initialises Mongoose manager. - * - * Closes and deallocates all active connections. - */ -void mg_mgr_free(struct mg_mgr *); - -/* - * This function performs the actual IO and must be called in a loop - * (an event loop). It returns the current timestamp. - * `milli` is the maximum number of milliseconds to sleep. - * `mg_mgr_poll()` checks all connections for IO readiness. If at least one - * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective - * event handlers and returns. - */ -time_t mg_mgr_poll(struct mg_mgr *, int milli); - -#if MG_ENABLE_BROADCAST -/* - * Passes a message of a given length to all connections. - * - * Must be called from a thread that does NOT call `mg_mgr_poll()`. - * Note that `mg_broadcast()` is the only function - * that can be, and must be, called from a different (non-IO) thread. - * - * `func` callback function will be called by the IO thread for each - * connection. When called, the event will be `MG_EV_POLL`, and a message will - * be passed as the `ev_data` pointer. Maximum message size is capped - * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes. - */ -void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, - size_t len); -#endif - -/* - * Iterates over all active connections. - * - * Returns the next connection from the list - * of active connections or `NULL` if there are no more connections. Below - * is the iteration idiom: - * - * ```c - * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) { - * // Do something with connection `c` - * } - * ``` - */ -struct mg_connection *mg_next(struct mg_mgr *mgr, struct mg_connection *c); - -/* - * Optional parameters to `mg_add_sock_opt()`. - * - * `flags` is an initial `struct mg_connection::flags` bitmask to set, - * see `MG_F_*` flags definitions. - */ -struct mg_add_sock_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Initial connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ -}; - -/* - * Creates a connection, associates it with the given socket and event handler - * and adds it to the manager. - * - * For more options see the `mg_add_sock_opt` variant. - */ -struct mg_connection *mg_add_sock(struct mg_mgr *mgr, sock_t sock, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -/* - * Creates a connection, associates it with the given socket and event handler - * and adds to the manager. - * - * See the `mg_add_sock_opts` structure for a description of the options. - */ -struct mg_connection *mg_add_sock_opt(struct mg_mgr *mgr, sock_t sock, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_add_sock_opts opts); - -/* - * Optional parameters to `mg_bind_opt()`. - * - * `flags` is an initial `struct mg_connection::flags` bitmask to set, - * see `MG_F_*` flags definitions. - */ -struct mg_bind_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Extra connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ -#if MG_ENABLE_SSL - /* - * SSL settings. - * - * Server certificate to present to clients or client certificate to - * present to tunnel dispatcher (for tunneled connections). - */ - const char *ssl_cert; - /* Private key corresponding to the certificate. If ssl_cert is set but - * ssl_key is not, ssl_cert is used. */ - const char *ssl_key; - /* CA bundle used to verify client certificates or tunnel dispatchers. */ - const char *ssl_ca_cert; - /* Colon-delimited list of acceptable cipher suites. - * Names depend on the library used, for example: - * - * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) - * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 - * (mbedTLS) - * - * For OpenSSL the list can be obtained by running "openssl ciphers". - * For mbedTLS, names can be found in library/ssl_ciphersuites.c - * If NULL, a reasonable default is used. - */ - const char *ssl_cipher_suites; -#endif -}; - -/* - * Creates a listening connection. - * - * See `mg_bind_opt` for full documentation. - */ -struct mg_connection *mg_bind(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data)); -/* - * Creates a listening connection. - * - * The `address` parameter specifies which address to bind to. It's format is - * the same as for the `mg_connect()` call, where `HOST` part is optional. - * `address` can be just a port number, e.g. `:8000`. To bind to a specific - * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default, - * a TCP connection is created. To create UDP connection, prepend `udp://` - * prefix, e.g. `udp://:8000`. To summarize, `address` parameter has following - * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or - * `udp`. - * - * See the `mg_bind_opts` structure for a description of the optional - * parameters. - * - * Returns a new listening connection or `NULL` on error. - * NOTE: The connection remains owned by the manager, do not free(). - */ -struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_bind_opts opts); - -/* Optional parameters to `mg_connect_opt()` */ -struct mg_connect_opts { - void *user_data; /* Initial value for connection's user_data */ - unsigned int flags; /* Extra connection flags */ - const char **error_string; /* Placeholder for the error string */ - struct mg_iface *iface; /* Interface instance */ - const char *nameserver; /* DNS server to use, NULL for default */ -#if MG_ENABLE_SSL - /* - * SSL settings. - * Client certificate to present to the server. - */ - const char *ssl_cert; - /* - * Private key corresponding to the certificate. - * If ssl_cert is set but ssl_key is not, ssl_cert is used. - */ - const char *ssl_key; - /* - * Verify server certificate using this CA bundle. If set to "*", then SSL - * is enabled but no cert verification is performed. - */ - const char *ssl_ca_cert; - /* Colon-delimited list of acceptable cipher suites. - * Names depend on the library used, for example: - * - * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL) - * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256 - * (mbedTLS) - * - * For OpenSSL the list can be obtained by running "openssl ciphers". - * For mbedTLS, names can be found in library/ssl_ciphersuites.c - * If NULL, a reasonable default is used. - */ - const char *ssl_cipher_suites; - /* - * Server name verification. If ssl_ca_cert is set and the certificate has - * passed verification, its subject will be verified against this string. - * By default (if ssl_server_name is NULL) hostname part of the address will - * be used. Wildcard matching is supported. A special value of "*" disables - * name verification. - */ - const char *ssl_server_name; - /* - * PSK identity and key. Identity is a NUL-terminated string and key is a hex - * string. Key must be either 16 or 32 bytes (32 or 64 hex digits) for AES-128 - * or AES-256 respectively. - * Note: Default list of cipher suites does not include PSK suites, if you - * want to use PSK you will need to set ssl_cipher_suites as well. - */ - const char *ssl_psk_identity; - const char *ssl_psk_key; -#endif -}; - -/* - * Connects to a remote host. - * - * See `mg_connect_opt()` for full documentation. - */ -struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -/* - * Connects to a remote host. - * - * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or - * `udp`. `HOST` could be an IP address, - * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host - * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples - * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`, - * `[::1]:80` - * - * See the `mg_connect_opts` structure for a description of the optional - * parameters. - * - * Returns a new outbound connection or `NULL` on error. - * - * NOTE: The connection remains owned by the manager, do not free(). - * - * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified - * in the compilation flags. - * - * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event - * which will report the connect success status. - * If the asynchronous resolution fails or the `connect()` syscall fails for - * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then - * `MG_EV_CONNECT` event will report failure. Code example below: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * int connect_status; - * - * switch (ev) { - * case MG_EV_CONNECT: - * connect_status = * (int *) ev_data; - * if (connect_status == 0) { - * // Success - * } else { - * // Error - * printf("connect() error: %s\n", strerror(connect_status)); - * } - * break; - * ... - * } - * } - * - * ... - * mg_connect(mgr, "my_site.com:80", ev_handler); - * ``` - */ -struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t handler, - void *user_data), - struct mg_connect_opts opts); - -#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK -/* - * Note: This function is deprecated. Please, use SSL options in - * mg_connect_opt. - * - * Enables SSL for a given connection. - * `cert` is a server certificate file name for a listening connection - * or a client certificate file name for an outgoing connection. - * The certificate files must be in PEM format. The server certificate file - * must contain a certificate, concatenated with a private key, optionally - * concatenated with DH parameters. - * `ca_cert` is a CA certificate or NULL if peer verification is not - * required. - * Return: NULL on success or error message on error. - */ -const char *mg_set_ssl(struct mg_connection *nc, const char *cert, - const char *ca_cert); -#endif - -/* - * Sends data to the connection. - * - * Note that sending functions do not actually push data to the socket. - * They just append data to the output buffer. MG_EV_SEND will be delivered when - * the data has actually been pushed out. - */ -void mg_send(struct mg_connection *, const void *buf, int len); - -/* Enables format string warnings for mg_printf */ -#if defined(__GNUC__) -__attribute__((format(printf, 2, 3))) -#endif -/* don't separate from mg_printf declaration */ - -/* - * Sends `printf`-style formatted data to the connection. - * - * See `mg_send` for more details on send semantics. - */ -int mg_printf(struct mg_connection *, const char *fmt, ...); - -/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */ -int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap); - -/* - * Creates a socket pair. - * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`. - * Returns 0 on failure and 1 on success. - */ -int mg_socketpair(sock_t[2], int sock_type); - -#if MG_ENABLE_SYNC_RESOLVER -/* - * Convert domain name into IP address. - * - * This is a utility function. If compilation flags have - * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name - * resolution. Otherwise, `gethostbyname()` is used. - * - * CAUTION: this function can block. - * Return 1 on success, 0 on failure. - */ -int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len); -#endif - -/* - * Verify given IP address against the ACL. - * - * `remote_ip` - an IPv4 address to check, in host byte order - * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`. - * Each subnet is - * prepended by either a - or a + sign. A plus sign means allow, where a - * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`, - * it means that only that single IP address is denied. - * Subnet masks may vary from 0 to 32, inclusive. The default setting - * is to allow all access. On each request the full list is traversed, - * and the last match wins. Example: - * - * `-0.0.0.0/0,+192.168/16` - deny all accesses, only allow 192.168/16 subnet - * - * To learn more about subnet masks, see this - * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork]. - * - * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. - */ -int mg_check_ip_acl(const char *acl, uint32_t remote_ip); - -/* - * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time. - * `timestamp` is UNIX time (the number of seconds since Epoch). It is - * `double` instead of `time_t` to allow for sub-second precision. - * Returns the old timer value. - * - * Example: set the connect timeout to 1.5 seconds: - * - * ``` - * c = mg_connect(&mgr, "cesanta.com", ev_handler); - * mg_set_timer(c, mg_time() + 1.5); - * ... - * - * void ev_handler(struct mg_connection *c, int ev, void *ev_data) { - * switch (ev) { - * case MG_EV_CONNECT: - * mg_set_timer(c, 0); // Clear connect timer - * break; - * case MG_EV_TIMER: - * log("Connect timeout"); - * c->flags |= MG_F_CLOSE_IMMEDIATELY; - * break; - * ``` - */ -double mg_set_timer(struct mg_connection *c, double timestamp); - -/* - * A sub-second precision version of time(). - */ -double mg_time(void); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_NET_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_uri.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === URI - */ - -#ifndef CS_MONGOOSE_SRC_URI_H_ -#define CS_MONGOOSE_SRC_URI_H_ - -/* Amalgamated: #include "mg_net.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Parses an URI and fills string chunks with locations of the respective - * uri components within the input uri string. NULL pointers will be - * ignored. - * - * General syntax: - * - * [scheme://[user_info@]]host[:port][/path][?query][#fragment] - * - * Example: - * - * foo.com:80 - * tcp://foo.com:1234 - * http://foo.com:80/bar?baz=1 - * https://user:pw@foo.com:443/blah - * - * `path` will include the leading slash. `query` won't include the leading `?`. - * `host` can contain embedded colons if surrounded by square brackets in order - * to support IPv6 literal addresses. - * - * - * Returns 0 on success, -1 on error. - */ -int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, - struct mg_str *user_info, struct mg_str *host, - unsigned int *port, struct mg_str *path, struct mg_str *query, - struct mg_str *fragment); - -/* - * Assemble URI from parts. Any of the inputs can be NULL or zero-length mg_str. - * - * If normalize_path is true, path is normalized by resolving relative refs. - * - * Result is a heap-allocated string (uri->p must be free()d after use). - * - * Returns 0 on success, -1 on error. - */ -int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, - const struct mg_str *host, unsigned int port, - const struct mg_str *path, const struct mg_str *query, - const struct mg_str *fragment, int normalize_path, - struct mg_str *uri); - -int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_URI_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_util.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === Utility API - */ - -#ifndef CS_MONGOOSE_SRC_UTIL_H_ -#define CS_MONGOOSE_SRC_UTIL_H_ - -#include - -/* Amalgamated: #include "mg_common.h" */ -/* Amalgamated: #include "mg_net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MAX_PATH -#ifdef PATH_MAX -#define MG_MAX_PATH PATH_MAX -#else -#define MG_MAX_PATH 256 -#endif -#endif - -/* - * Fetches substring from input string `s`, `end` into `v`. - * Skips initial delimiter characters. Records first non-delimiter character - * at the beginning of substring `v`. Then scans the rest of the string - * until a delimiter character or end-of-string is found. - * `delimiters` is a 0-terminated string containing delimiter characters. - * Either one of `delimiters` or `end_string` terminates the search. - * Returns an `s` pointer, advanced forward where parsing has stopped. - */ -const char *mg_skip(const char *s, const char *end_string, - const char *delimiters, struct mg_str *v); - -/* - * Decodes base64-encoded string `s`, `len` into the destination `dst`. - * The destination has to have enough space to hold the decoded buffer. - * Decoding stops either when all strings have been decoded or invalid an - * character appeared. - * Destination is '\0'-terminated. - * Returns the number of decoded characters. On success, that should be equal - * to `len`. On error (invalid character) the return value is smaller then - * `len`. - */ -int mg_base64_decode(const unsigned char *s, int len, char *dst); - -/* - * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`. - * Destination has to have enough space to hold encoded buffer. - * Destination is '\0'-terminated. - */ -void mg_base64_encode(const unsigned char *src, int src_len, char *dst); - -#if MG_ENABLE_FILESYSTEM -/* - * Performs a 64-bit `stat()` call against a given file. - * - * `path` should be UTF8 encoded. - * - * Return value is the same as for `stat()` syscall. - */ -int mg_stat(const char *path, cs_stat_t *st); - -/* - * Opens the given file and returns a file stream. - * - * `path` and `mode` should be UTF8 encoded. - * - * Return value is the same as for the `fopen()` call. - */ -FILE *mg_fopen(const char *path, const char *mode); - -/* - * Opens the given file and returns a file stream. - * - * `path` should be UTF8 encoded. - * - * Return value is the same as for the `open()` syscall. - */ -int mg_open(const char *path, int flag, int mode); - -/* - * Reads data from the given file stream. - * - * Return value is a number of bytes readen. - */ -size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f); - -/* - * Writes data to the given file stream. - * - * Return value is a number of bytes wtitten. - */ -size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f); - -#endif /* MG_ENABLE_FILESYSTEM */ - -#if MG_ENABLE_THREADS -/* - * Starts a new detached thread. - * Arguments and semantics are the same as pthead's `pthread_create()`. - * `thread_func` is a thread function, `thread_func_param` is a parameter - * that is passed to the thread function. - */ -void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param); -#endif - -void mg_set_close_on_exec(sock_t); - -#define MG_SOCK_STRINGIFY_IP 1 -#define MG_SOCK_STRINGIFY_PORT 2 -#define MG_SOCK_STRINGIFY_REMOTE 4 -/* - * Converts a connection's local or remote address into string. - * - * The `flags` parameter is a bit mask that controls the behaviour, - * see `MG_SOCK_STRINGIFY_*` definitions. - * - * - MG_SOCK_STRINGIFY_IP - print IP address - * - MG_SOCK_STRINGIFY_PORT - print port number - * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address - * - * If both port number and IP address are printed, they are separated by `:`. - * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported. - * Return length of the stringified address. - */ -int mg_conn_addr_to_str(struct mg_connection *c, char *buf, size_t len, - int flags); -#if MG_NET_IF == MG_NET_IF_SOCKET -/* Legacy interface. */ -void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags); -#endif - -/* - * Convert the socket's address into string. - * - * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT. - */ -int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, - int flags); - -#if MG_ENABLE_HEXDUMP -/* - * Generates a human-readable hexdump of memory chunk. - * - * Takes a memory buffer `buf` of length `len` and creates a hex dump of that - * buffer in `dst`. The generated output is a-la hexdump(1). - * Returns the length of generated string, excluding terminating `\0`. If - * returned length is bigger than `dst_len`, the overflow bytes are discarded. - */ -int mg_hexdump(const void *buf, int len, char *dst, int dst_len); - -/* Same as mg_hexdump, but with output going to file instead of a buffer. */ -void mg_hexdumpf(FILE *fp, const void *buf, int len); - -/* - * Generates human-readable hexdump of the data sent or received by the - * connection. `path` is a file name where hexdump should be written. - * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*` - * events sent to an event handler. This function is supposed to be called from - * the event handler. - */ -void mg_hexdump_connection(struct mg_connection *nc, const char *path, - const void *buf, int num_bytes, int ev); -#endif - -/* - * Returns true if target platform is big endian. - */ -int mg_is_big_endian(void); - -/* - * Use with cs_base64_init/update/finish in order to write out base64 in chunks. - */ -void mg_mbuf_append_base64_putc(char ch, void *user_data); - -/* - * Encode `len` bytes starting at `data` as base64 and append them to an mbuf. - */ -void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len); - -/* - * Generate a Basic Auth header and appends it to buf. - * If pass is NULL, then user is expected to contain the credentials pair - * already encoded as `user:pass`. - */ -void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, - struct mbuf *buf); - -/* - * URL-escape the specified string. - * All non-printable characters are escaped, plus `._-$,;~()/`. - * Input need not be NUL-terminated, but the returned string is. - * Returned string is heap-allocated and must be free()'d. - */ -struct mg_str mg_url_encode(const struct mg_str src); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_UTIL_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === Common API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_H_ -#define CS_MONGOOSE_SRC_HTTP_H_ - -#if MG_ENABLE_HTTP - -/* Amalgamated: #include "mg_net.h" */ -/* Amalgamated: #include "common/mg_str.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MAX_HTTP_HEADERS -#define MG_MAX_HTTP_HEADERS 20 -#endif - -#ifndef MG_MAX_HTTP_REQUEST_SIZE -#define MG_MAX_HTTP_REQUEST_SIZE 1024 -#endif - -#ifndef MG_MAX_HTTP_SEND_MBUF -#define MG_MAX_HTTP_SEND_MBUF 1024 -#endif - -#ifndef MG_CGI_ENVIRONMENT_SIZE -#define MG_CGI_ENVIRONMENT_SIZE 8192 -#endif - -/* HTTP message */ -struct http_message { - struct mg_str message; /* Whole message: request line + headers + body */ - struct mg_str body; /* Message body. 0-length for requests with no body */ - - /* HTTP Request line (or HTTP response line) */ - struct mg_str method; /* "GET" */ - struct mg_str uri; /* "/my_file.html" */ - struct mg_str proto; /* "HTTP/1.1" -- for both request and response */ - - /* For responses, code and response status message are set */ - int resp_code; - struct mg_str resp_status_msg; - - /* - * Query-string part of the URI. For example, for HTTP request - * GET /foo/bar?param1=val1¶m2=val2 - * | uri | query_string | - * - * Note that question mark character doesn't belong neither to the uri, - * nor to the query_string - */ - struct mg_str query_string; - - /* Headers */ - struct mg_str header_names[MG_MAX_HTTP_HEADERS]; - struct mg_str header_values[MG_MAX_HTTP_HEADERS]; -}; - -#if MG_ENABLE_HTTP_WEBSOCKET -/* WebSocket message */ -struct websocket_message { - unsigned char *data; - size_t size; - unsigned char flags; -}; -#endif - -/* HTTP multipart part */ -struct mg_http_multipart_part { - const char *file_name; - const char *var_name; - struct mg_str data; - int status; /* <0 on error */ - void *user_data; -}; - -/* SSI call context */ -struct mg_ssi_call_ctx { - struct http_message *req; /* The request being processed. */ - struct mg_str file; /* Filesystem path of the file being processed. */ - struct mg_str arg; /* The argument passed to the tag: . */ -}; - -/* HTTP and websocket events. void *ev_data is described in a comment. */ -#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */ -#define MG_EV_HTTP_REPLY 101 /* struct http_message * */ -#define MG_EV_HTTP_CHUNK 102 /* struct http_message * */ -#define MG_EV_SSI_CALL 105 /* char * */ -#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */ - -#if MG_ENABLE_HTTP_WEBSOCKET -#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */ -#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112 /* NULL */ -#define MG_EV_WEBSOCKET_FRAME 113 /* struct websocket_message * */ -#define MG_EV_WEBSOCKET_CONTROL_FRAME 114 /* struct websocket_message * */ -#endif - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */ -#define MG_EV_HTTP_PART_BEGIN 122 /* struct mg_http_multipart_part */ -#define MG_EV_HTTP_PART_DATA 123 /* struct mg_http_multipart_part */ -#define MG_EV_HTTP_PART_END 124 /* struct mg_http_multipart_part */ -/* struct mg_http_multipart_part */ -#define MG_EV_HTTP_MULTIPART_REQUEST_END 125 -#endif - -/* - * Attaches a built-in HTTP event handler to the given connection. - * The user-defined event handler will receive following extra events: - * - * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request - * is passed as - * `struct http_message` through the handler's `void *ev_data` pointer. - * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is - * passed as `struct http_message` through the handler's `void *ev_data` - * pointer. - * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived. - * The parsed HTTP reply is passed as `struct http_message` through the - * handler's `void *ev_data` pointer. `http_message::body` would contain - * incomplete, reassembled HTTP body. - * It will grow with every new chunk that arrives, and it can - * potentially consume a lot of memory. An event handler may process - * the body as chunks are coming, and signal Mongoose to delete processed - * body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When - * the last zero chunk is received, - * Mongoose sends `MG_EV_HTTP_REPLY` event with - * full reassembled body (if handler did not signal to delete chunks) or - * with empty body (if handler did signal to delete chunks). - * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket - * handshake request. `ev_data` contains parsed HTTP request. - * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket - * handshake. `ev_data` is `NULL`. - * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is - * `struct websocket_message *` - * - * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses - * multipart requests and splits them into separate events: - * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request. - * This event is sent before body is parsed. After this, the user - * should expect a sequence of PART_BEGIN/DATA/END requests. - * This is also the last time when headers and other request fields are - * accessible. - * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message. - * Argument: mg_http_multipart_part with var_name and file_name set - * (if present). No data is passed in this message. - * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message. - * Argument: mg_http_multipart_part. var_name and file_name are preserved, - * data is available in mg_http_multipart_part.data. - * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are - * the same, no data in the message. If status is 0, then the part is - * properly terminated with a boundary, status < 0 means that connection - * was terminated. - * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request. - * Argument: mg_http_multipart_part, var_name and file_name are NULL, - * status = 0 means request was properly closed, < 0 means connection - * was terminated (note: in this case both PART_END and REQUEST_END are - * delivered). - */ -void mg_set_protocol_http_websocket(struct mg_connection *nc); - -#if MG_ENABLE_HTTP_WEBSOCKET -/* - * Send websocket handshake to the server. - * - * `nc` must be a valid connection, connected to a server. `uri` is an URI - * to fetch, extra_headers` is extra HTTP headers to send or `NULL`. - * - * This function is intended to be used by websocket client. - * - * Note that the Host header is mandatory in HTTP/1.1 and must be - * included in `extra_headers`. `mg_send_websocket_handshake2` offers - * a better API for that. - * - * Deprecated in favour of `mg_send_websocket_handshake2` - */ -void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, - const char *extra_headers); - -/* - * Send websocket handshake to the server. - * - * `nc` must be a valid connection, connected to a server. `uri` is an URI - * to fetch, `host` goes into the `Host` header, `protocol` goes into the - * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP - * headers to send or `NULL`. - * - * This function is intended to be used by websocket client. - */ -void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers); - -/* Like mg_send_websocket_handshake2 but also passes basic auth header */ -void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers, const char *user, - const char *pass); - -/* Same as mg_send_websocket_handshake3 but with strings not necessarily - * NUL-temrinated */ -void mg_send_websocket_handshake3v(struct mg_connection *nc, - const struct mg_str path, - const struct mg_str host, - const struct mg_str protocol, - const struct mg_str extra_headers, - const struct mg_str user, - const struct mg_str pass); - -/* - * Helper function that creates an outbound WebSocket connection. - * - * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have - * no spaces, etc. By default, `mg_connect_ws()` sends Connection and - * Host headers. `extra_headers` is an extra HTTP header to send, e.g. - * `"User-Agent: my-app\r\n"`. - * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent. - * - * Examples: - * - * ```c - * nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL, - * NULL); - * nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL, - * NULL); - * nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com", - * "clubby.cesanta.com", NULL); - * ``` - */ -struct mg_connection *mg_connect_ws(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *url, const char *protocol, - const char *extra_headers); - -/* - * Helper function that creates an outbound WebSocket connection - * - * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters - * (for example, SSL parameters) - */ -struct mg_connection *mg_connect_ws_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *protocol, - const char *extra_headers); - -/* - * Send WebSocket frame to the remote end. - * - * `op_and_flags` specifies the frame's type. It's one of: - * - * - WEBSOCKET_OP_CONTINUE - * - WEBSOCKET_OP_TEXT - * - WEBSOCKET_OP_BINARY - * - WEBSOCKET_OP_CLOSE - * - WEBSOCKET_OP_PING - * - WEBSOCKET_OP_PONG - * - * Orred with one of the flags: - * - * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent. - * - * `data` and `data_len` contain frame data. - */ -void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags, - const void *data, size_t data_len); - -/* - * Like `mg_send_websocket_frame()`, but composes a single frame from multiple - * buffers. - */ -void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags, - const struct mg_str *strings, int num_strings); - -/* - * Sends WebSocket frame to the remote end. - * - * Like `mg_send_websocket_frame()`, but allows to create formatted messages - * with `printf()`-like semantics. - */ -void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags, - const char *fmt, ...); - -/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */ -#define WEBSOCKET_OP_CONTINUE 0 -#define WEBSOCKET_OP_TEXT 1 -#define WEBSOCKET_OP_BINARY 2 -#define WEBSOCKET_OP_CLOSE 8 -#define WEBSOCKET_OP_PING 9 -#define WEBSOCKET_OP_PONG 10 - -/* - * If set causes the FIN flag to not be set on outbound - * frames. This enables sending multiple fragments of a single - * logical message. - * - * The WebSocket protocol mandates that if the FIN flag of a data - * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE. - * The last frame must have the FIN bit set. - * - * Note that mongoose will automatically defragment incoming messages, - * so this flag is used only on outbound messages. - */ -#define WEBSOCKET_DONT_FIN 0x100 - -#endif /* MG_ENABLE_HTTP_WEBSOCKET */ - -/* - * Decodes a URL-encoded string. - * - * Source string is specified by (`src`, `src_len`), and destination is - * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then - * `+` character is decoded as a blank space character. This function - * guarantees to NUL-terminate the destination. If destination is too small, - * then the source string is partially decoded and `-1` is returned. - *Otherwise, - * a length of the decoded string is returned, not counting final NUL. - */ -int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, - int is_form_url_encoded); - -extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); -extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); - -/* - * Flags for `mg_http_is_authorized()`. - */ -#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0) -#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1) -#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2) - -/* - * Checks whether an http request is authorized. `domain` is the authentication - * realm, `passwords_file` is a htdigest file (can be created e.g. with - * `htdigest` utility). If either `domain` or `passwords_file` is NULL, this - * function always returns 1; otherwise checks the authentication in the - * http request and returns 1 only if there is a match; 0 otherwise. - */ -int mg_http_is_authorized(struct http_message *hm, struct mg_str path, - const char *domain, const char *passwords_file, - int flags); - -/* - * Sends 401 Unauthorized response. - */ -void mg_http_send_digest_auth_request(struct mg_connection *c, - const char *domain); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_HTTP */ - -#endif /* CS_MONGOOSE_SRC_HTTP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_server.h" -#endif -/* - * === Server API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_ -#define CS_MONGOOSE_SRC_HTTP_SERVER_H_ - -#if MG_ENABLE_HTTP - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Parses a HTTP message. - * - * `is_req` should be set to 1 if parsing a request, 0 if reply. - * - * Returns the number of bytes parsed. If HTTP message is - * incomplete `0` is returned. On parse error, a negative number is returned. - */ -int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req); - -/* - * Searches and returns the header `name` in parsed HTTP message `hm`. - * If header is not found, NULL is returned. Example: - * - * struct mg_str *host_hdr = mg_get_http_header(hm, "Host"); - */ -struct mg_str *mg_get_http_header(struct http_message *hm, const char *name); - -/* - * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value - * in the buffer `*buf`, `buf_size`. If the buffer size is not enough, - * allocates a buffer of required size and writes it to `*buf`, similar to - * asprintf(). The caller should always check whether the buffer was updated, - * and free it if so. - * - * This function is supposed to parse cookies, authentication headers, etc. - * Example (error handling omitted): - * - * char user_buf[20]; - * char *user = user_buf; - * struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); - * mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf)); - * // ... do something useful with user - * if (user != user_buf) { - * free(user); - * } - * - * Returns the length of the variable's value. If variable is not found, 0 is - * returned. - */ -int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, - size_t buf_size); - -/* - * DEPRECATED: use mg_http_parse_header2() instead. - * - * Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of - * `char **`), and thus it cannot allocate a new buffer if the provided one - * is not enough, and just returns 0 in that case. - */ -int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, - size_t buf_size) -#ifdef __GNUC__ - __attribute__((deprecated)); -#endif -; - -/* - * Gets and parses the Authorization: Basic header - * Returns -1 if no Authorization header is found, or if - * mg_parse_http_basic_auth - * fails parsing the resulting header. - */ -int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, - char *pass, size_t pass_len); - -/* - * Parses the Authorization: Basic header - * Returns -1 iif the authorization type is not "Basic" or any other error such - * as incorrectly encoded base64 user password pair. - */ -int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, - char *pass, size_t pass_len); - -/* - * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks. - * Stores the chunk name in a `var_name`, `var_name_len` buffer. - * If a chunk is an uploaded file, then `file_name`, `file_name_len` is - * filled with an uploaded file name. `chunk`, `chunk_len` - * points to the chunk data. - * - * Return: number of bytes to skip to the next chunk or 0 if there are - * no more chunks. - * - * Usage example: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch(ev) { - * case MG_EV_HTTP_REQUEST: { - * struct http_message *hm = (struct http_message *) ev_data; - * char var_name[100], file_name[100]; - * const char *chunk; - * size_t chunk_len, n1, n2; - * - * n1 = n2 = 0; - * while ((n2 = mg_parse_multipart(hm->body.p + n1, - * hm->body.len - n1, - * var_name, sizeof(var_name), - * file_name, sizeof(file_name), - * &chunk, &chunk_len)) > 0) { - * printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n", - * var_name, file_name, (int) chunk_len, - * (int) chunk_len, chunk); - * n1 += n2; - * } - * } - * break; - * ``` - */ -size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, - size_t var_name_len, char *file_name, - size_t file_name_len, const char **chunk, - size_t *chunk_len); - -/* - * Fetches a HTTP form variable. - * - * Fetches a variable `name` from a `buf` into a buffer specified by `dst`, - * `dst_len`. The destination is always zero-terminated. Returns the length of - * a fetched variable. If not found, 0 is returned. `buf` must be valid - * url-encoded buffer. If destination is too small or an error occured, - * negative number is returned. - */ -int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, - size_t dst_len); - -#if MG_ENABLE_FILESYSTEM -/* - * This structure defines how `mg_serve_http()` works. - * Best practice is to set only required settings, and leave the rest as NULL. - */ -struct mg_serve_http_opts { - /* Path to web root directory */ - const char *document_root; - - /* List of index files. Default is "" */ - const char *index_files; - - /* - * Leave as NULL to disable authentication. - * To enable directory protection with authentication, set this to ".htpasswd" - * Then, creating ".htpasswd" file in any directory automatically protects - * it with digest authentication. - * Use `mongoose` web server binary, or `htdigest` Apache utility to - * create/manipulate passwords file. - * Make sure `auth_domain` is set to a valid domain name. - */ - const char *per_directory_auth_file; - - /* Authorization domain (domain name of this web server) */ - const char *auth_domain; - - /* - * Leave as NULL to disable authentication. - * Normally, only selected directories in the document root are protected. - * If absolutely every access to the web server needs to be authenticated, - * regardless of the URI, set this option to the path to the passwords file. - * Format of that file is the same as ".htpasswd" file. Make sure that file - * is located outside document root to prevent people fetching it. - */ - const char *global_auth_file; - - /* Set to "no" to disable directory listing. Enabled by default. */ - const char *enable_directory_listing; - - /* - * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used. - * - * All files that match ssi_pattern are treated as SSI. - * - * Server Side Includes (SSI) is a simple interpreted server-side scripting - * language which is most commonly used to include the contents of a file - * into a web page. It can be useful when it is desirable to include a common - * piece of code throughout a website, for example, headers and footers. - * - * In order for a webpage to recognize an SSI-enabled HTML file, the - * filename should end with a special extension, by default the extension - * should be either .shtml or .shtm - * - * Unknown SSI directives are silently ignored by Mongoose. Currently, - * the following SSI directives are supported: - * <!--#include FILE_TO_INCLUDE --> - * <!--#exec "COMMAND_TO_EXECUTE" --> - * <!--#call COMMAND --> - * - * Note that <!--#include ...> directive supports three path - *specifications: - * - * <!--#include virtual="path" --> Path is relative to web server root - * <!--#include abspath="path" --> Path is absolute or relative to the - * web server working dir - * <!--#include file="path" -->, Path is relative to current document - * <!--#include "path" --> - * - * The include directive may be used to include the contents of a file or - * the result of running a CGI script. - * - * The exec directive is used to execute - * a command on a server, and show command's output. Example: - * - * <!--#exec "ls -l" --> - * - * The call directive is a way to invoke a C handler from the HTML page. - * On each occurence of <!--#call COMMAND OPTIONAL_PARAMS> directive, - * Mongoose calls a registered event handler with MG_EV_SSI_CALL event, - * and event parameter will point to the COMMAND OPTIONAL_PARAMS string. - * An event handler can output any text, for example by calling - * `mg_printf()`. This is a flexible way of generating a web page on - * server side by calling a C event handler. Example: - * - * <!--#call foo --> ... <!--#call bar --> - * - * In the event handler: - * case MG_EV_SSI_CALL: { - * const char *param = (const char *) ev_data; - * if (strcmp(param, "foo") == 0) { - * mg_printf(c, "hello from foo"); - * } else if (strcmp(param, "bar") == 0) { - * mg_printf(c, "hello from bar"); - * } - * break; - * } - */ - const char *ssi_pattern; - - /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */ - const char *ip_acl; - -#if MG_ENABLE_HTTP_URL_REWRITES - /* URL rewrites. - * - * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites. - * When HTTP request is received, Mongoose constructs a file name from the - * requested URI by combining `document_root` and the URI. However, if the - * rewrite option is used and `uri_pattern` matches requested URI, then - * `document_root` is ignored. Instead, `url_file_or_directory_path` is used, - * which should be a full path name or a path relative to the web server's - * current working directory. It can also be an URI (http:// or https://) - * in which case mongoose will behave as a reverse proxy for that destination. - * - * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern. - * - * If uri_pattern starts with `@` symbol, then Mongoose compares it with the - * HOST header of the request. If they are equal, Mongoose sets document root - * to `file_or_directory_path`, implementing virtual hosts support. - * Example: `@foo.com=/document/root/for/foo.com` - * - * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with - * the listening port. If they match, then Mongoose issues a 301 redirect. - * For example, to redirect all HTTP requests to the - * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is - * automatically appended to the redirect location. - */ - const char *url_rewrites; -#endif - - /* DAV document root. If NULL, DAV requests are going to fail. */ - const char *dav_document_root; - - /* - * DAV passwords file. If NULL, DAV requests are going to fail. - * If passwords file is set to "-", then DAV auth is disabled. - */ - const char *dav_auth_file; - - /* Glob pattern for the files to hide. */ - const char *hidden_file_pattern; - - /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */ - const char *cgi_file_pattern; - - /* If not NULL, ignore CGI script hashbang and use this interpreter */ - const char *cgi_interpreter; - - /* - * Comma-separated list of Content-Type overrides for path suffixes, e.g. - * ".txt=text/plain; charset=utf-8,.c=text/plain" - */ - const char *custom_mime_types; - - /* - * Extra HTTP headers to add to each server response. - * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *". - */ - const char *extra_headers; -}; - -/* - * Serves given HTTP request according to the `options`. - * - * Example code snippet: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * struct http_message *hm = (struct http_message *) ev_data; - * struct mg_serve_http_opts opts = { .document_root = "/var/www" }; // C99 - * - * switch (ev) { - * case MG_EV_HTTP_REQUEST: - * mg_serve_http(nc, hm, opts); - * break; - * default: - * break; - * } - * } - * ``` - */ -void mg_serve_http(struct mg_connection *nc, struct http_message *hm, - struct mg_serve_http_opts opts); - -/* - * Serves a specific file with a given MIME type and optional extra headers. - * - * Example code snippet: - * - * ```c - * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch (ev) { - * case MG_EV_HTTP_REQUEST: { - * struct http_message *hm = (struct http_message *) ev_data; - * mg_http_serve_file(nc, hm, "file.txt", - * mg_mk_str("text/plain"), mg_mk_str("")); - * break; - * } - * ... - * } - * } - * ``` - */ -void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, - const char *path, const struct mg_str mime_type, - const struct mg_str extra_headers); - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - -/* Callback prototype for `mg_file_upload_handler()`. */ -typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc, - struct mg_str fname); - -/* - * File upload handler. - * This handler can be used to implement file uploads with minimum code. - * This handler will process MG_EV_HTTP_PART_* events and store file data into - * a local file. - * `local_name_fn` will be invoked with whatever name was provided by the client - * and will expect the name of the local file to open. A return value of NULL - * will abort file upload (client will get a "403 Forbidden" response). If - * non-null, the returned string must be heap-allocated and will be freed by - * the caller. - * Exception: it is ok to return the same string verbatim. - * - * Example: - * - * ```c - * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) { - * // Just return the same filename. Do not actually do this except in test! - * // fname is user-controlled and needs to be sanitized. - * return fname; - * } - * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) { - * switch (ev) { - * ... - * case MG_EV_HTTP_PART_BEGIN: - * case MG_EV_HTTP_PART_DATA: - * case MG_EV_HTTP_PART_END: - * mg_file_upload_handler(nc, ev, ev_data, upload_fname); - * break; - * } - * } - * ``` - */ -void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, - mg_fu_fname_fn local_name_fn - MG_UD_ARG(void *user_data)); -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ -#endif /* MG_ENABLE_FILESYSTEM */ - -/* - * Registers a callback for a specified http endpoint - * Note: if callback is registered it is called instead of the - * callback provided in mg_bind - * - * Example code snippet: - * - * ```c - * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) { - * (void) ev; (void) ev_data; - * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]"); - * nc->flags |= MG_F_SEND_AND_CLOSE; - * } - * - * static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) { - * (void) ev; (void) ev_data; - * mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]"); - * nc->flags |= MG_F_SEND_AND_CLOSE; - * } - * - * void init() { - * nc = mg_bind(&mgr, local_addr, cb1); - * mg_register_http_endpoint(nc, "/hello1", handle_hello1); - * mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2); - * } - * ``` - */ -void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, - MG_CB(mg_event_handler_t handler, - void *user_data)); - -struct mg_http_endpoint_opts { - void *user_data; - /* Authorization domain (realm) */ - const char *auth_domain; - const char *auth_file; -}; - -void mg_register_http_endpoint_opt(struct mg_connection *nc, - const char *uri_path, - mg_event_handler_t handler, - struct mg_http_endpoint_opts opts); - -/* - * Authenticates a HTTP request against an opened password file. - * Returns 1 if authenticated, 0 otherwise. - */ -int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, - FILE *fp); - -/* - * Authenticates given response params against an opened password file. - * Returns 1 if authenticated, 0 otherwise. - * - * It's used by mg_http_check_digest_auth(). - */ -int mg_check_digest_auth(struct mg_str method, struct mg_str uri, - struct mg_str username, struct mg_str cnonce, - struct mg_str response, struct mg_str qop, - struct mg_str nc, struct mg_str nonce, - struct mg_str auth_domain, FILE *fp); - -/* - * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding. - * This function sends the buffer size as hex number + newline first, then - * the buffer itself, then the newline. For example, - * `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string - * to the `nc->send_mbuf` output IO buffer. - * - * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to - * using this function. - * - * NOTE: do not forget to send an empty chunk at the end of the response, - * to tell the client that everything was sent. Example: - * - * ``` - * mg_printf_http_chunk(nc, "%s", "my response!"); - * mg_send_http_chunk(nc, "", 0); // Tell the client we're finished - * ``` - */ -void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len); - -/* - * Sends a printf-formatted HTTP chunk. - * Functionality is similar to `mg_send_http_chunk()`. - */ -void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...); - -/* - * Sends the response status line. - * If `extra_headers` is not NULL, then `extra_headers` are also sent - * after the response line. `extra_headers` must NOT end end with new line. - * Example: - * - * mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *"); - * - * Will result in: - * - * HTTP/1.1 200 OK\r\n - * Access-Control-Allow-Origin: *\r\n - */ -void mg_send_response_line(struct mg_connection *nc, int status_code, - const char *extra_headers); - -/* - * Sends an error response. If reason is NULL, the message will be inferred - * from the error code (if supported). - */ -void mg_http_send_error(struct mg_connection *nc, int code, const char *reason); - -/* - * Sends a redirect response. - * `status_code` should be either 301 or 302 and `location` point to the - * new location. - * If `extra_headers` is not empty, then `extra_headers` are also sent - * after the response line. `extra_headers` must NOT end end with new line. - * - * Example: - * - * mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL)); - */ -void mg_http_send_redirect(struct mg_connection *nc, int status_code, - const struct mg_str location, - const struct mg_str extra_headers); - -/* - * Sends the response line and headers. - * This function sends the response line with the `status_code`, and - * automatically - * sends one header: either "Content-Length" or "Transfer-Encoding". - * If `content_length` is negative, then "Transfer-Encoding: chunked" header - * is sent, otherwise, "Content-Length" header is sent. - * - * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent - * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions. - * Otherwise, `mg_send()` or `mg_printf()` must be used. - * Extra headers could be set through `extra_headers`. Note `extra_headers` - * must NOT be terminated by a new line. - */ -void mg_send_head(struct mg_connection *n, int status_code, - int64_t content_length, const char *extra_headers); - -/* - * Sends a printf-formatted HTTP chunk, escaping HTML tags. - */ -void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...); - -#if MG_ENABLE_HTTP_URL_REWRITES -/* - * Proxies a given request to a given upstream http server. The path prefix - * in `mount` will be stripped of the path requested to the upstream server, - * e.g. if mount is /api and upstream is http://localhost:8001/foo - * then an incoming request to /api/bar will cause a request to - * http://localhost:8001/foo/bar - * - * EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static - * mapping is good enough. - */ -void mg_http_reverse_proxy(struct mg_connection *nc, - const struct http_message *hm, struct mg_str mount, - struct mg_str upstream); -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_HTTP */ - -#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_client.h" -#endif -/* - * === Client API reference - */ - -#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_ -#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Helper function that creates an outbound HTTP connection. - * - * `url` is the URL to fetch. It must be properly URL-encoded, e.g. have - * no spaces, etc. By default, `mg_connect_http()` sends the Connection and - * Host headers. `extra_headers` is an extra HTTP header to send, e.g. - * `"User-Agent: my-app\r\n"`. - * If `post_data` is NULL, then a GET request is created. Otherwise, a POST - * request is created with the specified POST data. Note that if the data being - * posted is a form submission, the `Content-Type` header should be set - * accordingly (see example below). - * - * Examples: - * - * ```c - * nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL, - * NULL); - * nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL); - * nc3 = mg_connect_http( - * mgr, ev_handler_1, "my_server:8000/form_submit/", - * "Content-Type: application/x-www-form-urlencoded\r\n", - * "var_1=value_1&var_2=value_2"); - * ``` - */ -struct mg_connection *mg_connect_http( - struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url, - const char *extra_headers, const char *post_data); - -/* - * Helper function that creates an outbound HTTP connection. - * - * Mostly identical to mg_connect_http, but allows you to provide extra - *parameters - * (for example, SSL parameters) - */ -struct mg_connection *mg_connect_http_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *extra_headers, - const char *post_data); - -/* Creates digest authentication header for a client request. */ -int mg_http_create_digest_auth_header(char *buf, size_t buf_len, - const char *method, const char *uri, - const char *auth_domain, const char *user, - const char *passwd, const char *nonce); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === MQTT API reference - */ - -#ifndef CS_MONGOOSE_SRC_MQTT_H_ -#define CS_MONGOOSE_SRC_MQTT_H_ - -/* Amalgamated: #include "mg_net.h" */ - -struct mg_mqtt_message { - int cmd; - int qos; - int len; /* message length in the IO buffer */ - struct mg_str topic; - struct mg_str payload; - - uint8_t connack_ret_code; /* connack */ - uint16_t message_id; /* puback */ - - /* connect */ - uint8_t protocol_version; - uint8_t connect_flags; - uint16_t keep_alive_timer; - struct mg_str protocol_name; - struct mg_str client_id; - struct mg_str will_topic; - struct mg_str will_message; - struct mg_str user_name; - struct mg_str password; -}; - -struct mg_mqtt_topic_expression { - const char *topic; - uint8_t qos; -}; - -struct mg_send_mqtt_handshake_opts { - unsigned char flags; /* connection flags */ - uint16_t keep_alive; - const char *will_topic; - const char *will_message; - const char *user_name; - const char *password; -}; - -/* mg_mqtt_proto_data should be in header to allow external access to it */ -struct mg_mqtt_proto_data { - uint16_t keep_alive; - double last_control_time; -}; - -/* Message types */ -#define MG_MQTT_CMD_CONNECT 1 -#define MG_MQTT_CMD_CONNACK 2 -#define MG_MQTT_CMD_PUBLISH 3 -#define MG_MQTT_CMD_PUBACK 4 -#define MG_MQTT_CMD_PUBREC 5 -#define MG_MQTT_CMD_PUBREL 6 -#define MG_MQTT_CMD_PUBCOMP 7 -#define MG_MQTT_CMD_SUBSCRIBE 8 -#define MG_MQTT_CMD_SUBACK 9 -#define MG_MQTT_CMD_UNSUBSCRIBE 10 -#define MG_MQTT_CMD_UNSUBACK 11 -#define MG_MQTT_CMD_PINGREQ 12 -#define MG_MQTT_CMD_PINGRESP 13 -#define MG_MQTT_CMD_DISCONNECT 14 - -/* MQTT event types */ -#define MG_MQTT_EVENT_BASE 200 -#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT) -#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK) -#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH) -#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK) -#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC) -#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL) -#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP) -#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE) -#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK) -#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE) -#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK) -#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ) -#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP) -#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT) - -/* Message flags */ -#define MG_MQTT_RETAIN 0x1 -#define MG_MQTT_DUP 0x4 -#define MG_MQTT_QOS(qos) ((qos) << 1) -#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1) -#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1) - -/* Connection flags */ -#define MG_MQTT_CLEAN_SESSION 0x02 -#define MG_MQTT_HAS_WILL 0x04 -#define MG_MQTT_WILL_RETAIN 0x20 -#define MG_MQTT_HAS_PASSWORD 0x40 -#define MG_MQTT_HAS_USER_NAME 0x80 -#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3) -#define MG_MQTT_SET_WILL_QOS(flags, qos) \ - (flags) = ((flags) & ~0x18) | ((qos) << 3) - -/* CONNACK return codes */ -#define MG_EV_MQTT_CONNACK_ACCEPTED 0 -#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1 -#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2 -#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3 -#define MG_EV_MQTT_CONNACK_BAD_AUTH 4 -#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5 - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Attaches a built-in MQTT event handler to the given connection. - * - * The user-defined event handler will receive following extra events: - * - * - MG_EV_MQTT_CONNACK - * - MG_EV_MQTT_PUBLISH - * - MG_EV_MQTT_PUBACK - * - MG_EV_MQTT_PUBREC - * - MG_EV_MQTT_PUBREL - * - MG_EV_MQTT_PUBCOMP - * - MG_EV_MQTT_SUBACK - */ -void mg_set_protocol_mqtt(struct mg_connection *nc); - -/* Sends an MQTT handshake. */ -void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id); - -/* Sends an MQTT handshake with optional parameters. */ -void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, - struct mg_send_mqtt_handshake_opts); - -/* Publishes a message to a given topic. */ -void mg_mqtt_publish(struct mg_connection *nc, const char *topic, - uint16_t message_id, int flags, const void *data, - size_t len); - -/* Subscribes to a bunch of topics. */ -void mg_mqtt_subscribe(struct mg_connection *nc, - const struct mg_mqtt_topic_expression *topics, - size_t topics_len, uint16_t message_id); - -/* Unsubscribes from a bunch of topics. */ -void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, - size_t topics_len, uint16_t message_id); - -/* Sends a DISCONNECT command. */ -void mg_mqtt_disconnect(struct mg_connection *nc); - -/* Sends a CONNACK command with a given `return_code`. */ -void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code); - -/* Sends a PUBACK command with a given `message_id`. */ -void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBREC command with a given `message_id`. */ -void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBREL command with a given `message_id`. */ -void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PUBCOMP command with a given `message_id`. */ -void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id); - -/* - * Sends a SUBACK command with a given `message_id` - * and a sequence of granted QoSs. - */ -void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, - uint16_t message_id); - -/* Sends a UNSUBACK command with a given `message_id`. */ -void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id); - -/* Sends a PINGREQ command. */ -void mg_mqtt_ping(struct mg_connection *nc); - -/* Sends a PINGRESP command. */ -void mg_mqtt_pong(struct mg_connection *nc); - -/* - * Extracts the next topic expression from a SUBSCRIBE command payload. - * - * The topic expression name will point to a string in the payload buffer. - * Returns the pos of the next topic expression or -1 when the list - * of topics is exhausted. - */ -int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, - struct mg_str *topic, uint8_t *qos, int pos); - -/* - * Matches a topic against a topic expression - * - * Returns 1 if it matches; 0 otherwise. - */ -int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic); - -/* - * Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a - * NULL-terminated string. - */ -int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_MQTT_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt_server.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === MQTT Server API reference - */ - -#ifndef CS_MONGOOSE_SRC_MQTT_BROKER_H_ -#define CS_MONGOOSE_SRC_MQTT_BROKER_H_ - -#if MG_ENABLE_MQTT_BROKER - -/* Amalgamated: #include "common/queue.h" */ -/* Amalgamated: #include "mg_mqtt.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_MQTT_MAX_SESSION_SUBSCRIPTIONS -#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512 -#endif - -struct mg_mqtt_broker; - -/* MQTT session (Broker side). */ -struct mg_mqtt_session { - struct mg_mqtt_broker *brk; /* Broker */ - LIST_ENTRY(mg_mqtt_session) link; /* mg_mqtt_broker::sessions linkage */ - struct mg_connection *nc; /* Connection with the client */ - size_t num_subscriptions; /* Size of `subscriptions` array */ - void *user_data; /* User data */ - struct mg_mqtt_topic_expression *subscriptions; -}; - -/* MQTT broker. */ -struct mg_mqtt_broker { - LIST_HEAD(_mg_sesshead, mg_mqtt_session) sessions; /* Session list */ - void *user_data; /* User data */ -}; - -/* Initialises a MQTT broker. */ -void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data); - -/* - * Processes a MQTT broker message. - * - * The listening connection expects a pointer to an initialised - * `mg_mqtt_broker` structure in the `user_data` field. - * - * Basic usage: - * - * ```c - * mg_mqtt_broker_init(&brk, NULL); - * - * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) { - * // fail; - * } - * nc->user_data = &brk; - * ``` - * - * New incoming connections will receive a `mg_mqtt_session` structure - * in the connection `user_data`. The original `user_data` will be stored - * in the `user_data` field of the session structure. This allows the user - * handler to store user data before `mg_mqtt_broker` creates the session. - * - * Since only the MG_EV_ACCEPT message is processed by the listening socket, - * for most events the `user_data` will thus point to a `mg_mqtt_session`. - */ -void mg_mqtt_broker(struct mg_connection *brk, int ev, void *data); - -/* - * Iterates over all MQTT session connections. Example: - * - * ```c - * struct mg_mqtt_session *s; - * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { - * // Do something - * } - * ``` - */ -struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_MQTT_BROKER */ -#endif /* CS_MONGOOSE_SRC_MQTT_BROKER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === DNS API reference - */ - -#ifndef CS_MONGOOSE_SRC_DNS_H_ -#define CS_MONGOOSE_SRC_DNS_H_ - -/* Amalgamated: #include "mg_net.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_DNS_A_RECORD 0x01 /* Lookup IP address */ -#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */ -#define MG_DNS_PTR_RECORD 0x0c /* Lookup PTR */ -#define MG_DNS_TXT_RECORD 0x10 /* Lookup TXT */ -#define MG_DNS_AAAA_RECORD 0x1c /* Lookup IPv6 address */ -#define MG_DNS_SRV_RECORD 0x21 /* Lookup SRV */ -#define MG_DNS_MX_RECORD 0x0f /* Lookup mail server for domain */ -#define MG_DNS_ANY_RECORD 0xff -#define MG_DNS_NSEC_RECORD 0x2f - -#define MG_MAX_DNS_QUESTIONS 32 -#define MG_MAX_DNS_ANSWERS 32 - -#define MG_DNS_MESSAGE 100 /* High-level DNS message event */ - -enum mg_dns_resource_record_kind { - MG_DNS_INVALID_RECORD = 0, - MG_DNS_QUESTION, - MG_DNS_ANSWER -}; - -/* DNS resource record. */ -struct mg_dns_resource_record { - struct mg_str name; /* buffer with compressed name */ - int rtype; - int rclass; - int ttl; - enum mg_dns_resource_record_kind kind; - struct mg_str rdata; /* protocol data (can be a compressed name) */ -}; - -/* DNS message (request and response). */ -struct mg_dns_message { - struct mg_str pkt; /* packet body */ - uint16_t flags; - uint16_t transaction_id; - int num_questions; - int num_answers; - struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]; - struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]; -}; - -struct mg_dns_resource_record *mg_dns_next_record( - struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev); - -/* - * Parses the record data from a DNS resource record. - * - * - A: struct in_addr *ina - * - AAAA: struct in6_addr *ina - * - CNAME: char buffer - * - * Returns -1 on error. - * - * TODO(mkm): MX - */ -int mg_dns_parse_record_data(struct mg_dns_message *msg, - struct mg_dns_resource_record *rr, void *data, - size_t data_len); - -/* - * Sends a DNS query to the remote end. - */ -void mg_send_dns_query(struct mg_connection *nc, const char *name, - int query_type); - -/* - * Inserts a DNS header to an IO buffer. - * - * Returns the number of bytes inserted. - */ -int mg_dns_insert_header(struct mbuf *io, size_t pos, - struct mg_dns_message *msg); - -/* - * Appends already encoded questions from an existing message. - * - * This is useful when generating a DNS reply message which includes - * all question records. - * - * Returns the number of appended bytes. - */ -int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg); - -/* - * Encodes and appends a DNS resource record to an IO buffer. - * - * The record metadata is taken from the `rr` parameter, while the name and data - * are taken from the parameters, encoded in the appropriate format depending on - * record type and stored in the IO buffer. The encoded values might contain - * offsets within the IO buffer. It's thus important that the IO buffer doesn't - * get trimmed while a sequence of records are encoded while preparing a DNS - * reply. - * - * This function doesn't update the `name` and `rdata` pointers in the `rr` - * struct because they might be invalidated as soon as the IO buffer grows - * again. - * - * Returns the number of bytes appended or -1 in case of error. - */ -int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, - const char *name, size_t nlen, const void *rdata, - size_t rlen); - -/* - * Encodes a DNS name. - */ -int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len); - -/* Low-level: parses a DNS response. */ -int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg); - -/* - * Uncompresses a DNS compressed name. - * - * The containing DNS message is required because of the compressed encoding - * and reference suffixes present elsewhere in the packet. - * - * If the name is less than `dst_len` characters long, the remainder - * of `dst` is terminated with `\0` characters. Otherwise, `dst` is not - * terminated. - * - * If `dst_len` is 0 `dst` can be NULL. - * Returns the uncompressed name length. - */ -size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, - char *dst, int dst_len); - -/* - * Attaches a built-in DNS event handler to the given listening connection. - * - * The DNS event handler parses the incoming UDP packets, treating them as DNS - * requests. If an incoming packet gets successfully parsed by the DNS event - * handler, a user event handler will receive an `MG_DNS_REQUEST` event, with - * `ev_data` pointing to the parsed `struct mg_dns_message`. - * - * See - * [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server) - * example on how to handle DNS request and send DNS reply. - */ -void mg_set_protocol_dns(struct mg_connection *nc); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_DNS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns_server.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === DNS server API reference - * - * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`. - */ - -#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_ -#define CS_MONGOOSE_SRC_DNS_SERVER_H_ - -#if MG_ENABLE_DNS_SERVER - -/* Amalgamated: #include "mg_dns.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#define MG_DNS_SERVER_DEFAULT_TTL 3600 - -struct mg_dns_reply { - struct mg_dns_message *msg; - struct mbuf *io; - size_t start; -}; - -/* - * Creates a DNS reply. - * - * The reply will be based on an existing query message `msg`. - * The query body will be appended to the output buffer. - * "reply + recursion allowed" will be added to the message flags and the - * message's num_answers will be set to 0. - * - * Answer records can be appended with `mg_dns_send_reply` or by lower - * level function defined in the DNS API. - * - * In order to send a reply use `mg_dns_send_reply`. - * It's possible to use a connection's send buffer as reply buffer, - * and it will work for both UDP and TCP connections. - * - * Example: - * - * ```c - * reply = mg_dns_create_reply(&nc->send_mbuf, msg); - * for (i = 0; i < msg->num_questions; i++) { - * rr = &msg->questions[i]; - * if (rr->rtype == MG_DNS_A_RECORD) { - * mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4); - * } - * } - * mg_dns_send_reply(nc, &reply); - * ``` - */ -struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, - struct mg_dns_message *msg); - -/* - * Appends a DNS reply record to the IO buffer and to the DNS message. - * - * The message's num_answers field will be incremented. It's the caller's duty - * to ensure num_answers is properly initialised. - * - * Returns -1 on error. - */ -int mg_dns_reply_record(struct mg_dns_reply *reply, - struct mg_dns_resource_record *question, - const char *name, int rtype, int ttl, const void *rdata, - size_t rdata_len); - -/* - * Sends a DNS reply through a connection. - * - * The DNS data is stored in an IO buffer pointed by reply structure in `r`. - * This function mutates the content of that buffer in order to ensure that - * the DNS header reflects the size and flags of the message, that might have - * been updated either with `mg_dns_reply_record` or by direct manipulation of - * `r->message`. - * - * Once sent, the IO buffer will be trimmed unless the reply IO buffer - * is the connection's send buffer and the connection is not in UDP mode. - */ -void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_DNS_SERVER */ -#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_resolv.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* - * === API reference - */ - -#ifndef CS_MONGOOSE_SRC_RESOLV_H_ -#define CS_MONGOOSE_SRC_RESOLV_H_ - -/* Amalgamated: #include "mg_dns.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -enum mg_resolve_err { - MG_RESOLVE_OK = 0, - MG_RESOLVE_NO_ANSWERS = 1, - MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2, - MG_RESOLVE_TIMEOUT = 3 -}; - -typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message, - void *user_data, enum mg_resolve_err); - -/* Options for `mg_resolve_async_opt`. */ -struct mg_resolve_async_opts { - const char *nameserver; - int max_retries; /* defaults to 2 if zero */ - int timeout; /* in seconds; defaults to 5 if zero */ - int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */ - int only_literal; /* only resolves literal addrs; sync cb invocation */ - struct mg_connection **dns_conn; /* return DNS connection */ -}; - -/* See `mg_resolve_async_opt()` */ -int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data); - -/* Set default DNS server */ -void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver); - -/* - * Resolved a DNS name asynchronously. - * - * Upon successful resolution, the user callback will be invoked - * with the full DNS response message and a pointer to the user's - * context `data`. - * - * In case of timeout while performing the resolution the callback - * will receive a NULL `msg`. - * - * The DNS answers can be extracted with `mg_next_record` and - * `mg_dns_parse_record_data`: - * - * [source,c] - * ---- - * struct in_addr ina; - * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD, - * NULL); - * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina)); - * ---- - */ -int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data, - struct mg_resolve_async_opts opts); - -/* - * Resolve a name from `/etc/hosts`. - * - * Returns 0 on success, -1 on failure. - */ -int mg_resolve_from_hosts_file(const char *host, union socket_address *usa); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* CS_MONGOOSE_SRC_RESOLV_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_coap.h" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* - * === CoAP API reference - * - * CoAP message format: - * - * ``` - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ... - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * | Options (if any) ... |1 1 1 1 1 1 1 1| Payload (if any) ... - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - * ``` - */ - -#ifndef CS_MONGOOSE_SRC_COAP_H_ -#define CS_MONGOOSE_SRC_COAP_H_ - -#if MG_ENABLE_COAP - -#define MG_COAP_MSG_TYPE_FIELD 0x2 -#define MG_COAP_CODE_CLASS_FIELD 0x4 -#define MG_COAP_CODE_DETAIL_FIELD 0x8 -#define MG_COAP_MSG_ID_FIELD 0x10 -#define MG_COAP_TOKEN_FIELD 0x20 -#define MG_COAP_OPTIOMG_FIELD 0x40 -#define MG_COAP_PAYLOAD_FIELD 0x80 - -#define MG_COAP_ERROR 0x10000 -#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000) -#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000) -#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000) -#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000) - -#define MG_COAP_MSG_CON 0 -#define MG_COAP_MSG_NOC 1 -#define MG_COAP_MSG_ACK 2 -#define MG_COAP_MSG_RST 3 -#define MG_COAP_MSG_MAX 3 - -#define MG_COAP_CODECLASS_REQUEST 0 -#define MG_COAP_CODECLASS_RESP_OK 2 -#define MG_COAP_CODECLASS_CLIENT_ERR 4 -#define MG_COAP_CODECLASS_SRV_ERR 5 - -#define MG_COAP_EVENT_BASE 300 -#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON) -#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC) -#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK) -#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST) - -/* - * CoAP options. - * Use mg_coap_add_option and mg_coap_free_options - * for creation and destruction. - */ -struct mg_coap_option { - struct mg_coap_option *next; - uint32_t number; - struct mg_str value; -}; - -/* CoAP message. See RFC 7252 for details. */ -struct mg_coap_message { - uint32_t flags; - uint8_t msg_type; - uint8_t code_class; - uint8_t code_detail; - uint16_t msg_id; - struct mg_str token; - struct mg_coap_option *options; - struct mg_str payload; - struct mg_coap_option *optiomg_tail; -}; - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Sets CoAP protocol handler - triggers CoAP specific events. */ -int mg_set_protocol_coap(struct mg_connection *nc); - -/* - * Adds a new option to mg_coap_message structure. - * Returns pointer to the newly created option. - * Note: options must be freed by using mg_coap_free_options - */ -struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, - uint32_t number, char *value, - size_t len); - -/* - * Frees the memory allocated for options. - * If the cm parameter doesn't contain any option it does nothing. - */ -void mg_coap_free_options(struct mg_coap_message *cm); - -/* - * Composes a CoAP message from `mg_coap_message` - * and sends it into `nc` connection. - * Returns 0 on success. On error, it is a bitmask: - * - * - `#define MG_COAP_ERROR 0x10000` - * - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)` - * - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)` - * - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)` - * - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)` - */ -uint32_t mg_coap_send_message(struct mg_connection *nc, - struct mg_coap_message *cm); - -/* - * Composes CoAP acknowledgement from `mg_coap_message` - * and sends it into `nc` connection. - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id); - -/* - * Parses CoAP message and fills mg_coap_message and returns cm->flags. - * This is a helper function. - * - * NOTE: usually CoAP works over UDP, so lack of data means format error. - * But, in theory, it is possible to use CoAP over TCP (according to RFC) - * - * The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to - * underlying protocol: - * - * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR, - * - in case of TCP client can try to receive more data - * - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm); - -/* - * Composes CoAP message from mg_coap_message structure. - * This is a helper function. - * Return value: see `mg_coap_send_message()` - */ -uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* MG_ENABLE_COAP */ - -#endif /* CS_MONGOOSE_SRC_COAP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_sntp.h" -#endif -/* - * Copyright (c) 2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SNTP_H_ -#define CS_MONGOOSE_SRC_SNTP_H_ - -#if MG_ENABLE_SNTP - -#define MG_SNTP_EVENT_BASE 500 - -/* - * Received reply from time server. Event handler parameter contains - * pointer to mg_sntp_message structure - */ -#define MG_SNTP_REPLY (MG_SNTP_EVENT_BASE + 1) - -/* Received malformed SNTP packet */ -#define MG_SNTP_MALFORMED_REPLY (MG_SNTP_EVENT_BASE + 2) - -/* Failed to get time from server (timeout etc) */ -#define MG_SNTP_FAILED (MG_SNTP_EVENT_BASE + 3) - -struct mg_sntp_message { - /* if server sends this flags, user should not send requests to it */ - int kiss_of_death; - /* usual mg_time */ - double time; -}; - -/* Establishes connection to given sntp server */ -struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *sntp_server_name); - -/* Sends time request to given connection */ -void mg_sntp_send_request(struct mg_connection *c); - -/* - * Helper function - * Establishes connection to time server, tries to send request - * repeats sending SNTP_ATTEMPTS times every SNTP_TIMEOUT sec - * (if needed) - * See sntp_client example - */ -struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, - mg_event_handler_t event_handler, - const char *sntp_server_name); - -#endif - -#endif /* CS_MONGOOSE_SRC_SNTP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_socks.h" -#endif -/* - * Copyright (c) 2017 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_SOCKS_H_ -#define CS_MONGOOSE_SRC_SOCKS_H_ - -#if MG_ENABLE_SOCKS - -#define MG_SOCKS_VERSION 5 - -#define MG_SOCKS_HANDSHAKE_DONE MG_F_USER_1 -#define MG_SOCKS_CONNECT_DONE MG_F_USER_2 - -/* SOCKS5 handshake methods */ -enum mg_socks_handshake_method { - MG_SOCKS_HANDSHAKE_NOAUTH = 0, /* Handshake method - no authentication */ - MG_SOCKS_HANDSHAKE_GSSAPI = 1, /* Handshake method - GSSAPI auth */ - MG_SOCKS_HANDSHAKE_USERPASS = 2, /* Handshake method - user/password auth */ - MG_SOCKS_HANDSHAKE_FAILURE = 0xff, /* Handshake method - failure */ -}; - -/* SOCKS5 commands */ -enum mg_socks_command { - MG_SOCKS_CMD_CONNECT = 1, /* Command: CONNECT */ - MG_SOCKS_CMD_BIND = 2, /* Command: BIND */ - MG_SOCKS_CMD_UDP_ASSOCIATE = 3, /* Command: UDP ASSOCIATE */ -}; - -/* SOCKS5 address types */ -enum mg_socks_address_type { - MG_SOCKS_ADDR_IPV4 = 1, /* Address type: IPv4 */ - MG_SOCKS_ADDR_DOMAIN = 3, /* Address type: Domain name */ - MG_SOCKS_ADDR_IPV6 = 4, /* Address type: IPv6 */ -}; - -/* SOCKS5 response codes */ -enum mg_socks_response { - MG_SOCKS_SUCCESS = 0, /* Response: success */ - MG_SOCKS_FAILURE = 1, /* Response: failure */ - MG_SOCKS_NOT_ALLOWED = 2, /* Response: connection not allowed */ - MG_SOCKS_NET_UNREACHABLE = 3, /* Response: network unreachable */ - MG_SOCKS_HOST_UNREACHABLE = 4, /* Response: network unreachable */ - MG_SOCKS_CONN_REFUSED = 5, /* Response: network unreachable */ - MG_SOCKS_TTL_EXPIRED = 6, /* Response: network unreachable */ - MG_SOCKS_CMD_NOT_SUPPORTED = 7, /* Response: network unreachable */ - MG_SOCKS_ADDR_NOT_SUPPORTED = 8, /* Response: network unreachable */ -}; - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* Turn the connection into the SOCKS server */ -void mg_set_protocol_socks(struct mg_connection *c); - -/* Create socks tunnel for the client connection */ -struct mg_iface *mg_socks_mk_iface(struct mg_mgr *, const char *proxy_addr); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif -#endif Index: plugins/htmlinterface/mongoose.c =================================================================== --- plugins/htmlinterface/mongoose.c +++ /dev/null @@ -1,16132 +0,0 @@ -#include "mongoose.h" -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_internal.h" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_INTERNAL_H_ -#define CS_MONGOOSE_SRC_INTERNAL_H_ - -/* Amalgamated: #include "common/mg_mem.h" */ - -#ifndef MBUF_REALLOC -#define MBUF_REALLOC MG_REALLOC -#endif - -#ifndef MBUF_FREE -#define MBUF_FREE MG_FREE -#endif - -#define MG_SET_PTRPTR(_ptr, _v) \ - do { \ - if (_ptr) *(_ptr) = _v; \ - } while (0) - -#ifndef MG_INTERNAL -#define MG_INTERNAL static -#endif - -#ifdef PICOTCP -#define NO_LIBC -#define MG_DISABLE_PFS -#endif - -/* Amalgamated: #include "common/cs_dbg.h" */ -/* Amalgamated: #include "mg_http.h" */ -/* Amalgamated: #include "mg_net.h" */ - -#define MG_CTL_MSG_MESSAGE_SIZE 8192 - -/* internals that need to be accessible in unit tests */ -MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, - int proto, - union socket_address *sa); - -MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, - int *proto, char *host, size_t host_len); -MG_INTERNAL void mg_call(struct mg_connection *nc, - mg_event_handler_t ev_handler, void *user_data, int ev, - void *ev_data); -void mg_forward(struct mg_connection *from, struct mg_connection *to); -MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c); -MG_INTERNAL void mg_remove_conn(struct mg_connection *c); -MG_INTERNAL struct mg_connection *mg_create_connection( - struct mg_mgr *mgr, mg_event_handler_t callback, - struct mg_add_sock_opts opts); -#ifdef _WIN32 -/* Retur value is the same as for MultiByteToWideChar. */ -int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len); -#endif - -struct ctl_msg { - mg_event_handler_t callback; - char message[MG_CTL_MSG_MESSAGE_SIZE]; -}; - -#if MG_ENABLE_MQTT -struct mg_mqtt_message; - -#define MG_MQTT_ERROR_INCOMPLETE_MSG -1 -#define MG_MQTT_ERROR_MALFORMED_MSG -2 - -MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm); -#endif - -/* Forward declarations for testing. */ -extern void *(*test_malloc)(size_t size); -extern void *(*test_calloc)(size_t count, size_t size); - -#ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif - -#if MG_ENABLE_HTTP -struct mg_serve_http_opts; - -/* - * Reassemble the content of the buffer (buf, blen) which should be - * in the HTTP chunked encoding, by collapsing data chunks to the - * beginning of the buffer. - * - * If chunks get reassembled, modify hm->body to point to the reassembled - * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK - * in nc->flags, delete reassembled body from the mbuf. - * - * Return reassembled body size. - */ -MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, - struct http_message *hm, char *buf, - size_t blen); - -#if MG_ENABLE_FILESYSTEM -MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, - const struct mg_serve_http_opts *opts, - char **local_path, - struct mg_str *remainder); -MG_INTERNAL time_t mg_parse_date_string(const char *datetime); -MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st); -#endif -#if MG_ENABLE_HTTP_CGI -MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, - const struct mg_str *path_info, - const struct http_message *hm, - const struct mg_serve_http_opts *opts); -struct mg_http_proto_data_cgi; -MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d); -#endif -#if MG_ENABLE_HTTP_SSI -MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, - struct http_message *hm, - const char *path, - const struct mg_serve_http_opts *opts); -#endif -#if MG_ENABLE_HTTP_WEBDAV -MG_INTERNAL int mg_is_dav_request(const struct mg_str *s); -MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, - cs_stat_t *stp, struct http_message *hm, - struct mg_serve_http_opts *opts); -MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path); -MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, - struct http_message *hm); -MG_INTERNAL void mg_handle_move(struct mg_connection *c, - const struct mg_serve_http_opts *opts, - const char *path, struct http_message *hm); -MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, - const struct mg_serve_http_opts *opts, - const char *path); -MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, - struct http_message *hm); -#endif -#if MG_ENABLE_HTTP_WEBSOCKET -MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)); -MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, - const struct mg_str *key, - struct http_message *); -#endif -#endif /* MG_ENABLE_HTTP */ - -MG_INTERNAL int mg_get_errno(void); - -MG_INTERNAL void mg_close_conn(struct mg_connection *conn); - -#if MG_ENABLE_SNTP -MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, - struct mg_sntp_message *msg); -#endif - -#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/mg_mem.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_MG_MEM_H_ -#define CS_COMMON_MG_MEM_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef MG_MALLOC -#define MG_MALLOC malloc -#endif - -#ifndef MG_CALLOC -#define MG_CALLOC calloc -#endif - -#ifndef MG_REALLOC -#define MG_REALLOC realloc -#endif - -#ifndef MG_FREE -#define MG_FREE free -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_MG_MEM_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_base64.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef EXCLUDE_COMMON - -/* Amalgamated: #include "common/cs_base64.h" */ - -#include - -/* Amalgamated: #include "common/cs_dbg.h" */ - -/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */ - -#define NUM_UPPERCASES ('Z' - 'A' + 1) -#define NUM_LETTERS (NUM_UPPERCASES * 2) -#define NUM_DIGITS ('9' - '0' + 1) - -/* - * Emit a base64 code char. - * - * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps - */ -static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) { - if (v < NUM_UPPERCASES) { - ctx->b64_putc(v + 'A', ctx->user_data); - } else if (v < (NUM_LETTERS)) { - ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data); - } else if (v < (NUM_LETTERS + NUM_DIGITS)) { - ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data); - } else { - ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/', - ctx->user_data); - } -} - -static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) { - int a, b, c; - - a = ctx->chunk[0]; - b = ctx->chunk[1]; - c = ctx->chunk[2]; - - cs_base64_emit_code(ctx, a >> 2); - cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4)); - if (ctx->chunk_size > 1) { - cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6)); - } - if (ctx->chunk_size > 2) { - cs_base64_emit_code(ctx, c & 63); - } -} - -void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, - void *user_data) { - ctx->chunk_size = 0; - ctx->b64_putc = b64_putc; - ctx->user_data = user_data; -} - -void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) { - const unsigned char *src = (const unsigned char *) str; - size_t i; - for (i = 0; i < len; i++) { - ctx->chunk[ctx->chunk_size++] = src[i]; - if (ctx->chunk_size == 3) { - cs_base64_emit_chunk(ctx); - ctx->chunk_size = 0; - } - } -} - -void cs_base64_finish(struct cs_base64_ctx *ctx) { - if (ctx->chunk_size > 0) { - int i; - memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size); - cs_base64_emit_chunk(ctx); - for (i = 0; i < (3 - ctx->chunk_size); i++) { - ctx->b64_putc('=', ctx->user_data); - } - } -} - -#define BASE64_ENCODE_BODY \ - static const char *b64 = \ - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \ - int i, j, a, b, c; \ - \ - for (i = j = 0; i < src_len; i += 3) { \ - a = src[i]; \ - b = i + 1 >= src_len ? 0 : src[i + 1]; \ - c = i + 2 >= src_len ? 0 : src[i + 2]; \ - \ - BASE64_OUT(b64[a >> 2]); \ - BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \ - if (i + 1 < src_len) { \ - BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \ - } \ - if (i + 2 < src_len) { \ - BASE64_OUT(b64[c & 63]); \ - } \ - } \ - \ - while (j % 4 != 0) { \ - BASE64_OUT('='); \ - } \ - BASE64_FLUSH() - -#define BASE64_OUT(ch) \ - do { \ - dst[j++] = (ch); \ - } while (0) - -#define BASE64_FLUSH() \ - do { \ - dst[j++] = '\0'; \ - } while (0) - -void cs_base64_encode(const unsigned char *src, int src_len, char *dst) { - BASE64_ENCODE_BODY; -} - -#undef BASE64_OUT -#undef BASE64_FLUSH - -#if CS_ENABLE_STDIO -#define BASE64_OUT(ch) \ - do { \ - fprintf(f, "%c", (ch)); \ - j++; \ - } while (0) - -#define BASE64_FLUSH() - -void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) { - BASE64_ENCODE_BODY; -} - -#undef BASE64_OUT -#undef BASE64_FLUSH -#endif /* CS_ENABLE_STDIO */ - -/* Convert one byte of encoded base64 input stream to 6-bit chunk */ -static unsigned char from_b64(unsigned char ch) { - /* Inverse lookup map */ - static const unsigned char tab[128] = { - 255, 255, 255, 255, - 255, 255, 255, 255, /* 0 */ - 255, 255, 255, 255, - 255, 255, 255, 255, /* 8 */ - 255, 255, 255, 255, - 255, 255, 255, 255, /* 16 */ - 255, 255, 255, 255, - 255, 255, 255, 255, /* 24 */ - 255, 255, 255, 255, - 255, 255, 255, 255, /* 32 */ - 255, 255, 255, 62, - 255, 255, 255, 63, /* 40 */ - 52, 53, 54, 55, - 56, 57, 58, 59, /* 48 */ - 60, 61, 255, 255, - 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */ - 255, 0, 1, 2, - 3, 4, 5, 6, /* 64 */ - 7, 8, 9, 10, - 11, 12, 13, 14, /* 72 */ - 15, 16, 17, 18, - 19, 20, 21, 22, /* 80 */ - 23, 24, 25, 255, - 255, 255, 255, 255, /* 88 */ - 255, 26, 27, 28, - 29, 30, 31, 32, /* 96 */ - 33, 34, 35, 36, - 37, 38, 39, 40, /* 104 */ - 41, 42, 43, 44, - 45, 46, 47, 48, /* 112 */ - 49, 50, 51, 255, - 255, 255, 255, 255, /* 120 */ - }; - return tab[ch & 127]; -} - -int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) { - unsigned char a, b, c, d; - int orig_len = len; - char *orig_dst = dst; - while (len >= 4 && (a = from_b64(s[0])) != 255 && - (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 && - (d = from_b64(s[3])) != 255) { - s += 4; - len -= 4; - if (a == 200 || b == 200) break; /* '=' can't be there */ - *dst++ = a << 2 | b >> 4; - if (c == 200) break; - *dst++ = b << 4 | c >> 2; - if (d == 200) break; - *dst++ = c << 6 | d; - } - *dst = 0; - if (dec_len != NULL) *dec_len = (dst - orig_dst); - return orig_len - len; -} - -#endif /* EXCLUDE_COMMON */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_dbg.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_CS_DBG_H_ -#define CS_COMMON_CS_DBG_H_ - -/* Amalgamated: #include "common/platform.h" */ - -#if CS_ENABLE_STDIO -#include -#endif - -#ifndef CS_ENABLE_DEBUG -#define CS_ENABLE_DEBUG 0 -#endif - -#ifndef CS_LOG_ENABLE_TS_DIFF -#define CS_LOG_ENABLE_TS_DIFF 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/* - * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it. - */ -enum cs_log_level { - LL_NONE = -1, - LL_ERROR = 0, - LL_WARN = 1, - LL_INFO = 2, - LL_DEBUG = 3, - LL_VERBOSE_DEBUG = 4, - - _LL_MIN = -2, - _LL_MAX = 5, -}; - -/* - * Set max log level to print; messages with the level above the given one will - * not be printed. - */ -void cs_log_set_level(enum cs_log_level level); - -/* - * Set log filter. NULL (a default) logs everything. - * Otherwise, function name and file name will be tested against the given - * pattern, and only matching messages will be printed. - * - * For the pattern syntax, refer to `mg_match_prefix()` in `str_util.h`. - * - * Example: - * ```c - * void foo(void) { - * LOG(LL_INFO, ("hello from foo")); - * } - * - * void bar(void) { - * LOG(LL_INFO, ("hello from bar")); - * } - * - * void test(void) { - * cs_log_set_filter(NULL); - * foo(); - * bar(); - * - * cs_log_set_filter("f*"); - * foo(); - * bar(); // Will NOT print anything - * - * cs_log_set_filter("bar"); - * foo(); // Will NOT print anything - * bar(); - * } - * ``` - */ -void cs_log_set_filter(const char *pattern); - -/* - * Helper function which prints message prefix with the given `level`, function - * name `func` and `filename`. If message should be printed (accordingly to the - * current log level and filter), prints the prefix and returns 1, otherwise - * returns 0. - * - * Clients should typically just use `LOG()` macro. - */ -int cs_log_print_prefix(enum cs_log_level level, const char *func, - const char *filename); - -extern enum cs_log_level cs_log_threshold; - -#if CS_ENABLE_STDIO - -/* - * Set file to write logs into. If `NULL`, logs go to `stderr`. - */ -void cs_log_set_file(FILE *file); - -/* - * Prints log to the current log file, appends "\n" in the end and flushes the - * stream. - */ -void cs_log_printf(const char *fmt, ...) -#ifdef __GNUC__ - __attribute__((format(printf, 1, 2))) -#endif - ; - -/* - * Format and print message `x` with the given level `l`. Example: - * - * ```c - * LOG(LL_INFO, ("my info message: %d", 123)); - * LOG(LL_DEBUG, ("my debug message: %d", 123)); - * ``` - */ -#define LOG(l, x) \ - do { \ - if (cs_log_print_prefix(l, __func__, __FILE__)) cs_log_printf x; \ - } while (0) - -#ifndef CS_NDEBUG - -/* - * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))` - */ -#define DBG(x) LOG(LL_VERBOSE_DEBUG, x) - -#else /* NDEBUG */ - -#define DBG(x) - -#endif - -#else /* CS_ENABLE_STDIO */ - -#define LOG(l, x) -#define DBG(x) - -#endif - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_CS_DBG_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_dbg.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/cs_dbg.h" */ - -#include -#include -#include - -/* Amalgamated: #include "common/cs_time.h" */ -/* Amalgamated: #include "common/str_util.h" */ - -enum cs_log_level cs_log_threshold WEAK = -#if CS_ENABLE_DEBUG - LL_VERBOSE_DEBUG; -#else - LL_ERROR; -#endif - -static char *s_filter_pattern = NULL; -static size_t s_filter_pattern_len; - -void cs_log_set_filter(const char *pattern) WEAK; - -#if CS_ENABLE_STDIO - -FILE *cs_log_file WEAK = NULL; - -#if CS_LOG_ENABLE_TS_DIFF -double cs_log_ts WEAK; -#endif - -enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE; - -void cs_log_set_filter(const char *pattern) { - free(s_filter_pattern); - if (pattern != NULL) { - s_filter_pattern = strdup(pattern); - s_filter_pattern_len = strlen(pattern); - } else { - s_filter_pattern = NULL; - s_filter_pattern_len = 0; - } -} - -int cs_log_print_prefix(enum cs_log_level, const char *, const char *) WEAK; -int cs_log_print_prefix(enum cs_log_level level, const char *func, - const char *filename) { - char prefix[21]; - - if (level > cs_log_threshold) return 0; - if (s_filter_pattern != NULL && - mg_match_prefix(s_filter_pattern, s_filter_pattern_len, func) == 0 && - mg_match_prefix(s_filter_pattern, s_filter_pattern_len, filename) == 0) { - return 0; - } - - strncpy(prefix, func, 20); - prefix[20] = '\0'; - if (cs_log_file == NULL) cs_log_file = stderr; - cs_log_cur_msg_level = level; - fprintf(cs_log_file, "%-20s ", prefix); -#if CS_LOG_ENABLE_TS_DIFF - { - double now = cs_time(); - fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000)); - cs_log_ts = now; - } -#endif - return 1; -} - -void cs_log_printf(const char *fmt, ...) WEAK; -void cs_log_printf(const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - vfprintf(cs_log_file, fmt, ap); - va_end(ap); - fputc('\n', cs_log_file); - fflush(cs_log_file); - cs_log_cur_msg_level = LL_NONE; -} - -void cs_log_set_file(FILE *file) WEAK; -void cs_log_set_file(FILE *file) { - cs_log_file = file; -} - -#else - -void cs_log_set_filter(const char *pattern) { - (void) pattern; -} - -#endif /* CS_ENABLE_STDIO */ - -void cs_log_set_level(enum cs_log_level level) WEAK; -void cs_log_set_level(enum cs_log_level level) { - cs_log_threshold = level; -#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO - cs_log_ts = cs_time(); -#endif -} -#ifdef MG_MODULE_LINES -#line 1 "common/cs_dirent.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_CS_DIRENT_H_ -#define CS_COMMON_CS_DIRENT_H_ - -#include - -/* Amalgamated: #include "common/platform.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifdef CS_DEFINE_DIRENT -typedef struct { int dummy; } DIR; - -struct dirent { - int d_ino; -#ifdef _WIN32 - char d_name[MAX_PATH]; -#else - /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */ - char d_name[256]; -#endif -}; - -DIR *opendir(const char *dir_name); -int closedir(DIR *dir); -struct dirent *readdir(DIR *dir); -#endif /* CS_DEFINE_DIRENT */ - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_CS_DIRENT_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_dirent.c" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - */ - -#ifndef EXCLUDE_COMMON - -/* Amalgamated: #include "common/mg_mem.h" */ -/* Amalgamated: #include "common/cs_dirent.h" */ - -/* - * This file contains POSIX opendir/closedir/readdir API implementation - * for systems which do not natively support it (e.g. Windows). - */ - -#ifdef _WIN32 -struct win32_dir { - DIR d; - HANDLE handle; - WIN32_FIND_DATAW info; - struct dirent result; -}; - -DIR *opendir(const char *name) { - struct win32_dir *dir = NULL; - wchar_t wpath[MAX_PATH]; - DWORD attrs; - - if (name == NULL) { - SetLastError(ERROR_BAD_ARGUMENTS); - } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - } else { - to_wchar(name, wpath, ARRAY_SIZE(wpath)); - attrs = GetFileAttributesW(wpath); - if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) { - (void) wcscat(wpath, L"\\*"); - dir->handle = FindFirstFileW(wpath, &dir->info); - dir->result.d_name[0] = '\0'; - } else { - MG_FREE(dir); - dir = NULL; - } - } - - return (DIR *) dir; -} - -int closedir(DIR *d) { - struct win32_dir *dir = (struct win32_dir *) d; - int result = 0; - - if (dir != NULL) { - if (dir->handle != INVALID_HANDLE_VALUE) - result = FindClose(dir->handle) ? 0 : -1; - MG_FREE(dir); - } else { - result = -1; - SetLastError(ERROR_BAD_ARGUMENTS); - } - - return result; -} - -struct dirent *readdir(DIR *d) { - struct win32_dir *dir = (struct win32_dir *) d; - struct dirent *result = NULL; - - if (dir) { - memset(&dir->result, 0, sizeof(dir->result)); - if (dir->handle != INVALID_HANDLE_VALUE) { - result = &dir->result; - (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, - result->d_name, sizeof(result->d_name), NULL, - NULL); - - if (!FindNextFileW(dir->handle, &dir->info)) { - (void) FindClose(dir->handle); - dir->handle = INVALID_HANDLE_VALUE; - } - - } else { - SetLastError(ERROR_FILE_NOT_FOUND); - } - } else { - SetLastError(ERROR_BAD_ARGUMENTS); - } - - return result; -} -#endif - -#endif /* EXCLUDE_COMMON */ - -/* ISO C requires a translation unit to contain at least one declaration */ -typedef int cs_dirent_dummy; -#ifdef MG_MODULE_LINES -#line 1 "common/cs_time.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/cs_time.h" */ - -#ifndef _WIN32 -#include -/* - * There is no sys/time.h on ARMCC. - */ -#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \ - !defined(__TI_COMPILER_VERSION__) && \ - (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC) -#include -#endif -#else -#include -#endif - -double cs_time(void) WEAK; -double cs_time(void) { - double now; -#ifndef _WIN32 - struct timeval tv; - if (gettimeofday(&tv, NULL /* tz */) != 0) return 0; - now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0); -#else - SYSTEMTIME sysnow; - FILETIME ftime; - GetLocalTime(&sysnow); - SystemTimeToFileTime(&sysnow, &ftime); - /* - * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64 - * This should not cause a problems in this (21th) century - * 2. Windows FILETIME is a number of 100-nanosecond intervals since January - * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC, - * thus, we need to convert to seconds and adjust amount (subtract 11644473600 - * seconds) - */ - now = (double) (((int64_t) ftime.dwLowDateTime + - ((int64_t) ftime.dwHighDateTime << 32)) / - 10000000.0) - - 11644473600; -#endif /* _WIN32 */ - return now; -} - -double cs_timegm(const struct tm *tm) { - /* Month-to-day offset for non-leap-years. */ - static const int month_day[12] = {0, 31, 59, 90, 120, 151, - 181, 212, 243, 273, 304, 334}; - - /* Most of the calculation is easy; leap years are the main difficulty. */ - int month = tm->tm_mon % 12; - int year = tm->tm_year + tm->tm_mon / 12; - int year_for_leap; - int64_t rt; - - if (month < 0) { /* Negative values % 12 are still negative. */ - month += 12; - --year; - } - - /* This is the number of Februaries since 1900. */ - year_for_leap = (month > 1) ? year + 1 : year; - - rt = - tm->tm_sec /* Seconds */ - + - 60 * - (tm->tm_min /* Minute = 60 seconds */ - + - 60 * (tm->tm_hour /* Hour = 60 minutes */ - + - 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */ - + 365 * (year - 70) /* Year = 365 days */ - + (year_for_leap - 69) / 4 /* Every 4 years is leap... */ - - (year_for_leap - 1) / 100 /* Except centuries... */ - + (year_for_leap + 299) / 400))); /* Except 400s. */ - return rt < 0 ? -1 : (double) rt; -} -#ifdef MG_MODULE_LINES -#line 1 "common/cs_endian.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_CS_ENDIAN_H_ -#define CS_COMMON_CS_ENDIAN_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* - * clang with std=-c99 uses __LITTLE_ENDIAN, by default - * while for ex, RTOS gcc - LITTLE_ENDIAN, by default - * it depends on __USE_BSD, but let's have everything - */ -#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER) -#define BYTE_ORDER __BYTE_ORDER -#ifndef LITTLE_ENDIAN -#define LITTLE_ENDIAN __LITTLE_ENDIAN -#endif /* LITTLE_ENDIAN */ -#ifndef BIG_ENDIAN -#define BIG_ENDIAN __LITTLE_ENDIAN -#endif /* BIG_ENDIAN */ -#endif /* BYTE_ORDER */ - -#ifdef __cplusplus -} -#endif - -#endif /* CS_COMMON_CS_ENDIAN_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_md5.c" -#endif -/* - * This code implements the MD5 message-digest algorithm. - * The algorithm is due to Ron Rivest. This code was - * written by Colin Plumb in 1993, no copyright is claimed. - * This code is in the public domain; do with it what you wish. - * - * Equivalent code is available from RSA Data Security, Inc. - * This code has been tested against that, and is equivalent, - * except that you don't need to include two pages of legalese - * with every copy. - * - * To compute the message digest of a chunk of bytes, declare an - * MD5Context structure, pass it to MD5Init, call MD5Update as - * needed on buffers full of bytes, and then call MD5Final, which - * will fill a supplied 16-byte array with the digest. - */ - -/* Amalgamated: #include "common/cs_md5.h" */ -/* Amalgamated: #include "common/str_util.h" */ - -#if !defined(EXCLUDE_COMMON) -#if !CS_DISABLE_MD5 - -/* Amalgamated: #include "common/cs_endian.h" */ - -static void byteReverse(unsigned char *buf, unsigned longs) { -/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */ -#if BYTE_ORDER == BIG_ENDIAN - do { - uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 | - ((unsigned) buf[1] << 8 | buf[0]); - *(uint32_t *) buf = t; - buf += 4; - } while (--longs); -#else - (void) buf; - (void) longs; -#endif -} - -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -#define MD5STEP(f, w, x, y, z, data, s) \ - (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) - -/* - * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious - * initialization constants. - */ -void cs_md5_init(cs_md5_ctx *ctx) { - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) { - register uint32_t a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} - -void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) { - uint32_t t; - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++; - ctx->bits[1] += (uint32_t) len >> 29; - - t = (t >> 3) & 0x3f; - - if (t) { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) { - memcpy(p, buf, len); - return; - } - memcpy(p, buf, t); - byteReverse(ctx->in, 16); - cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); - buf += t; - len -= t; - } - - while (len >= 64) { - memcpy(ctx->in, buf, 64); - byteReverse(ctx->in, 16); - cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); - buf += 64; - len -= 64; - } - - memcpy(ctx->in, buf, len); -} - -void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) { - unsigned count; - unsigned char *p; - uint32_t *a; - - count = (ctx->bits[0] >> 3) & 0x3F; - - p = ctx->in + count; - *p++ = 0x80; - count = 64 - 1 - count; - if (count < 8) { - memset(p, 0, count); - byteReverse(ctx->in, 16); - cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); - memset(ctx->in, 0, 56); - } else { - memset(p, 0, count - 8); - } - byteReverse(ctx->in, 14); - - a = (uint32_t *) ctx->in; - a[14] = ctx->bits[0]; - a[15] = ctx->bits[1]; - - cs_md5_transform(ctx->buf, (uint32_t *) ctx->in); - byteReverse((unsigned char *) ctx->buf, 4); - memcpy(digest, ctx->buf, 16); - memset((char *) ctx, 0, sizeof(*ctx)); -} - -#endif /* CS_DISABLE_MD5 */ -#endif /* EXCLUDE_COMMON */ -#ifdef MG_MODULE_LINES -#line 1 "common/cs_sha1.c" -#endif -/* Copyright(c) By Steve Reid */ -/* 100% Public Domain */ - -/* Amalgamated: #include "common/cs_sha1.h" */ - -#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON) - -/* Amalgamated: #include "common/cs_endian.h" */ - -#define SHA1HANDSOFF -#if defined(__sun) -/* Amalgamated: #include "common/solarisfixes.h" */ -#endif - -union char64long16 { - unsigned char c[64]; - uint32_t l[16]; -}; - -#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) - -static uint32_t blk0(union char64long16 *block, int i) { -/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */ -#if BYTE_ORDER == LITTLE_ENDIAN - block->l[i] = - (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); -#endif - return block->l[i]; -} - -/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */ -#undef blk -#undef R0 -#undef R1 -#undef R2 -#undef R3 -#undef R4 - -#define blk(i) \ - (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \ - block->l[(i + 2) & 15] ^ block->l[i & 15], \ - 1)) -#define R0(v, w, x, y, z, i) \ - z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \ - w = rol(w, 30); -#define R1(v, w, x, y, z, i) \ - z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \ - w = rol(w, 30); -#define R2(v, w, x, y, z, i) \ - z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \ - w = rol(w, 30); -#define R3(v, w, x, y, z, i) \ - z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \ - w = rol(w, 30); -#define R4(v, w, x, y, z, i) \ - z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \ - w = rol(w, 30); - -void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) { - uint32_t a, b, c, d, e; - union char64long16 block[1]; - - memcpy(block, buffer, 64); - a = state[0]; - b = state[1]; - c = state[2]; - d = state[3]; - e = state[4]; - R0(a, b, c, d, e, 0); - R0(e, a, b, c, d, 1); - R0(d, e, a, b, c, 2); - R0(c, d, e, a, b, 3); - R0(b, c, d, e, a, 4); - R0(a, b, c, d, e, 5); - R0(e, a, b, c, d, 6); - R0(d, e, a, b, c, 7); - R0(c, d, e, a, b, 8); - R0(b, c, d, e, a, 9); - R0(a, b, c, d, e, 10); - R0(e, a, b, c, d, 11); - R0(d, e, a, b, c, 12); - R0(c, d, e, a, b, 13); - R0(b, c, d, e, a, 14); - R0(a, b, c, d, e, 15); - R1(e, a, b, c, d, 16); - R1(d, e, a, b, c, 17); - R1(c, d, e, a, b, 18); - R1(b, c, d, e, a, 19); - R2(a, b, c, d, e, 20); - R2(e, a, b, c, d, 21); - R2(d, e, a, b, c, 22); - R2(c, d, e, a, b, 23); - R2(b, c, d, e, a, 24); - R2(a, b, c, d, e, 25); - R2(e, a, b, c, d, 26); - R2(d, e, a, b, c, 27); - R2(c, d, e, a, b, 28); - R2(b, c, d, e, a, 29); - R2(a, b, c, d, e, 30); - R2(e, a, b, c, d, 31); - R2(d, e, a, b, c, 32); - R2(c, d, e, a, b, 33); - R2(b, c, d, e, a, 34); - R2(a, b, c, d, e, 35); - R2(e, a, b, c, d, 36); - R2(d, e, a, b, c, 37); - R2(c, d, e, a, b, 38); - R2(b, c, d, e, a, 39); - R3(a, b, c, d, e, 40); - R3(e, a, b, c, d, 41); - R3(d, e, a, b, c, 42); - R3(c, d, e, a, b, 43); - R3(b, c, d, e, a, 44); - R3(a, b, c, d, e, 45); - R3(e, a, b, c, d, 46); - R3(d, e, a, b, c, 47); - R3(c, d, e, a, b, 48); - R3(b, c, d, e, a, 49); - R3(a, b, c, d, e, 50); - R3(e, a, b, c, d, 51); - R3(d, e, a, b, c, 52); - R3(c, d, e, a, b, 53); - R3(b, c, d, e, a, 54); - R3(a, b, c, d, e, 55); - R3(e, a, b, c, d, 56); - R3(d, e, a, b, c, 57); - R3(c, d, e, a, b, 58); - R3(b, c, d, e, a, 59); - R4(a, b, c, d, e, 60); - R4(e, a, b, c, d, 61); - R4(d, e, a, b, c, 62); - R4(c, d, e, a, b, 63); - R4(b, c, d, e, a, 64); - R4(a, b, c, d, e, 65); - R4(e, a, b, c, d, 66); - R4(d, e, a, b, c, 67); - R4(c, d, e, a, b, 68); - R4(b, c, d, e, a, 69); - R4(a, b, c, d, e, 70); - R4(e, a, b, c, d, 71); - R4(d, e, a, b, c, 72); - R4(c, d, e, a, b, 73); - R4(b, c, d, e, a, 74); - R4(a, b, c, d, e, 75); - R4(e, a, b, c, d, 76); - R4(d, e, a, b, c, 77); - R4(c, d, e, a, b, 78); - R4(b, c, d, e, a, 79); - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - state[4] += e; - /* Erase working structures. The order of operations is important, - * used to ensure that compiler doesn't optimize those out. */ - memset(block, 0, sizeof(block)); - a = b = c = d = e = 0; - (void) a; - (void) b; - (void) c; - (void) d; - (void) e; -} - -void cs_sha1_init(cs_sha1_ctx *context) { - context->state[0] = 0x67452301; - context->state[1] = 0xEFCDAB89; - context->state[2] = 0x98BADCFE; - context->state[3] = 0x10325476; - context->state[4] = 0xC3D2E1F0; - context->count[0] = context->count[1] = 0; -} - -void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, - uint32_t len) { - uint32_t i, j; - - j = context->count[0]; - if ((context->count[0] += len << 3) < j) context->count[1]++; - context->count[1] += (len >> 29); - j = (j >> 3) & 63; - if ((j + len) > 63) { - memcpy(&context->buffer[j], data, (i = 64 - j)); - cs_sha1_transform(context->state, context->buffer); - for (; i + 63 < len; i += 64) { - cs_sha1_transform(context->state, &data[i]); - } - j = 0; - } else - i = 0; - memcpy(&context->buffer[j], &data[i], len - i); -} - -void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) { - unsigned i; - unsigned char finalcount[8], c; - - for (i = 0; i < 8; i++) { - finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> - ((3 - (i & 3)) * 8)) & - 255); - } - c = 0200; - cs_sha1_update(context, &c, 1); - while ((context->count[0] & 504) != 448) { - c = 0000; - cs_sha1_update(context, &c, 1); - } - cs_sha1_update(context, finalcount, 8); - for (i = 0; i < 20; i++) { - digest[i] = - (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); - } - memset(context, '\0', sizeof(*context)); - memset(&finalcount, '\0', sizeof(finalcount)); -} - -void cs_hmac_sha1(const unsigned char *key, size_t keylen, - const unsigned char *data, size_t datalen, - unsigned char out[20]) { - cs_sha1_ctx ctx; - unsigned char buf1[64], buf2[64], tmp_key[20], i; - - if (keylen > sizeof(buf1)) { - cs_sha1_init(&ctx); - cs_sha1_update(&ctx, key, keylen); - cs_sha1_final(tmp_key, &ctx); - key = tmp_key; - keylen = sizeof(tmp_key); - } - - memset(buf1, 0, sizeof(buf1)); - memset(buf2, 0, sizeof(buf2)); - memcpy(buf1, key, keylen); - memcpy(buf2, key, keylen); - - for (i = 0; i < sizeof(buf1); i++) { - buf1[i] ^= 0x36; - buf2[i] ^= 0x5c; - } - - cs_sha1_init(&ctx); - cs_sha1_update(&ctx, buf1, sizeof(buf1)); - cs_sha1_update(&ctx, data, datalen); - cs_sha1_final(out, &ctx); - - cs_sha1_init(&ctx); - cs_sha1_update(&ctx, buf2, sizeof(buf2)); - cs_sha1_update(&ctx, out, 20); - cs_sha1_final(out, &ctx); -} - -#endif /* EXCLUDE_COMMON */ -#ifdef MG_MODULE_LINES -#line 1 "common/mbuf.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#ifndef EXCLUDE_COMMON - -#include -#include -/* Amalgamated: #include "common/mbuf.h" */ - -#ifndef MBUF_REALLOC -#define MBUF_REALLOC realloc -#endif - -#ifndef MBUF_FREE -#define MBUF_FREE free -#endif - -void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK; -void mbuf_init(struct mbuf *mbuf, size_t initial_size) { - mbuf->len = mbuf->size = 0; - mbuf->buf = NULL; - mbuf_resize(mbuf, initial_size); -} - -void mbuf_free(struct mbuf *mbuf) WEAK; -void mbuf_free(struct mbuf *mbuf) { - if (mbuf->buf != NULL) { - MBUF_FREE(mbuf->buf); - mbuf_init(mbuf, 0); - } -} - -void mbuf_resize(struct mbuf *a, size_t new_size) WEAK; -void mbuf_resize(struct mbuf *a, size_t new_size) { - if (new_size > a->size || (new_size < a->size && new_size >= a->len)) { - char *buf = (char *) MBUF_REALLOC(a->buf, new_size); - /* - * In case realloc fails, there's not much we can do, except keep things as - * they are. Note that NULL is a valid return value from realloc when - * size == 0, but that is covered too. - */ - if (buf == NULL && new_size != 0) return; - a->buf = buf; - a->size = new_size; - } -} - -void mbuf_trim(struct mbuf *mbuf) WEAK; -void mbuf_trim(struct mbuf *mbuf) { - mbuf_resize(mbuf, mbuf->len); -} - -size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK; -size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) { - char *p = NULL; - - assert(a != NULL); - assert(a->len <= a->size); - assert(off <= a->len); - - /* check overflow */ - if (~(size_t) 0 - (size_t) a->buf < len) return 0; - - if (a->len + len <= a->size) { - memmove(a->buf + off + len, a->buf + off, a->len - off); - if (buf != NULL) { - memcpy(a->buf + off, buf, len); - } - a->len += len; - } else { - size_t new_size = (size_t)((a->len + len) * MBUF_SIZE_MULTIPLIER); - if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) { - a->buf = p; - memmove(a->buf + off + len, a->buf + off, a->len - off); - if (buf != NULL) memcpy(a->buf + off, buf, len); - a->len += len; - a->size = new_size; - } else { - len = 0; - } - } - - return len; -} - -size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK; -size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) { - return mbuf_insert(a, a->len, buf, len); -} - -void mbuf_remove(struct mbuf *mb, size_t n) WEAK; -void mbuf_remove(struct mbuf *mb, size_t n) { - if (n > 0 && n <= mb->len) { - memmove(mb->buf, mb->buf + n, mb->len - n); - mb->len -= n; - } -} - -#endif /* EXCLUDE_COMMON */ -#ifdef MG_MODULE_LINES -#line 1 "common/mg_str.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/mg_mem.h" */ -/* Amalgamated: #include "common/mg_str.h" */ - -#include -#include - -int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; - -struct mg_str mg_mk_str(const char *s) WEAK; -struct mg_str mg_mk_str(const char *s) { - struct mg_str ret = {s, 0}; - if (s != NULL) ret.len = strlen(s); - return ret; -} - -struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK; -struct mg_str mg_mk_str_n(const char *s, size_t len) { - struct mg_str ret = {s, len}; - return ret; -} - -int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK; -int mg_vcmp(const struct mg_str *str1, const char *str2) { - size_t n2 = strlen(str2), n1 = str1->len; - int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2); - if (r == 0) { - return n1 - n2; - } - return r; -} - -int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK; -int mg_vcasecmp(const struct mg_str *str1, const char *str2) { - size_t n2 = strlen(str2), n1 = str1->len; - int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2); - if (r == 0) { - return n1 - n2; - } - return r; -} - -static struct mg_str mg_strdup_common(const struct mg_str s, - int nul_terminate) { - struct mg_str r = {NULL, 0}; - if (s.len > 0 && s.p != NULL) { - char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0)); - if (sc != NULL) { - memcpy(sc, s.p, s.len); - if (nul_terminate) sc[s.len] = '\0'; - r.p = sc; - r.len = s.len; - } - } - return r; -} - -struct mg_str mg_strdup(const struct mg_str s) WEAK; -struct mg_str mg_strdup(const struct mg_str s) { - return mg_strdup_common(s, 0 /* NUL-terminate */); -} - -struct mg_str mg_strdup_nul(const struct mg_str s) WEAK; -struct mg_str mg_strdup_nul(const struct mg_str s) { - return mg_strdup_common(s, 1 /* NUL-terminate */); -} - -const char *mg_strchr(const struct mg_str s, int c) WEAK; -const char *mg_strchr(const struct mg_str s, int c) { - size_t i; - for (i = 0; i < s.len; i++) { - if (s.p[i] == c) return &s.p[i]; - } - return NULL; -} - -int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK; -int mg_strcmp(const struct mg_str str1, const struct mg_str str2) { - size_t i = 0; - while (i < str1.len && i < str2.len) { - if (str1.p[i] < str2.p[i]) return -1; - if (str1.p[i] > str2.p[i]) return 1; - i++; - } - if (i < str1.len) return 1; - if (i < str2.len) return -1; - return 0; -} - -int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK; -int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) { - struct mg_str s1 = str1; - struct mg_str s2 = str2; - - if (s1.len > n) { - s1.len = n; - } - if (s2.len > n) { - s2.len = n; - } - return mg_strcmp(s1, s2); -} - -const char *mg_strstr(const struct mg_str haystack, - const struct mg_str needle) WEAK; -const char *mg_strstr(const struct mg_str haystack, - const struct mg_str needle) { - size_t i; - if (needle.len > haystack.len) return NULL; - for (i = 0; i <= haystack.len - needle.len; i++) { - if (memcmp(haystack.p + i, needle.p, needle.len) == 0) { - return haystack.p + i; - } - } - return NULL; -} -#ifdef MG_MODULE_LINES -#line 1 "common/str_util.c" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - */ - -#ifndef EXCLUDE_COMMON - -/* Amalgamated: #include "common/str_util.h" */ -/* Amalgamated: #include "common/mg_mem.h" */ -/* Amalgamated: #include "common/platform.h" */ - -#ifndef C_DISABLE_BUILTIN_SNPRINTF -#define C_DISABLE_BUILTIN_SNPRINTF 0 -#endif - -/* Amalgamated: #include "common/mg_mem.h" */ - -size_t c_strnlen(const char *s, size_t maxlen) WEAK; -size_t c_strnlen(const char *s, size_t maxlen) { - size_t l = 0; - for (; l < maxlen && s[l] != '\0'; l++) { - } - return l; -} - -#define C_SNPRINTF_APPEND_CHAR(ch) \ - do { \ - if (i < (int) buf_size) buf[i] = ch; \ - i++; \ - } while (0) - -#define C_SNPRINTF_FLAG_ZERO 1 - -#if C_DISABLE_BUILTIN_SNPRINTF -int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; -int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { - return vsnprintf(buf, buf_size, fmt, ap); -} -#else -static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, - int field_width) { - char tmp[40]; - int i = 0, k = 0, neg = 0; - - if (num < 0) { - neg++; - num = -num; - } - - /* Print into temporary buffer - in reverse order */ - do { - int rem = num % base; - if (rem < 10) { - tmp[k++] = '0' + rem; - } else { - tmp[k++] = 'a' + (rem - 10); - } - num /= base; - } while (num > 0); - - /* Zero padding */ - if (flags && C_SNPRINTF_FLAG_ZERO) { - while (k < field_width && k < (int) sizeof(tmp) - 1) { - tmp[k++] = '0'; - } - } - - /* And sign */ - if (neg) { - tmp[k++] = '-'; - } - - /* Now output */ - while (--k >= 0) { - C_SNPRINTF_APPEND_CHAR(tmp[k]); - } - - return i; -} - -int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK; -int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) { - int ch, i = 0, len_mod, flags, precision, field_width; - - while ((ch = *fmt++) != '\0') { - if (ch != '%') { - C_SNPRINTF_APPEND_CHAR(ch); - } else { - /* - * Conversion specification: - * zero or more flags (one of: # 0 - + ') - * an optional minimum field width (digits) - * an optional precision (. followed by digits, or *) - * an optional length modifier (one of: hh h l ll L q j z t) - * conversion specifier (one of: d i o u x X e E f F g G a A c s p n) - */ - flags = field_width = precision = len_mod = 0; - - /* Flags. only zero-pad flag is supported. */ - if (*fmt == '0') { - flags |= C_SNPRINTF_FLAG_ZERO; - } - - /* Field width */ - while (*fmt >= '0' && *fmt <= '9') { - field_width *= 10; - field_width += *fmt++ - '0'; - } - /* Dynamic field width */ - if (*fmt == '*') { - field_width = va_arg(ap, int); - fmt++; - } - - /* Precision */ - if (*fmt == '.') { - fmt++; - if (*fmt == '*') { - precision = va_arg(ap, int); - fmt++; - } else { - while (*fmt >= '0' && *fmt <= '9') { - precision *= 10; - precision += *fmt++ - '0'; - } - } - } - - /* Length modifier */ - switch (*fmt) { - case 'h': - case 'l': - case 'L': - case 'I': - case 'q': - case 'j': - case 'z': - case 't': - len_mod = *fmt++; - if (*fmt == 'h') { - len_mod = 'H'; - fmt++; - } - if (*fmt == 'l') { - len_mod = 'q'; - fmt++; - } - break; - } - - ch = *fmt++; - if (ch == 's') { - const char *s = va_arg(ap, const char *); /* Always fetch parameter */ - int j; - int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0); - for (j = 0; j < pad; j++) { - C_SNPRINTF_APPEND_CHAR(' '); - } - - /* `s` may be NULL in case of %.*s */ - if (s != NULL) { - /* Ignore negative and 0 precisions */ - for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) { - C_SNPRINTF_APPEND_CHAR(s[j]); - } - } - } else if (ch == 'c') { - ch = va_arg(ap, int); /* Always fetch parameter */ - C_SNPRINTF_APPEND_CHAR(ch); - } else if (ch == 'd' && len_mod == 0) { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags, - field_width); - } else if (ch == 'd' && len_mod == 'l') { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags, - field_width); -#ifdef SSIZE_MAX - } else if (ch == 'd' && len_mod == 'z') { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags, - field_width); -#endif - } else if (ch == 'd' && len_mod == 'q') { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags, - field_width); - } else if ((ch == 'x' || ch == 'u') && len_mod == 0) { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned), - ch == 'x' ? 16 : 10, flags, field_width); - } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long), - ch == 'x' ? 16 : 10, flags, field_width); - } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') { - i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t), - ch == 'x' ? 16 : 10, flags, field_width); - } else if (ch == 'p') { - unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *); - C_SNPRINTF_APPEND_CHAR('0'); - C_SNPRINTF_APPEND_CHAR('x'); - i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0); - } else { -#ifndef NO_LIBC - /* - * TODO(lsm): abort is not nice in a library, remove it - * Also, ESP8266 SDK doesn't have it - */ - abort(); -#endif - } - } - } - - /* Zero-terminate the result */ - if (buf_size > 0) { - buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0'; - } - - return i; -} -#endif - -int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK; -int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) { - int result; - va_list ap; - va_start(ap, fmt); - result = c_vsnprintf(buf, buf_size, fmt, ap); - va_end(ap); - return result; -} - -#ifdef _WIN32 -int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { - int ret; - char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p; - - strncpy(buf, path, sizeof(buf)); - buf[sizeof(buf) - 1] = '\0'; - - /* Trim trailing slashes. Leave backslash for paths like "X:\" */ - p = buf + strlen(buf) - 1; - while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; - - memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); - ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); - - /* - * Convert back to Unicode. If doubly-converted string does not match the - * original, something is fishy, reject. - */ - WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), - NULL, NULL); - if (strcmp(buf, buf2) != 0) { - wbuf[0] = L'\0'; - ret = 0; - } - - return ret; -} -#endif /* _WIN32 */ - -/* The simplest O(mn) algorithm. Better implementation are GPLed */ -const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK; -const char *c_strnstr(const char *s, const char *find, size_t slen) { - size_t find_length = strlen(find); - size_t i; - - for (i = 0; i < slen; i++) { - if (i + find_length > slen) { - return NULL; - } - - if (strncmp(&s[i], find, find_length) == 0) { - return &s[i]; - } - } - - return NULL; -} - -#if CS_ENABLE_STRDUP -char *strdup(const char *src) WEAK; -char *strdup(const char *src) { - size_t len = strlen(src) + 1; - char *ret = MG_MALLOC(len); - if (ret != NULL) { - strcpy(ret, src); - } - return ret; -} -#endif - -void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK; -void cs_to_hex(char *to, const unsigned char *p, size_t len) { - static const char *hex = "0123456789abcdef"; - - for (; len--; p++) { - *to++ = hex[p[0] >> 4]; - *to++ = hex[p[0] & 0x0f]; - } - *to = '\0'; -} - -static int fourbit(int ch) { - if (ch >= '0' && ch <= '9') { - return ch - '0'; - } else if (ch >= 'a' && ch <= 'f') { - return ch - 'a' + 10; - } else if (ch >= 'A' && ch <= 'F') { - return ch - 'A' + 10; - } - return 0; -} - -void cs_from_hex(char *to, const char *p, size_t len) WEAK; -void cs_from_hex(char *to, const char *p, size_t len) { - size_t i; - - for (i = 0; i < len; i += 2) { - *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]); - } - *to = '\0'; -} - -#if CS_ENABLE_TO64 -int64_t cs_to64(const char *s) WEAK; -int64_t cs_to64(const char *s) { - int64_t result = 0; - int64_t neg = 1; - while (*s && isspace((unsigned char) *s)) s++; - if (*s == '-') { - neg = -1; - s++; - } - while (isdigit((unsigned char) *s)) { - result *= 10; - result += (*s - '0'); - s++; - } - return result * neg; -} -#endif - -static int str_util_lowercase(const char *s) { - return tolower(*(const unsigned char *) s); -} - -int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK; -int mg_ncasecmp(const char *s1, const char *s2, size_t len) { - int diff = 0; - - if (len > 0) do { - diff = str_util_lowercase(s1++) - str_util_lowercase(s2++); - } while (diff == 0 && s1[-1] != '\0' && --len > 0); - - return diff; -} - -int mg_casecmp(const char *s1, const char *s2) WEAK; -int mg_casecmp(const char *s1, const char *s2) { - return mg_ncasecmp(s1, s2, (size_t) ~0); -} - -int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK; -int mg_asprintf(char **buf, size_t size, const char *fmt, ...) { - int ret; - va_list ap; - va_start(ap, fmt); - ret = mg_avprintf(buf, size, fmt, ap); - va_end(ap); - return ret; -} - -int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK; -int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { - va_list ap_copy; - int len; - - va_copy(ap_copy, ap); - len = vsnprintf(*buf, size, fmt, ap_copy); - va_end(ap_copy); - - if (len < 0) { - /* eCos and Windows are not standard-compliant and return -1 when - * the buffer is too small. Keep allocating larger buffers until we - * succeed or out of memory. */ - *buf = NULL; /* LCOV_EXCL_START */ - while (len < 0) { - MG_FREE(*buf); - if (size == 0) { - size = 5; - } - size *= 2; - if ((*buf = (char *) MG_MALLOC(size)) == NULL) { - len = -1; - break; - } - va_copy(ap_copy, ap); - len = vsnprintf(*buf, size - 1, fmt, ap_copy); - va_end(ap_copy); - } - - /* - * Microsoft version of vsnprintf() is not always null-terminated, so put - * the terminator manually - */ - (*buf)[len] = 0; - /* LCOV_EXCL_STOP */ - } else if (len >= (int) size) { - /* Standard-compliant code path. Allocate a buffer that is large enough. */ - if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) { - len = -1; /* LCOV_EXCL_LINE */ - } else { /* LCOV_EXCL_LINE */ - va_copy(ap_copy, ap); - len = vsnprintf(*buf, len + 1, fmt, ap_copy); - va_end(ap_copy); - } - } - - return len; -} - -const char *mg_next_comma_list_entry(const char *, struct mg_str *, - struct mg_str *) WEAK; -const char *mg_next_comma_list_entry(const char *list, struct mg_str *val, - struct mg_str *eq_val) { - struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val); - return ret.p; -} - -struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, - struct mg_str *eq_val) WEAK; -struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, - struct mg_str *eq_val) { - if (list.len == 0) { - /* End of the list */ - list = mg_mk_str(NULL); - } else { - const char *chr = NULL; - *val = list; - - if ((chr = mg_strchr(*val, ',')) != NULL) { - /* Comma found. Store length and shift the list ptr */ - val->len = chr - val->p; - chr++; - list.len -= (chr - list.p); - list.p = chr; - } else { - /* This value is the last one */ - list = mg_mk_str_n(list.p + list.len, 0); - } - - if (eq_val != NULL) { - /* Value has form "x=y", adjust pointers and lengths */ - /* so that val points to "x", and eq_val points to "y". */ - eq_val->len = 0; - eq_val->p = (const char *) memchr(val->p, '=', val->len); - if (eq_val->p != NULL) { - eq_val->p++; /* Skip over '=' character */ - eq_val->len = val->p + val->len - eq_val->p; - val->len = (eq_val->p - val->p) - 1; - } - } - } - - return list; -} - -size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK; -size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) { - const char *or_str; - size_t res = 0, len = 0, i = 0, j = 0; - - if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL || - (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) { - struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)}; - res = mg_match_prefix_n(pstr, str); - if (res > 0) return res; - pstr.p = or_str + 1; - pstr.len = (pattern.p + pattern.len) - (or_str + 1); - return mg_match_prefix_n(pstr, str); - } - - for (; i < pattern.len && j < str.len; i++, j++) { - if (pattern.p[i] == '?') { - continue; - } else if (pattern.p[i] == '*') { - i++; - if (i < pattern.len && pattern.p[i] == '*') { - i++; - len = str.len - j; - } else { - len = 0; - while (j + len < str.len && str.p[j + len] != '/') len++; - } - if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1)) - return j + len; - do { - const struct mg_str pstr = {pattern.p + i, pattern.len - i}; - const struct mg_str sstr = {str.p + j + len, str.len - j - len}; - res = mg_match_prefix_n(pstr, sstr); - } while (res == 0 && len != 0 && len-- > 0); - return res == 0 ? 0 : j + res + len; - } else if (str_util_lowercase(&pattern.p[i]) != - str_util_lowercase(&str.p[j])) { - break; - } - } - if (i < pattern.len && pattern.p[i] == '$') { - return j == str.len ? str.len : 0; - } - return i == pattern.len ? j : 0; -} - -size_t mg_match_prefix(const char *, int, const char *) WEAK; -size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) { - const struct mg_str pstr = {pattern, (size_t) pattern_len}; - struct mg_str s = {str, 0}; - if (str != NULL) s.len = strlen(str); - return mg_match_prefix_n(pstr, s); -} - -#endif /* EXCLUDE_COMMON */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - * - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* Amalgamated: #include "common/cs_time.h" */ -/* Amalgamated: #include "mg_dns.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_resolv.h" */ -/* Amalgamated: #include "mg_util.h" */ - -#define MG_MAX_HOST_LEN 200 - -#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \ - memcpy(dst, src, sizeof(*dst)); - -/* Which flags can be pre-set by the user at connection creation time. */ -#define _MG_ALLOWED_CONNECT_FLAGS_MASK \ - (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ - MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST) -/* Which flags should be modifiable by user's callbacks. */ -#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \ - (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \ - MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \ - MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK) - -#ifndef intptr_t -#define intptr_t long -#endif - -MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) { - DBG(("%p %p", mgr, c)); - c->mgr = mgr; - c->next = mgr->active_connections; - mgr->active_connections = c; - c->prev = NULL; - if (c->next != NULL) c->next->prev = c; - if (c->sock != INVALID_SOCKET) { - c->iface->vtable->add_conn(c); - } -} - -MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) { - if (conn->prev == NULL) conn->mgr->active_connections = conn->next; - if (conn->prev) conn->prev->next = conn->next; - if (conn->next) conn->next->prev = conn->prev; - conn->prev = conn->next = NULL; - conn->iface->vtable->remove_conn(conn); -} - -MG_INTERNAL void mg_call(struct mg_connection *nc, - mg_event_handler_t ev_handler, void *user_data, int ev, - void *ev_data) { - static int nesting_level = 0; - nesting_level++; - if (ev_handler == NULL) { - /* - * If protocol handler is specified, call it. Otherwise, call user-specified - * event handler. - */ - ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler; - } - if (ev != MG_EV_POLL) { - DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc, - ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags, - (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); - } - -#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP - if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV && - ev != MG_EV_SEND /* handled separately */) { - mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev); - } -#endif - if (ev_handler != NULL) { - unsigned long flags_before = nc->flags; - size_t recv_mbuf_before = nc->recv_mbuf.len, recved; - ev_handler(nc, ev, ev_data MG_UD_ARG(user_data)); - recved = (recv_mbuf_before - nc->recv_mbuf.len); - /* Prevent user handler from fiddling with system flags. */ - if (ev_handler == nc->handler && nc->flags != flags_before) { - nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) | - (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK); - } - /* It's important to not double-count recved bytes, and since mg_call can be - * called recursively (e.g. proto_handler invokes user handler), we keep - * track of recursion and only report received bytes at the top level. */ - if (nesting_level == 1 && recved > 0 && !(nc->flags & MG_F_UDP)) { - nc->iface->vtable->recved(nc, recved); - } - } - if (ev != MG_EV_POLL) { - DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc, - ev_handler == nc->handler ? "user" : "proto", nc->flags, - (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); - } - nesting_level--; -#if !MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -void mg_if_timer(struct mg_connection *c, double now) { - if (c->ev_timer_time > 0 && now >= c->ev_timer_time) { - double old_value = c->ev_timer_time; - c->ev_timer_time = 0; - mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value); - } -} - -void mg_if_poll(struct mg_connection *nc, time_t now) { - if (!(nc->flags & MG_F_SSL) || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) { - mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now); - } -} - -void mg_destroy_conn(struct mg_connection *conn, int destroy_if) { - if (destroy_if) conn->iface->vtable->destroy_conn(conn); - if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) { - conn->proto_data_destructor(conn->proto_data); - } -#if MG_ENABLE_SSL - mg_ssl_if_conn_free(conn); -#endif - mbuf_free(&conn->recv_mbuf); - mbuf_free(&conn->send_mbuf); - - memset(conn, 0, sizeof(*conn)); - MG_FREE(conn); -} - -void mg_close_conn(struct mg_connection *conn) { - DBG(("%p %lu %d", conn, conn->flags, conn->sock)); -#if MG_ENABLE_SSL - if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { - mg_ssl_if_conn_close_notify(conn); - } -#endif - mg_remove_conn(conn); - conn->iface->vtable->destroy_conn(conn); - mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL); - mg_destroy_conn(conn, 0 /* destroy_if */); -} - -void mg_mgr_init(struct mg_mgr *m, void *user_data) { - struct mg_mgr_init_opts opts; - memset(&opts, 0, sizeof(opts)); - mg_mgr_init_opt(m, user_data, opts); -} - -void mg_mgr_init_opt(struct mg_mgr *m, void *user_data, - struct mg_mgr_init_opts opts) { - memset(m, 0, sizeof(*m)); -#if MG_ENABLE_BROADCAST - m->ctl[0] = m->ctl[1] = INVALID_SOCKET; -#endif - m->user_data = user_data; - -#ifdef _WIN32 - { - WSADATA data; - WSAStartup(MAKEWORD(2, 2), &data); - } -#elif defined(__unix__) - /* Ignore SIGPIPE signal, so if client cancels the request, it - * won't kill the whole process. */ - signal(SIGPIPE, SIG_IGN); -#endif - -#if MG_ENABLE_SSL - { - static int init_done; - if (!init_done) { - mg_ssl_if_init(); - init_done++; - } - } -#endif - { - int i; - if (opts.num_ifaces == 0) { - opts.num_ifaces = mg_num_ifaces; - opts.ifaces = mg_ifaces; - } - if (opts.main_iface != NULL) { - opts.ifaces[MG_MAIN_IFACE] = opts.main_iface; - } - m->num_ifaces = opts.num_ifaces; - m->ifaces = - (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces); - for (i = 0; i < mg_num_ifaces; i++) { - m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m); - m->ifaces[i]->vtable->init(m->ifaces[i]); - } - } - if (opts.nameserver != NULL) { - m->nameserver = strdup(opts.nameserver); - } - DBG(("==================================")); - DBG(("init mgr=%p", m)); -} - -void mg_mgr_free(struct mg_mgr *m) { - struct mg_connection *conn, *tmp_conn; - - DBG(("%p", m)); - if (m == NULL) return; - /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */ - mg_mgr_poll(m, 0); - -#if MG_ENABLE_BROADCAST - if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]); - if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]); - m->ctl[0] = m->ctl[1] = INVALID_SOCKET; -#endif - - for (conn = m->active_connections; conn != NULL; conn = tmp_conn) { - tmp_conn = conn->next; - mg_close_conn(conn); - } - - { - int i; - for (i = 0; i < m->num_ifaces; i++) { - m->ifaces[i]->vtable->free(m->ifaces[i]); - MG_FREE(m->ifaces[i]); - } - MG_FREE(m->ifaces); - } - - MG_FREE((char *) m->nameserver); -} - -time_t mg_mgr_poll(struct mg_mgr *m, int timeout_ms) { - int i; - time_t now = 0; /* oh GCC, seriously ? */ - - if (m->num_ifaces == 0) { - LOG(LL_ERROR, ("cannot poll: no interfaces")); - return 0; - } - - for (i = 0; i < m->num_ifaces; i++) { - now = m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms); - } - return now; -} - -int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) { - char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; - int len; - - if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { - mg_send(nc, buf, len); - } - if (buf != mem && buf != NULL) { - MG_FREE(buf); /* LCOV_EXCL_LINE */ - } /* LCOV_EXCL_LINE */ - - return len; -} - -int mg_printf(struct mg_connection *conn, const char *fmt, ...) { - int len; - va_list ap; - va_start(ap, fmt); - len = mg_vprintf(conn, fmt, ap); - va_end(ap); - return len; -} - -#if MG_ENABLE_SYNC_RESOLVER -/* TODO(lsm): use non-blocking resolver */ -static int mg_resolve2(const char *host, struct in_addr *ina) { -#if MG_ENABLE_GETADDRINFO - int rv = 0; - struct addrinfo hints, *servinfo, *p; - struct sockaddr_in *h = NULL; - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) { - DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno()))); - return 0; - } - for (p = servinfo; p != NULL; p = p->ai_next) { - memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *)); - memcpy(ina, &h->sin_addr, sizeof(ina)); - } - freeaddrinfo(servinfo); - return 1; -#else - struct hostent *he; - if ((he = gethostbyname(host)) == NULL) { - DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno()))); - } else { - memcpy(ina, he->h_addr_list[0], sizeof(*ina)); - return 1; - } - return 0; -#endif /* MG_ENABLE_GETADDRINFO */ -} - -int mg_resolve(const char *host, char *buf, size_t n) { - struct in_addr ad; - return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0; -} -#endif /* MG_ENABLE_SYNC_RESOLVER */ - -MG_INTERNAL struct mg_connection *mg_create_connection_base( - struct mg_mgr *mgr, mg_event_handler_t callback, - struct mg_add_sock_opts opts) { - struct mg_connection *conn; - - if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) { - conn->sock = INVALID_SOCKET; - conn->handler = callback; - conn->mgr = mgr; - conn->last_io_time = (time_t) mg_time(); - conn->iface = - (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]); - conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; - conn->user_data = opts.user_data; - /* - * SIZE_MAX is defined as a long long constant in - * system headers on some platforms and so it - * doesn't compile with pedantic ansi flags. - */ - conn->recv_mbuf_limit = ~0; - } else { - MG_SET_PTRPTR(opts.error_string, "failed to create connection"); - } - - return conn; -} - -MG_INTERNAL struct mg_connection *mg_create_connection( - struct mg_mgr *mgr, mg_event_handler_t callback, - struct mg_add_sock_opts opts) { - struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts); - - if (conn != NULL && !conn->iface->vtable->create_conn(conn)) { - MG_FREE(conn); - conn = NULL; - } - if (conn == NULL) { - MG_SET_PTRPTR(opts.error_string, "failed to init connection"); - } - - return conn; -} - -/* - * Address format: [PROTO://][HOST]:PORT - * - * HOST could be IPv4/IPv6 address or a host name. - * `host` is a destination buffer to hold parsed HOST part. Should be at least - * MG_MAX_HOST_LEN bytes long. - * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM - * - * Return: - * -1 on parse error - * 0 if HOST needs DNS lookup - * >0 length of the address string - */ -MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa, - int *proto, char *host, size_t host_len) { - unsigned int a, b, c, d, port = 0; - int ch, len = 0; -#if MG_ENABLE_IPV6 - char buf[100]; -#endif - - /* - * MacOS needs that. If we do not zero it, subsequent bind() will fail. - * Also, all-zeroes in the socket address means binding to all addresses - * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). - */ - memset(sa, 0, sizeof(*sa)); - sa->sin.sin_family = AF_INET; - - *proto = SOCK_STREAM; - - if (strncmp(str, "udp://", 6) == 0) { - str += 6; - *proto = SOCK_DGRAM; - } else if (strncmp(str, "tcp://", 6) == 0) { - str += 6; - } - - if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { - /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ - sa->sin.sin_addr.s_addr = - htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d); - sa->sin.sin_port = htons((uint16_t) port); -#if MG_ENABLE_IPV6 - } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 && - inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { - /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */ - sa->sin6.sin6_family = AF_INET6; - sa->sin.sin_port = htons((uint16_t) port); -#endif -#if MG_ENABLE_ASYNC_RESOLVER - } else if (strlen(str) < host_len && - sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) { - sa->sin.sin_port = htons((uint16_t) port); - if (mg_resolve_from_hosts_file(host, sa) != 0) { - /* - * if resolving from hosts file failed and the host - * we are trying to resolve is `localhost` - we should - * try to resolve it using `gethostbyname` and do not try - * to resolve it via DNS server if gethostbyname has failed too - */ - if (mg_ncasecmp(host, "localhost", 9) != 0) { - return 0; - } - -#if MG_ENABLE_SYNC_RESOLVER - if (!mg_resolve2(host, &sa->sin.sin_addr)) { - return -1; - } -#else - return -1; -#endif - } -#endif - } else if (sscanf(str, ":%u%n", &port, &len) == 1 || - sscanf(str, "%u%n", &port, &len) == 1) { - /* If only port is specified, bind to IPv4, INADDR_ANY */ - sa->sin.sin_port = htons((uint16_t) port); - } else { - return -1; - } - - /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */ - (void) host; - (void) host_len; - - ch = str[len]; /* Character that follows the address */ - return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1; -} - -struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) { - struct mg_add_sock_opts opts; - struct mg_connection *nc; - memset(&opts, 0, sizeof(opts)); - nc = mg_create_connection(lc->mgr, lc->handler, opts); - if (nc == NULL) return NULL; - nc->listener = lc; - nc->proto_handler = lc->proto_handler; - nc->user_data = lc->user_data; - nc->recv_mbuf_limit = lc->recv_mbuf_limit; - nc->iface = lc->iface; - if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL; - mg_add_conn(nc->mgr, nc); - DBG(("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags)); - return nc; -} - -void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, - size_t sa_len) { - (void) sa_len; - nc->sa = *sa; - mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); -} - -void mg_send(struct mg_connection *nc, const void *buf, int len) { - nc->last_io_time = (time_t) mg_time(); - if (nc->flags & MG_F_UDP) { - nc->iface->vtable->udp_send(nc, buf, len); - } else { - nc->iface->vtable->tcp_send(nc, buf, len); - } -} - -void mg_if_sent_cb(struct mg_connection *nc, int num_sent) { - DBG(("%p %d", nc, num_sent)); -#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP - if (nc->mgr && nc->mgr->hexdump_file != NULL) { - char *buf = nc->send_mbuf.buf; - mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, num_sent, MG_EV_SEND); - } -#endif - if (num_sent < 0) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } else { - mbuf_remove(&nc->send_mbuf, num_sent); - mbuf_trim(&nc->send_mbuf); - } - mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &num_sent); -} - -MG_INTERNAL void mg_recv_common(struct mg_connection *nc, void *buf, int len, - int own) { - DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len)); - -#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP - if (nc->mgr && nc->mgr->hexdump_file != NULL) { - mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_RECV); - } -#endif - - if (nc->flags & MG_F_CLOSE_IMMEDIATELY) { - DBG(("%p discarded %d bytes", nc, len)); - /* - * This connection will not survive next poll. Do not deliver events, - * send data to /dev/null without acking. - */ - if (own) { - MG_FREE(buf); - } - return; - } - nc->last_io_time = (time_t) mg_time(); - if (!own) { - mbuf_append(&nc->recv_mbuf, buf, len); - } else if (nc->recv_mbuf.len == 0) { - /* Adopt buf as recv_mbuf's backing store. */ - mbuf_free(&nc->recv_mbuf); - nc->recv_mbuf.buf = (char *) buf; - nc->recv_mbuf.size = nc->recv_mbuf.len = len; - } else { - mbuf_append(&nc->recv_mbuf, buf, len); - MG_FREE(buf); - } - mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &len); -} - -void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own) { - mg_recv_common(nc, buf, len, own); -} - -void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len, - union socket_address *sa, size_t sa_len) { - assert(nc->flags & MG_F_UDP); - DBG(("%p %u", nc, (unsigned int) len)); - if (nc->flags & MG_F_LISTENING) { - struct mg_connection *lc = nc; - /* - * Do we have an existing connection for this source? - * This is very inefficient for long connection lists. - */ - for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) { - if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) { - break; - } - } - if (nc == NULL) { - struct mg_add_sock_opts opts; - memset(&opts, 0, sizeof(opts)); - /* Create fake connection w/out sock initialization */ - nc = mg_create_connection_base(lc->mgr, lc->handler, opts); - if (nc != NULL) { - nc->sock = lc->sock; - nc->listener = lc; - nc->sa = *sa; - nc->proto_handler = lc->proto_handler; - nc->user_data = lc->user_data; - nc->recv_mbuf_limit = lc->recv_mbuf_limit; - nc->flags = MG_F_UDP; - /* - * Long-lived UDP "connections" i.e. interactions that involve more - * than one request and response are rare, most are transactional: - * response is sent and the "connection" is closed. Or - should be. - * But users (including ourselves) tend to forget about that part, - * because UDP is connectionless and one does not think about - * processing a UDP request as handling a connection that needs to be - * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should - * be a reasonable default for most use cases, but it is possible to - * turn it off the connection should be kept alive after processing. - */ - nc->flags |= MG_F_SEND_AND_CLOSE; - mg_add_conn(lc->mgr, nc); - mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa); - } else { - DBG(("OOM")); - /* No return here, we still need to drop on the floor */ - } - } - } - if (nc != NULL) { - mg_recv_common(nc, buf, len, 1); - } else { - /* Drop on the floor. */ - MG_FREE(buf); - } -} - -/* - * Schedules an async connect for a resolved address and proto. - * Called from two places: `mg_connect_opt()` and from async resolver. - * When called from the async resolver, it must trigger `MG_EV_CONNECT` event - * with a failure flag to indicate connection failure. - */ -MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc, - int proto, - union socket_address *sa) { - DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp", - inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port))); - - nc->flags |= MG_F_CONNECTING; - if (proto == SOCK_DGRAM) { - nc->iface->vtable->connect_udp(nc); - } else { - nc->iface->vtable->connect_tcp(nc, sa); - } - mg_add_conn(nc->mgr, nc); - return nc; -} - -void mg_if_connect_cb(struct mg_connection *nc, int err) { - DBG(("%p connect, err=%d", nc, err)); - nc->flags &= ~MG_F_CONNECTING; - if (err != 0) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err); -} - -#if MG_ENABLE_ASYNC_RESOLVER -/* - * Callback for the async resolver on mg_connect_opt() call. - * Main task of this function is to trigger MG_EV_CONNECT event with - * either failure (and dealloc the connection) - * or success (and proceed with connect() - */ -static void resolve_cb(struct mg_dns_message *msg, void *data, - enum mg_resolve_err e) { - struct mg_connection *nc = (struct mg_connection *) data; - int i; - int failure = -1; - - nc->flags &= ~MG_F_RESOLVING; - if (msg != NULL) { - /* - * Take the first DNS A answer and run... - */ - for (i = 0; i < msg->num_answers; i++) { - if (msg->answers[i].rtype == MG_DNS_A_RECORD) { - /* - * Async resolver guarantees that there is at least one answer. - * TODO(lsm): handle IPv6 answers too - */ - mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr, - 4); - mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM, - &nc->sa); - return; - } - } - } - - if (e == MG_RESOLVE_TIMEOUT) { - double now = mg_time(); - mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now); - } - - /* - * If we get there was no MG_DNS_A_RECORD in the answer - */ - mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure); - mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL); - mg_destroy_conn(nc, 1 /* destroy_if */); -} -#endif - -struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t callback, - void *user_data)) { - struct mg_connect_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts); -} - -struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t callback, - void *user_data), - struct mg_connect_opts opts) { - struct mg_connection *nc = NULL; - int proto, rc; - struct mg_add_sock_opts add_sock_opts; - char host[MG_MAX_HOST_LEN]; - - MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); - - if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) { - return NULL; - } - - if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) < - 0) { - /* Address is malformed */ - MG_SET_PTRPTR(opts.error_string, "cannot parse address"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - - nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK; - nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0; -#if MG_ENABLE_CALLBACK_USERDATA - nc->user_data = user_data; -#else - nc->user_data = opts.user_data; -#endif - -#if MG_ENABLE_SSL - DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), - (opts.ssl_key ? opts.ssl_key : "-"), - (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); - - if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL || - opts.ssl_psk_identity != NULL) { - const char *err_msg = NULL; - struct mg_ssl_if_conn_params params; - if (nc->flags & MG_F_UDP) { - MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - memset(¶ms, 0, sizeof(params)); - params.cert = opts.ssl_cert; - params.key = opts.ssl_key; - params.ca_cert = opts.ssl_ca_cert; - params.cipher_suites = opts.ssl_cipher_suites; - params.psk_identity = opts.ssl_psk_identity; - params.psk_key = opts.ssl_psk_key; - if (opts.ssl_ca_cert != NULL) { - if (opts.ssl_server_name != NULL) { - if (strcmp(opts.ssl_server_name, "*") != 0) { - params.server_name = opts.ssl_server_name; - } - } else if (rc == 0) { /* If it's a DNS name, use host. */ - params.server_name = host; - } - } - if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { - MG_SET_PTRPTR(opts.error_string, err_msg); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - nc->flags |= MG_F_SSL; - } -#endif /* MG_ENABLE_SSL */ - - if (rc == 0) { -#if MG_ENABLE_ASYNC_RESOLVER - /* - * DNS resolution is required for host. - * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb() - */ - struct mg_connection *dns_conn = NULL; - struct mg_resolve_async_opts o; - memset(&o, 0, sizeof(o)); - o.dns_conn = &dns_conn; - o.nameserver = opts.nameserver; - if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc, - o) != 0) { - MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - nc->priv_2 = dns_conn; - nc->flags |= MG_F_RESOLVING; - return nc; -#else - MG_SET_PTRPTR(opts.error_string, "Resolver is disabled"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; -#endif - } else { - /* Address is parsed and resolved to IP. proceed with connect() */ - return mg_do_connect(nc, proto, &nc->sa); - } -} - -struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address, - MG_CB(mg_event_handler_t event_handler, - void *user_data)) { - struct mg_bind_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts); -} - -struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address, - MG_CB(mg_event_handler_t callback, - void *user_data), - struct mg_bind_opts opts) { - union socket_address sa; - struct mg_connection *nc = NULL; - int proto, rc; - struct mg_add_sock_opts add_sock_opts; - char host[MG_MAX_HOST_LEN]; - -#if MG_ENABLE_CALLBACK_USERDATA - opts.user_data = user_data; -#endif - - if (callback == NULL) { - MG_SET_PTRPTR(opts.error_string, "handler is required"); - return NULL; - } - - MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts); - - if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) { - MG_SET_PTRPTR(opts.error_string, "cannot parse address"); - return NULL; - } - - nc = mg_create_connection(mgr, callback, add_sock_opts); - if (nc == NULL) { - return NULL; - } - - nc->sa = sa; - nc->flags |= MG_F_LISTENING; - if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP; - -#if MG_ENABLE_SSL - DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"), - (opts.ssl_key ? opts.ssl_key : "-"), - (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-"))); - - if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) { - const char *err_msg = NULL; - struct mg_ssl_if_conn_params params; - if (nc->flags & MG_F_UDP) { - MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - memset(¶ms, 0, sizeof(params)); - params.cert = opts.ssl_cert; - params.key = opts.ssl_key; - params.ca_cert = opts.ssl_ca_cert; - params.cipher_suites = opts.ssl_cipher_suites; - if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { - MG_SET_PTRPTR(opts.error_string, err_msg); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - nc->flags |= MG_F_SSL; - } -#endif /* MG_ENABLE_SSL */ - - if (nc->flags & MG_F_UDP) { - rc = nc->iface->vtable->listen_udp(nc, &nc->sa); - } else { - rc = nc->iface->vtable->listen_tcp(nc, &nc->sa); - } - if (rc != 0) { - DBG(("Failed to open listener: %d", rc)); - MG_SET_PTRPTR(opts.error_string, "failed to open listener"); - mg_destroy_conn(nc, 1 /* destroy_if */); - return NULL; - } - mg_add_conn(nc->mgr, nc); - - return nc; -} - -struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) { - return conn == NULL ? s->active_connections : conn->next; -} - -#if MG_ENABLE_BROADCAST -void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data, - size_t len) { - struct ctl_msg ctl_msg; - - /* - * Mongoose manager has a socketpair, `struct mg_mgr::ctl`, - * where `mg_broadcast()` pushes the message. - * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls - * specified callback for each connection. Thus the callback function executes - * in event manager thread. - */ - if (mgr->ctl[0] != INVALID_SOCKET && data != NULL && - len < sizeof(ctl_msg.message)) { - size_t dummy; - - ctl_msg.callback = cb; - memcpy(ctl_msg.message, data, len); - dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg, - offsetof(struct ctl_msg, message) + len, 0); - dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0); - (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ - } -} -#endif /* MG_ENABLE_BROADCAST */ - -static int isbyte(int n) { - return n >= 0 && n <= 255; -} - -static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { - int n, a, b, c, d, slash = 32, len = 0; - - if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || - sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && - isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && - slash < 33) { - len = n; - *net = - ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d; - *mask = slash ? 0xffffffffU << (32 - slash) : 0; - } - - return len; -} - -int mg_check_ip_acl(const char *acl, uint32_t remote_ip) { - int allowed, flag; - uint32_t net, mask; - struct mg_str vec; - - /* If any ACL is set, deny by default */ - allowed = (acl == NULL || *acl == '\0') ? '+' : '-'; - - while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) { - flag = vec.p[0]; - if ((flag != '+' && flag != '-') || - parse_net(&vec.p[1], &net, &mask) == 0) { - return -1; - } - - if (net == (remote_ip & mask)) { - allowed = flag; - } - } - - DBG(("%08x %c", (unsigned int) remote_ip, allowed)); - return allowed == '+'; -} - -/* Move data from one connection to another */ -void mg_forward(struct mg_connection *from, struct mg_connection *to) { - mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len); - mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len); -} - -double mg_set_timer(struct mg_connection *c, double timestamp) { - double result = c->ev_timer_time; - c->ev_timer_time = timestamp; - /* - * If this connection is resolving, it's not in the list of active - * connections, so not processed yet. It has a DNS resolver connection - * linked to it. Set up a timer for the DNS connection. - */ - DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0), - (unsigned long) timestamp)); - if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) { - ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp; - } - return result; -} - -void mg_sock_set(struct mg_connection *nc, sock_t sock) { - if (sock != INVALID_SOCKET) { - nc->iface->vtable->sock_set(nc, sock); - } -} - -void mg_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - nc->iface->vtable->get_conn_addr(nc, remote, sa); -} - -struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock, - MG_CB(mg_event_handler_t callback, - void *user_data), - struct mg_add_sock_opts opts) { -#if MG_ENABLE_CALLBACK_USERDATA - opts.user_data = user_data; -#endif - - struct mg_connection *nc = mg_create_connection_base(s, callback, opts); - if (nc != NULL) { - mg_sock_set(nc, sock); - mg_add_conn(nc->mgr, nc); - } - return nc; -} - -struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock, - MG_CB(mg_event_handler_t callback, - void *user_data)) { - struct mg_add_sock_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts); -} - -double mg_time(void) { - return cs_time(); -} -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if_socket.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ -#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ - -/* Amalgamated: #include "mg_net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_ENABLE_NET_IF_SOCKET -#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET -#endif - -extern const struct mg_iface_vtable mg_socket_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if_socks.h" -#endif -/* -* Copyright (c) 2014-2017 Cesanta Software Limited -* All rights reserved -*/ - -#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ -#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ - -#if MG_ENABLE_SOCKS -/* Amalgamated: #include "mg_net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -extern const struct mg_iface_vtable mg_socks_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ -#endif /* MG_ENABLE_SOCKS */ -#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if.c" -#endif -/* Amalgamated: #include "mg_net_if.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_net_if_socket.h" */ - -extern const struct mg_iface_vtable mg_default_iface_vtable; - -const struct mg_iface_vtable *mg_ifaces[] = { - &mg_default_iface_vtable, -}; - -int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0])); - -struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable, - struct mg_mgr *mgr) { - struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface)); - iface->mgr = mgr; - iface->data = NULL; - iface->vtable = vtable; - return iface; -} - -struct mg_iface *mg_find_iface(struct mg_mgr *mgr, - const struct mg_iface_vtable *vtable, - struct mg_iface *from) { - int i = 0; - if (from != NULL) { - for (i = 0; i < mgr->num_ifaces; i++) { - if (mgr->ifaces[i] == from) { - i++; - break; - } - } - } - - for (; i < mgr->num_ifaces; i++) { - if (mgr->ifaces[i]->vtable == vtable) { - return mgr->ifaces[i]; - } - } - return NULL; -} -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if_socket.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_NET_IF_SOCKET - -/* Amalgamated: #include "mg_net_if_socket.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_util.h" */ - -#define MG_TCP_RECV_BUFFER_SIZE 1024 -#define MG_UDP_RECV_BUFFER_SIZE 1500 - -static sock_t mg_open_listening_socket(union socket_address *sa, int type, - int proto); -#if MG_ENABLE_SSL -static void mg_ssl_begin(struct mg_connection *nc); -#endif - -void mg_set_non_blocking_mode(sock_t sock) { -#ifdef _WIN32 - unsigned long on = 1; - ioctlsocket(sock, FIONBIO, &on); -#else - int flags = fcntl(sock, F_GETFL, 0); - fcntl(sock, F_SETFL, flags | O_NONBLOCK); -#endif -} - -static int mg_is_error(void) { - int err = mg_get_errno(); - return err != EINPROGRESS && err != EWOULDBLOCK -#ifndef WINCE - && err != EAGAIN && err != EINTR -#endif -#ifdef _WIN32 - && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK -#endif - ; -} - -void mg_socket_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - int rc, proto = 0; - nc->sock = socket(AF_INET, SOCK_STREAM, proto); - if (nc->sock == INVALID_SOCKET) { - nc->err = mg_get_errno() ? mg_get_errno() : 1; - return; - } -#if !defined(MG_ESP8266) - mg_set_non_blocking_mode(nc->sock); -#endif - rc = connect(nc->sock, &sa->sa, sizeof(sa->sin)); - nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0; - DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(), - nc->err)); -} - -void mg_socket_if_connect_udp(struct mg_connection *nc) { - nc->sock = socket(AF_INET, SOCK_DGRAM, 0); - if (nc->sock == INVALID_SOCKET) { - nc->err = mg_get_errno() ? mg_get_errno() : 1; - return; - } - if (nc->flags & MG_F_ENABLE_BROADCAST) { - int optval = 1; - if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval, - sizeof(optval)) < 0) { - nc->err = mg_get_errno() ? mg_get_errno() : 1; - return; - } - } - nc->err = 0; -} - -int mg_socket_if_listen_tcp(struct mg_connection *nc, - union socket_address *sa) { - int proto = 0; - sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto); - if (sock == INVALID_SOCKET) { - return (mg_get_errno() ? mg_get_errno() : 1); - } - mg_sock_set(nc, sock); - return 0; -} - -int mg_socket_if_listen_udp(struct mg_connection *nc, - union socket_address *sa) { - sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0); - if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1); - mg_sock_set(nc, sock); - return 0; -} - -void mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_socket_if_udp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_socket_if_recved(struct mg_connection *nc, size_t len) { - (void) nc; - (void) len; -} - -int mg_socket_if_create_conn(struct mg_connection *nc) { - (void) nc; - return 1; -} - -void mg_socket_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - if (!(nc->flags & MG_F_UDP)) { - closesocket(nc->sock); - } else { - /* Only close outgoing UDP sockets or listeners. */ - if (nc->listener == NULL) closesocket(nc->sock); - } - nc->sock = INVALID_SOCKET; -} - -static int mg_accept_conn(struct mg_connection *lc) { - struct mg_connection *nc; - union socket_address sa; - socklen_t sa_len = sizeof(sa); - /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */ - sock_t sock = accept(lc->sock, &sa.sa, &sa_len); - if (sock == INVALID_SOCKET) { - if (mg_is_error()) DBG(("%p: failed to accept: %d", lc, mg_get_errno())); - return 0; - } - nc = mg_if_accept_new_conn(lc); - if (nc == NULL) { - closesocket(sock); - return 0; - } - DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), - ntohs(sa.sin.sin_port))); - mg_sock_set(nc, sock); -#if MG_ENABLE_SSL - if (lc->flags & MG_F_SSL) { - if (mg_ssl_if_conn_accept(nc, lc) != MG_SSL_OK) mg_close_conn(nc); - } else -#endif - { - mg_if_accept_tcp_cb(nc, &sa, sa_len); - } - return 1; -} - -/* 'sa' must be an initialized address to bind to */ -static sock_t mg_open_listening_socket(union socket_address *sa, int type, - int proto) { - socklen_t sa_len = - (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); - sock_t sock = INVALID_SOCKET; -#if !MG_LWIP - int on = 1; -#endif - - if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET && -#if !MG_LWIP /* LWIP doesn't support either */ -#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE) - /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */ - !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on, - sizeof(on)) && -#endif - -#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE) - /* - * SO_RESUSEADDR is not enabled on Windows because the semantics of - * SO_REUSEADDR on UNIX and Windows is different. On Windows, - * SO_REUSEADDR allows to bind a socket to a port without error even if - * the port is already open by another program. This is not the behavior - * SO_REUSEADDR was designed for, and leads to hard-to-track failure - * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless - * SO_EXCLUSIVEADDRUSE is supported and set on a socket. - */ - !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && -#endif -#endif /* !MG_LWIP */ - - !bind(sock, &sa->sa, sa_len) && - (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) { -#if !MG_LWIP - mg_set_non_blocking_mode(sock); - /* In case port was set to 0, get the real port number */ - (void) getsockname(sock, &sa->sa, &sa_len); -#endif - } else if (sock != INVALID_SOCKET) { - closesocket(sock); - sock = INVALID_SOCKET; - } - - return sock; -} - -static void mg_write_to_socket(struct mg_connection *nc) { - struct mbuf *io = &nc->send_mbuf; - int n = 0; - -#if MG_LWIP - /* With LWIP we don't know if the socket is ready */ - if (io->len == 0) return; -#endif - - assert(io->len > 0); - - if (nc->flags & MG_F_UDP) { - int n = - sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin)); - DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, mg_get_errno(), - inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); - mg_if_sent_cb(nc, n); - return; - } - -#if MG_ENABLE_SSL - if (nc->flags & MG_F_SSL) { - if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { - n = mg_ssl_if_write(nc, io->buf, io->len); - DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock)); - if (n < 0) { - if (n != MG_SSL_WANT_READ && n != MG_SSL_WANT_WRITE) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - return; - } else { - /* Successful SSL operation, clear off SSL wait flags */ - nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); - } - } else { - mg_ssl_begin(nc); - return; - } - } else -#endif - { - n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0); - DBG(("%p %d bytes -> %d", nc, n, nc->sock)); - } - - mg_if_sent_cb(nc, n); -} - -MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) { - size_t avail; - if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; - avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; - return avail > max ? max : avail; -} - -static void mg_handle_tcp_read(struct mg_connection *conn) { - int n = 0; - char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE); - - if (buf == NULL) { - DBG(("OOM")); - return; - } - -#if MG_ENABLE_SSL - if (conn->flags & MG_F_SSL) { - if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) { - /* SSL library may have more bytes ready to read than we ask to read. - * Therefore, read in a loop until we read everything. Without the loop, - * we skip to the next select() cycle which can just timeout. */ - while ((n = mg_ssl_if_read(conn, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) { - DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock)); - mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */); - buf = NULL; - if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break; - /* buf has been freed, we need a new one. */ - buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE); - if (buf == NULL) break; - } - MG_FREE(buf); - if (n < 0 && n != MG_SSL_WANT_READ) conn->flags |= MG_F_CLOSE_IMMEDIATELY; - } else { - MG_FREE(buf); - mg_ssl_begin(conn); - return; - } - } else -#endif - { - n = (int) MG_RECV_FUNC(conn->sock, buf, - recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0); - DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock)); - if (n > 0) { - mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */); - } else { - MG_FREE(buf); - } - if (n == 0) { - /* Orderly shutdown of the socket, try flushing output. */ - conn->flags |= MG_F_SEND_AND_CLOSE; - } else if (n < 0 && mg_is_error()) { - conn->flags |= MG_F_CLOSE_IMMEDIATELY; - } - } -} - -static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa, - socklen_t *sa_len, char **buf) { - int n; - *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE); - if (*buf == NULL) { - DBG(("Out of memory")); - return -ENOMEM; - } - n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len); - if (n <= 0) { - DBG(("%p recvfrom: %s", nc, strerror(mg_get_errno()))); - MG_FREE(*buf); - } - return n; -} - -static void mg_handle_udp_read(struct mg_connection *nc) { - char *buf = NULL; - union socket_address sa; - socklen_t sa_len = sizeof(sa); - int n = mg_recvfrom(nc, &sa, &sa_len, &buf); - DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len); -} - -#if MG_ENABLE_SSL -static void mg_ssl_begin(struct mg_connection *nc) { - int server_side = (nc->listener != NULL); - enum mg_ssl_if_result res = mg_ssl_if_handshake(nc); - DBG(("%p %d res %d", nc, server_side, res)); - - if (res == MG_SSL_OK) { - nc->flags |= MG_F_SSL_HANDSHAKE_DONE; - nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE); - - if (server_side) { - union socket_address sa; - socklen_t sa_len = sizeof(sa); - (void) getpeername(nc->sock, &sa.sa, &sa_len); - mg_if_accept_tcp_cb(nc, &sa, sa_len); - } else { - mg_if_connect_cb(nc, 0); - } - } else if (res != MG_SSL_WANT_READ && res != MG_SSL_WANT_WRITE) { - if (!server_side) { - mg_if_connect_cb(nc, res); - } - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} -#endif /* MG_ENABLE_SSL */ - -#define _MG_F_FD_CAN_READ 1 -#define _MG_F_FD_CAN_WRITE 1 << 1 -#define _MG_F_FD_ERROR 1 << 2 - -void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { - int worth_logging = - fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)); - if (worth_logging) { - DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, - fd_flags, nc->flags, (int) nc->recv_mbuf.len, - (int) nc->send_mbuf.len)); - } - - if (nc->flags & MG_F_CONNECTING) { - if (fd_flags != 0) { - int err = 0; -#if !defined(MG_ESP8266) - if (!(nc->flags & MG_F_UDP)) { - socklen_t len = sizeof(err); - int ret = - getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len); - if (ret != 0) { - err = 1; - } else if (err == EAGAIN || err == EWOULDBLOCK) { - err = 0; - } - } -#else - /* - * On ESP8266 we use blocking connect. - */ - err = nc->err; -#endif -#if MG_ENABLE_SSL - if ((nc->flags & MG_F_SSL) && err == 0) { - mg_ssl_begin(nc); - } else { - mg_if_connect_cb(nc, err); - } -#else - mg_if_connect_cb(nc, err); -#endif - } else if (nc->err != 0) { - mg_if_connect_cb(nc, nc->err); - } - } - - if (fd_flags & _MG_F_FD_CAN_READ) { - if (nc->flags & MG_F_UDP) { - mg_handle_udp_read(nc); - } else { - if (nc->flags & MG_F_LISTENING) { - /* - * We're not looping here, and accepting just one connection at - * a time. The reason is that eCos does not respect non-blocking - * flag on a listening socket and hangs in a loop. - */ - mg_accept_conn(nc); - } else { - mg_handle_tcp_read(nc); - } - } - } - - if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { - if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) { - mg_write_to_socket(nc); - } - mg_if_poll(nc, (time_t) now); - mg_if_timer(nc, now); - } - - if (worth_logging) { - DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags, - (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); - } -} - -#if MG_ENABLE_BROADCAST -static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) { - struct ctl_msg ctl_msg; - int len = - (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); - size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0); - DBG(("read %d from ctl socket", len)); - (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */ - if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { - struct mg_connection *nc; - for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { - ctl_msg.callback(nc, MG_EV_POLL, - ctl_msg.message MG_UD_ARG(nc->user_data)); - } - } -} -#endif - -/* Associate a socket to a connection. */ -void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) { - mg_set_non_blocking_mode(sock); - mg_set_close_on_exec(sock); - nc->sock = sock; - DBG(("%p %d", nc, sock)); -} - -void mg_socket_if_init(struct mg_iface *iface) { - (void) iface; - DBG(("%p using select()", iface->mgr)); -#if MG_ENABLE_BROADCAST - mg_socketpair(iface->mgr->ctl, SOCK_DGRAM); -#endif -} - -void mg_socket_if_free(struct mg_iface *iface) { - (void) iface; -} - -void mg_socket_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_socket_if_remove_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { - if (sock != INVALID_SOCKET -#ifdef __unix__ - && sock < (sock_t) FD_SETSIZE -#endif - ) { - FD_SET(sock, set); - if (*max_fd == INVALID_SOCKET || sock > *max_fd) { - *max_fd = sock; - } - } -} - -time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - double now = mg_time(); - double min_timer; - struct mg_connection *nc, *tmp; - struct timeval tv; - fd_set read_set, write_set, err_set; - sock_t max_fd = INVALID_SOCKET; - int num_fds, num_ev, num_timers = 0; -#ifdef __unix__ - int try_dup = 1; -#endif - - FD_ZERO(&read_set); - FD_ZERO(&write_set); - FD_ZERO(&err_set); -#if MG_ENABLE_BROADCAST - mg_add_to_set(mgr->ctl[1], &read_set, &max_fd); -#endif - - /* - * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, - * e.g. timer-only "connections". - */ - min_timer = 0; - for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { - tmp = nc->next; - - if (nc->sock != INVALID_SOCKET) { - num_fds++; - -#ifdef __unix__ - /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */ - if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) { - int new_sock = dup(nc->sock); - if (new_sock >= 0) { - if (new_sock < (sock_t) FD_SETSIZE) { - closesocket(nc->sock); - DBG(("new sock %d -> %d", nc->sock, new_sock)); - nc->sock = new_sock; - } else { - closesocket(new_sock); - DBG(("new sock is still larger than FD_SETSIZE, disregard")); - try_dup = 0; - } - } else { - try_dup = 0; - } - } -#endif - - if (!(nc->flags & MG_F_WANT_WRITE) && - nc->recv_mbuf.len < nc->recv_mbuf_limit && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { - mg_add_to_set(nc->sock, &read_set, &max_fd); - } - - if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || - (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { - mg_add_to_set(nc->sock, &write_set, &max_fd); - mg_add_to_set(nc->sock, &err_set, &max_fd); - } - } - - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - } - - /* - * If there is a timer to be fired earlier than the requested timeout, - * adjust the timeout. - */ - if (num_timers > 0) { - double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; - if (timer_timeout_ms < timeout_ms) { - timeout_ms = (int) timer_timeout_ms; - } - } - if (timeout_ms < 0) timeout_ms = 0; - - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - - num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); - now = mg_time(); -#if 0 - DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds, - timeout_ms)); -#endif - -#if MG_ENABLE_BROADCAST - if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET && - FD_ISSET(mgr->ctl[1], &read_set)) { - mg_mgr_handle_ctl_sock(mgr); - } -#endif - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - int fd_flags = 0; - if (nc->sock != INVALID_SOCKET) { - if (num_ev > 0) { - fd_flags = (FD_ISSET(nc->sock, &read_set) && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL) - ? _MG_F_FD_CAN_READ - : 0) | - (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) | - (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); - } -#if MG_LWIP - /* With LWIP socket emulation layer, we don't get write events for UDP */ - if ((nc->flags & MG_F_UDP) && nc->listener == NULL) { - fd_flags |= _MG_F_FD_CAN_WRITE; - } -#endif - } - tmp = nc->next; - mg_mgr_handle_conn(nc, fd_flags, now); - } - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || - (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { - mg_close_conn(nc); - } - } - - return (time_t) now; -} - -#if MG_ENABLE_BROADCAST -MG_INTERNAL void mg_socketpair_close(sock_t *sock) { - while (1) { - if (closesocket(*sock) == -1 && errno == EINTR) continue; - break; - } - *sock = INVALID_SOCKET; -} - -MG_INTERNAL sock_t -mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) { - sock_t rc; - while (1) { - if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET && - errno == EINTR) - continue; - break; - } - return rc; -} - -int mg_socketpair(sock_t sp[2], int sock_type) { - union socket_address sa; - sock_t sock; - socklen_t len = sizeof(sa.sin); - int ret = 0; - - sock = sp[0] = sp[1] = INVALID_SOCKET; - - (void) memset(&sa, 0, sizeof(sa)); - sa.sin.sin_family = AF_INET; - sa.sin.sin_port = htons(0); - sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */ - - if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { - } else if (bind(sock, &sa.sa, len) != 0) { - } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) { - } else if (getsockname(sock, &sa.sa, &len) != 0) { - } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) { - } else if (connect(sp[0], &sa.sa, len) != 0) { - } else if (sock_type == SOCK_DGRAM && - (getsockname(sp[0], &sa.sa, &len) != 0 || - connect(sock, &sa.sa, len) != 0)) { - } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept( - sock, &sa, len))) == - INVALID_SOCKET) { - } else { - mg_set_close_on_exec(sp[0]); - mg_set_close_on_exec(sp[1]); - if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock); - ret = 1; - } - - if (!ret) { - if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]); - if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]); - if (sock != INVALID_SOCKET) mg_socketpair_close(&sock); - } - - return ret; -} -#endif /* MG_ENABLE_BROADCAST */ - -static void mg_sock_get_addr(sock_t sock, int remote, - union socket_address *sa) { - socklen_t slen = sizeof(*sa); - memset(sa, 0, slen); - if (remote) { - getpeername(sock, &sa->sa, &slen); - } else { - getsockname(sock, &sa->sa, &slen); - } -} - -void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { - union socket_address sa; - mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); - mg_sock_addr_to_str(&sa, buf, len, flags); -} - -void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - if ((nc->flags & MG_F_UDP) && remote) { - memcpy(sa, &nc->sa, sizeof(*sa)); - return; - } - mg_sock_get_addr(nc->sock, remote, sa); -} - -/* clang-format off */ -#define MG_SOCKET_IFACE_VTABLE \ - { \ - mg_socket_if_init, \ - mg_socket_if_free, \ - mg_socket_if_add_conn, \ - mg_socket_if_remove_conn, \ - mg_socket_if_poll, \ - mg_socket_if_listen_tcp, \ - mg_socket_if_listen_udp, \ - mg_socket_if_connect_tcp, \ - mg_socket_if_connect_udp, \ - mg_socket_if_tcp_send, \ - mg_socket_if_udp_send, \ - mg_socket_if_recved, \ - mg_socket_if_create_conn, \ - mg_socket_if_destroy_conn, \ - mg_socket_if_sock_set, \ - mg_socket_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_SOCKET -const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_SOCKET */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_net_if_socks.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SOCKS - -struct socksdata { - char *proxy_addr; /* HOST:PORT of the socks5 proxy server */ - struct mg_connection *s; /* Respective connection to the server */ - struct mg_connection *c; /* Connection to the client */ - struct mbuf tmp; /* Temporary buffer for sent data */ -}; - -static void socks_if_disband(struct socksdata *d) { - LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s)); - if (d->c) d->c->flags |= MG_F_SEND_AND_CLOSE; - if (d->s) d->s->flags |= MG_F_SEND_AND_CLOSE; - d->c = d->s = NULL; -} - -static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) { - struct socksdata *d = (struct socksdata *) c->user_data; - if (ev == MG_EV_CONNECT) { - int res = *(int *) ev_data; - if (res == 0) { - /* Send handshake to the proxy server */ - unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH}; - mg_send(d->s, buf, sizeof(buf)); - LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr)); - } else { - LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res)); - d->c->flags |= MG_F_CLOSE_IMMEDIATELY; - } - } else if (ev == MG_EV_CLOSE) { - socks_if_disband(d); - } else if (ev == MG_EV_RECV) { - /* Handle handshake reply */ - if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) { - /* TODO(lsm): process IPv6 too */ - unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0, - MG_SOCKS_ADDR_IPV4}; - if (c->recv_mbuf.len < 2) return; - if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) { - LOG(LL_ERROR, ("Server kicked us out")); - socks_if_disband(d); - return; - } - mbuf_remove(&c->recv_mbuf, 2); - c->flags |= MG_SOCKS_HANDSHAKE_DONE; - - /* Send connect request */ - memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4); - memcpy(buf + 8, &d->c->sa.sin.sin_port, 2); - mg_send(c, buf, sizeof(buf)); - } - /* Process connect request */ - if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) && - !(c->flags & MG_SOCKS_CONNECT_DONE)) { - if (c->recv_mbuf.len < 10) return; - if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) { - LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1])); - socks_if_disband(d); - return; - } - mbuf_remove(&c->recv_mbuf, 10); - c->flags |= MG_SOCKS_CONNECT_DONE; - /* Connected. Move sent data from client, if any, to server */ - if (d->s && d->c) { - mbuf_append(&d->s->send_mbuf, d->tmp.buf, d->tmp.len); - mbuf_free(&d->tmp); - } - } - /* All flags are set, we're in relay mode */ - if ((c->flags & MG_SOCKS_CONNECT_DONE) && d->c && d->s) { - mbuf_append(&d->c->recv_mbuf, d->s->recv_mbuf.buf, d->s->recv_mbuf.len); - mbuf_remove(&d->s->recv_mbuf, d->s->recv_mbuf.len); - } - } -} - -static void mg_socks_if_connect_tcp(struct mg_connection *c, - const union socket_address *sa) { - struct socksdata *d = (struct socksdata *) c->iface->data; - d->c = c; - d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler); - d->s->user_data = d; - LOG(LL_DEBUG, ("%p %s", c, d->proxy_addr)); - (void) sa; -} - -static void mg_socks_if_connect_udp(struct mg_connection *c) { - (void) c; -} - -static int mg_socks_if_listen_tcp(struct mg_connection *c, - union socket_address *sa) { - (void) c; - (void) sa; - return 0; -} - -static int mg_socks_if_listen_udp(struct mg_connection *c, - union socket_address *sa) { - (void) c; - (void) sa; - return -1; -} - -static void mg_socks_if_tcp_send(struct mg_connection *c, const void *buf, - size_t len) { - struct socksdata *d = (struct socksdata *) c->iface->data; - LOG(LL_DEBUG, ("%p -> %p %d %d", c, buf, (int) len, (int) c->send_mbuf.len)); - if (d && d->s && d->s->flags & MG_SOCKS_CONNECT_DONE) { - mbuf_append(&d->s->send_mbuf, d->tmp.buf, d->tmp.len); - mbuf_append(&d->s->send_mbuf, buf, len); - mbuf_free(&d->tmp); - } else { - mbuf_append(&d->tmp, buf, len); - } -} - -static void mg_socks_if_udp_send(struct mg_connection *c, const void *buf, - size_t len) { - (void) c; - (void) buf; - (void) len; -} - -static void mg_socks_if_recved(struct mg_connection *c, size_t len) { - (void) c; - (void) len; -} - -static int mg_socks_if_create_conn(struct mg_connection *c) { - (void) c; - return 1; -} - -static void mg_socks_if_destroy_conn(struct mg_connection *c) { - c->iface->vtable->free(c->iface); - MG_FREE(c->iface); - c->iface = NULL; - LOG(LL_DEBUG, ("%p", c)); -} - -static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) { - (void) c; - (void) sock; -} - -static void mg_socks_if_init(struct mg_iface *iface) { - (void) iface; -} - -static void mg_socks_if_free(struct mg_iface *iface) { - struct socksdata *d = (struct socksdata *) iface->data; - LOG(LL_DEBUG, ("%p", iface)); - if (d != NULL) { - socks_if_disband(d); - mbuf_free(&d->tmp); - MG_FREE(d->proxy_addr); - MG_FREE(d); - iface->data = NULL; - } -} - -static void mg_socks_if_add_conn(struct mg_connection *c) { - c->sock = INVALID_SOCKET; -} - -static void mg_socks_if_remove_conn(struct mg_connection *c) { - (void) c; -} - -static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) { - LOG(LL_DEBUG, ("%p", iface)); - (void) iface; - (void) timeout_ms; - return (time_t) cs_time(); -} - -static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote, - union socket_address *sa) { - LOG(LL_DEBUG, ("%p", c)); - (void) c; - (void) remote; - (void) sa; -} - -const struct mg_iface_vtable mg_socks_iface_vtable = { - mg_socks_if_init, mg_socks_if_free, - mg_socks_if_add_conn, mg_socks_if_remove_conn, - mg_socks_if_poll, mg_socks_if_listen_tcp, - mg_socks_if_listen_udp, mg_socks_if_connect_tcp, - mg_socks_if_connect_udp, mg_socks_if_tcp_send, - mg_socks_if_udp_send, mg_socks_if_recved, - mg_socks_if_create_conn, mg_socks_if_destroy_conn, - mg_socks_if_sock_set, mg_socks_if_get_conn_addr, -}; - -struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) { - struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr); - iface->data = MG_CALLOC(1, sizeof(struct socksdata)); - ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr); - return iface; -} - -#endif -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_ssl_if_openssl.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL - -#ifdef __APPLE__ -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - -#include - -struct mg_ssl_if_ctx { - SSL *ssl; - SSL_CTX *ssl_ctx; - struct mbuf psk; - size_t identity_len; -}; - -void mg_ssl_if_init() { - SSL_library_init(); -} - -enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, - struct mg_connection *lc) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; - nc->ssl_if_data = ctx; - if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; - ctx->ssl_ctx = lc_ctx->ssl_ctx; - if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { - return MG_SSL_ERROR; - } - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, - const char *key, const char **err_msg); -static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert); -static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl); -static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, - const char *identity, - const char *key_str); - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), - (params->key ? params->key : ""), - (params->ca_cert ? params->ca_cert : ""))); - if (ctx == NULL) { - MG_SET_PTRPTR(err_msg, "Out of memory"); - return MG_SSL_ERROR; - } - nc->ssl_if_data = ctx; - if (nc->flags & MG_F_LISTENING) { - ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method()); - } else { - ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); - } - if (ctx->ssl_ctx == NULL) { - MG_SET_PTRPTR(err_msg, "Failed to create SSL context"); - return MG_SSL_ERROR; - } - -#ifndef KR_VERSION - /* Disable deprecated protocols. */ - SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2); - SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3); - SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1); -#ifdef MG_SSL_OPENSSL_NO_COMPRESSION - SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION); -#endif -#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE - SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); -#endif -#else -/* Krypton only supports TLSv1.2 anyway. */ -#endif - - if (params->cert != NULL && - mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) != - MG_SSL_OK) { - return MG_SSL_ERROR; - } - - if (params->ca_cert != NULL && - mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); - return MG_SSL_ERROR; - } - - if (params->server_name != NULL) { -#ifdef KR_VERSION - SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name); -#else -/* TODO(rojer): Implement server name verification on OpenSSL. */ -#endif - } - - if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); - return MG_SSL_ERROR; - } - - mbuf_init(&ctx->psk, 0); - if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) != - MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); - return MG_SSL_ERROR; - } - - if (!(nc->flags & MG_F_LISTENING) && - (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) { - MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); - return MG_SSL_ERROR; - } - - nc->flags |= MG_F_SSL; - - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc, - int res) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int err = SSL_get_error(ctx->ssl, res); - if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ; - if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE; - DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err)); - nc->err = err; - return MG_SSL_ERROR; -} - -enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int server_side = (nc->listener != NULL); - int res; - /* If descriptor is not yet set, do it now. */ - if (SSL_get_fd(ctx->ssl) < 0) { - if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR; - } - res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl); - if (res != 1) return mg_ssl_if_ssl_err(nc, res); - return MG_SSL_OK; -} - -int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int n = SSL_read(ctx->ssl, buf, buf_size); - DBG(("%p %d -> %d", nc, (int) buf_size, n)); - if (n < 0) return mg_ssl_if_ssl_err(nc, n); - if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return n; -} - -int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int n = SSL_write(ctx->ssl, data, len); - DBG(("%p %d -> %d", nc, (int) len, n)); - if (n <= 0) return mg_ssl_if_ssl_err(nc, n); - return n; -} - -void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - SSL_shutdown(ctx->ssl); -} - -void mg_ssl_if_conn_free(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - nc->ssl_if_data = NULL; - if (ctx->ssl != NULL) SSL_free(ctx->ssl); - if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx); - mbuf_free(&ctx->psk); - memset(ctx, 0, sizeof(*ctx)); - MG_FREE(ctx); -} - -/* - * Cipher suite options used for TLS negotiation. - * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations - */ -static const char mg_s_cipher_list[] = -#if defined(MG_SSL_CRYPTO_MODERN) - "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:" - "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:" - "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" - "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" - "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" - "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" - "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" - "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:" - "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK" -#elif defined(MG_SSL_CRYPTO_OLD) - "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" - "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" - "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" - "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" - "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" - "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" - "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" - "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:" - "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" - "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:" - "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" - "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" -#else /* Default - intermediate. */ - "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:" - "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:" - "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:" - "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:" - "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:" - "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:" - "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:" - "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:" - "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:" - "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:" - "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA" -#endif - ; - -/* - * Default DH params for PFS cipher negotiation. This is a 2048-bit group. - * Will be used if none are provided by the user in the certificate file. - */ -#if !MG_DISABLE_PFS && !defined(KR_VERSION) -static const char mg_s_default_dh_params[] = - "\ ------BEGIN DH PARAMETERS-----\n\ -MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\ -Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\ -+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\ -ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\ -wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\ -9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\ ------END DH PARAMETERS-----\n"; -#endif - -static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) { - if (cert == NULL || strcmp(cert, "*") == 0) { - return MG_SSL_OK; - } - SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); - return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK - : MG_SSL_ERROR; -} - -static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert, - const char *key, - const char **err_msg) { - if (key == NULL) key = cert; - if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { - return MG_SSL_OK; - } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) { - MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); - return MG_SSL_ERROR; - } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) { - MG_SET_PTRPTR(err_msg, "Invalid SSL key"); - return MG_SSL_ERROR; - } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) { - MG_SET_PTRPTR(err_msg, "Invalid CA bundle"); - return MG_SSL_ERROR; - } else { - SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); -#if !MG_DISABLE_PFS && !defined(KR_VERSION) - BIO *bio = NULL; - DH *dh = NULL; - - /* Try to read DH parameters from the cert/key file. */ - bio = BIO_new_file(cert, "r"); - if (bio != NULL) { - dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); - BIO_free(bio); - } - /* - * If there are no DH params in the file, fall back to hard-coded ones. - * Not ideal, but better than nothing. - */ - if (dh == NULL) { - bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1); - dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL); - BIO_free(bio); - } - if (dh != NULL) { - SSL_CTX_set_tmp_dh(ctx, dh); - SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE); - DH_free(dh); - } -#if OPENSSL_VERSION_NUMBER > 0x10002000L - SSL_CTX_set_ecdh_auto(ctx, 1); -#endif -#endif - } - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) { - return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1 - ? MG_SSL_OK - : MG_SSL_ERROR); -} - -#ifndef KR_VERSION -static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint, - char *identity, - unsigned int max_identity_len, - unsigned char *psk, - unsigned int max_psk_len) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)); - size_t key_len = ctx->psk.len - ctx->identity_len - 1; - DBG(("hint: '%s'", (hint ? hint : ""))); - if (ctx->identity_len + 1 > max_identity_len) { - DBG(("identity too long")); - return 0; - } - if (key_len > max_psk_len) { - DBG(("key too long")); - return 0; - } - memcpy(identity, ctx->psk.buf, ctx->identity_len + 1); - memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len); - (void) ssl; - return key_len; -} - -static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, - const char *identity, - const char *key_str) { - unsigned char key[32]; - size_t key_len; - size_t i = 0; - if (identity == NULL && key_str == NULL) return MG_SSL_OK; - if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; - key_len = strlen(key_str); - if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; - memset(key, 0, sizeof(key)); - key_len = 0; - for (i = 0; key_str[i] != '\0'; i++) { - unsigned char c; - char hc = tolower((int) key_str[i]); - if (hc >= '0' && hc <= '9') { - c = hc - '0'; - } else if (hc >= 'a' && hc <= 'f') { - c = hc - 'a' + 0xa; - } else { - return MG_SSL_ERROR; - } - key_len = i / 2; - key[key_len] <<= 4; - key[key_len] |= c; - } - key_len++; - DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); - ctx->identity_len = strlen(identity); - mbuf_append(&ctx->psk, identity, ctx->identity_len + 1); - mbuf_append(&ctx->psk, key, key_len); - SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb); - SSL_CTX_set_app_data(ctx->ssl_ctx, ctx); - return MG_SSL_OK; -} -#else -static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx, - const char *identity, - const char *key_str) { - (void) ctx; - (void) identity; - (void) key_str; - /* Krypton does not support PSK. */ - return MG_SSL_ERROR; -} -#endif /* defined(KR_VERSION) */ - -const char *mg_set_ssl(struct mg_connection *nc, const char *cert, - const char *ca_cert) { - const char *err_msg = NULL; - struct mg_ssl_if_conn_params params; - memset(¶ms, 0, sizeof(params)); - params.cert = cert; - params.ca_cert = ca_cert; - if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { - return err_msg; - } - return NULL; -} - -#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_ssl_if_mbedtls.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS - -#include -#include -#include -#include -#include - -static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line, - const char *str) { - enum cs_log_level cs_level; - switch (level) { - case 1: - cs_level = LL_ERROR; - break; - case 2: - case 3: - cs_level = LL_DEBUG; - break; - default: - cs_level = LL_VERBOSE_DEBUG; - } - /* mbedTLS passes strings with \n at the end, strip it. */ - LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str)); - (void) file; - (void) line; -} - -struct mg_ssl_if_ctx { - mbedtls_ssl_config *conf; - mbedtls_ssl_context *ssl; - mbedtls_x509_crt *cert; - mbedtls_pk_context *key; - mbedtls_x509_crt *ca_cert; - struct mbuf cipher_suites; -}; - -/* Must be provided by the platform. ctx is struct mg_connection. */ -extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len); - -void mg_ssl_if_init() { -} - -enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc, - struct mg_connection *lc) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data; - nc->ssl_if_data = ctx; - if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR; - ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); - if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) { - return MG_SSL_ERROR; - } - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, - const char *cert, const char *key, - const char **err_msg); -static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, - const char *cert); -static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, - const char *ciphers); -static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, - const char *identity, - const char *key); - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""), - (params->key ? params->key : ""), - (params->ca_cert ? params->ca_cert : ""))); - - if (ctx == NULL) { - MG_SET_PTRPTR(err_msg, "Out of memory"); - return MG_SSL_ERROR; - } - nc->ssl_if_data = ctx; - ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf)); - mbuf_init(&ctx->cipher_suites, 0); - mbedtls_ssl_config_init(ctx->conf); - mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc); - if (mbedtls_ssl_config_defaults( - ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER - : MBEDTLS_SSL_IS_CLIENT), - MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { - MG_SET_PTRPTR(err_msg, "Failed to init SSL config"); - return MG_SSL_ERROR; - } - - /* TLS 1.2 and up */ - mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3, - MBEDTLS_SSL_MINOR_VERSION_3); - mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc); - - if (params->cert != NULL && - mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) { - return MG_SSL_ERROR; - } - - if (params->ca_cert != NULL && - mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert"); - return MG_SSL_ERROR; - } - - if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid cipher suite list"); - return MG_SSL_ERROR; - } - - if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) != - MG_SSL_OK) { - MG_SET_PTRPTR(err_msg, "Invalid PSK settings"); - return MG_SSL_ERROR; - } - - if (!(nc->flags & MG_F_LISTENING)) { - ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl)); - mbedtls_ssl_init(ctx->ssl); - if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) { - MG_SET_PTRPTR(err_msg, "Failed to create SSL session"); - return MG_SSL_ERROR; - } - if (params->server_name != NULL && - mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) { - return MG_SSL_ERROR; - } - } - -#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN - if (mbedtls_ssl_conf_max_frag_len(ctx->conf, -#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512 - MBEDTLS_SSL_MAX_FRAG_LEN_512 -#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024 - MBEDTLS_SSL_MAX_FRAG_LEN_1024 -#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048 - MBEDTLS_SSL_MAX_FRAG_LEN_2048 -#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096 - MBEDTLS_SSL_MAX_FRAG_LEN_4096 -#else -#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN -#endif - ) != 0) { - return MG_SSL_ERROR; - } -#endif - - nc->flags |= MG_F_SSL; - - return MG_SSL_OK; -} - -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len); -int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len); -#else -static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) { - struct mg_connection *nc = (struct mg_connection *) ctx; - int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0); - LOG(LL_DEBUG, ("%p %d -> %d", nc, (int) len, n)); - if (n >= 0) return n; - n = mg_get_errno(); - return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1); -} - -static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) { - struct mg_connection *nc = (struct mg_connection *) ctx; - int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0); - LOG(LL_DEBUG, ("%p %d <- %d", nc, (int) len, n)); - if (n >= 0) return n; - n = mg_get_errno(); - return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1); -} -#endif - -static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc, - int ret) { - if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ; - if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE; - if (ret != - MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */ - LOG(LL_ERROR, ("%p SSL error: %d", nc, ret)); - } - nc->err = ret; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return MG_SSL_ERROR; -} - -static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) { - if (ctx->cert != NULL) { - mbedtls_x509_crt_free(ctx->cert); - MG_FREE(ctx->cert); - ctx->cert = NULL; - mbedtls_pk_free(ctx->key); - MG_FREE(ctx->key); - ctx->key = NULL; - } - if (ctx->ca_cert != NULL) { - mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); -#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK - if (ctx->ca_cert->ca_chain_file != NULL) { - MG_FREE((void *) ctx->ca_cert->ca_chain_file); - ctx->ca_cert->ca_chain_file = NULL; - } -#endif - mbedtls_x509_crt_free(ctx->ca_cert); - MG_FREE(ctx->ca_cert); - ctx->ca_cert = NULL; - } -} - -enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int err; - /* If bio is not yet set, do it now. */ - if (ctx->ssl->p_bio == NULL) { - mbedtls_ssl_set_bio(ctx->ssl, nc, ssl_socket_send, ssl_socket_recv, NULL); - } - err = mbedtls_ssl_handshake(ctx->ssl); - if (err != 0) return mg_ssl_if_mbed_err(nc, err); -#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS - /* - * Free the peer certificate, we don't need it after handshake. - * Note that this effectively disables renegotiation. - */ - mbedtls_x509_crt_free(ctx->ssl->session->peer_cert); - mbedtls_free(ctx->ssl->session->peer_cert); - ctx->ssl->session->peer_cert = NULL; - /* On a client connection we can also free our own and CA certs. */ - if (nc->listener == NULL) { - if (ctx->conf->key_cert != NULL) { - /* Note that this assumes one key_cert entry, which matches our init. */ - MG_FREE(ctx->conf->key_cert); - ctx->conf->key_cert = NULL; - } - mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL); - mg_ssl_if_mbed_free_certs_and_keys(ctx); - } -#endif - return MG_SSL_OK; -} - -int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, buf_size); - DBG(("%p %d -> %d", nc, (int) buf_size, n)); - if (n < 0) return mg_ssl_if_mbed_err(nc, n); - if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return n; -} - -int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) data, len); - DBG(("%p %d -> %d", nc, (int) len, n)); - if (n < 0) return mg_ssl_if_mbed_err(nc, n); - return n; -} - -void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - mbedtls_ssl_close_notify(ctx->ssl); -} - -void mg_ssl_if_conn_free(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - nc->ssl_if_data = NULL; - if (ctx->ssl != NULL) { - mbedtls_ssl_free(ctx->ssl); - MG_FREE(ctx->ssl); - } - mg_ssl_if_mbed_free_certs_and_keys(ctx); - if (ctx->conf != NULL) { - mbedtls_ssl_config_free(ctx->conf); - MG_FREE(ctx->conf); - } - mbuf_free(&ctx->cipher_suites); - memset(ctx, 0, sizeof(*ctx)); - MG_FREE(ctx); -} - -static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx, - const char *ca_cert) { - if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) { - mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE); - return MG_SSL_OK; - } - ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert)); - mbedtls_x509_crt_init(ctx->ca_cert); -#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK - ca_cert = strdup(ca_cert); - if (mbedtls_x509_crt_set_ca_chain_file(ctx->ca_cert, ca_cert) != 0) { - return MG_SSL_ERROR; - } -#else - if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) { - return MG_SSL_ERROR; - } -#endif - mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL); - mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED); - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx, - const char *cert, const char *key, - const char **err_msg) { - if (key == NULL) key = cert; - if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') { - return MG_SSL_OK; - } - ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert)); - mbedtls_x509_crt_init(ctx->cert); - ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key)); - mbedtls_pk_init(ctx->key); - if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) { - MG_SET_PTRPTR(err_msg, "Invalid SSL cert"); - return MG_SSL_ERROR; - } - if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) { - MG_SET_PTRPTR(err_msg, "Invalid SSL key"); - return MG_SSL_ERROR; - } - if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) { - MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert"); - return MG_SSL_ERROR; - } - return MG_SSL_OK; -} - -static const int mg_s_cipher_list[] = { -#if CS_PLATFORM != CS_P_ESP8266 - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, - MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, -#else - /* - * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results - * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true. - * Disable DHE completely because it's just hopelessly slow. - */ - MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, - MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, - MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, -#endif /* CS_PLATFORM != CS_P_ESP8266 */ - 0, -}; - -/* - * Ciphers can be specified as a colon-separated list of cipher suite names. - * These can be found in - * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267 - * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM - */ -static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx, - const char *ciphers) { - if (ciphers != NULL) { - int l, id; - const char *s = ciphers, *e; - char tmp[50]; - while (s != NULL) { - e = strchr(s, ':'); - l = (e != NULL ? (e - s) : (int) strlen(s)); - strncpy(tmp, s, l); - tmp[l] = '\0'; - id = mbedtls_ssl_get_ciphersuite_id(tmp); - DBG(("%s -> %04x", tmp, id)); - if (id != 0) { - mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); - } - s = (e != NULL ? e + 1 : NULL); - } - if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR; - id = 0; - mbuf_append(&ctx->cipher_suites, &id, sizeof(id)); - mbuf_trim(&ctx->cipher_suites); - mbedtls_ssl_conf_ciphersuites(ctx->conf, - (const int *) ctx->cipher_suites.buf); - } else { - mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list); - } - return MG_SSL_OK; -} - -static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx, - const char *identity, - const char *key_str) { - unsigned char key[32]; - size_t key_len; - if (identity == NULL && key_str == NULL) return MG_SSL_OK; - if (identity == NULL || key_str == NULL) return MG_SSL_ERROR; - key_len = strlen(key_str); - if (key_len != 32 && key_len != 64) return MG_SSL_ERROR; - size_t i = 0; - memset(key, 0, sizeof(key)); - key_len = 0; - for (i = 0; key_str[i] != '\0'; i++) { - unsigned char c; - char hc = tolower((int) key_str[i]); - if (hc >= '0' && hc <= '9') { - c = hc - '0'; - } else if (hc >= 'a' && hc <= 'f') { - c = hc - 'a' + 0xa; - } else { - return MG_SSL_ERROR; - } - key_len = i / 2; - key[key_len] <<= 4; - key[key_len] |= c; - } - key_len++; - DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len)); - /* mbedTLS makes copies of psk and identity. */ - if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len, - (const unsigned char *) identity, - strlen(identity)) != 0) { - return MG_SSL_ERROR; - } - return MG_SSL_OK; -} - -const char *mg_set_ssl(struct mg_connection *nc, const char *cert, - const char *ca_cert) { - const char *err_msg = NULL; - struct mg_ssl_if_conn_params params; - memset(¶ms, 0, sizeof(params)); - params.cert = cert; - params.ca_cert = ca_cert; - if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) { - return err_msg; - } - return NULL; -} - -/* Lazy RNG. Warning: it would be a bad idea to do this in production! */ -#ifdef MG_SSL_MBED_DUMMY_RANDOM -int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) { - (void) ctx; - while (len--) *buf++ = rand(); - return 0; -} -#endif - -#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_uri.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_uri.h" */ - -/* - * scan string until encountering one of `seps`, keeping track of component - * boundaries in `res`. - * - * `p` will point to the char after the separator or it will be `end`. - */ -static void parse_uri_component(const char **p, const char *end, - const char *seps, struct mg_str *res) { - const char *q; - res->p = *p; - for (; *p < end; (*p)++) { - for (q = seps; *q != '\0'; q++) { - if (**p == *q) break; - } - if (*q != '\0') break; - } - res->len = (*p) - res->p; - if (*p < end) (*p)++; -} - -int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, - struct mg_str *user_info, struct mg_str *host, - unsigned int *port, struct mg_str *path, struct mg_str *query, - struct mg_str *fragment) { - struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0}, - rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0}; - unsigned int rport = 0; - enum { - P_START, - P_SCHEME_OR_PORT, - P_USER_INFO, - P_HOST, - P_PORT, - P_REST - } state = P_START; - - const char *p = uri.p, *end = p + uri.len; - while (p < end) { - switch (state) { - case P_START: - /* - * expecting on of: - * - `scheme://xxxx` - * - `xxxx:port` - * - `[a:b:c]:port` - * - `xxxx/path` - */ - if (*p == '[') { - state = P_HOST; - break; - } - for (; p < end; p++) { - if (*p == ':') { - state = P_SCHEME_OR_PORT; - break; - } else if (*p == '/') { - state = P_REST; - break; - } - } - if (state == P_START || state == P_REST) { - rhost.p = uri.p; - rhost.len = p - uri.p; - } - break; - case P_SCHEME_OR_PORT: - if (end - p >= 3 && strncmp(p, "://", 3) == 0) { - rscheme.p = uri.p; - rscheme.len = p - uri.p; - state = P_USER_INFO; - p += 3; - } else { - rhost.p = uri.p; - rhost.len = p - uri.p; - state = P_PORT; - } - break; - case P_USER_INFO: - ruser_info.p = p; - for (; p < end; p++) { - if (*p == '@' || *p == '[' || *p == '/') { - break; - } - } - if (p == end || *p == '/' || *p == '[') { - /* backtrack and parse as host */ - p = ruser_info.p; - } - ruser_info.len = p - ruser_info.p; - state = P_HOST; - break; - case P_HOST: - if (*p == '@') p++; - rhost.p = p; - if (*p == '[') { - int found = 0; - for (; !found && p < end; p++) { - found = (*p == ']'); - } - if (!found) return -1; - } else { - for (; p < end; p++) { - if (*p == ':' || *p == '/') break; - } - } - rhost.len = p - rhost.p; - if (p < end) { - if (*p == ':') { - state = P_PORT; - break; - } else if (*p == '/') { - state = P_REST; - break; - } - } - break; - case P_PORT: - p++; - for (; p < end; p++) { - if (*p == '/') { - state = P_REST; - break; - } - rport *= 10; - rport += *p - '0'; - } - break; - case P_REST: - /* `p` points to separator. `path` includes the separator */ - parse_uri_component(&p, end, "?#", &rpath); - if (p < end && *(p - 1) == '?') { - parse_uri_component(&p, end, "#", &rquery); - } - parse_uri_component(&p, end, "", &rfragment); - break; - } - } - - if (scheme != 0) *scheme = rscheme; - if (user_info != 0) *user_info = ruser_info; - if (host != 0) *host = rhost; - if (port != 0) *port = rport; - if (path != 0) *path = rpath; - if (query != 0) *query = rquery; - if (fragment != 0) *fragment = rfragment; - - return 0; -} - -/* Normalize the URI path. Remove/resolve "." and "..". */ -int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) { - const char *s = in->p, *se = s + in->len; - char *cp = (char *) out->p, *d; - - if (in->len == 0 || *s != '/') { - out->len = 0; - return 0; - } - - d = cp; - - while (s < se) { - const char *next = s; - struct mg_str component; - parse_uri_component(&next, se, "/", &component); - if (mg_vcmp(&component, ".") == 0) { - /* Yum. */ - } else if (mg_vcmp(&component, "..") == 0) { - /* Backtrack to previous slash. */ - if (d > cp + 1 && *(d - 1) == '/') d--; - while (d > cp && *(d - 1) != '/') d--; - } else { - memmove(d, s, next - s); - d += next - s; - } - s = next; - } - if (d == cp) *d++ = '/'; - - out->p = cp; - out->len = d - cp; - return 1; -} - -int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, - const struct mg_str *host, unsigned int port, - const struct mg_str *path, const struct mg_str *query, - const struct mg_str *fragment, int normalize_path, - struct mg_str *uri) { - int result = -1; - struct mbuf out; - mbuf_init(&out, 0); - - if (scheme != NULL && scheme->len > 0) { - mbuf_append(&out, scheme->p, scheme->len); - mbuf_append(&out, "://", 3); - } - - if (user_info != NULL && user_info->len > 0) { - mbuf_append(&out, user_info->p, user_info->len); - mbuf_append(&out, "@", 1); - } - - if (host != NULL && host->len > 0) { - mbuf_append(&out, host->p, host->len); - } - - if (port != 0) { - char port_str[20]; - int port_str_len = sprintf(port_str, ":%u", port); - mbuf_append(&out, port_str, port_str_len); - } - - if (path != NULL && path->len > 0) { - if (normalize_path) { - struct mg_str npath = mg_strdup(*path); - if (npath.len != path->len) goto out; - if (!mg_normalize_uri_path(path, &npath)) { - free((void *) npath.p); - goto out; - } - mbuf_append(&out, npath.p, npath.len); - free((void *) npath.p); - } else { - mbuf_append(&out, path->p, path->len); - } - } else if (normalize_path) { - mbuf_append(&out, "/", 1); - } - - if (query != NULL && query->len > 0) { - mbuf_append(&out, "?", 1); - mbuf_append(&out, query->p, query->len); - } - - if (fragment != NULL && fragment->len > 0) { - mbuf_append(&out, "#", 1); - mbuf_append(&out, fragment->p, fragment->len); - } - - result = 0; - -out: - if (result == 0) { - uri->p = out.buf; - uri->len = out.len; - } else { - mbuf_free(&out); - uri->p = NULL; - uri->len = 0; - } - return result; -} -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP - -/* Amalgamated: #include "common/cs_md5.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_util.h" */ - -/* altbuf {{{ */ - -/* - * Alternate buffer: fills the client-provided buffer with data; and if it's - * not large enough, allocates another buffer (via mbuf), similar to asprintf. - */ -struct altbuf { - struct mbuf m; - char *user_buf; - size_t len; - size_t user_buf_size; -}; - -/* - * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer. - */ -MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) { - mbuf_init(&ab->m, 0); - ab->user_buf = buf; - ab->user_buf_size = buf_size; - ab->len = 0; -} - -/* - * Appends a single char to the altbuf. - */ -MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) { - if (ab->len < ab->user_buf_size) { - /* The data fits into the original buffer */ - ab->user_buf[ab->len++] = c; - } else { - /* The data can't fit into the original buffer, so write it to mbuf. */ - - /* - * First of all, see if that's the first byte which overflows the original - * buffer: if so, copy the existing data from there to a newly allocated - * mbuf. - */ - if (ab->len > 0 && ab->m.len == 0) { - mbuf_append(&ab->m, ab->user_buf, ab->len); - } - - mbuf_append(&ab->m, &c, 1); - ab->len = ab->m.len; - } -} - -/* - * Resets any data previously appended to altbuf. - */ -MG_INTERNAL void altbuf_reset(struct altbuf *ab) { - mbuf_free(&ab->m); - ab->len = 0; -} - -/* - * Returns whether the additional buffer was allocated (and thus the data - * is in the mbuf, not the client-provided buffer) - */ -MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) { - return ab->len > ab->user_buf_size; -} - -/* - * Returns the actual buffer with data, either the client-provided or a newly - * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first. - */ -MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) { - if (altbuf_reallocated(ab)) { - if (trim) { - mbuf_trim(&ab->m); - } - return ab->m.buf; - } else { - return ab->user_buf; - } -} - -/* }}} */ - -static const char *mg_version_header = "Mongoose/" MG_VERSION; - -enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT }; - -struct mg_http_proto_data_file { - FILE *fp; /* Opened file. */ - int64_t cl; /* Content-Length. How many bytes to send. */ - int64_t sent; /* How many bytes have been already sent. */ - int keepalive; /* Keep connection open after sending. */ - enum mg_http_proto_data_type type; -}; - -#if MG_ENABLE_HTTP_CGI -struct mg_http_proto_data_cgi { - struct mg_connection *cgi_nc; -}; -#endif - -struct mg_http_proto_data_chuncked { - int64_t body_len; /* How many bytes of chunked body was reassembled. */ -}; - -struct mg_http_endpoint { - struct mg_http_endpoint *next; - struct mg_str uri_pattern; /* owned */ - char *auth_domain; /* owned */ - char *auth_file; /* owned */ - - mg_event_handler_t handler; -#if MG_ENABLE_CALLBACK_USERDATA - void *user_data; -#endif -}; - -enum mg_http_multipart_stream_state { - MPS_BEGIN, - MPS_WAITING_FOR_BOUNDARY, - MPS_WAITING_FOR_CHUNK, - MPS_GOT_CHUNK, - MPS_GOT_BOUNDARY, - MPS_FINALIZE, - MPS_FINISHED -}; - -struct mg_http_multipart_stream { - const char *boundary; - int boundary_len; - const char *var_name; - const char *file_name; - void *user_data; - int prev_io_len; - enum mg_http_multipart_stream_state state; - int processing_part; -}; - -struct mg_reverse_proxy_data { - struct mg_connection *linked_conn; -}; - -struct mg_ws_proto_data { - /* - * Defragmented size of the frame so far. - * - * First byte of nc->recv_mbuf.buf is an op, the rest of the data is - * defragmented data. - */ - size_t reass_len; -}; - -struct mg_http_proto_data { -#if MG_ENABLE_FILESYSTEM - struct mg_http_proto_data_file file; -#endif -#if MG_ENABLE_HTTP_CGI - struct mg_http_proto_data_cgi cgi; -#endif -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - struct mg_http_multipart_stream mp_stream; -#endif -#if MG_ENABLE_HTTP_WEBSOCKET - struct mg_ws_proto_data ws_data; -#endif - struct mg_http_proto_data_chuncked chunk; - struct mg_http_endpoint *endpoints; - mg_event_handler_t endpoint_handler; - struct mg_reverse_proxy_data reverse_proxy_data; - size_t rcvd; /* How many bytes we have received. */ -}; - -static void mg_http_conn_destructor(void *proto_data); -struct mg_connection *mg_connect_http_base( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *scheme1, const char *scheme2, - const char *scheme_ssl1, const char *scheme_ssl2, const char *url, - struct mg_str *path, struct mg_str *user_info, struct mg_str *host); - -static struct mg_http_proto_data *mg_http_get_proto_data( - struct mg_connection *c) { - if (c->proto_data == NULL) { - c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data)); - c->proto_data_destructor = mg_http_conn_destructor; - } - - return (struct mg_http_proto_data *) c->proto_data; -} - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -static void mg_http_free_proto_data_mp_stream( - struct mg_http_multipart_stream *mp) { - MG_FREE((void *) mp->boundary); - MG_FREE((void *) mp->var_name); - MG_FREE((void *) mp->file_name); - memset(mp, 0, sizeof(*mp)); -} -#endif - -#if MG_ENABLE_FILESYSTEM -static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) { - if (d != NULL) { - if (d->fp != NULL) { - fclose(d->fp); - } - memset(d, 0, sizeof(struct mg_http_proto_data_file)); - } -} -#endif - -static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) { - struct mg_http_endpoint *current = *ep; - - while (current != NULL) { - struct mg_http_endpoint *tmp = current->next; - MG_FREE((void *) current->uri_pattern.p); - MG_FREE((void *) current->auth_domain); - MG_FREE((void *) current->auth_file); - MG_FREE(current); - current = tmp; - } - - ep = NULL; -} - -static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) { - if (rpd->linked_conn != NULL) { - /* - * Connection has linked one, we have to unlink & close it - * since _this_ connection is going to die and - * it doesn't make sense to keep another one - */ - struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn); - if (pd->reverse_proxy_data.linked_conn != NULL) { - pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; - pd->reverse_proxy_data.linked_conn = NULL; - } - rpd->linked_conn = NULL; - } -} - -static void mg_http_conn_destructor(void *proto_data) { - struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data; -#if MG_ENABLE_FILESYSTEM - mg_http_free_proto_data_file(&pd->file); -#endif -#if MG_ENABLE_HTTP_CGI - mg_http_free_proto_data_cgi(&pd->cgi); -#endif -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - mg_http_free_proto_data_mp_stream(&pd->mp_stream); -#endif - mg_http_free_proto_data_endpoints(&pd->endpoints); - mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data); - MG_FREE(proto_data); -} - -#if MG_ENABLE_FILESYSTEM - -#define MIME_ENTRY(_ext, _type) \ - { _ext, sizeof(_ext) - 1, _type } -static const struct { - const char *extension; - size_t ext_len; - const char *mime_type; -} mg_static_builtin_mime_types[] = { - MIME_ENTRY("html", "text/html"), - MIME_ENTRY("html", "text/html"), - MIME_ENTRY("htm", "text/html"), - MIME_ENTRY("shtm", "text/html"), - MIME_ENTRY("shtml", "text/html"), - MIME_ENTRY("css", "text/css"), - MIME_ENTRY("js", "application/x-javascript"), - MIME_ENTRY("ico", "image/x-icon"), - MIME_ENTRY("gif", "image/gif"), - MIME_ENTRY("jpg", "image/jpeg"), - MIME_ENTRY("jpeg", "image/jpeg"), - MIME_ENTRY("png", "image/png"), - MIME_ENTRY("svg", "image/svg+xml"), - MIME_ENTRY("txt", "text/plain"), - MIME_ENTRY("torrent", "application/x-bittorrent"), - MIME_ENTRY("wav", "audio/x-wav"), - MIME_ENTRY("mp3", "audio/x-mp3"), - MIME_ENTRY("mid", "audio/mid"), - MIME_ENTRY("m3u", "audio/x-mpegurl"), - MIME_ENTRY("ogg", "application/ogg"), - MIME_ENTRY("ram", "audio/x-pn-realaudio"), - MIME_ENTRY("xml", "text/xml"), - MIME_ENTRY("ttf", "application/x-font-ttf"), - MIME_ENTRY("json", "application/json"), - MIME_ENTRY("xslt", "application/xml"), - MIME_ENTRY("xsl", "application/xml"), - MIME_ENTRY("ra", "audio/x-pn-realaudio"), - MIME_ENTRY("doc", "application/msword"), - MIME_ENTRY("exe", "application/octet-stream"), - MIME_ENTRY("zip", "application/x-zip-compressed"), - MIME_ENTRY("xls", "application/excel"), - MIME_ENTRY("tgz", "application/x-tar-gz"), - MIME_ENTRY("tar", "application/x-tar"), - MIME_ENTRY("gz", "application/x-gunzip"), - MIME_ENTRY("arj", "application/x-arj-compressed"), - MIME_ENTRY("rar", "application/x-rar-compressed"), - MIME_ENTRY("rtf", "application/rtf"), - MIME_ENTRY("pdf", "application/pdf"), - MIME_ENTRY("swf", "application/x-shockwave-flash"), - MIME_ENTRY("mpg", "video/mpeg"), - MIME_ENTRY("webm", "video/webm"), - MIME_ENTRY("mpeg", "video/mpeg"), - MIME_ENTRY("mov", "video/quicktime"), - MIME_ENTRY("mp4", "video/mp4"), - MIME_ENTRY("m4v", "video/x-m4v"), - MIME_ENTRY("asf", "video/x-ms-asf"), - MIME_ENTRY("avi", "video/x-msvideo"), - MIME_ENTRY("bmp", "image/bmp"), - {NULL, 0, NULL}}; - -static struct mg_str mg_get_mime_type(const char *path, const char *dflt, - const struct mg_serve_http_opts *opts) { - const char *ext, *overrides; - size_t i, path_len; - struct mg_str r, k, v; - - path_len = strlen(path); - - overrides = opts->custom_mime_types; - while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) { - ext = path + (path_len - k.len); - if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) { - return v; - } - } - - for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) { - ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len); - if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' && - mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) { - r.p = mg_static_builtin_mime_types[i].mime_type; - r.len = strlen(r.p); - return r; - } - } - - r.p = dflt; - r.len = strlen(r.p); - return r; -} -#endif - -/* - * Check whether full request is buffered. Return: - * -1 if request is malformed - * 0 if request is not yet fully buffered - * >0 actual request length, including last \r\n\r\n - */ -static int mg_http_get_request_len(const char *s, int buf_len) { - const unsigned char *buf = (unsigned char *) s; - int i; - - for (i = 0; i < buf_len; i++) { - if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { - return -1; - } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { - return i + 2; - } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && - buf[i + 2] == '\n') { - return i + 3; - } - } - - return 0; -} - -static const char *mg_http_parse_headers(const char *s, const char *end, - int len, struct http_message *req) { - int i = 0; - while (i < (int) ARRAY_SIZE(req->header_names) - 1) { - struct mg_str *k = &req->header_names[i], *v = &req->header_values[i]; - - s = mg_skip(s, end, ": ", k); - s = mg_skip(s, end, "\r\n", v); - - while (v->len > 0 && v->p[v->len - 1] == ' ') { - v->len--; /* Trim trailing spaces in header value */ - } - - /* - * If header value is empty - skip it and go to next (if any). - * NOTE: Do not add it to headers_values because such addition changes API - * behaviour - */ - if (k->len != 0 && v->len == 0) { - continue; - } - - if (k->len == 0 || v->len == 0) { - k->p = v->p = NULL; - k->len = v->len = 0; - break; - } - - if (!mg_ncasecmp(k->p, "Content-Length", 14)) { - req->body.len = (size_t) to64(v->p); - req->message.len = len + req->body.len; - } - - i++; - } - - return s; -} - -int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) { - const char *end, *qs; - int len = mg_http_get_request_len(s, n); - - if (len <= 0) return len; - - memset(hm, 0, sizeof(*hm)); - hm->message.p = s; - hm->body.p = s + len; - hm->message.len = hm->body.len = (size_t) ~0; - end = s + len; - - /* Request is fully buffered. Skip leading whitespaces. */ - while (s < end && isspace(*(unsigned char *) s)) s++; - - if (is_req) { - /* Parse request line: method, URI, proto */ - s = mg_skip(s, end, " ", &hm->method); - s = mg_skip(s, end, " ", &hm->uri); - s = mg_skip(s, end, "\r\n", &hm->proto); - if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1; - - /* If URI contains '?' character, initialize query_string */ - if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) { - hm->query_string.p = qs + 1; - hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1); - hm->uri.len = qs - hm->uri.p; - } - } else { - s = mg_skip(s, end, " ", &hm->proto); - if (end - s < 4 || s[3] != ' ') return -1; - hm->resp_code = atoi(s); - if (hm->resp_code < 100 || hm->resp_code >= 600) return -1; - s += 4; - s = mg_skip(s, end, "\r\n", &hm->resp_status_msg); - } - - s = mg_http_parse_headers(s, end, len, hm); - - /* - * mg_parse_http() is used to parse both HTTP requests and HTTP - * responses. If HTTP response does not have Content-Length set, then - * body is read until socket is closed, i.e. body.len is infinite (~0). - * - * For HTTP requests though, according to - * http://tools.ietf.org/html/rfc7231#section-8.1.3, - * only POST and PUT methods have defined body semantics. - * Therefore, if Content-Length is not specified and methods are - * not one of PUT or POST, set body length to 0. - * - * So, - * if it is HTTP request, and Content-Length is not set, - * and method is not (PUT or POST) then reset body length to zero. - */ - if (hm->body.len == (size_t) ~0 && is_req && - mg_vcasecmp(&hm->method, "PUT") != 0 && - mg_vcasecmp(&hm->method, "POST") != 0) { - hm->body.len = 0; - hm->message.len = len; - } - - return len; -} - -struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) { - size_t i, len = strlen(name); - - for (i = 0; hm->header_names[i].len > 0; i++) { - struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i]; - if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len)) - return v; - } - - return NULL; -} - -#if MG_ENABLE_FILESYSTEM -static void mg_http_transfer_file_data(struct mg_connection *nc) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - char buf[MG_MAX_HTTP_SEND_MBUF]; - size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent); - - if (pd->file.type == DATA_FILE) { - struct mbuf *io = &nc->send_mbuf; - if (io->len >= MG_MAX_HTTP_SEND_MBUF) { - to_read = 0; - } else { - to_read = MG_MAX_HTTP_SEND_MBUF - io->len; - } - if (to_read > left) { - to_read = left; - } - if (to_read > 0) { - n = mg_fread(buf, 1, to_read, pd->file.fp); - if (n > 0) { - mg_send(nc, buf, n); - pd->file.sent += n; - DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent)); - } - } else { - /* Rate-limited */ - } - if (pd->file.sent >= pd->file.cl) { - LOG(LL_DEBUG, ("%p done, %d bytes", nc, (int) pd->file.sent)); - if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; - mg_http_free_proto_data_file(&pd->file); - } - } else if (pd->file.type == DATA_PUT) { - struct mbuf *io = &nc->recv_mbuf; - size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len; - size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp); - if (n > 0) { - mbuf_remove(io, n); - pd->file.sent += n; - } - if (n == 0 || pd->file.sent >= pd->file.cl) { - if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE; - mg_http_free_proto_data_file(&pd->file); - } - } -#if MG_ENABLE_HTTP_CGI - else if (pd->cgi.cgi_nc != NULL) { - /* This is POST data that needs to be forwarded to the CGI process */ - if (pd->cgi.cgi_nc != NULL) { - mg_forward(nc, pd->cgi.cgi_nc); - } else { - nc->flags |= MG_F_SEND_AND_CLOSE; - } - } -#endif -} -#endif /* MG_ENABLE_FILESYSTEM */ - -/* - * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or - * if it's incomplete. If the chunk is fully buffered, return total number of - * bytes in a chunk, and store data in `data`, `data_len`. - */ -static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, - size_t *chunk_len) { - unsigned char *s = (unsigned char *) buf; - size_t n = 0; /* scanned chunk length */ - size_t i = 0; /* index in s */ - - /* Scan chunk length. That should be a hexadecimal number. */ - while (i < len && isxdigit(s[i])) { - n *= 16; - n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10; - i++; - } - - /* Skip new line */ - if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { - return 0; - } - i += 2; - - /* Record where the data is */ - *chunk_data = (char *) s + i; - *chunk_len = n; - - /* Skip data */ - i += n; - - /* Skip new line */ - if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') { - return 0; - } - return i + 2; -} - -MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, - struct http_message *hm, char *buf, - size_t blen) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - char *data; - size_t i, n, data_len, body_len, zero_chunk_received = 0; - /* Find out piece of received data that is not yet reassembled */ - body_len = (size_t) pd->chunk.body_len; - assert(blen >= body_len); - - /* Traverse all fully buffered chunks */ - for (i = body_len; - (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0; - i += n) { - /* Collapse chunk data to the rest of HTTP body */ - memmove(buf + body_len, data, data_len); - body_len += data_len; - hm->body.len = body_len; - - if (data_len == 0) { - zero_chunk_received = 1; - i += n; - break; - } - } - - if (i > body_len) { - /* Shift unparsed content to the parsed body */ - assert(i <= blen); - memmove(buf + body_len, buf + i, blen - i); - memset(buf + body_len + blen - i, 0, i - body_len); - nc->recv_mbuf.len -= i - body_len; - pd->chunk.body_len = body_len; - - /* Send MG_EV_HTTP_CHUNK event */ - nc->flags &= ~MG_F_DELETE_CHUNK; - mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm); - - /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ - if (nc->flags & MG_F_DELETE_CHUNK) { - memset(buf, 0, body_len); - memmove(buf, buf + body_len, blen - i); - nc->recv_mbuf.len -= body_len; - hm->body.len = 0; - pd->chunk.body_len = 0; - } - - if (zero_chunk_received) { - /* Total message size is len(body) + len(headers) */ - hm->message.len = - (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p); - } - } - - return body_len; -} - -struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc, - struct mg_str *uri_path) { - struct mg_http_proto_data *pd; - struct mg_http_endpoint *ret = NULL; - int matched, matched_max = 0; - struct mg_http_endpoint *ep; - - if (nc == NULL) { - return NULL; - } - - pd = mg_http_get_proto_data(nc); - - ep = pd->endpoints; - while (ep != NULL) { - if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) { - if (matched > matched_max) { - /* Looking for the longest suitable handler */ - ret = ep; - matched_max = matched; - } - } - - ep = ep->next; - } - - return ret; -} - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -static void mg_http_multipart_continue(struct mg_connection *nc); - -static void mg_http_multipart_begin(struct mg_connection *nc, - struct http_message *hm, int req_len); - -#endif - -static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, - struct http_message *hm); - -static void deliver_chunk(struct mg_connection *c, struct http_message *hm, - int req_len) { - /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */ - hm->body.len = c->recv_mbuf.len - req_len; - c->flags &= ~MG_F_DELETE_CHUNK; - mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm); - /* Delete processed data if user set MG_F_DELETE_CHUNK flag */ - if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len; -} - -/* - * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here) - * If a big structure is declared in a big function, lx106 gcc will make it - * even bigger (round up to 4k, from 700 bytes of actual size). - */ -#ifdef __xtensa__ -static void mg_http_handler2(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data), - struct http_message *hm) __attribute__((noinline)); - -void mg_http_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct http_message hm; - mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm); -} - -static void mg_http_handler2(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data), - struct http_message *hm) { -#else /* !__XTENSA__ */ -void mg_http_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct http_message shm, *hm = &shm; -#endif /* __XTENSA__ */ - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - struct mbuf *io = &nc->recv_mbuf; - int req_len; - const int is_req = (nc->listener != NULL); -#if MG_ENABLE_HTTP_WEBSOCKET - struct mg_str *vec; -#endif - if (ev == MG_EV_CLOSE) { -#if MG_ENABLE_HTTP_CGI - /* Close associated CGI forwarder connection */ - if (pd->cgi.cgi_nc != NULL) { - pd->cgi.cgi_nc->user_data = NULL; - pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -#endif -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - if (pd->mp_stream.boundary != NULL) { - /* - * Multipart message is in progress, but connection is closed. - * Finish part and request with an error flag. - */ - struct mg_http_multipart_part mp; - memset(&mp, 0, sizeof(mp)); - mp.status = -1; - mp.var_name = pd->mp_stream.var_name; - mp.file_name = pd->mp_stream.file_name; - mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), - nc->user_data, MG_EV_HTTP_PART_END, &mp); - mp.var_name = NULL; - mp.file_name = NULL; - mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler), - nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp); - } else -#endif - if (io->len > 0 && - (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) { - /* - * For HTTP messages without Content-Length, always send HTTP message - * before MG_EV_CLOSE message. - */ - int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; - hm->message.len = io->len; - hm->body.len = io->buf + io->len - hm->body.p; - deliver_chunk(nc, hm, req_len); - mg_http_call_endpoint_handler(nc, ev2, hm); - } - pd->rcvd = 0; - } - -#if MG_ENABLE_FILESYSTEM - if (pd->file.fp != NULL) { - mg_http_transfer_file_data(nc); - } -#endif - - mg_call(nc, nc->handler, nc->user_data, ev, ev_data); - - if (ev == MG_EV_RECV) { - struct mg_str *s; - pd->rcvd += *(int *) ev_data; - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - if (pd->mp_stream.boundary != NULL) { - mg_http_multipart_continue(nc); - return; - } -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ - - req_len = mg_parse_http(io->buf, io->len, hm, is_req); - - if (req_len > 0 && - (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL && - mg_vcasecmp(s, "chunked") == 0) { - mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len); - } - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL && - s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) { - mg_http_multipart_begin(nc, hm, req_len); - mg_http_multipart_continue(nc); - return; - } -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ - - /* TODO(alashkin): refactor this ifelseifelseifelseifelse */ - if ((req_len < 0 || - (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) { - DBG(("invalid request")); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } else if (req_len == 0) { - /* Do nothing, request is not yet fully buffered */ - } -#if MG_ENABLE_HTTP_WEBSOCKET - else if (nc->listener == NULL && - mg_get_http_header(hm, "Sec-WebSocket-Accept")) { - /* We're websocket client, got handshake response from server. */ - /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */ - mbuf_remove(io, req_len); - nc->proto_handler = mg_ws_handler; - nc->flags |= MG_F_IS_WEBSOCKET; - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, - NULL); - mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); - } else if (nc->listener != NULL && - (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) { - struct mg_http_endpoint *ep; - - /* This is a websocket request. Switch protocol handlers. */ - mbuf_remove(io, req_len); - nc->proto_handler = mg_ws_handler; - nc->flags |= MG_F_IS_WEBSOCKET; - - /* - * If we have a handler set up with mg_register_http_endpoint(), - * deliver subsequent websocket events to this handler after the - * protocol switch. - */ - ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); - if (ep != NULL) { - nc->handler = ep->handler; -#if MG_ENABLE_CALLBACK_USERDATA - nc->user_data = ep->user_data; -#endif - } - - /* Send handshake */ - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, - hm); - if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) { - if (nc->send_mbuf.len == 0) { - mg_ws_handshake(nc, vec, hm); - } - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE, - NULL); - mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data)); - } - } -#endif /* MG_ENABLE_HTTP_WEBSOCKET */ - else if (hm->message.len > pd->rcvd) { - /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */ - deliver_chunk(nc, hm, req_len); - if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) { - LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " - "%lu bytes, and not drained, closing", - nc, (unsigned long) nc->recv_mbuf.len, - (unsigned long) nc->recv_mbuf_limit)); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - } else { - /* We did receive all HTTP body. */ - int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY; - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), - MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); - DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p, - (int) hm->uri.len, hm->uri.p)); - deliver_chunk(nc, hm, req_len); - /* Whole HTTP message is fully buffered, call event handler */ - mg_http_call_endpoint_handler(nc, trigger_ev, hm); - mbuf_remove(io, hm->message.len); - pd->rcvd = 0; - } - } -} - -static size_t mg_get_line_len(const char *buf, size_t buf_len) { - size_t len = 0; - while (len < buf_len && buf[len] != '\n') len++; - return len == buf_len ? 0 : len + 1; -} - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -static void mg_http_multipart_begin(struct mg_connection *nc, - struct http_message *hm, int req_len) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - struct mg_str *ct; - struct mbuf *io = &nc->recv_mbuf; - - char boundary_buf[100]; - char *boundary = boundary_buf; - int boundary_len; - - ct = mg_get_http_header(hm, "Content-Type"); - if (ct == NULL) { - /* We need more data - or it isn't multipart mesage */ - goto exit_mp; - } - - /* Content-type should start with "multipart" */ - if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) { - goto exit_mp; - } - - boundary_len = - mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf)); - if (boundary_len == 0) { - /* - * Content type is multipart, but there is no boundary, - * probably malformed request - */ - nc->flags = MG_F_CLOSE_IMMEDIATELY; - DBG(("invalid request")); - goto exit_mp; - } - - /* If we reach this place - that is multipart request */ - - if (pd->mp_stream.boundary != NULL) { - /* - * Another streaming request was in progress, - * looks like protocol error - */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } else { - struct mg_http_endpoint *ep = NULL; - pd->mp_stream.state = MPS_BEGIN; - pd->mp_stream.boundary = strdup(boundary); - pd->mp_stream.boundary_len = strlen(boundary); - pd->mp_stream.var_name = pd->mp_stream.file_name = NULL; - pd->endpoint_handler = nc->handler; - - ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri); - if (ep != NULL) { - pd->endpoint_handler = ep->handler; - } - - mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm); - - mbuf_remove(io, req_len); - } -exit_mp: - if (boundary != boundary_buf) MG_FREE(boundary); -} - -#define CONTENT_DISPOSITION "Content-Disposition: " - -static void mg_http_multipart_call_handler(struct mg_connection *c, int ev, - const char *data, size_t data_len) { - struct mg_http_multipart_part mp; - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - memset(&mp, 0, sizeof(mp)); - - mp.var_name = pd->mp_stream.var_name; - mp.file_name = pd->mp_stream.file_name; - mp.user_data = pd->mp_stream.user_data; - mp.data.p = data; - mp.data.len = data_len; - mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp); - pd->mp_stream.user_data = mp.user_data; -} - -static int mg_http_multipart_got_chunk(struct mg_connection *c) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - struct mbuf *io = &c->recv_mbuf; - - mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, - pd->mp_stream.prev_io_len); - mbuf_remove(io, pd->mp_stream.prev_io_len); - pd->mp_stream.prev_io_len = 0; - pd->mp_stream.state = MPS_WAITING_FOR_CHUNK; - - return 0; -} - -static int mg_http_multipart_finalize(struct mg_connection *c) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - - mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); - MG_FREE((void *) pd->mp_stream.file_name); - pd->mp_stream.file_name = NULL; - MG_FREE((void *) pd->mp_stream.var_name); - pd->mp_stream.var_name = NULL; - mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0); - mg_http_free_proto_data_mp_stream(&pd->mp_stream); - pd->mp_stream.state = MPS_FINISHED; - - return 1; -} - -static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) { - const char *boundary; - struct mbuf *io = &c->recv_mbuf; - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - - if (pd->mp_stream.boundary == NULL) { - pd->mp_stream.state = MPS_FINALIZE; - DBG(("Invalid request: boundary not initialized")); - return 0; - } - - if ((int) io->len < pd->mp_stream.boundary_len + 2) { - return 0; - } - - boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); - if (boundary != NULL) { - const char *boundary_end = (boundary + pd->mp_stream.boundary_len); - if (io->len - (boundary_end - io->buf) < 4) { - return 0; - } - if (strncmp(boundary_end, "--\r\n", 4) == 0) { - pd->mp_stream.state = MPS_FINALIZE; - mbuf_remove(io, (boundary_end - io->buf) + 4); - } else { - pd->mp_stream.state = MPS_GOT_BOUNDARY; - } - } else { - return 0; - } - - return 1; -} - -static void mg_http_parse_header_internal(struct mg_str *hdr, - const char *var_name, - struct altbuf *ab); - -static int mg_http_multipart_process_boundary(struct mg_connection *c) { - int data_size; - const char *boundary, *block_begin; - struct mbuf *io = &c->recv_mbuf; - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - struct altbuf ab_file_name, ab_var_name; - int line_len; - boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); - block_begin = boundary + pd->mp_stream.boundary_len + 2; - data_size = io->len - (block_begin - io->buf); - - altbuf_init(&ab_file_name, NULL, 0); - altbuf_init(&ab_var_name, NULL, 0); - - while (data_size > 0 && - (line_len = mg_get_line_len(block_begin, data_size)) != 0) { - if (line_len > (int) sizeof(CONTENT_DISPOSITION) && - mg_ncasecmp(block_begin, CONTENT_DISPOSITION, - sizeof(CONTENT_DISPOSITION) - 1) == 0) { - struct mg_str header; - - header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1; - header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1; - - altbuf_reset(&ab_var_name); - mg_http_parse_header_internal(&header, "name", &ab_var_name); - - altbuf_reset(&ab_file_name); - mg_http_parse_header_internal(&header, "filename", &ab_file_name); - - block_begin += line_len; - data_size -= line_len; - - continue; - } - - if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) { - mbuf_remove(io, block_begin - io->buf + 2); - - if (pd->mp_stream.processing_part != 0) { - mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0); - } - - /* Reserve 2 bytes for "\r\n" in file_name and var_name */ - altbuf_append(&ab_file_name, '\0'); - altbuf_append(&ab_file_name, '\0'); - altbuf_append(&ab_var_name, '\0'); - altbuf_append(&ab_var_name, '\0'); - - MG_FREE((void *) pd->mp_stream.file_name); - pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */); - MG_FREE((void *) pd->mp_stream.var_name); - pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */); - - mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0); - pd->mp_stream.state = MPS_WAITING_FOR_CHUNK; - pd->mp_stream.processing_part++; - return 1; - } - - block_begin += line_len; - } - - pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; - - altbuf_reset(&ab_var_name); - altbuf_reset(&ab_file_name); - - return 0; -} - -static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - struct mbuf *io = &c->recv_mbuf; - - const char *boundary; - if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) { - return 0; - } - - boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len); - if (boundary == NULL && pd->mp_stream.prev_io_len == 0) { - pd->mp_stream.prev_io_len = io->len; - return 0; - } else if (boundary == NULL && - (int) io->len > - pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) { - pd->mp_stream.state = MPS_GOT_CHUNK; - return 1; - } else if (boundary != NULL) { - int data_size = (boundary - io->buf - 4); - mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size); - mbuf_remove(io, (boundary - io->buf)); - pd->mp_stream.prev_io_len = 0; - pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; - return 1; - } else { - return 0; - } -} - -static void mg_http_multipart_continue(struct mg_connection *c) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(c); - while (1) { - switch (pd->mp_stream.state) { - case MPS_BEGIN: { - pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY; - break; - } - case MPS_WAITING_FOR_BOUNDARY: { - if (mg_http_multipart_wait_for_boundary(c) == 0) { - return; - } - break; - } - case MPS_GOT_BOUNDARY: { - if (mg_http_multipart_process_boundary(c) == 0) { - return; - } - break; - } - case MPS_WAITING_FOR_CHUNK: { - if (mg_http_multipart_continue_wait_for_chunk(c) == 0) { - return; - } - break; - } - case MPS_GOT_CHUNK: { - if (mg_http_multipart_got_chunk(c) == 0) { - return; - } - break; - } - case MPS_FINALIZE: { - if (mg_http_multipart_finalize(c) == 0) { - return; - } - break; - } - case MPS_FINISHED: { - mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); - return; - } - } - } -} - -struct file_upload_state { - char *lfn; - size_t num_recd; - FILE *fp; -}; - -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ - -void mg_set_protocol_http_websocket(struct mg_connection *nc) { - nc->proto_handler = mg_http_handler; -} - -const char *mg_status_message(int status_code) { - switch (status_code) { - case 206: - return "Partial Content"; - case 301: - return "Moved"; - case 302: - return "Found"; - case 400: - return "Bad Request"; - case 401: - return "Unauthorized"; - case 403: - return "Forbidden"; - case 404: - return "Not Found"; - case 416: - return "Requested Range Not Satisfiable"; - case 418: - return "I'm a teapot"; - case 500: - return "Internal Server Error"; - case 502: - return "Bad Gateway"; - case 503: - return "Service Unavailable"; - -#if MG_ENABLE_EXTRA_ERRORS_DESC - case 100: - return "Continue"; - case 101: - return "Switching Protocols"; - case 102: - return "Processing"; - case 200: - return "OK"; - case 201: - return "Created"; - case 202: - return "Accepted"; - case 203: - return "Non-Authoritative Information"; - case 204: - return "No Content"; - case 205: - return "Reset Content"; - case 207: - return "Multi-Status"; - case 208: - return "Already Reported"; - case 226: - return "IM Used"; - case 300: - return "Multiple Choices"; - case 303: - return "See Other"; - case 304: - return "Not Modified"; - case 305: - return "Use Proxy"; - case 306: - return "Switch Proxy"; - case 307: - return "Temporary Redirect"; - case 308: - return "Permanent Redirect"; - case 402: - return "Payment Required"; - case 405: - return "Method Not Allowed"; - case 406: - return "Not Acceptable"; - case 407: - return "Proxy Authentication Required"; - case 408: - return "Request Timeout"; - case 409: - return "Conflict"; - case 410: - return "Gone"; - case 411: - return "Length Required"; - case 412: - return "Precondition Failed"; - case 413: - return "Payload Too Large"; - case 414: - return "URI Too Long"; - case 415: - return "Unsupported Media Type"; - case 417: - return "Expectation Failed"; - case 422: - return "Unprocessable Entity"; - case 423: - return "Locked"; - case 424: - return "Failed Dependency"; - case 426: - return "Upgrade Required"; - case 428: - return "Precondition Required"; - case 429: - return "Too Many Requests"; - case 431: - return "Request Header Fields Too Large"; - case 451: - return "Unavailable For Legal Reasons"; - case 501: - return "Not Implemented"; - case 504: - return "Gateway Timeout"; - case 505: - return "HTTP Version Not Supported"; - case 506: - return "Variant Also Negotiates"; - case 507: - return "Insufficient Storage"; - case 508: - return "Loop Detected"; - case 510: - return "Not Extended"; - case 511: - return "Network Authentication Required"; -#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */ - - default: - return "OK"; - } -} - -void mg_send_response_line_s(struct mg_connection *nc, int status_code, - const struct mg_str extra_headers) { - mg_printf(nc, "HTTP/1.1 %d %s\r\nServer: %s\r\n", status_code, - mg_status_message(status_code), mg_version_header); - if (extra_headers.len > 0) { - mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p); - } -} - -void mg_send_response_line(struct mg_connection *nc, int status_code, - const char *extra_headers) { - mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers)); -} - -void mg_http_send_redirect(struct mg_connection *nc, int status_code, - const struct mg_str location, - const struct mg_str extra_headers) { - char bbody[100], *pbody = bbody; - int bl = mg_asprintf(&pbody, sizeof(bbody), - "

Moved here.\r\n", - (int) location.len, location.p); - char bhead[150], *phead = bhead; - mg_asprintf(&phead, sizeof(bhead), - "Location: %.*s\r\n" - "Content-Type: text/html\r\n" - "Content-Length: %d\r\n" - "Cache-Control: no-cache\r\n" - "%.*s%s", - (int) location.len, location.p, bl, (int) extra_headers.len, - extra_headers.p, (extra_headers.len > 0 ? "\r\n" : "")); - mg_send_response_line(nc, status_code, phead); - if (phead != bhead) MG_FREE(phead); - mg_send(nc, pbody, bl); - if (pbody != bbody) MG_FREE(pbody); -} - -void mg_send_head(struct mg_connection *c, int status_code, - int64_t content_length, const char *extra_headers) { - mg_send_response_line(c, status_code, extra_headers); - if (content_length < 0) { - mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n"); - } else { - mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length); - } - mg_send(c, "\r\n", 2); -} - -void mg_http_send_error(struct mg_connection *nc, int code, - const char *reason) { - if (!reason) reason = mg_status_message(code); - LOG(LL_DEBUG, ("%p %d %s", nc, code, reason)); - mg_send_head(nc, code, strlen(reason), - "Content-Type: text/plain\r\nConnection: close"); - mg_send(nc, reason, strlen(reason)); - nc->flags |= MG_F_SEND_AND_CLOSE; -} - -#if MG_ENABLE_FILESYSTEM -static void mg_http_construct_etag(char *buf, size_t buf_len, - const cs_stat_t *st) { - snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, - (int64_t) st->st_size); -} - -#ifndef WINCE -static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { - strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); -} -#else -/* Look wince_lib.c for WindowsCE implementation */ -static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t); -#endif - -static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, - int64_t *b) { - /* - * There is no snscanf. Headers are not guaranteed to be NUL-terminated, - * so we have this. Ugh. - */ - int result; - char *p = (char *) MG_MALLOC(header->len + 1); - if (p == NULL) return 0; - memcpy(p, header->p, header->len); - p[header->len] = '\0'; - result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); - MG_FREE(p); - return result; -} - -void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm, - const char *path, const struct mg_str mime_type, - const struct mg_str extra_headers) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - cs_stat_t st; - LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p)); - if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) { - int code, err = mg_get_errno(); - switch (err) { - case EACCES: - code = 403; - break; - case ENOENT: - code = 404; - break; - default: - code = 500; - }; - mg_http_send_error(nc, code, "Open failed"); - } else { - char etag[50], current_time[50], last_modified[50], range[70]; - time_t t = (time_t) mg_time(); - int64_t r1 = 0, r2 = 0, cl = st.st_size; - struct mg_str *range_hdr = mg_get_http_header(hm, "Range"); - int n, status_code = 200; - - /* Handle Range header */ - range[0] = '\0'; - if (range_hdr != NULL && - (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 && - r2 >= 0) { - /* If range is specified like "400-", set second limit to content len */ - if (n == 1) { - r2 = cl - 1; - } - if (r1 > r2 || r2 >= cl) { - status_code = 416; - cl = 0; - snprintf(range, sizeof(range), - "Content-Range: bytes */%" INT64_FMT "\r\n", - (int64_t) st.st_size); - } else { - status_code = 206; - cl = r2 - r1 + 1; - snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT - "-%" INT64_FMT "/%" INT64_FMT "\r\n", - r1, r1 + cl - 1, (int64_t) st.st_size); -#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \ - _XOPEN_SOURCE >= 600 - fseeko(pd->file.fp, r1, SEEK_SET); -#else - fseek(pd->file.fp, (long) r1, SEEK_SET); -#endif - } - } - -#if !MG_DISABLE_HTTP_KEEP_ALIVE - { - struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection"); - if (conn_hdr != NULL) { - pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0); - } else { - pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0); - } - } -#endif - - mg_http_construct_etag(etag, sizeof(etag), &st); - mg_gmt_time_string(current_time, sizeof(current_time), &t); - mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime); - /* - * Content length casted to size_t because: - * 1) that's the maximum buffer size anyway - * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last - * position - * TODO(mkm): fix ESP8266 RTOS SDK - */ - mg_send_response_line_s(nc, status_code, extra_headers); - mg_printf(nc, - "Date: %s\r\n" - "Last-Modified: %s\r\n" - "Accept-Ranges: bytes\r\n" - "Content-Type: %.*s\r\n" - "Connection: %s\r\n" - "Content-Length: %" SIZE_T_FMT - "\r\n" - "%sEtag: %s\r\n\r\n", - current_time, last_modified, (int) mime_type.len, mime_type.p, - (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range, - etag); - - pd->file.cl = cl; - pd->file.type = DATA_FILE; - mg_http_transfer_file_data(nc); - } -} - -static void mg_http_serve_file2(struct mg_connection *nc, const char *path, - struct http_message *hm, - struct mg_serve_http_opts *opts) { -#if MG_ENABLE_HTTP_SSI - if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) { - mg_handle_ssi_request(nc, hm, path, opts); - return; - } -#endif - mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts), - mg_mk_str(opts->extra_headers)); -} - -#endif - -int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, - int is_form_url_encoded) { - int i, j, a, b; -#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') - - for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { - if (src[i] == '%') { - if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) && - isxdigit(*(const unsigned char *) (src + i + 2))) { - a = tolower(*(const unsigned char *) (src + i + 1)); - b = tolower(*(const unsigned char *) (src + i + 2)); - dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); - i += 2; - } else { - return -1; - } - } else if (is_form_url_encoded && src[i] == '+') { - dst[j] = ' '; - } else { - dst[j] = src[i]; - } - } - - dst[j] = '\0'; /* Null-terminate the destination */ - - return i >= src_len ? j : -1; -} - -int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, - size_t dst_len) { - const char *p, *e, *s; - size_t name_len; - int len; - - /* - * According to the documentation function returns negative - * value in case of error. For debug purposes it returns: - * -1 - src is wrong (NUUL) - * -2 - dst is wrong (NULL) - * -3 - failed to decode url or dst is to small - * -4 - name does not exist - */ - if (dst == NULL || dst_len == 0) { - len = -2; - } else if (buf->p == NULL || name == NULL || buf->len == 0) { - len = -1; - dst[0] = '\0'; - } else { - name_len = strlen(name); - e = buf->p + buf->len; - len = -4; - dst[0] = '\0'; - - for (p = buf->p; p + name_len < e; p++) { - if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' && - !mg_ncasecmp(name, p, name_len)) { - p += name_len + 1; - s = (const char *) memchr(p, '&', (size_t)(e - p)); - if (s == NULL) { - s = e; - } - len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1); - /* -1 means: failed to decode or dst is too small */ - if (len == -1) { - len = -3; - } - break; - } - } - } - - return len; -} - -void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) { - char chunk_size[50]; - int n; - - n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len); - mg_send(nc, chunk_size, n); - mg_send(nc, buf, len); - mg_send(nc, "\r\n", 2); -} - -void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) { - char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; - int len; - va_list ap; - - va_start(ap, fmt); - len = mg_avprintf(&buf, sizeof(mem), fmt, ap); - va_end(ap); - - if (len >= 0) { - mg_send_http_chunk(nc, buf, len); - } - - /* LCOV_EXCL_START */ - if (buf != mem && buf != NULL) { - MG_FREE(buf); - } - /* LCOV_EXCL_STOP */ -} - -void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) { - char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; - int i, j, len; - va_list ap; - - va_start(ap, fmt); - len = mg_avprintf(&buf, sizeof(mem), fmt, ap); - va_end(ap); - - if (len >= 0) { - for (i = j = 0; i < len; i++) { - if (buf[i] == '<' || buf[i] == '>') { - mg_send(nc, buf + j, i - j); - mg_send(nc, buf[i] == '<' ? "<" : ">", 4); - j = i + 1; - } - } - mg_send(nc, buf + j, i - j); - } - - /* LCOV_EXCL_START */ - if (buf != mem && buf != NULL) { - MG_FREE(buf); - } - /* LCOV_EXCL_STOP */ -} - -static void mg_http_parse_header_internal(struct mg_str *hdr, - const char *var_name, - struct altbuf *ab) { - int ch = ' ', ch1 = ',', n = strlen(var_name); - const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL; - - /* Find where variable starts */ - for (s = hdr->p; s != NULL && s + n < end; s++) { - if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') && - s[n] == '=' && !strncmp(s, var_name, n)) - break; - } - - if (s != NULL && &s[n + 1] < end) { - s += n + 1; - if (*s == '"' || *s == '\'') { - ch = ch1 = *s++; - } - p = s; - while (p < end && p[0] != ch && p[0] != ch1) { - if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++; - altbuf_append(ab, *p++); - } - - if (ch != ' ' && *p != ch) { - altbuf_reset(ab); - } - } - - /* If there is some data, append a NUL. */ - if (ab->len > 0) { - altbuf_append(ab, '\0'); - } -} - -int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, - size_t buf_size) { - struct altbuf ab; - altbuf_init(&ab, *buf, buf_size); - if (hdr == NULL) return 0; - if (*buf != NULL && buf_size > 0) *buf[0] = '\0'; - - mg_http_parse_header_internal(hdr, var_name, &ab); - - /* - * Get a (trimmed) buffer, and return a len without a NUL byte which might - * have been added. - */ - *buf = altbuf_get_buf(&ab, 1 /* trim */); - return ab.len > 0 ? ab.len - 1 : 0; -} - -int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, - size_t buf_size) { - char *buf2 = buf; - - int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size); - - if (buf2 != buf) { - /* Buffer was not enough and was reallocated: free it and just return 0 */ - MG_FREE(buf2); - return 0; - } - - return len; -} - -int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, - char *pass, size_t pass_len) { - struct mg_str *hdr = mg_get_http_header(hm, "Authorization"); - if (hdr == NULL) return -1; - return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len); -} - -int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, - char *pass, size_t pass_len) { - char *buf = NULL; - char fmt[64]; - int res = 0; - - if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1; - - buf = (char *) MG_MALLOC(hdr->len); - cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL); - - /* e.g. "%123[^:]:%321[^\n]" */ - snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]", - user_len - 1, pass_len - 1); - if (sscanf(buf, fmt, user, pass) == 0) { - res = -1; - } - - MG_FREE(buf); - return res; -} - -#if MG_ENABLE_FILESYSTEM -static int mg_is_file_hidden(const char *path, - const struct mg_serve_http_opts *opts, - int exclude_specials) { - const char *p1 = opts->per_directory_auth_file; - const char *p2 = opts->hidden_file_pattern; - - /* Strip directory path from the file name */ - const char *pdir = strrchr(path, DIRSEP); - if (pdir != NULL) { - path = pdir + 1; - } - - return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) || - (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) || - (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0); -} - -#if !MG_DISABLE_HTTP_DIGEST_AUTH - -#ifndef MG_EXT_MD5 -void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest) { - size_t i; - cs_md5_ctx md5_ctx; - cs_md5_init(&md5_ctx); - for (i = 0; i < num_msgs; i++) { - cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]); - } - cs_md5_final(digest, &md5_ctx); -} -#else -extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); -#endif - -void cs_md5(char buf[33], ...) { - unsigned char hash[16]; - const uint8_t *msgs[20], *p; - size_t msg_lens[20]; - size_t num_msgs = 0; - va_list ap; - - va_start(ap, buf); - while ((p = va_arg(ap, const unsigned char *) ) != NULL) { - msgs[num_msgs] = p; - msg_lens[num_msgs] = va_arg(ap, size_t); - num_msgs++; - } - va_end(ap); - - mg_hash_md5_v(num_msgs, msgs, msg_lens, hash); - cs_to_hex(buf, hash, sizeof(hash)); -} - -static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri, - size_t uri_len, const char *ha1, size_t ha1_len, - const char *nonce, size_t nonce_len, const char *nc, - size_t nc_len, const char *cnonce, size_t cnonce_len, - const char *qop, size_t qop_len, char *resp) { - static const char colon[] = ":"; - static const size_t one = 1; - char ha2[33]; - cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL); - cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc, - nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len, - colon, one, ha2, sizeof(ha2) - 1, NULL); -} - -int mg_http_create_digest_auth_header(char *buf, size_t buf_len, - const char *method, const char *uri, - const char *auth_domain, const char *user, - const char *passwd, const char *nonce) { - static const char colon[] = ":", qop[] = "auth"; - static const size_t one = 1; - char ha1[33], resp[33], cnonce[40]; - - snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time()); - cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain, - (size_t) strlen(auth_domain), colon, one, passwd, - (size_t) strlen(passwd), NULL); - mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1, - nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop, - sizeof(qop) - 1, resp); - return snprintf(buf, buf_len, - "Authorization: Digest username=\"%s\"," - "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s," - "nonce=%s,response=%s\r\n", - user, auth_domain, uri, qop, cnonce, nonce, resp); -} - -/* - * Check for authentication timeout. - * Clients send time stamp encoded in nonce. Make sure it is not too old, - * to prevent replay attacks. - * Assumption: nonce is a hexadecimal number of seconds since 1970. - */ -static int mg_check_nonce(const char *nonce) { - unsigned long now = (unsigned long) mg_time(); - unsigned long val = (unsigned long) strtoul(nonce, NULL, 16); - return (now >= val) && (now - val < 60 * 60); -} - -int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, - FILE *fp) { - int ret = 0; - struct mg_str *hdr; - char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200], - qop_buf[20], nc_buf[20], nonce_buf[16]; - - char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf, - *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf; - - /* Parse "Authorization:" header, fail fast on parse error */ - if (hm == NULL || fp == NULL || - (hdr = mg_get_http_header(hm, "Authorization")) == NULL || - mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) == - 0 || - mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 || - mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) == - 0 || - mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 || - mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 || - mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 || - mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 || - mg_check_nonce(nonce) == 0) { - ret = 0; - goto clean; - } - - /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */ - - ret = mg_check_digest_auth( - hm->method, - mg_mk_str_n( - hm->uri.p, - hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)), - mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response), - mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain), - fp); - -clean: - if (username != username_buf) MG_FREE(username); - if (cnonce != cnonce_buf) MG_FREE(cnonce); - if (response != response_buf) MG_FREE(response); - if (uri != uri_buf) MG_FREE(uri); - if (qop != qop_buf) MG_FREE(qop); - if (nc != nc_buf) MG_FREE(nc); - if (nonce != nonce_buf) MG_FREE(nonce); - - return ret; -} - -int mg_check_digest_auth(struct mg_str method, struct mg_str uri, - struct mg_str username, struct mg_str cnonce, - struct mg_str response, struct mg_str qop, - struct mg_str nc, struct mg_str nonce, - struct mg_str auth_domain, FILE *fp) { - char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)]; - char expected_response[33]; - - /* - * Read passwords file line by line. If should have htdigest format, - * i.e. each line should be a colon-separated sequence: - * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD - */ - while (fgets(buf, sizeof(buf), fp) != NULL) { - if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 && - mg_vcmp(&username, f_user) == 0 && - mg_vcmp(&auth_domain, f_domain) == 0) { - /* Username and domain matched, check the password */ - mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1), - nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len, - qop.p, qop.len, expected_response); - LOG(LL_DEBUG, - ("%.*s %s %.*s %s", (int) username.len, username.p, f_domain, - (int) response.len, response.p, expected_response)); - return mg_ncasecmp(response.p, expected_response, response.len) == 0; - } - } - - /* None of the entries in the passwords file matched - return failure */ - return 0; -} - -int mg_http_is_authorized(struct http_message *hm, struct mg_str path, - const char *domain, const char *passwords_file, - int flags) { - char buf[MG_MAX_PATH]; - const char *p; - FILE *fp; - int authorized = 1; - - if (domain != NULL && passwords_file != NULL) { - if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) { - fp = mg_fopen(passwords_file, "r"); - } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) { - snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP, - passwords_file); - fp = mg_fopen(buf, "r"); - } else { - p = strrchr(path.p, DIRSEP); - if (p == NULL) p = path.p; - snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP, - passwords_file); - fp = mg_fopen(buf, "r"); - } - - if (fp != NULL) { - authorized = mg_http_check_digest_auth(hm, domain, fp); - fclose(fp); - } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) { - authorized = 0; - } - } - - LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p, - passwords_file ? passwords_file : "", flags, authorized)); - return authorized; -} -#else -int mg_http_is_authorized(struct http_message *hm, const struct mg_str path, - const char *domain, const char *passwords_file, - int flags) { - (void) hm; - (void) path; - (void) domain; - (void) passwords_file; - (void) flags; - return 1; -} -#endif - -#if MG_ENABLE_DIRECTORY_LISTING -static void mg_escape(const char *src, char *dst, size_t dst_len) { - size_t n = 0; - while (*src != '\0' && n + 5 < dst_len) { - unsigned char ch = *(unsigned char *) src++; - if (ch == '<') { - n += snprintf(dst + n, dst_len - n, "%s", "<"); - } else { - dst[n++] = ch; - } - } - dst[n] = '\0'; -} - -static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, - cs_stat_t *stp) { - char size[64], mod[64], path[MG_MAX_PATH]; - int64_t fsize = stp->st_size; - int is_dir = S_ISDIR(stp->st_mode); - const char *slash = is_dir ? "/" : ""; - struct mg_str href; - - if (is_dir) { - snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); - } else { - /* - * We use (double) cast below because MSVC 6 compiler cannot - * convert unsigned __int64 to double. - */ - if (fsize < 1024) { - snprintf(size, sizeof(size), "%d", (int) fsize); - } else if (fsize < 0x100000) { - snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); - } else if (fsize < 0x40000000) { - snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); - } else { - snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); - } - } - strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime)); - mg_escape(file_name, path, sizeof(path)); - href = mg_url_encode(mg_mk_str(file_name)); - mg_printf_http_chunk(nc, - "%s%s" - "%s%s\n", - href.p, slash, path, slash, mod, is_dir ? -1 : fsize, - size); - free((void *) href.p); -} - -static void mg_scan_directory(struct mg_connection *nc, const char *dir, - const struct mg_serve_http_opts *opts, - void (*func)(struct mg_connection *, const char *, - cs_stat_t *)) { - char path[MG_MAX_PATH]; - cs_stat_t st; - struct dirent *dp; - DIR *dirp; - - LOG(LL_DEBUG, ("%p [%s]", nc, dir)); - if ((dirp = (opendir(dir))) != NULL) { - while ((dp = readdir(dirp)) != NULL) { - /* Do not show current dir and hidden files */ - if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { - continue; - } - snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name); - if (mg_stat(path, &st) == 0) { - func(nc, (const char *) dp->d_name, &st); - } - } - closedir(dirp); - } else { - LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno())); - } -} - -static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, - struct http_message *hm, - struct mg_serve_http_opts *opts) { - static const char *sort_js_code = - ""; - - mg_send_response_line(nc, 200, opts->extra_headers); - mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked", - "Content-Type", "text/html; charset=utf-8"); - - mg_printf_http_chunk( - nc, - "Index of %.*s%s%s" - "\n" - "

Index of %.*s

\n" - "" - "\n" - "\n" - "", - (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2, - (int) hm->uri.len, hm->uri.p); - mg_scan_directory(nc, dir, opts, mg_print_dir_entry); - mg_printf_http_chunk(nc, - "\n" - "
Name" - "Modified" - "Size


\n" - "
%s
\n" - "", - mg_version_header); - mg_send_http_chunk(nc, "", 0); - /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */ - nc->flags |= MG_F_SEND_AND_CLOSE; -} -#endif /* MG_ENABLE_DIRECTORY_LISTING */ - -/* - * Given a directory path, find one of the files specified in the - * comma-separated list of index files `list`. - * First found index file wins. If an index file is found, then gets - * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`. - * If index file is not found, then `path` and `stp` remain unchanged. - */ -MG_INTERNAL void mg_find_index_file(const char *path, const char *list, - char **index_file, cs_stat_t *stp) { - struct mg_str vec; - size_t path_len = strlen(path); - int found = 0; - *index_file = NULL; - - /* Traverse index files list. For each entry, append it to the given */ - /* path and see if the file exists. If it exists, break the loop */ - while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) { - cs_stat_t st; - size_t len = path_len + 1 + vec.len + 1; - *index_file = (char *) MG_REALLOC(*index_file, len); - if (*index_file == NULL) break; - snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p); - - /* Does it exist? Is it a file? */ - if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) { - /* Yes it does, break the loop */ - *stp = st; - found = 1; - break; - } - } - if (!found) { - MG_FREE(*index_file); - *index_file = NULL; - } - LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : ""))); -} - -#if MG_ENABLE_HTTP_URL_REWRITES -static int mg_http_send_port_based_redirect( - struct mg_connection *c, struct http_message *hm, - const struct mg_serve_http_opts *opts) { - const char *rewrites = opts->url_rewrites; - struct mg_str a, b; - char local_port[20] = {'%'}; - - mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1, - MG_SOCK_STRINGIFY_PORT); - - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (mg_vcmp(&a, local_port) == 0) { - mg_send_response_line(c, 301, NULL); - mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n", - (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1), - hm->uri.p); - return 1; - } - } - - return 0; -} - -static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct http_message *hm = (struct http_message *) ev_data; - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - - if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) { - DBG(("%p: upstream closed", nc)); - return; - } - - switch (ev) { - case MG_EV_CONNECT: - if (*(int *) ev_data != 0) { - mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL); - } - break; - /* TODO(mkm): handle streaming */ - case MG_EV_HTTP_REPLY: - mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p, - hm->message.len); - pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE; - break; - } - -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -void mg_http_reverse_proxy(struct mg_connection *nc, - const struct http_message *hm, struct mg_str mount, - struct mg_str upstream) { - struct mg_connection *be; - char burl[256], *purl = burl; - int i; - const char *error; - struct mg_connect_opts opts; - struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR; - memset(&opts, 0, sizeof(opts)); - opts.error_string = &error; - - mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p, - (int) (hm->uri.len - mount.len), hm->uri.p + mount.len); - - be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL), - opts, "http", NULL, "https", NULL, purl, &path, - &user_info, &host); - LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len, - hm->uri.p, purl, (int) mount.len, mount.p)); - - if (be == NULL) { - LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error)); - mg_http_send_error(nc, 502, NULL); - goto cleanup; - } - - /* link connections to each other, they must live and die together */ - mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc; - mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be; - - /* send request upstream */ - mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p, - (int) path.len, path.p); - - mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p); - for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) { - struct mg_str hn = hm->header_names[i]; - struct mg_str hv = hm->header_values[i]; - - /* we rewrite the host header */ - if (mg_vcasecmp(&hn, "Host") == 0) continue; - /* - * Don't pass chunked transfer encoding to the client because hm->body is - * already dechunked when we arrive here. - */ - if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 && - mg_vcasecmp(&hv, "chunked") == 0) { - mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len); - continue; - } - /* We don't support proxying Expect: 100-continue. */ - if (mg_vcasecmp(&hn, "Expect") == 0 && - mg_vcasecmp(&hv, "100-continue") == 0) { - continue; - } - - mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p); - } - - mg_send(be, "\r\n", 2); - mg_send(be, hm->body.p, hm->body.len); - -cleanup: - if (purl != burl) MG_FREE(purl); -} - -static int mg_http_handle_forwarding(struct mg_connection *nc, - struct http_message *hm, - const struct mg_serve_http_opts *opts) { - const char *rewrites = opts->url_rewrites; - struct mg_str a, b; - struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://"); - - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (mg_strncmp(a, hm->uri, a.len) == 0) { - if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) { - mg_http_reverse_proxy(nc, hm, a, b); - return 1; - } - } - } - - return 0; -} -#endif /* MG_ENABLE_FILESYSTEM */ - -MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, - const struct mg_serve_http_opts *opts, - char **local_path, - struct mg_str *remainder) { - int ok = 1; - const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len; - struct mg_str root = {NULL, 0}; - const char *file_uri_start = cp; - *local_path = NULL; - remainder->p = NULL; - remainder->len = 0; - - { /* 1. Determine which root to use. */ - -#if MG_ENABLE_HTTP_URL_REWRITES - const char *rewrites = opts->url_rewrites; -#else - const char *rewrites = ""; -#endif - struct mg_str *hh = mg_get_http_header(hm, "Host"); - struct mg_str a, b; - /* Check rewrites first. */ - while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) { - if (a.len > 1 && a.p[0] == '@') { - /* Host rewrite. */ - if (hh != NULL && hh->len == a.len - 1 && - mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) { - root = b; - break; - } - } else { - /* Regular rewrite, URI=directory */ - size_t match_len = mg_match_prefix_n(a, hm->uri); - if (match_len > 0) { - file_uri_start = hm->uri.p + match_len; - if (*file_uri_start == '/' || file_uri_start == cp_end) { - /* Match ended at component boundary, ok. */ - } else if (*(file_uri_start - 1) == '/') { - /* Pattern ends with '/', backtrack. */ - file_uri_start--; - } else { - /* No match: must fall on the component boundary. */ - continue; - } - root = b; - break; - } - } - } - /* If no rewrite rules matched, use DAV or regular document root. */ - if (root.p == NULL) { -#if MG_ENABLE_HTTP_WEBDAV - if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) { - root.p = opts->dav_document_root; - root.len = strlen(opts->dav_document_root); - } else -#endif - { - root.p = opts->document_root; - root.len = strlen(opts->document_root); - } - } - assert(root.p != NULL && root.len > 0); - } - - { /* 2. Find where in the canonical URI path the local path ends. */ - const char *u = file_uri_start + 1; - char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1); - char *lp_end = lp + root.len + hm->uri.len + 1; - char *p = lp, *ps; - int exists = 1; - if (lp == NULL) { - ok = 0; - goto out; - } - memcpy(p, root.p, root.len); - p += root.len; - if (*(p - 1) == DIRSEP) p--; - *p = '\0'; - ps = p; - - /* Chop off URI path components one by one and build local path. */ - while (u <= cp_end) { - const char *next = u; - struct mg_str component; - if (exists) { - cs_stat_t st; - exists = (mg_stat(lp, &st) == 0); - if (exists && S_ISREG(st.st_mode)) { - /* We found the terminal, the rest of the URI (if any) is path_info. - */ - if (*(u - 1) == '/') u--; - break; - } - } - if (u >= cp_end) break; - parse_uri_component((const char **) &next, cp_end, "/", &component); - if (component.len > 0) { - int len; - memmove(p + 1, component.p, component.len); - len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0); - if (len <= 0) { - ok = 0; - break; - } - component.p = p + 1; - component.len = len; - if (mg_vcmp(&component, ".") == 0) { - /* Yum. */ - } else if (mg_vcmp(&component, "..") == 0) { - while (p > ps && *p != DIRSEP) p--; - *p = '\0'; - } else { - size_t i; -#ifdef _WIN32 - /* On Windows, make sure it's valid Unicode (no funny stuff). */ - wchar_t buf[MG_MAX_PATH * 2]; - if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) { - DBG(("[%.*s] smells funny", (int) component.len, component.p)); - ok = 0; - break; - } -#endif - *p++ = DIRSEP; - /* No NULs and DIRSEPs in the component (percent-encoded). */ - for (i = 0; i < component.len; i++, p++) { - if (*p == '\0' || *p == DIRSEP -#ifdef _WIN32 - /* On Windows, "/" is also accepted, so check for that too. */ - || - *p == '/' -#endif - ) { - ok = 0; - break; - } - } - } - } - u = next; - } - if (ok) { - *local_path = lp; - if (u > cp_end) u = cp_end; - remainder->p = u; - remainder->len = cp_end - u; - } else { - MG_FREE(lp); - } - } - -out: - LOG(LL_DEBUG, - ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p, - *local_path ? *local_path : "", (int) remainder->len, remainder->p)); - return ok; -} - -static int mg_get_month_index(const char *s) { - static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; - size_t i; - - for (i = 0; i < ARRAY_SIZE(month_names); i++) - if (!strcmp(s, month_names[i])) return (int) i; - - return -1; -} - -static int mg_num_leap_years(int year) { - return year / 4 - year / 100 + year / 400; -} - -/* Parse UTC date-time string, and return the corresponding time_t value. */ -MG_INTERNAL time_t mg_parse_date_string(const char *datetime) { - static const unsigned short days_before_month[] = { - 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; - char month_str[32]; - int second, minute, hour, day, month, year, leap_days, days; - time_t result = (time_t) 0; - - if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6) || - (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6) || - (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, - &hour, &minute, &second) == 6) || - (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, - &minute, &second) == 6)) && - year > 1970 && (month = mg_get_month_index(month_str)) != -1) { - leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970); - year -= 1970; - days = year * 365 + days_before_month[month] + (day - 1) + leap_days; - result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; - } - - return result; -} - -MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) { - struct mg_str *hdr; - if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) { - char etag[64]; - mg_http_construct_etag(etag, sizeof(etag), st); - return mg_vcasecmp(hdr, etag) == 0; - } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) { - return st->st_mtime <= mg_parse_date_string(hdr->p); - } else { - return 0; - } -} - -void mg_http_send_digest_auth_request(struct mg_connection *c, - const char *domain) { - mg_printf(c, - "HTTP/1.1 401 Unauthorized\r\n" - "WWW-Authenticate: Digest qop=\"auth\", " - "realm=\"%s\", nonce=\"%lx\"\r\n" - "Content-Length: 0\r\n\r\n", - domain, (unsigned long) mg_time()); -} - -static void mg_http_send_options(struct mg_connection *nc) { - mg_printf(nc, "%s", - "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS" -#if MG_ENABLE_HTTP_WEBDAV - ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2" -#endif - "\r\n\r\n"); - nc->flags |= MG_F_SEND_AND_CLOSE; -} - -static int mg_is_creation_request(const struct http_message *hm) { - return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0; -} - -MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, - const struct mg_str *path_info, - struct http_message *hm, - struct mg_serve_http_opts *opts) { - int exists, is_directory, is_cgi; -#if MG_ENABLE_HTTP_WEBDAV - int is_dav = mg_is_dav_request(&hm->method); -#else - int is_dav = 0; -#endif - char *index_file = NULL; - cs_stat_t st; - - exists = (mg_stat(path, &st) == 0); - is_directory = exists && S_ISDIR(st.st_mode); - - if (is_directory) - mg_find_index_file(path, opts->index_files, &index_file, &st); - - is_cgi = - (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern), - index_file ? index_file : path) > 0); - - LOG(LL_DEBUG, - ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc, - (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav, - is_cgi, index_file ? index_file : "")); - - if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) { - mg_printf(nc, - "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n" - "Content-Length: 0\r\n\r\n", - (int) hm->uri.len, hm->uri.p); - MG_FREE(index_file); - return; - } - - /* If we have path_info, the only way to handle it is CGI. */ - if (path_info->len > 0 && !is_cgi) { - mg_http_send_error(nc, 501, NULL); - MG_FREE(index_file); - return; - } - - if (is_dav && opts->dav_document_root == NULL) { - mg_http_send_error(nc, 501, NULL); - } else if (!mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | - MG_AUTH_FLAG_ALLOW_MISSING_FILE)) || - !mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, - opts->per_directory_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_ALLOW_MISSING_FILE))) { - mg_http_send_digest_auth_request(nc, opts->auth_domain); - } else if (is_cgi) { -#if MG_ENABLE_HTTP_CGI - mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts); -#else - mg_http_send_error(nc, 501, NULL); -#endif /* MG_ENABLE_HTTP_CGI */ - } else if ((!exists || - mg_is_file_hidden(path, opts, 0 /* specials are ok */)) && - !mg_is_creation_request(hm)) { - mg_http_send_error(nc, 404, NULL); -#if MG_ENABLE_HTTP_WEBDAV - } else if (!mg_vcmp(&hm->method, "PROPFIND")) { - mg_handle_propfind(nc, path, &st, hm, opts); -#if !MG_DISABLE_DAV_AUTH - } else if (is_dav && - (opts->dav_auth_file == NULL || - (strcmp(opts->dav_auth_file, "-") != 0 && - !mg_http_is_authorized( - hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file, - ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) | - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE | - MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) { - mg_http_send_digest_auth_request(nc, opts->auth_domain); -#endif - } else if (!mg_vcmp(&hm->method, "MKCOL")) { - mg_handle_mkcol(nc, path, hm); - } else if (!mg_vcmp(&hm->method, "DELETE")) { - mg_handle_delete(nc, opts, path); - } else if (!mg_vcmp(&hm->method, "PUT")) { - mg_handle_put(nc, path, hm); - } else if (!mg_vcmp(&hm->method, "MOVE")) { - mg_handle_move(nc, opts, path, hm); -#if MG_ENABLE_FAKE_DAVLOCK - } else if (!mg_vcmp(&hm->method, "LOCK")) { - mg_handle_lock(nc, path); -#endif -#endif /* MG_ENABLE_HTTP_WEBDAV */ - } else if (!mg_vcmp(&hm->method, "OPTIONS")) { - mg_http_send_options(nc); - } else if (is_directory && index_file == NULL) { -#if MG_ENABLE_DIRECTORY_LISTING - if (strcmp(opts->enable_directory_listing, "yes") == 0) { - mg_send_directory_listing(nc, path, hm, opts); - } else { - mg_http_send_error(nc, 403, NULL); - } -#else - mg_http_send_error(nc, 501, NULL); -#endif - } else if (mg_is_not_modified(hm, &st)) { - mg_http_send_error(nc, 304, "Not Modified"); - } else { - mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts); - } - MG_FREE(index_file); -} - -void mg_serve_http(struct mg_connection *nc, struct http_message *hm, - struct mg_serve_http_opts opts) { - char *path = NULL; - struct mg_str *hdr, path_info; - uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr); - - if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) { - /* Not allowed to connect */ - mg_http_send_error(nc, 403, NULL); - nc->flags |= MG_F_SEND_AND_CLOSE; - return; - } - -#if MG_ENABLE_HTTP_URL_REWRITES - if (mg_http_handle_forwarding(nc, hm, &opts)) { - return; - } - - if (mg_http_send_port_based_redirect(nc, hm, &opts)) { - return; - } -#endif - - if (opts.document_root == NULL) { - opts.document_root = "."; - } - if (opts.per_directory_auth_file == NULL) { - opts.per_directory_auth_file = ".htpasswd"; - } - if (opts.enable_directory_listing == NULL) { - opts.enable_directory_listing = "yes"; - } - if (opts.cgi_file_pattern == NULL) { - opts.cgi_file_pattern = "**.cgi$|**.php$"; - } - if (opts.ssi_pattern == NULL) { - opts.ssi_pattern = "**.shtml$|**.shtm$"; - } - if (opts.index_files == NULL) { - opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php"; - } - /* Normalize path - resolve "." and ".." (in-place). */ - if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) { - mg_http_send_error(nc, 400, NULL); - return; - } - if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) { - mg_http_send_error(nc, 404, NULL); - return; - } - mg_send_http_file(nc, path, &path_info, hm, &opts); - - MG_FREE(path); - path = NULL; - - /* Close connection for non-keep-alive requests */ - if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 || - ((hdr = mg_get_http_header(hm, "Connection")) != NULL && - mg_vcmp(hdr, "keep-alive") != 0)) { -#if 0 - nc->flags |= MG_F_SEND_AND_CLOSE; -#endif - } -} - -#if MG_ENABLE_HTTP_STREAMING_MULTIPART -void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data, - mg_fu_fname_fn local_name_fn - MG_UD_ARG(void *user_data)) { - switch (ev) { - case MG_EV_HTTP_PART_BEGIN: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus = - (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus)); - struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name)); - mp->user_data = NULL; - if (lfn.p == NULL || lfn.len == 0) { - LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name)); - mg_printf(nc, - "HTTP/1.1 403 Not Allowed\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n" - "Not allowed to upload %s\r\n", - mp->file_name); - nc->flags |= MG_F_SEND_AND_CLOSE; - return; - } - fus->lfn = (char *) MG_MALLOC(lfn.len + 1); - memcpy(fus->lfn, lfn.p, lfn.len); - fus->lfn[lfn.len] = '\0'; - if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p); - LOG(LL_DEBUG, - ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn)); - fus->fp = mg_fopen(fus->lfn, "w"); - if (fus->fp == NULL) { - mg_printf(nc, - "HTTP/1.1 500 Internal Server Error\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno())); - mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno()); - /* Do not close the connection just yet, discard remainder of the data. - * This is because at the time of writing some browsers (Chrome) fail to - * render response before all the data is sent. */ - } - mp->user_data = (void *) fus; - break; - } - case MG_EV_HTTP_PART_DATA: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus = - (struct file_upload_state *) mp->user_data; - if (fus == NULL || fus->fp == NULL) break; - if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) { - LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, - mg_get_errno(), (int) fus->num_recd)); - if (mg_get_errno() == ENOSPC -#ifdef SPIFFS_ERR_FULL - || mg_get_errno() == SPIFFS_ERR_FULL -#endif - ) { - mg_printf(nc, - "HTTP/1.1 413 Payload Too Large\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n", - fus->lfn, (int) fus->num_recd); - } else { - mg_printf(nc, - "HTTP/1.1 500 Internal Server Error\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n"); - mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name, - mg_get_errno(), (int) fus->num_recd); - } - fclose(fus->fp); - remove(fus->lfn); - fus->fp = NULL; - /* Do not close the connection just yet, discard remainder of the data. - * This is because at the time of writing some browsers (Chrome) fail to - * render response before all the data is sent. */ - return; - } - fus->num_recd += mp->data.len; - LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len, - (int) fus->num_recd)); - break; - } - case MG_EV_HTTP_PART_END: { - struct mg_http_multipart_part *mp = - (struct mg_http_multipart_part *) ev_data; - struct file_upload_state *fus = - (struct file_upload_state *) mp->user_data; - if (fus == NULL) break; - if (mp->status >= 0 && fus->fp != NULL) { - LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name, - fus->lfn, (int) fus->num_recd)); - mg_printf(nc, - "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Connection: close\r\n\r\n" - "Ok, %s - %d bytes.\r\n", - mp->file_name, (int) fus->num_recd); - } else { - LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn)); - /* - * mp->status < 0 means connection was terminated, so no reason to send - * HTTP reply - */ - } - if (fus->fp != NULL) fclose(fus->fp); - MG_FREE(fus->lfn); - MG_FREE(fus); - mp->user_data = NULL; - nc->flags |= MG_F_SEND_AND_CLOSE; - break; - } - } - -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */ -#endif /* MG_ENABLE_FILESYSTEM */ - -struct mg_connection *mg_connect_http_base( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *scheme1, const char *scheme2, - const char *scheme_ssl1, const char *scheme_ssl2, const char *url, - struct mg_str *path, struct mg_str *user_info, struct mg_str *host) { - struct mg_connection *nc = NULL; - unsigned int port_i = 0; - int use_ssl = 0; - struct mg_str scheme, query, fragment; - char conn_addr_buf[2]; - char *conn_addr = conn_addr_buf; - - if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path, - &query, &fragment) != 0) { - MG_SET_PTRPTR(opts.error_string, "cannot parse url"); - goto out; - } - - /* If query is present, do not strip it. Pass to the caller. */ - if (query.len > 0) path->len += query.len + 1; - - if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 || - (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) { - use_ssl = 0; - if (port_i == 0) port_i = 80; - } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 || - (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) { - use_ssl = 1; - if (port_i == 0) port_i = 443; - } else { - goto out; - } - - mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u", - (int) host->len, host->p, port_i); - if (conn_addr == NULL) goto out; - - LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr)); - if (use_ssl) { -#if MG_ENABLE_SSL - /* - * Schema requires SSL, but no SSL parameters were provided in opts. - * In order to maintain backward compatibility, use a faux-SSL with no - * verification. - */ - if (opts.ssl_ca_cert == NULL) { - opts.ssl_ca_cert = "*"; - } -#else - MG_SET_PTRPTR(opts.error_string, "ssl is disabled"); - goto out; -#endif - } - - if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data), - opts)) != NULL) { - mg_set_protocol_http_websocket(nc); - } - -out: - if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr); - return nc; -} - -struct mg_connection *mg_connect_http_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *extra_headers, - const char *post_data) { - struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR; - struct mg_str host = MG_NULL_STR, path = MG_NULL_STR; - struct mbuf auth; - struct mg_connection *nc = - mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", - NULL, "https", NULL, url, &path, &user, &host); - - if (nc == NULL) { - return NULL; - } - - mbuf_init(&auth, 0); - if (user.len > 0) { - mg_basic_auth_header(user, null_str, &auth); - } - - if (post_data == NULL) post_data = ""; - if (extra_headers == NULL) extra_headers = ""; - if (path.len == 0) path = mg_mk_str("/"); - if (host.len == 0) host = mg_mk_str(""); - - mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT - "\r\n%.*s%s\r\n%s", - (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p, - (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len, - (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data); - - mbuf_free(&auth); - return nc; -} - -struct mg_connection *mg_connect_http( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - const char *url, const char *extra_headers, const char *post_data) { - struct mg_connect_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url, - extra_headers, post_data); -} - -size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, - size_t var_name_len, char *file_name, - size_t file_name_len, const char **data, - size_t *data_len) { - static const char cd[] = "Content-Disposition: "; - size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1; - int shl; - - if (buf == NULL || buf_len <= 0) return 0; - if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0; - hl = shl; - if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0; - - /* Get boundary length */ - bl = mg_get_line_len(buf, buf_len); - - /* Loop through headers, fetch variable name and file name */ - var_name[0] = file_name[0] = '\0'; - for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) { - if (mg_ncasecmp(cd, buf + n, cdl) == 0) { - struct mg_str header; - header.p = buf + n + cdl; - header.len = ll - (cdl + 2); - { - char *var_name2 = var_name; - mg_http_parse_header2(&header, "name", &var_name2, var_name_len); - /* TODO: handle reallocated buffer correctly */ - if (var_name2 != var_name) { - MG_FREE(var_name2); - var_name[0] = '\0'; - } - } - { - char *file_name2 = file_name; - mg_http_parse_header2(&header, "filename", &file_name2, file_name_len); - /* TODO: handle reallocated buffer correctly */ - if (file_name2 != file_name) { - MG_FREE(file_name2); - file_name[0] = '\0'; - } - } - } - } - - /* Scan through the body, search for terminating boundary */ - for (pos = hl; pos + (bl - 2) < buf_len; pos++) { - if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) { - if (data_len != NULL) *data_len = (pos - 2) - hl; - if (data != NULL) *data = buf + hl; - return pos; - } - } - - return 0; -} - -void mg_register_http_endpoint_opt(struct mg_connection *nc, - const char *uri_path, - mg_event_handler_t handler, - struct mg_http_endpoint_opts opts) { - struct mg_http_proto_data *pd = NULL; - struct mg_http_endpoint *new_ep = NULL; - - if (nc == NULL) return; - new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep)); - if (new_ep == NULL) return; - - pd = mg_http_get_proto_data(nc); - new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path)); - if (opts.auth_domain != NULL && opts.auth_file != NULL) { - new_ep->auth_domain = strdup(opts.auth_domain); - new_ep->auth_file = strdup(opts.auth_file); - } - new_ep->handler = handler; -#if MG_ENABLE_CALLBACK_USERDATA - new_ep->user_data = opts.user_data; -#endif - new_ep->next = pd->endpoints; - pd->endpoints = new_ep; -} - -static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, - struct http_message *hm) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - void *user_data = nc->user_data; - - if (ev == MG_EV_HTTP_REQUEST -#if MG_ENABLE_HTTP_STREAMING_MULTIPART - || ev == MG_EV_HTTP_MULTIPART_REQUEST -#endif - ) { - struct mg_http_endpoint *ep = - mg_http_get_endpoint_handler(nc->listener, &hm->uri); - if (ep != NULL) { -#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH - if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file, - MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) { - mg_http_send_digest_auth_request(nc, ep->auth_domain); - return; - } -#endif - pd->endpoint_handler = ep->handler; -#if MG_ENABLE_CALLBACK_USERDATA - user_data = ep->user_data; -#endif - } - } - mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, - user_data, ev, hm); -} - -void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, - MG_CB(mg_event_handler_t handler, - void *user_data)) { - struct mg_http_endpoint_opts opts; - memset(&opts, 0, sizeof(opts)); -#if MG_ENABLE_CALLBACK_USERDATA - opts.user_data = user_data; -#endif - mg_register_http_endpoint_opt(nc, uri_path, handler, opts); -} - -#endif /* MG_ENABLE_HTTP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_cgi.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef _WIN32 -#include -#endif - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI - -#ifndef MG_MAX_CGI_ENVIR_VARS -#define MG_MAX_CGI_ENVIR_VARS 64 -#endif - -#ifndef MG_ENV_EXPORT_TO_CGI -#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI" -#endif - -#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1 - -/* - * This structure helps to create an environment for the spawned CGI program. - * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, - * last element must be NULL. - * However, on Windows there is a requirement that all these VARIABLE=VALUE\0 - * strings must reside in a contiguous buffer. The end of the buffer is - * marked by two '\0' characters. - * We satisfy both worlds: we create an envp array (which is vars), all - * entries are actually pointers inside buf. - */ -struct mg_cgi_env_block { - struct mg_connection *nc; - char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */ - const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */ - int len; /* Space taken */ - int nvars; /* Number of variables in envp[] */ -}; - -#ifdef _WIN32 -struct mg_threadparam { - sock_t s; - HANDLE hPipe; -}; - -static int mg_wait_until_ready(sock_t sock, int for_read) { - fd_set set; - FD_ZERO(&set); - FD_SET(sock, &set); - return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1; -} - -static void *mg_push_to_stdin(void *arg) { - struct mg_threadparam *tp = (struct mg_threadparam *) arg; - int n, sent, stop = 0; - DWORD k; - char buf[BUFSIZ]; - - while (!stop && mg_wait_until_ready(tp->s, 1) && - (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { - if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; - for (sent = 0; !stop && sent < n; sent += k) { - if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; - } - } - DBG(("%s", "FORWARED EVERYTHING TO CGI")); - CloseHandle(tp->hPipe); - MG_FREE(tp); - return NULL; -} - -static void *mg_pull_from_stdout(void *arg) { - struct mg_threadparam *tp = (struct mg_threadparam *) arg; - int k = 0, stop = 0; - DWORD n, sent; - char buf[BUFSIZ]; - - while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { - for (sent = 0; !stop && sent < n; sent += k) { - if (mg_wait_until_ready(tp->s, 0) && - (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) - stop = 1; - } - } - DBG(("%s", "EOF FROM CGI")); - CloseHandle(tp->hPipe); - shutdown(tp->s, 2); // Without this, IO thread may get truncated data - closesocket(tp->s); - MG_FREE(tp); - return NULL; -} - -static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe, - void *(*func)(void *)) { - struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp)); - if (tp != NULL) { - tp->s = sock; - tp->hPipe = hPipe; - mg_start_thread(func, tp); - } -} - -static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) { - wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH]; - to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); - GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); - WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); -} - -static int mg_start_process(const char *interp, const char *cmd, - const char *env, const char *envp[], - const char *dir, sock_t sock) { - STARTUPINFOW si; - PROCESS_INFORMATION pi; - HANDLE a[2], b[2], me = GetCurrentProcess(); - wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH]; - char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH], - buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH]; - DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; - FILE *fp; - - memset(&si, 0, sizeof(si)); - memset(&pi, 0, sizeof(pi)); - - si.cb = sizeof(si); - si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - si.hStdError = GetStdHandle(STD_ERROR_HANDLE); - - CreatePipe(&a[0], &a[1], NULL, 0); - CreatePipe(&b[0], &b[1], NULL, 0); - DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); - DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); - - if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) { - buf[0] = buf[1] = '\0'; - fgets(buf, sizeof(buf), fp); - buf[sizeof(buf) - 1] = '\0'; - if (buf[0] == '#' && buf[1] == '!') { - interp = buf + 2; - /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */ - while (*interp != '\0' && isspace(*(unsigned char *) interp)) { - interp++; - } - } - fclose(fp); - } - - snprintf(buf, sizeof(buf), "%s/%s", dir, cmd); - mg_abs_path(buf, buf2, ARRAY_SIZE(buf2)); - - mg_abs_path(dir, buf5, ARRAY_SIZE(buf5)); - to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); - - if (interp != NULL) { - mg_abs_path(interp, buf4, ARRAY_SIZE(buf4)); - snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2); - } else { - snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2); - } - to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); - - if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, - (void *) env, full_dir, &si, &pi) != 0) { - mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin); - mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout); - - CloseHandle(si.hStdOutput); - CloseHandle(si.hStdInput); - - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - } else { - CloseHandle(a[1]); - CloseHandle(b[0]); - closesocket(sock); - } - DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); - - /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */ - (void) envp; - return (pi.hProcess != NULL); -} -#else -static int mg_start_process(const char *interp, const char *cmd, - const char *env, const char *envp[], - const char *dir, sock_t sock) { - char buf[500]; - pid_t pid = fork(); - (void) env; - - if (pid == 0) { - /* - * In Linux `chdir` declared with `warn_unused_result` attribute - * To shutup compiler we have yo use result in some way - */ - int tmp = chdir(dir); - (void) tmp; - (void) dup2(sock, 0); - (void) dup2(sock, 1); - closesocket(sock); - - /* - * After exec, all signal handlers are restored to their default values, - * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's - * implementation, SIGCHLD's handler will leave unchanged after exec - * if it was set to be ignored. Restore it to default action. - */ - signal(SIGCHLD, SIG_DFL); - - if (interp == NULL) { - execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */ - } else { - execle(interp, interp, cmd, (char *) 0, envp); - } - snprintf(buf, sizeof(buf), - "Status: 500\r\n\r\n" - "500 Server Error: %s%s%s: %s", - interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, - strerror(errno)); - send(1, buf, strlen(buf), 0); - _exit(EXIT_FAILURE); /* exec call failed */ - } - - return (pid != 0); -} -#endif /* _WIN32 */ - -/* - * Append VARIABLE=VALUE\0 string to the buffer, and add a respective - * pointer into the vars array. - */ -static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) { - int n, space; - char *added = block->buf + block->len; - va_list ap; - - /* Calculate how much space is left in the buffer */ - space = sizeof(block->buf) - (block->len + 2); - if (space > 0) { - /* Copy VARIABLE=VALUE\0 string into the free space */ - va_start(ap, fmt); - n = vsnprintf(added, (size_t) space, fmt, ap); - va_end(ap); - - /* Make sure we do not overflow buffer and the envp array */ - if (n > 0 && n + 1 < space && - block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { - /* Append a pointer to the added string into the envp array */ - block->vars[block->nvars++] = added; - /* Bump up used length counter. Include \0 terminator */ - block->len += n + 1; - } - } - - return added; -} - -static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) { - const char *s; - if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s); -} - -static void mg_prepare_cgi_environment(struct mg_connection *nc, - const char *prog, - const struct mg_str *path_info, - const struct http_message *hm, - const struct mg_serve_http_opts *opts, - struct mg_cgi_env_block *blk) { - const char *s; - struct mg_str *h; - char *p; - size_t i; - char buf[100]; - size_t path_info_len = path_info != NULL ? path_info->len : 0; - - blk->len = blk->nvars = 0; - blk->nc = nc; - - if ((s = getenv("SERVER_NAME")) != NULL) { - mg_addenv(blk, "SERVER_NAME=%s", s); - } else { - mg_sock_to_str(nc->sock, buf, sizeof(buf), 3); - mg_addenv(blk, "SERVER_NAME=%s", buf); - } - mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root); - mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root); - mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION); - - /* Prepare the environment block */ - mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); - mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); - mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */ - - mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p); - - mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p, - hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len, - hm->query_string.p); - - mg_conn_addr_to_str(nc, buf, sizeof(buf), - MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP); - mg_addenv(blk, "REMOTE_ADDR=%s", buf); - mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT); - mg_addenv(blk, "SERVER_PORT=%s", buf); - - s = hm->uri.p + hm->uri.len - path_info_len - 1; - if (*s == '/') { - const char *base_name = strrchr(prog, DIRSEP); - mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p, - (base_name != NULL ? base_name + 1 : prog)); - } else { - mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p); - } - mg_addenv(blk, "SCRIPT_FILENAME=%s", prog); - - if (path_info != NULL && path_info->len > 0) { - mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p); - /* Not really translated... */ - mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p); - } - -#if MG_ENABLE_SSL - mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off")); -#else - mg_addenv(blk, "HTTPS=off"); -#endif - - if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) != - NULL) { - mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p); - } - - if (hm->query_string.len > 0) { - mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len, - hm->query_string.p); - } - - if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) != - NULL) { - mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p); - } - - mg_addenv2(blk, "PATH"); - mg_addenv2(blk, "TMP"); - mg_addenv2(blk, "TEMP"); - mg_addenv2(blk, "TMPDIR"); - mg_addenv2(blk, "PERLLIB"); - mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI); - -#ifdef _WIN32 - mg_addenv2(blk, "COMSPEC"); - mg_addenv2(blk, "SYSTEMROOT"); - mg_addenv2(blk, "SystemDrive"); - mg_addenv2(blk, "ProgramFiles"); - mg_addenv2(blk, "ProgramFiles(x86)"); - mg_addenv2(blk, "CommonProgramFiles(x86)"); -#else - mg_addenv2(blk, "LD_LIBRARY_PATH"); -#endif /* _WIN32 */ - - /* Add all headers as HTTP_* variables */ - for (i = 0; hm->header_names[i].len > 0; i++) { - p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len, - hm->header_names[i].p, (int) hm->header_values[i].len, - hm->header_values[i].p); - - /* Convert variable name into uppercase, and change - to _ */ - for (; *p != '=' && *p != '\0'; p++) { - if (*p == '-') *p = '_'; - *p = (char) toupper(*(unsigned char *) p); - } - } - - blk->vars[blk->nvars++] = NULL; - blk->buf[blk->len++] = '\0'; -} - -static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = cgi_nc->user_data; -#endif - struct mg_connection *nc = (struct mg_connection *) user_data; - (void) ev_data; - - if (nc == NULL) { - /* The corresponding network connection was closed. */ - cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - - switch (ev) { - case MG_EV_RECV: - /* - * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n" - * It outputs headers, then body. Headers might include "Status" - * header, which changes CODE, and it might include "Location" header - * which changes CODE to 302. - * - * Therefore we do not send the output from the CGI script to the user - * until all CGI headers are received. - * - * Here we parse the output from the CGI script, and if all headers has - * been received, send appropriate reply line, and forward all - * received headers to the client. - */ - if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) { - struct mbuf *io = &cgi_nc->recv_mbuf; - int len = mg_http_get_request_len(io->buf, io->len); - - if (len == 0) break; - if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) { - cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - mg_http_send_error(nc, 500, "Bad headers"); - } else { - struct http_message hm; - struct mg_str *h; - mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm); - if (mg_get_http_header(&hm, "Location") != NULL) { - mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n"); - } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) { - mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p); - } else { - mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n"); - } - } - nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS; - } - if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) { - mg_forward(cgi_nc, nc); - } - break; - case MG_EV_CLOSE: - DBG(("%p CLOSE", cgi_nc)); - mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi); - nc->flags |= MG_F_SEND_AND_CLOSE; - break; - } -} - -MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog, - const struct mg_str *path_info, - const struct http_message *hm, - const struct mg_serve_http_opts *opts) { - struct mg_cgi_env_block blk; - char dir[MG_MAX_PATH]; - const char *p; - sock_t fds[2]; - - DBG(("%p [%s]", nc, prog)); - mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk); - /* - * CGI must be executed in its own directory. 'dir' must point to the - * directory containing executable program, 'p' must point to the - * executable program name relative to 'dir'. - */ - if ((p = strrchr(prog, DIRSEP)) == NULL) { - snprintf(dir, sizeof(dir), "%s", "."); - } else { - snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); - prog = p + 1; - } - - if (!mg_socketpair(fds, SOCK_STREAM)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - -#ifndef _WIN32 - struct sigaction sa; - - sigemptyset(&sa.sa_mask); - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigaction(SIGCHLD, &sa, NULL); -#endif - - if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir, - fds[1]) != 0) { - size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len); - struct mg_connection *cgi_nc = - mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc)); - struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc); - cgi_pd->cgi.cgi_nc = cgi_nc; -#if !MG_ENABLE_CALLBACK_USERDATA - cgi_pd->cgi.cgi_nc->user_data = nc; -#endif - nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS; - /* Push POST data to the CGI */ - if (n > 0 && n < nc->recv_mbuf.len) { - mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n); - } - mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len); - } else { - closesocket(fds[0]); - mg_http_send_error(nc, 500, "CGI failure"); - } - -#ifndef _WIN32 - closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */ -#endif -} - -MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) { - if (d == NULL) return; - if (d->cgi_nc != NULL) { - d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY; - d->cgi_nc->user_data = NULL; - } - memset(d, 0, sizeof(*d)); -} - -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_ssi.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM - -static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, - const char *path, FILE *fp, int include_level, - const struct mg_serve_http_opts *opts); - -static void mg_send_file_data(struct mg_connection *nc, FILE *fp) { - char buf[BUFSIZ]; - size_t n; - while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) { - mg_send(nc, buf, n); - } -} - -static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm, - const char *ssi, char *tag, int include_level, - const struct mg_serve_http_opts *opts) { - char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p; - FILE *fp; - - /* - * sscanf() is safe here, since send_ssi_file() also uses buffer - * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN. - */ - if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) { - /* File name is relative to the webserver root */ - snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name); - } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) { - /* - * File name is relative to the webserver working directory - * or it is absolute system path - */ - snprintf(path, sizeof(path), "%s", file_name); - } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 || - sscanf(tag, " \"%[^\"]\"", file_name) == 1) { - /* File name is relative to the currect document */ - snprintf(path, sizeof(path), "%s", ssi); - if ((p = strrchr(path, DIRSEP)) != NULL) { - p[1] = '\0'; - } - snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name); - } else { - mg_printf(nc, "Bad SSI #include: [%s]", tag); - return; - } - - if ((fp = mg_fopen(path, "rb")) == NULL) { - mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path, - strerror(mg_get_errno())); - } else { - mg_set_close_on_exec((sock_t) fileno(fp)); - if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > - 0) { - mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts); - } else { - mg_send_file_data(nc, fp); - } - fclose(fp); - } -} - -#if MG_ENABLE_HTTP_SSI_EXEC -static void do_ssi_exec(struct mg_connection *nc, char *tag) { - char cmd[BUFSIZ]; - FILE *fp; - - if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) { - mg_printf(nc, "Bad SSI #exec: [%s]", tag); - } else if ((fp = popen(cmd, "r")) == NULL) { - mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno())); - } else { - mg_send_file_data(nc, fp); - pclose(fp); - } -} -#endif /* MG_ENABLE_HTTP_SSI_EXEC */ - -/* - * SSI directive has the following format: - * - */ -static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm, - const char *path, FILE *fp, int include_level, - const struct mg_serve_http_opts *opts) { - static const struct mg_str btag = MG_MK_STR(" */ - buf[i--] = '\0'; - while (i > 0 && buf[i] == ' ') { - buf[i--] = '\0'; - } - - /* Handle known SSI directives */ - if (strncmp(p, d_include.p, d_include.len) == 0) { - mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level, - opts); - } else if (strncmp(p, d_call.p, d_call.len) == 0) { - struct mg_ssi_call_ctx cctx; - memset(&cctx, 0, sizeof(cctx)); - cctx.req = hm; - cctx.file = mg_mk_str(path); - cctx.arg = mg_mk_str(p + d_call.len + 1); - mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL, - (void *) cctx.arg.p); /* NUL added above */ - mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx); -#if MG_ENABLE_HTTP_SSI_EXEC - } else if (strncmp(p, d_exec.p, d_exec.len) == 0) { - do_ssi_exec(nc, p + d_exec.len + 1); -#endif - } else { - /* Silently ignore unknown SSI directive. */ - } - len = 0; - } else if (ch == '<') { - in_ssi_tag = 1; - if (len > 0) { - mg_send(nc, buf, (size_t) len); - } - len = 0; - buf[len++] = ch & 0xff; - } else if (in_ssi_tag) { - if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) { - /* Not an SSI tag */ - in_ssi_tag = 0; - } else if (len == (int) sizeof(buf) - 2) { - mg_printf(nc, "%s: SSI tag is too large", path); - len = 0; - } - buf[len++] = ch & 0xff; - } else { - buf[len++] = ch & 0xff; - if (len == (int) sizeof(buf)) { - mg_send(nc, buf, (size_t) len); - len = 0; - } - } - } - - /* Send the rest of buffered data */ - if (len > 0) { - mg_send(nc, buf, (size_t) len); - } -} - -MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc, - struct http_message *hm, - const char *path, - const struct mg_serve_http_opts *opts) { - FILE *fp; - struct mg_str mime_type; - DBG(("%p %s", nc, path)); - - if ((fp = mg_fopen(path, "rb")) == NULL) { - mg_http_send_error(nc, 404, NULL); - } else { - mg_set_close_on_exec((sock_t) fileno(fp)); - - mime_type = mg_get_mime_type(path, "text/plain", opts); - mg_send_response_line(nc, 200, opts->extra_headers); - mg_printf(nc, - "Content-Type: %.*s\r\n" - "Connection: close\r\n\r\n", - (int) mime_type.len, mime_type.p); - mg_send_ssi_file(nc, hm, path, fp, 0, opts); - fclose(fp); - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_webdav.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV - -MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) { - static const char *methods[] = { - "PUT", - "DELETE", - "MKCOL", - "PROPFIND", - "MOVE" -#if MG_ENABLE_FAKE_DAVLOCK - , - "LOCK", - "UNLOCK" -#endif - }; - size_t i; - - for (i = 0; i < ARRAY_SIZE(methods); i++) { - if (mg_vcmp(s, methods[i]) == 0) { - return 1; - } - } - - return 0; -} - -static int mg_mkdir(const char *path, uint32_t mode) { -#ifndef _WIN32 - return mkdir(path, mode); -#else - (void) mode; - return _mkdir(path); -#endif -} - -static void mg_print_props(struct mg_connection *nc, const char *name, - cs_stat_t *stp) { - char mtime[64]; - time_t t = stp->st_mtime; /* store in local variable for NDK compile */ - struct mg_str name_esc = mg_url_encode(mg_mk_str(name)); - mg_gmt_time_string(mtime, sizeof(mtime), &t); - mg_printf(nc, - "" - "%s" - "" - "" - "%s" - "%" INT64_FMT - "" - "%s" - "" - "HTTP/1.1 200 OK" - "" - "\n", - name_esc.p, S_ISDIR(stp->st_mode) ? "" : "", - (int64_t) stp->st_size, mtime); - free((void *) name_esc.p); -} - -MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path, - cs_stat_t *stp, struct http_message *hm, - struct mg_serve_http_opts *opts) { - static const char header[] = - "HTTP/1.1 207 Multi-Status\r\n" - "Connection: close\r\n" - "Content-Type: text/xml; charset=utf-8\r\n\r\n" - "" - "\n"; - static const char footer[] = "\n"; - const struct mg_str *depth = mg_get_http_header(hm, "Depth"); - - /* Print properties for the requested resource itself */ - if (S_ISDIR(stp->st_mode) && - strcmp(opts->enable_directory_listing, "yes") != 0) { - mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n"); - } else { - char uri[MG_MAX_PATH]; - mg_send(nc, header, sizeof(header) - 1); - snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p); - mg_print_props(nc, uri, stp); - if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) { - mg_scan_directory(nc, path, opts, mg_print_props); - } - mg_send(nc, footer, sizeof(footer) - 1); - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -#if MG_ENABLE_FAKE_DAVLOCK -/* - * Windows explorer (probably there are another WebDav clients like it) - * requires LOCK support in webdav. W/out this, it still works, but fails - * to save file: shows error message and offers "Save As". - * "Save as" works, but this message is very annoying. - * This is fake lock, which doesn't lock something, just returns LOCK token, - * UNLOCK always answers "OK". - * With this fake LOCK Windows Explorer looks happy and saves file. - * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up - * Windows native DAV client. This is why FAKE LOCK is not enabed by default - */ -MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) { - static const char *reply = - "HTTP/1.1 207 Multi-Status\r\n" - "Connection: close\r\n" - "Content-Type: text/xml; charset=utf-8\r\n\r\n" - "" - "\n" - "\n" - "\n" - "\n" - "\n" - "opaquelocktoken:%s%u" - "" - "" - "\n" - "" - "\n"; - mg_printf(nc, reply, path, (unsigned int) mg_time()); - nc->flags |= MG_F_SEND_AND_CLOSE; -} -#endif - -MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path, - struct http_message *hm) { - int status_code = 500; - if (hm->body.len != (size_t) ~0 && hm->body.len > 0) { - status_code = 415; - } else if (!mg_mkdir(path, 0755)) { - status_code = 201; - } else if (errno == EEXIST) { - status_code = 405; - } else if (errno == EACCES) { - status_code = 403; - } else if (errno == ENOENT) { - status_code = 409; - } else { - status_code = 500; - } - mg_http_send_error(nc, status_code, NULL); -} - -static int mg_remove_directory(const struct mg_serve_http_opts *opts, - const char *dir) { - char path[MG_MAX_PATH]; - struct dirent *dp; - cs_stat_t st; - DIR *dirp; - - if ((dirp = opendir(dir)) == NULL) return 0; - - while ((dp = readdir(dirp)) != NULL) { - if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) { - continue; - } - snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); - mg_stat(path, &st); - if (S_ISDIR(st.st_mode)) { - mg_remove_directory(opts, path); - } else { - remove(path); - } - } - closedir(dirp); - rmdir(dir); - - return 1; -} - -MG_INTERNAL void mg_handle_move(struct mg_connection *c, - const struct mg_serve_http_opts *opts, - const char *path, struct http_message *hm) { - const struct mg_str *dest = mg_get_http_header(hm, "Destination"); - if (dest == NULL) { - mg_http_send_error(c, 411, NULL); - } else { - const char *p = (char *) memchr(dest->p, '/', dest->len); - if (p != NULL && p[1] == '/' && - (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) { - char buf[MG_MAX_PATH]; - snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root, - (int) (dest->p + dest->len - p), p); - if (rename(path, buf) == 0) { - mg_http_send_error(c, 200, NULL); - } else { - mg_http_send_error(c, 418, NULL); - } - } else { - mg_http_send_error(c, 500, NULL); - } - } -} - -MG_INTERNAL void mg_handle_delete(struct mg_connection *nc, - const struct mg_serve_http_opts *opts, - const char *path) { - cs_stat_t st; - if (mg_stat(path, &st) != 0) { - mg_http_send_error(nc, 404, NULL); - } else if (S_ISDIR(st.st_mode)) { - mg_remove_directory(opts, path); - mg_http_send_error(nc, 204, NULL); - } else if (remove(path) == 0) { - mg_http_send_error(nc, 204, NULL); - } else { - mg_http_send_error(nc, 423, NULL); - } -} - -/* Return -1 on error, 1 on success. */ -static int mg_create_itermediate_directories(const char *path) { - const char *s; - - /* Create intermediate directories if they do not exist */ - for (s = path + 1; *s != '\0'; s++) { - if (*s == '/') { - char buf[MG_MAX_PATH]; - cs_stat_t st; - snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path); - buf[sizeof(buf) - 1] = '\0'; - if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) { - return -1; - } - } - } - - return 1; -} - -MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path, - struct http_message *hm) { - struct mg_http_proto_data *pd = mg_http_get_proto_data(nc); - cs_stat_t st; - const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length"); - int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201; - - mg_http_free_proto_data_file(&pd->file); - if ((rc = mg_create_itermediate_directories(path)) == 0) { - mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); - } else if (rc == -1) { - mg_http_send_error(nc, 500, NULL); - } else if (cl_hdr == NULL) { - mg_http_send_error(nc, 411, NULL); - } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) { - mg_http_send_error(nc, 500, NULL); - } else { - const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range"); - int64_t r1 = 0, r2 = 0; - pd->file.type = DATA_PUT; - mg_set_close_on_exec((sock_t) fileno(pd->file.fp)); - pd->file.cl = to64(cl_hdr->p); - if (range_hdr != NULL && - mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) { - status_code = 206; - fseeko(pd->file.fp, r1, SEEK_SET); - pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1; - } - mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code); - /* Remove HTTP request from the mbuf, leave only payload */ - mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len); - mg_http_transfer_file_data(nc); - } -} - -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_http_websocket.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET - -/* Amalgamated: #include "common/cs_sha1.h" */ - -#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS -#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5 -#endif - -#define FLAGS_MASK_FIN (1 << 7) -#define FLAGS_MASK_OP 0x0f - -static int mg_is_ws_fragment(unsigned char flags) { - return (flags & FLAGS_MASK_FIN) == 0 || - (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE; -} - -static int mg_is_ws_first_fragment(unsigned char flags) { - return (flags & FLAGS_MASK_FIN) == 0 && - (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE; -} - -static int mg_is_ws_control_frame(unsigned char flags) { - unsigned char op = (flags & FLAGS_MASK_OP); - return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING || - op == WEBSOCKET_OP_PONG; -} - -static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, - struct websocket_message *wsm) { - if (wsm->flags & 0x8) { - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm); - } else { - mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm); - } -} - -static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) { - struct mg_http_proto_data *htd = mg_http_get_proto_data(nc); - return (htd != NULL ? &htd->ws_data : NULL); -} - -/* - * Sends a Close websocket frame with the given data, and closes the underlying - * connection. If `len` is ~0, strlen(data) is used. - */ -static void mg_ws_close(struct mg_connection *nc, const void *data, - size_t len) { - if ((int) len == ~0) { - len = strlen((const char *) data); - } - mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len); - nc->flags |= MG_F_SEND_AND_CLOSE; -} - -static int mg_deliver_websocket_data(struct mg_connection *nc) { - /* Using unsigned char *, cause of integer arithmetic below */ - uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len, - len, mask_len = 0, header_len = 0; - struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc); - unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf, - *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len; - uint8_t flags; - int ok, reass; - - if (wsd->reass_len > 0) { - /* - * We already have some previously received data which we need to - * reassemble and deliver to the client code when we get the final - * fragment. - * - * NOTE: it doesn't mean that the current message must be a continuation: - * it might be a control frame (Close, Ping or Pong), which should be - * handled without breaking the fragmented message. - */ - - size_t existing_len = wsd->reass_len; - assert(new_data_len >= existing_len); - - new_data += existing_len; - new_data_len -= existing_len; - } - - flags = new_data[0]; - - reass = new_data_len > 0 && mg_is_ws_fragment(flags) && - !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG); - - if (reass && mg_is_ws_control_frame(flags)) { - /* - * Control frames can't be fragmented, so if we encounter fragmented - * control frame, close connection immediately. - */ - mg_ws_close(nc, "fragmented control frames are illegal", ~0); - return 0; - } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) && - wsd->reass_len > 0) { - /* - * When in the middle of a fragmented message, only the continuations - * and control frames are allowed. - */ - mg_ws_close(nc, "non-continuation in the middle of a fragmented message", - ~0); - return 0; - } - - if (new_data_len >= 2) { - len = new_data[1] & 0x7f; - mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0; - if (len < 126 && new_data_len >= mask_len) { - data_len = len; - header_len = 2 + mask_len; - } else if (len == 126 && new_data_len >= 4 + mask_len) { - header_len = 4 + mask_len; - data_len = ntohs(*(uint16_t *) &new_data[2]); - } else if (new_data_len >= 10 + mask_len) { - header_len = 10 + mask_len; - data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) + - ntohl(*(uint32_t *) &new_data[6]); - } - } - - frame_len = header_len + data_len; - ok = (frame_len > 0 && frame_len <= new_data_len); - - /* Check for overflow */ - if (frame_len < header_len || frame_len < data_len) { - ok = 0; - mg_ws_close(nc, "overflowed message", ~0); - } - - if (ok) { - size_t cleanup_len = 0; - struct websocket_message wsm; - - wsm.size = (size_t) data_len; - wsm.data = new_data + header_len; - wsm.flags = flags; - - /* Apply mask if necessary */ - if (mask_len > 0) { - for (i = 0; i < data_len; i++) { - new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4]; - } - } - - if (reass) { - /* This is a message fragment */ - - if (mg_is_ws_first_fragment(flags)) { - /* - * On the first fragmented frame, skip the first byte (op) and also - * reset size to 1 (op), it'll be incremented with the data len below. - */ - new_data += 1; - wsd->reass_len = 1 /* op */; - } - - /* Append this frame to the reassembled buffer */ - memmove(new_data, wsm.data, e - wsm.data); - wsd->reass_len += wsm.size; - nc->recv_mbuf.len -= wsm.data - new_data; - - if (flags & FLAGS_MASK_FIN) { - /* On last fragmented frame - call user handler and remove data */ - wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0]; - wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */; - wsm.size = wsd->reass_len - 1 /* op */; - cleanup_len = wsd->reass_len; - wsd->reass_len = 0; - - /* Pass reassembled message to the client code. */ - mg_handle_incoming_websocket_frame(nc, &wsm); - mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */ - } - } else { - /* - * This is a complete message, not a fragment. It might happen in between - * of a fragmented message (in this case, WebSocket protocol requires - * current message to be a control frame). - */ - cleanup_len = (size_t) frame_len; - - /* First of all, check if we need to react on a control frame. */ - switch (flags & FLAGS_MASK_OP) { - case WEBSOCKET_OP_PING: - mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size); - break; - - case WEBSOCKET_OP_CLOSE: - mg_ws_close(nc, wsm.data, wsm.size); - break; - } - - /* Pass received message to the client code. */ - mg_handle_incoming_websocket_frame(nc, &wsm); - - /* Cleanup frame */ - memmove(nc->recv_mbuf.buf + wsd->reass_len, - nc->recv_mbuf.buf + wsd->reass_len + cleanup_len, - nc->recv_mbuf.len - wsd->reass_len - cleanup_len); - nc->recv_mbuf.len -= cleanup_len; - } - } - - return ok; -} - -struct ws_mask_ctx { - size_t pos; /* zero means unmasked */ - uint32_t mask; -}; - -static uint32_t mg_ws_random_mask(void) { - uint32_t mask; -/* - * The spec requires WS client to generate hard to - * guess mask keys. From RFC6455, Section 5.3: - * - * The unpredictability of the masking key is essential to prevent - * authors of malicious applications from selecting the bytes that appear on - * the wire. - * - * Hence this feature is essential when the actual end user of this API - * is untrusted code that wouldn't have access to a lower level net API - * anyway (e.g. web browsers). Hence this feature is low prio for most - * mongoose use cases and thus can be disabled, e.g. when porting to a platform - * that lacks rand(). - */ -#if MG_DISABLE_WS_RANDOM_MASK - mask = 0xefbeadde; /* generated with a random number generator, I swear */ -#else - if (sizeof(long) >= 4) { - mask = (uint32_t) rand(); - } else if (sizeof(long) == 2) { - mask = (uint32_t) rand() << 16 | (uint32_t) rand(); - } -#endif - return mask; -} - -static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, - struct ws_mask_ctx *ctx) { - int header_len; - unsigned char header[10]; - - header[0] = - (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP); - if (len < 126) { - header[1] = (unsigned char) len; - header_len = 2; - } else if (len < 65535) { - uint16_t tmp = htons((uint16_t) len); - header[1] = 126; - memcpy(&header[2], &tmp, sizeof(tmp)); - header_len = 4; - } else { - uint32_t tmp; - header[1] = 127; - tmp = htonl((uint32_t)((uint64_t) len >> 32)); - memcpy(&header[2], &tmp, sizeof(tmp)); - tmp = htonl((uint32_t)(len & 0xffffffff)); - memcpy(&header[6], &tmp, sizeof(tmp)); - header_len = 10; - } - - /* client connections enable masking */ - if (nc->listener == NULL) { - header[1] |= 1 << 7; /* set masking flag */ - mg_send(nc, header, header_len); - ctx->mask = mg_ws_random_mask(); - mg_send(nc, &ctx->mask, sizeof(ctx->mask)); - ctx->pos = nc->send_mbuf.len; - } else { - mg_send(nc, header, header_len); - ctx->pos = 0; - } -} - -static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) { - size_t i; - if (ctx->pos == 0) return; - for (i = 0; i < (mbuf->len - ctx->pos); i++) { - mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4]; - } -} - -void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data, - size_t len) { - struct ws_mask_ctx ctx; - DBG(("%p %d %d", nc, op, (int) len)); - mg_send_ws_header(nc, op, len, &ctx); - mg_send(nc, data, len); - - mg_ws_mask_frame(&nc->send_mbuf, &ctx); - - if (op == WEBSOCKET_OP_CLOSE) { - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -void mg_send_websocket_framev(struct mg_connection *nc, int op, - const struct mg_str *strv, int strvcnt) { - struct ws_mask_ctx ctx; - int i; - int len = 0; - for (i = 0; i < strvcnt; i++) { - len += strv[i].len; - } - - mg_send_ws_header(nc, op, len, &ctx); - - for (i = 0; i < strvcnt; i++) { - mg_send(nc, strv[i].p, strv[i].len); - } - - mg_ws_mask_frame(&nc->send_mbuf, &ctx); - - if (op == WEBSOCKET_OP_CLOSE) { - nc->flags |= MG_F_SEND_AND_CLOSE; - } -} - -void mg_printf_websocket_frame(struct mg_connection *nc, int op, - const char *fmt, ...) { - char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem; - va_list ap; - int len; - - va_start(ap, fmt); - if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { - mg_send_websocket_frame(nc, op, buf, len); - } - va_end(ap); - - if (buf != mem && buf != NULL) { - MG_FREE(buf); - } -} - -MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - mg_call(nc, nc->handler, nc->user_data, ev, ev_data); - - switch (ev) { - case MG_EV_RECV: - do { - } while (mg_deliver_websocket_data(nc)); - break; - case MG_EV_POLL: - /* Ping idle websocket connections */ - { - time_t now = *(time_t *) ev_data; - if (nc->flags & MG_F_IS_WEBSOCKET && - now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) { - mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0); - } - } - break; - default: - break; - } -#if MG_ENABLE_CALLBACK_USERDATA - (void) user_data; -#endif -} - -#ifndef MG_EXT_SHA1 -void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest) { - size_t i; - cs_sha1_ctx sha_ctx; - cs_sha1_init(&sha_ctx); - for (i = 0; i < num_msgs; i++) { - cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]); - } - cs_sha1_final(digest, &sha_ctx); -} -#else -extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], - const size_t *msg_lens, uint8_t *digest); -#endif - -MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc, - const struct mg_str *key, - struct http_message *hm) { - static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic}; - const size_t msg_lens[2] = {key->len, 36}; - unsigned char sha[20]; - char b64_sha[30]; - struct mg_str *s; - - mg_hash_sha1_v(2, msgs, msg_lens, sha); - mg_base64_encode(sha, sizeof(sha), b64_sha); - mg_printf(nc, "%s", - "HTTP/1.1 101 Switching Protocols\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n"); - - s = mg_get_http_header(hm, "Sec-WebSocket-Protocol"); - if (s != NULL) { - mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p); - } - mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n"); - - DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha)); -} - -void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers) { - mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL, - NULL); -} - -void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, - const char *host, const char *protocol, - const char *extra_headers, const char *user, - const char *pass) { - mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host), - mg_mk_str(protocol), mg_mk_str(extra_headers), - mg_mk_str(user), mg_mk_str(pass)); -} - -void mg_send_websocket_handshake3v(struct mg_connection *nc, - const struct mg_str path, - const struct mg_str host, - const struct mg_str protocol, - const struct mg_str extra_headers, - const struct mg_str user, - const struct mg_str pass) { - struct mbuf auth; - char key[25]; - uint32_t nonce[4]; - nonce[0] = mg_ws_random_mask(); - nonce[1] = mg_ws_random_mask(); - nonce[2] = mg_ws_random_mask(); - nonce[3] = mg_ws_random_mask(); - mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key); - - mbuf_init(&auth, 0); - if (user.len > 0) { - mg_basic_auth_header(user, pass, &auth); - } - - /* - * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is - * broken: it doesn't like zero length to be passed to %.*s - * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`. - * because it handles NULL specially (and incorrectly). - */ - mg_printf(nc, - "GET %.*s HTTP/1.1\r\n" - "Upgrade: websocket\r\n" - "Connection: Upgrade\r\n" - "%.*s" - "Sec-WebSocket-Version: 13\r\n" - "Sec-WebSocket-Key: %s\r\n", - (int) path.len, path.p, (int) auth.len, - (auth.buf == NULL ? "" : auth.buf), key); - - /* TODO(mkm): take default hostname from http proto data if host == NULL */ - if (host.len > 0) { - int host_len = (int) (path.p - host.p); /* Account for possible :PORT */ - mg_printf(nc, "Host: %.*s\r\n", host_len, host.p); - } - if (protocol.len > 0) { - mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len, - protocol.p); - } - if (extra_headers.len > 0) { - mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p); - } - mg_printf(nc, "\r\n"); - - mbuf_free(&auth); -} - -void mg_send_websocket_handshake(struct mg_connection *nc, const char *path, - const char *extra_headers) { - struct mg_str null_str = MG_NULL_STR; - mg_send_websocket_handshake3v( - nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */, - mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */); -} - -struct mg_connection *mg_connect_ws_opt( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - struct mg_connect_opts opts, const char *url, const char *protocol, - const char *extra_headers) { - struct mg_str null_str = MG_NULL_STR; - struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR; - struct mg_connection *nc = - mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http", - "ws", "https", "wss", url, &path, &user_info, &host); - if (nc != NULL) { - mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol), - mg_mk_str(extra_headers), user_info, - null_str); - } - return nc; -} - -struct mg_connection *mg_connect_ws( - struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data), - const char *url, const char *protocol, const char *extra_headers) { - struct mg_connect_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url, - protocol, extra_headers); -} -#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_util.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/cs_base64.h" */ -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_util.h" */ - -/* For platforms with limited libc */ -#ifndef MAX -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#endif - -const char *mg_skip(const char *s, const char *end, const char *delims, - struct mg_str *v) { - v->p = s; - while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++; - v->len = s - v->p; - while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++; - return s; -} - -#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS) -int mg_stat(const char *path, cs_stat_t *st) { -#ifdef _WIN32 - wchar_t wpath[MG_MAX_PATH]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); - return _wstati64(wpath, st); -#else - return stat(path, st); -#endif -} - -FILE *mg_fopen(const char *path, const char *mode) { -#ifdef _WIN32 - wchar_t wpath[MG_MAX_PATH], wmode[10]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - to_wchar(mode, wmode, ARRAY_SIZE(wmode)); - return _wfopen(wpath, wmode); -#else - return fopen(path, mode); -#endif -} - -int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */ -#if defined(_WIN32) && !defined(WINCE) - wchar_t wpath[MG_MAX_PATH]; - to_wchar(path, wpath, ARRAY_SIZE(wpath)); - return _wopen(wpath, flag, mode); -#else - return open(path, flag, mode); /* LCOV_EXCL_LINE */ -#endif -} - -size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) { - return fread(ptr, size, count, f); -} - -size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) { - return fwrite(ptr, size, count, f); -} -#endif - -void mg_base64_encode(const unsigned char *src, int src_len, char *dst) { - cs_base64_encode(src, src_len, dst); -} - -int mg_base64_decode(const unsigned char *s, int len, char *dst) { - return cs_base64_decode(s, len, dst, NULL); -} - -#if MG_ENABLE_THREADS -void *mg_start_thread(void *(*f)(void *), void *p) { -#ifdef WINCE - return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL); -#elif defined(_WIN32) - return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p); -#else - pthread_t thread_id = (pthread_t) 0; - pthread_attr_t attr; - - (void) pthread_attr_init(&attr); - (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - -#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1 - (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE); -#endif - - pthread_create(&thread_id, &attr, f, p); - pthread_attr_destroy(&attr); - - return (void *) thread_id; -#endif -} -#endif /* MG_ENABLE_THREADS */ - -/* Set close-on-exec bit for a given socket. */ -void mg_set_close_on_exec(sock_t sock) { -#if defined(_WIN32) && !defined(WINCE) - (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); -#elif defined(__unix__) - fcntl(sock, F_SETFD, FD_CLOEXEC); -#else - (void) sock; -#endif -} - -int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, - int flags) { - int is_v6; - if (buf == NULL || len <= 0) return 0; - memset(buf, 0, len); -#if MG_ENABLE_IPV6 - is_v6 = sa->sa.sa_family == AF_INET6; -#else - is_v6 = 0; -#endif - if (flags & MG_SOCK_STRINGIFY_IP) { -#if MG_ENABLE_IPV6 - const void *addr = NULL; - char *start = buf; - socklen_t capacity = len; - if (!is_v6) { - addr = &sa->sin.sin_addr; - } else { - addr = (void *) &sa->sin6.sin6_addr; - if (flags & MG_SOCK_STRINGIFY_PORT) { - *buf = '['; - start++; - capacity--; - } - } - if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) { - goto cleanup; - } -#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32) - /* Only Windoze Vista (and newer) have inet_ntop() */ - char *addr_str = inet_ntoa(sa->sin.sin_addr); - if (addr_str != NULL) { - strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1); - } else { - goto cleanup; - } -#else - if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) { - goto cleanup; - } -#endif - } - if (flags & MG_SOCK_STRINGIFY_PORT) { - int port = ntohs(sa->sin.sin_port); - if (flags & MG_SOCK_STRINGIFY_IP) { - int buf_len = strlen(buf); - snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""), - port); - } else { - snprintf(buf, len, "%d", port); - } - } - - return strlen(buf); - -cleanup: - *buf = '\0'; - return 0; -} - -int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, - int flags) { - union socket_address sa; - memset(&sa, 0, sizeof(sa)); - mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa); - return mg_sock_addr_to_str(&sa, buf, len, flags); -} - -#if MG_ENABLE_HEXDUMP -static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len, - int offset) { - const unsigned char *p = (const unsigned char *) buf; - char ascii[17] = ""; - int i, idx, n = 0; - - for (i = 0; i < len; i++) { - idx = i % 16; - if (idx == 0) { - if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); - n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset); - } - if (dst_len - n < 0) { - return n; - } - n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]); - ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; - ascii[idx + 1] = '\0'; - } - - while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " "); - n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii); - - return n; -} - -int mg_hexdump(const void *buf, int len, char *dst, int dst_len) { - return mg_hexdump_n(buf, len, dst, dst_len, 0); -} - -void mg_hexdumpf(FILE *fp, const void *buf, int len) { - char tmp[80]; - int offset = 0, n; - while (len > 0) { - n = (len < 16 ? len : 16); - mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset); - fputs(tmp, fp); - offset += n; - len -= n; - } -} - -void mg_hexdump_connection(struct mg_connection *nc, const char *path, - const void *buf, int num_bytes, int ev) { - FILE *fp = NULL; - char src[60], dst[60]; - const char *tag = NULL; - switch (ev) { - case MG_EV_RECV: - tag = "<-"; - break; - case MG_EV_SEND: - tag = "->"; - break; - case MG_EV_ACCEPT: - tag = " 0) { - mg_hexdumpf(fp, buf, num_bytes); - } - if (fp != stdout && fp != stderr) fclose(fp); -} -#endif - -int mg_is_big_endian(void) { - static const int n = 1; - /* TODO(mkm) use compiletime check with 4-byte char literal */ - return ((char *) &n)[0] == 0; -} - -DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) { -#ifndef WINCE - return errno; -#else - /* TODO(alashkin): translate error codes? */ - return GetLastError(); -#endif -} - -void mg_mbuf_append_base64_putc(char ch, void *user_data) { - struct mbuf *mbuf = (struct mbuf *) user_data; - mbuf_append(mbuf, &ch, sizeof(ch)); -} - -void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) { - struct cs_base64_ctx ctx; - cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf); - cs_base64_update(&ctx, (const char *) data, len); - cs_base64_finish(&ctx); -} - -void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, - struct mbuf *buf) { - const char *header_prefix = "Authorization: Basic "; - const char *header_suffix = "\r\n"; - - struct cs_base64_ctx ctx; - cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf); - - mbuf_append(buf, header_prefix, strlen(header_prefix)); - - cs_base64_update(&ctx, user.p, user.len); - if (pass.len > 0) { - cs_base64_update(&ctx, ":", 1); - cs_base64_update(&ctx, pass.p, pass.len); - } - cs_base64_finish(&ctx); - mbuf_append(buf, header_suffix, strlen(header_suffix)); -} - -struct mg_str mg_url_encode(const struct mg_str src) { - static const char *dont_escape = "._-$,;~()/"; - static const char *hex = "0123456789abcdef"; - size_t i = 0; - struct mbuf mb; - mbuf_init(&mb, src.len); - - for (i = 0; i < src.len; i++) { - const unsigned char c = *((const unsigned char *) src.p + i); - if (isalnum(c) || strchr(dont_escape, c) != NULL) { - mbuf_append(&mb, &c, 1); - } else { - mbuf_append(&mb, "%", 1); - mbuf_append(&mb, &hex[c >> 4], 1); - mbuf_append(&mb, &hex[c & 15], 1); - } - } - mbuf_append(&mb, "", 1); - mbuf_trim(&mb); - return mg_mk_str_n(mb.buf, mb.len - 1); -} -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_MQTT - -#include - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_mqtt.h" */ - -static uint16_t getu16(const char *p) { - const uint8_t *up = (const uint8_t *) p; - return (up[0] << 8) + up[1]; -} - -static const char *scanto(const char *p, struct mg_str *s) { - s->len = getu16(p); - s->p = p + 2; - return s->p + s->len; -} - -MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) { - uint8_t header; - size_t len = 0, len_len = 0; - const char *p, *end; - unsigned char lc = 0; - int cmd; - - if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG; - header = io->buf[0]; - cmd = header >> 4; - - /* decode mqtt variable length */ - len = len_len = 0; - p = io->buf + 1; - while ((size_t)(p - io->buf) < io->len) { - lc = *((const unsigned char *) p++); - len += (lc & 0x7f) << 7 * len_len; - len_len++; - if (!(lc & 0x80)) break; - if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG; - } - - end = p + len; - if (lc & 0x80 || len > (io->len - (p - io->buf))) { - return MG_MQTT_ERROR_INCOMPLETE_MSG; - } - - mm->cmd = cmd; - mm->qos = MG_MQTT_GET_QOS(header); - - switch (cmd) { - case MG_MQTT_CMD_CONNECT: { - p = scanto(p, &mm->protocol_name); - if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->protocol_version = *(uint8_t *) p++; - mm->connect_flags = *(uint8_t *) p++; - mm->keep_alive_timer = getu16(p); - p += 2; - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->client_id); - if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; - if (mm->connect_flags & MG_MQTT_HAS_WILL) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->will_topic); - } - if (mm->connect_flags & MG_MQTT_HAS_WILL) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->will_message); - } - if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->user_name); - } - if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) { - if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG; - p = scanto(p, &mm->password); - } - if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG; - - LOG(LL_DEBUG, - ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] " - "will_msg [%.*s] user_name [%.*s] password [%.*s]", - (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer, - (int) mm->protocol_name.len, mm->protocol_name.p, - (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len, - mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p, - (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len, - mm->password.p)); - break; - } - case MG_MQTT_CMD_CONNACK: - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->connack_ret_code = p[1]; - break; - case MG_MQTT_CMD_PUBACK: - case MG_MQTT_CMD_PUBREC: - case MG_MQTT_CMD_PUBREL: - case MG_MQTT_CMD_PUBCOMP: - case MG_MQTT_CMD_SUBACK: - mm->message_id = getu16(p); - break; - case MG_MQTT_CMD_PUBLISH: { - p = scanto(p, &mm->topic); - if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG; - if (mm->qos > 0) { - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->message_id = getu16(p); - p += 2; - } - mm->payload.p = p; - mm->payload.len = end - p; - break; - } - case MG_MQTT_CMD_SUBSCRIBE: - if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG; - mm->message_id = getu16(p); - p += 2; - /* - * topic expressions are left in the payload and can be parsed with - * `mg_mqtt_next_subscribe_topic` - */ - mm->payload.p = p; - mm->payload.len = end - p; - break; - default: - /* Unhandled command */ - break; - } - - mm->len = end - io->buf; - return mm->len; -} - -static void mqtt_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_mqtt_message mm; - memset(&mm, 0, sizeof(mm)); - - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_ACCEPT: - if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); - break; - case MG_EV_RECV: { - /* There can be multiple messages in the buffer, process them all. */ - while (1) { - int len = parse_mqtt(io, &mm); - if (len < 0) { - if (len == MG_MQTT_ERROR_MALFORMED_MSG) { - /* Protocol error. */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) { - /* Not fully buffered, let's check if we have a chance to get more - * data later */ - if (nc->recv_mbuf_limit > 0 && - nc->recv_mbuf.len >= nc->recv_mbuf_limit) { - LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit " - "%lu bytes, and not drained, closing", - nc, (unsigned long) nc->recv_mbuf.len, - (unsigned long) nc->recv_mbuf_limit)); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - } else { - /* Should never be here */ - LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len)); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - } - - nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data)); - mbuf_remove(io, len); - } - break; - } - case MG_EV_POLL: { - struct mg_mqtt_proto_data *pd = - (struct mg_mqtt_proto_data *) nc->proto_data; - double now = mg_time(); - if (pd->keep_alive > 0 && pd->last_control_time > 0 && - (now - pd->last_control_time) > pd->keep_alive) { - LOG(LL_DEBUG, ("Send PINGREQ")); - mg_mqtt_ping(nc); - } - break; - } - } -} - -static void mg_mqtt_proto_data_destructor(void *proto_data) { - MG_FREE(proto_data); -} - -int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) { - /* TODO(mkm): implement real matching */ - if (memchr(exp.p, '#', exp.len)) { - /* exp `foo/#` will become `foo/` */ - exp.len -= 1; - /* - * topic should be longer than the expression: e.g. topic `foo/bar` does - * match `foo/#`, but neither `foo` nor `foo/` do. - */ - if (topic.len <= exp.len) { - return 0; - } - - /* Truncate topic so that it'll pass the next length check */ - topic.len = exp.len; - } - if (topic.len != exp.len) { - return 0; - } - return strncmp(topic.p, exp.p, exp.len) == 0; -} - -int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) { - return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic); -} - -void mg_set_protocol_mqtt(struct mg_connection *nc) { - nc->proto_handler = mqtt_handler; - nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data)); - nc->proto_data_destructor = mg_mqtt_proto_data_destructor; -} - -static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd, - uint8_t flags, size_t len) { - struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; - size_t off = nc->send_mbuf.len - len; - uint8_t header = cmd << 4 | (uint8_t) flags; - - uint8_t buf[1 + sizeof(size_t)]; - uint8_t *vlen = &buf[1]; - - assert(nc->send_mbuf.len >= len); - - buf[0] = header; - - /* mqtt variable length encoding */ - do { - *vlen = len % 0x80; - len /= 0x80; - if (len > 0) *vlen |= 0x80; - vlen++; - } while (len > 0); - - mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf); - pd->last_control_time = mg_time(); -} - -void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) { - static struct mg_send_mqtt_handshake_opts opts; - mg_send_mqtt_handshake_opt(nc, client_id, opts); -} - -void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, - struct mg_send_mqtt_handshake_opts opts) { - uint16_t hlen, nlen, rem_len = 0; - struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data; - - mg_send(nc, "\00\04MQTT\04", 7); - rem_len += 7; - - if (opts.user_name != NULL) { - opts.flags |= MG_MQTT_HAS_USER_NAME; - } - if (opts.password != NULL) { - opts.flags |= MG_MQTT_HAS_PASSWORD; - } - if (opts.will_topic != NULL && opts.will_message != NULL) { - opts.flags |= MG_MQTT_HAS_WILL; - } - if (opts.keep_alive == 0) { - opts.keep_alive = 60; - } - - mg_send(nc, &opts.flags, 1); - rem_len += 1; - - nlen = htons(opts.keep_alive); - mg_send(nc, &nlen, 2); - rem_len += 2; - - hlen = strlen(client_id); - nlen = htons((uint16_t) hlen); - mg_send(nc, &nlen, 2); - mg_send(nc, client_id, hlen); - rem_len += 2 + hlen; - - if (opts.flags & MG_MQTT_HAS_WILL) { - hlen = strlen(opts.will_topic); - nlen = htons((uint16_t) hlen); - mg_send(nc, &nlen, 2); - mg_send(nc, opts.will_topic, hlen); - rem_len += 2 + hlen; - - hlen = strlen(opts.will_message); - nlen = htons((uint16_t) hlen); - mg_send(nc, &nlen, 2); - mg_send(nc, opts.will_message, hlen); - rem_len += 2 + hlen; - } - - if (opts.flags & MG_MQTT_HAS_USER_NAME) { - hlen = strlen(opts.user_name); - nlen = htons((uint16_t) hlen); - mg_send(nc, &nlen, 2); - mg_send(nc, opts.user_name, hlen); - rem_len += 2 + hlen; - } - if (opts.flags & MG_MQTT_HAS_PASSWORD) { - hlen = strlen(opts.password); - nlen = htons((uint16_t) hlen); - mg_send(nc, &nlen, 2); - mg_send(nc, opts.password, hlen); - rem_len += 2 + hlen; - } - - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNECT, 0, rem_len); - - if (pd != NULL) { - pd->keep_alive = opts.keep_alive; - } -} - -void mg_mqtt_publish(struct mg_connection *nc, const char *topic, - uint16_t message_id, int flags, const void *data, - size_t len) { - size_t old_len = nc->send_mbuf.len; - - uint16_t topic_len = htons((uint16_t) strlen(topic)); - uint16_t message_id_net = htons(message_id); - - mg_send(nc, &topic_len, 2); - mg_send(nc, topic, strlen(topic)); - if (MG_MQTT_GET_QOS(flags) > 0) { - mg_send(nc, &message_id_net, 2); - } - mg_send(nc, data, len); - - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags, - nc->send_mbuf.len - old_len); -} - -void mg_mqtt_subscribe(struct mg_connection *nc, - const struct mg_mqtt_topic_expression *topics, - size_t topics_len, uint16_t message_id) { - size_t old_len = nc->send_mbuf.len; - - uint16_t message_id_n = htons(message_id); - size_t i; - - mg_send(nc, (char *) &message_id_n, 2); - for (i = 0; i < topics_len; i++) { - uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic)); - mg_send(nc, &topic_len_n, 2); - mg_send(nc, topics[i].topic, strlen(topics[i].topic)); - mg_send(nc, &topics[i].qos, 1); - } - - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), - nc->send_mbuf.len - old_len); -} - -int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, - struct mg_str *topic, uint8_t *qos, int pos) { - unsigned char *buf = (unsigned char *) msg->payload.p + pos; - int new_pos; - - if ((size_t) pos >= msg->payload.len) return -1; - - topic->len = buf[0] << 8 | buf[1]; - topic->p = (char *) buf + 2; - new_pos = pos + 2 + topic->len + 1; - if ((size_t) new_pos > msg->payload.len) return -1; - *qos = buf[2 + topic->len]; - return new_pos; -} - -void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, - size_t topics_len, uint16_t message_id) { - size_t old_len = nc->send_mbuf.len; - - uint16_t message_id_n = htons(message_id); - size_t i; - - mg_send(nc, (char *) &message_id_n, 2); - for (i = 0; i < topics_len; i++) { - uint16_t topic_len_n = htons((uint16_t) strlen(topics[i])); - mg_send(nc, &topic_len_n, 2); - mg_send(nc, topics[i], strlen(topics[i])); - } - - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), - nc->send_mbuf.len - old_len); -} - -void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) { - uint8_t unused = 0; - mg_send(nc, &unused, 1); - mg_send(nc, &return_code, 1); - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2); -} - -/* - * Sends a command which contains only a `message_id` and a QoS level of 1. - * - * Helper function. - */ -static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, - uint16_t message_id) { - uint16_t message_id_net = htons(message_id); - uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0); - mg_send(nc, &message_id_net, 2); - mg_mqtt_prepend_header(nc, cmd, flags, 2 /* len */); -} - -void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id); -} - -void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id); -} - -void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id); -} - -void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id); -} - -void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, - uint16_t message_id) { - size_t i; - uint16_t message_id_net = htons(message_id); - mg_send(nc, &message_id_net, 2); - for (i = 0; i < qoss_len; i++) { - mg_send(nc, &qoss[i], 1); - } - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len); -} - -void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) { - mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id); -} - -void mg_mqtt_ping(struct mg_connection *nc) { - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0); -} - -void mg_mqtt_pong(struct mg_connection *nc) { - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0); -} - -void mg_mqtt_disconnect(struct mg_connection *nc) { - mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0); -} - -#endif /* MG_ENABLE_MQTT */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_mqtt_server.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_mqtt_server.h" */ - -#if MG_ENABLE_MQTT_BROKER - -static void mg_mqtt_session_init(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s, - struct mg_connection *nc) { - s->brk = brk; - s->subscriptions = NULL; - s->num_subscriptions = 0; - s->nc = nc; -} - -static void mg_mqtt_add_session(struct mg_mqtt_session *s) { - LIST_INSERT_HEAD(&s->brk->sessions, s, link); -} - -static void mg_mqtt_remove_session(struct mg_mqtt_session *s) { - LIST_REMOVE(s, link); -} - -static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) { - size_t i; - for (i = 0; i < s->num_subscriptions; i++) { - MG_FREE((void *) s->subscriptions[i].topic); - } - MG_FREE(s->subscriptions); - MG_FREE(s); -} - -static void mg_mqtt_close_session(struct mg_mqtt_session *s) { - mg_mqtt_remove_session(s); - mg_mqtt_destroy_session(s); -} - -void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) { - LIST_INIT(&brk->sessions); - brk->user_data = user_data; -} - -static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk, - struct mg_connection *nc) { - struct mg_mqtt_session *s = - (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s); - if (s == NULL) { - /* LCOV_EXCL_START */ - mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE); - return; - /* LCOV_EXCL_STOP */ - } - - /* TODO(mkm): check header (magic and version) */ - - mg_mqtt_session_init(brk, s, nc); - nc->priv_2 = s; - mg_mqtt_add_session(s); - - mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED); -} - -static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc, - struct mg_mqtt_message *msg) { - struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2; - uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS]; - size_t num_subs = 0; - struct mg_str topic; - uint8_t qos; - int pos; - struct mg_mqtt_topic_expression *te; - - for (pos = 0; - (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) { - if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) || - (ss->num_subscriptions + num_subs >= - MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - qoss[num_subs++] = qos; - } - - if (num_subs > 0) { - te = (struct mg_mqtt_topic_expression *) MG_REALLOC( - ss->subscriptions, - sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs)); - if (te == NULL) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - ss->subscriptions = te; - for (pos = 0; - pos < (int) msg->payload.len && - (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1; - ss->num_subscriptions++) { - te = &ss->subscriptions[ss->num_subscriptions]; - te->topic = (char *) MG_MALLOC(topic.len + 1); - te->qos = qos; - memcpy((char *) te->topic, topic.p, topic.len); - ((char *) te->topic)[topic.len] = '\0'; - } - } - - if (pos == (int) msg->payload.len) { - mg_mqtt_suback(nc, qoss, num_subs, msg->message_id); - } else { - /* We did not fully parse the payload, something must be wrong. */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk, - struct mg_mqtt_message *msg) { - struct mg_mqtt_session *s; - size_t i; - - for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) { - for (i = 0; i < s->num_subscriptions; i++) { - if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic, - msg->topic)) { - char buf[100], *p = buf; - mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len, - msg->topic.p); - if (p == NULL) { - return; - } - mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len); - if (p != buf) { - MG_FREE(p); - } - break; - } - } - } -} - -void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) { - struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data; - struct mg_mqtt_broker *brk; - - if (nc->listener) { - brk = (struct mg_mqtt_broker *) nc->listener->priv_2; - } else { - brk = (struct mg_mqtt_broker *) nc->priv_2; - } - - switch (ev) { - case MG_EV_ACCEPT: - if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc); - nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */ - break; - case MG_EV_MQTT_CONNECT: - if (nc->priv_2 == NULL) { - mg_mqtt_broker_handle_connect(brk, nc); - } else { - /* Repeated CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_MQTT_SUBSCRIBE: - if (nc->priv_2 != NULL) { - mg_mqtt_broker_handle_subscribe(nc, msg); - } else { - /* Subscribe before CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_MQTT_PUBLISH: - if (nc->priv_2 != NULL) { - mg_mqtt_broker_handle_publish(brk, msg); - } else { - /* Publish before CONNECT */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_EV_CLOSE: - if (nc->listener && nc->priv_2 != NULL) { - mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2); - } - break; - } -} - -struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk, - struct mg_mqtt_session *s) { - return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link); -} - -#endif /* MG_ENABLE_MQTT_BROKER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_DNS - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_dns.h" */ - -static int mg_dns_tid = 0xa0; - -struct mg_dns_header { - uint16_t transaction_id; - uint16_t flags; - uint16_t num_questions; - uint16_t num_answers; - uint16_t num_authority_prs; - uint16_t num_other_prs; -}; - -struct mg_dns_resource_record *mg_dns_next_record( - struct mg_dns_message *msg, int query, - struct mg_dns_resource_record *prev) { - struct mg_dns_resource_record *rr; - - for (rr = (prev == NULL ? msg->answers : prev + 1); - rr - msg->answers < msg->num_answers; rr++) { - if (rr->rtype == query) { - return rr; - } - } - return NULL; -} - -int mg_dns_parse_record_data(struct mg_dns_message *msg, - struct mg_dns_resource_record *rr, void *data, - size_t data_len) { - switch (rr->rtype) { - case MG_DNS_A_RECORD: - if (data_len < sizeof(struct in_addr)) { - return -1; - } - if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) { - return -1; - } - memcpy(data, rr->rdata.p, data_len); - return 0; -#if MG_ENABLE_IPV6 - case MG_DNS_AAAA_RECORD: - if (data_len < sizeof(struct in6_addr)) { - return -1; /* LCOV_EXCL_LINE */ - } - memcpy(data, rr->rdata.p, data_len); - return 0; -#endif - case MG_DNS_CNAME_RECORD: - mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len); - return 0; - } - - return -1; -} - -int mg_dns_insert_header(struct mbuf *io, size_t pos, - struct mg_dns_message *msg) { - struct mg_dns_header header; - - memset(&header, 0, sizeof(header)); - header.transaction_id = msg->transaction_id; - header.flags = htons(msg->flags); - header.num_questions = htons(msg->num_questions); - header.num_answers = htons(msg->num_answers); - - return mbuf_insert(io, pos, &header, sizeof(header)); -} - -int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) { - unsigned char *begin, *end; - struct mg_dns_resource_record *last_q; - if (msg->num_questions <= 0) return 0; - begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header); - last_q = &msg->questions[msg->num_questions - 1]; - end = (unsigned char *) last_q->name.p + last_q->name.len + 4; - return mbuf_append(io, begin, end - begin); -} - -int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) { - const char *s; - unsigned char n; - size_t pos = io->len; - - do { - if ((s = strchr(name, '.')) == NULL) { - s = name + len; - } - - if (s - name > 127) { - return -1; /* TODO(mkm) cover */ - } - n = s - name; /* chunk length */ - mbuf_append(io, &n, 1); /* send length */ - mbuf_append(io, name, n); - - if (*s == '.') { - n++; - } - - name += n; - len -= n; - } while (*s != '\0'); - mbuf_append(io, "\0", 1); /* Mark end of host name */ - - return io->len - pos; -} - -int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, - const char *name, size_t nlen, const void *rdata, - size_t rlen) { - size_t pos = io->len; - uint16_t u16; - uint32_t u32; - - if (rr->kind == MG_DNS_INVALID_RECORD) { - return -1; /* LCOV_EXCL_LINE */ - } - - if (mg_dns_encode_name(io, name, nlen) == -1) { - return -1; - } - - u16 = htons(rr->rtype); - mbuf_append(io, &u16, 2); - u16 = htons(rr->rclass); - mbuf_append(io, &u16, 2); - - if (rr->kind == MG_DNS_ANSWER) { - u32 = htonl(rr->ttl); - mbuf_append(io, &u32, 4); - - if (rr->rtype == MG_DNS_CNAME_RECORD) { - int clen; - /* fill size after encoding */ - size_t off = io->len; - mbuf_append(io, &u16, 2); - if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) { - return -1; - } - u16 = clen; - io->buf[off] = u16 >> 8; - io->buf[off + 1] = u16 & 0xff; - } else { - u16 = htons((uint16_t) rlen); - mbuf_append(io, &u16, 2); - mbuf_append(io, rdata, rlen); - } - } - - return io->len - pos; -} - -void mg_send_dns_query(struct mg_connection *nc, const char *name, - int query_type) { - struct mg_dns_message *msg = - (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg)); - struct mbuf pkt; - struct mg_dns_resource_record *rr = &msg->questions[0]; - - DBG(("%s %d", name, query_type)); - - mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */); - - msg->transaction_id = ++mg_dns_tid; - msg->flags = 0x100; - msg->num_questions = 1; - - mg_dns_insert_header(&pkt, 0, msg); - - rr->rtype = query_type; - rr->rclass = 1; /* Class: inet */ - rr->kind = MG_DNS_QUESTION; - - if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) { - /* TODO(mkm): return an error code */ - goto cleanup; /* LCOV_EXCL_LINE */ - } - - /* TCP DNS requires messages to be prefixed with len */ - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) pkt.len); - mbuf_insert(&pkt, 0, &len, 2); - } - - mg_send(nc, pkt.buf, pkt.len); - mbuf_free(&pkt); - -cleanup: - MG_FREE(msg); -} - -static unsigned char *mg_parse_dns_resource_record( - unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, - int reply) { - unsigned char *name = data; - int chunk_len, data_len; - - while (data < end && (chunk_len = *data)) { - if (((unsigned char *) data)[0] & 0xc0) { - data += 1; - break; - } - data += chunk_len + 1; - } - - if (data > end - 5) { - return NULL; - } - - rr->name.p = (char *) name; - rr->name.len = data - name + 1; - data++; - - rr->rtype = data[0] << 8 | data[1]; - data += 2; - - rr->rclass = data[0] << 8 | data[1]; - data += 2; - - rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION; - if (reply) { - if (data >= end - 6) { - return NULL; - } - - rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 | - data[2] << 8 | data[3]; - data += 4; - - data_len = *data << 8 | *(data + 1); - data += 2; - - rr->rdata.p = (char *) data; - rr->rdata.len = data_len; - data += data_len; - } - return data; -} - -int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) { - struct mg_dns_header *header = (struct mg_dns_header *) buf; - unsigned char *data = (unsigned char *) buf + sizeof(*header); - unsigned char *end = (unsigned char *) buf + len; - int i; - - memset(msg, 0, sizeof(*msg)); - msg->pkt.p = buf; - msg->pkt.len = len; - - if (len < (int) sizeof(*header)) return -1; - - msg->transaction_id = header->transaction_id; - msg->flags = ntohs(header->flags); - msg->num_questions = ntohs(header->num_questions); - if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) { - msg->num_questions = (int) ARRAY_SIZE(msg->questions); - } - msg->num_answers = ntohs(header->num_answers); - if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) { - msg->num_answers = (int) ARRAY_SIZE(msg->answers); - } - - for (i = 0; i < msg->num_questions; i++) { - data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0); - if (data == NULL) return -1; - } - - for (i = 0; i < msg->num_answers; i++) { - data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1); - if (data == NULL) return -1; - } - - return 0; -} - -size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, - char *dst, int dst_len) { - int chunk_len, num_ptrs = 0; - char *old_dst = dst; - const unsigned char *data = (unsigned char *) name->p; - const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len; - - if (data >= end) { - return 0; - } - - while ((chunk_len = *data++)) { - int leeway = dst_len - (dst - old_dst); - if (data >= end) { - return 0; - } - - if ((chunk_len & 0xc0) == 0xc0) { - uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0]; - if (off >= msg->pkt.len) { - return 0; - } - /* Basic circular loop avoidance: allow up to 16 pointer hops. */ - if (++num_ptrs > 15) { - return 0; - } - data = (unsigned char *) msg->pkt.p + off; - continue; - } - if (chunk_len > 63) { - return 0; - } - if (chunk_len > leeway) { - chunk_len = leeway; - } - - if (data + chunk_len >= end) { - return 0; - } - - memcpy(dst, data, chunk_len); - data += chunk_len; - dst += chunk_len; - leeway -= chunk_len; - if (leeway == 0) { - return dst - old_dst; - } - *dst++ = '.'; - } - - if (dst != old_dst) { - *--dst = 0; - } - return dst - old_dst; -} - -static void dns_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_dns_message msg; - - /* Pass low-level events to the user handler */ - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: - if (!(nc->flags & MG_F_UDP)) { - mbuf_remove(&nc->recv_mbuf, 2); - } - if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) { - /* reply + recursion allowed + format error */ - memset(&msg, 0, sizeof(msg)); - msg.flags = 0x8081; - mg_dns_insert_header(io, 0, &msg); - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) io->len); - mbuf_insert(io, 0, &len, 2); - } - mg_send(nc, io->buf, io->len); - } else { - /* Call user handler with parsed message */ - nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data)); - } - mbuf_remove(io, io->len); - break; - } -} - -void mg_set_protocol_dns(struct mg_connection *nc) { - nc->proto_handler = dns_handler; -} - -#endif /* MG_ENABLE_DNS */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_dns_server.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_DNS_SERVER - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "dns-server.h" */ - -struct mg_dns_reply mg_dns_create_reply(struct mbuf *io, - struct mg_dns_message *msg) { - struct mg_dns_reply rep; - rep.msg = msg; - rep.io = io; - rep.start = io->len; - - /* reply + recursion allowed */ - msg->flags |= 0x8080; - mg_dns_copy_questions(io, msg); - - msg->num_answers = 0; - return rep; -} - -void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) { - size_t sent = r->io->len - r->start; - mg_dns_insert_header(r->io, r->start, r->msg); - if (!(nc->flags & MG_F_UDP)) { - uint16_t len = htons((uint16_t) sent); - mbuf_insert(r->io, r->start, &len, 2); - } - - if (&nc->send_mbuf != r->io) { - mg_send(nc, r->io->buf + r->start, r->io->len - r->start); - r->io->len = r->start; - } -} - -int mg_dns_reply_record(struct mg_dns_reply *reply, - struct mg_dns_resource_record *question, - const char *name, int rtype, int ttl, const void *rdata, - size_t rdata_len) { - struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg; - char rname[512]; - struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers]; - if (msg->num_answers >= MG_MAX_DNS_ANSWERS) { - return -1; /* LCOV_EXCL_LINE */ - } - - if (name == NULL) { - name = rname; - rname[511] = 0; - mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1); - } - - *ans = *question; - ans->kind = MG_DNS_ANSWER; - ans->rtype = rtype; - ans->ttl = ttl; - - if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata, - rdata_len) == -1) { - return -1; /* LCOV_EXCL_LINE */ - }; - - msg->num_answers++; - return 0; -} - -#endif /* MG_ENABLE_DNS_SERVER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_resolv.c" -#endif -/* - * Copyright (c) 2014 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_ASYNC_RESOLVER - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_resolv.h" */ - -#ifndef MG_DEFAULT_NAMESERVER -#define MG_DEFAULT_NAMESERVER "8.8.8.8" -#endif - -struct mg_resolve_async_request { - char name[1024]; - int query; - mg_resolve_callback_t callback; - void *data; - time_t timeout; - int max_retries; - enum mg_resolve_err err; - - /* state */ - time_t last_time; - int retries; -}; - -/* - * Find what nameserver to use. - * - * Return 0 if OK, -1 if error - */ -static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) { - int ret = -1; - -#ifdef _WIN32 - int i; - LONG err; - HKEY hKey, hSub; - wchar_t subkey[512], value[128], - *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces"; - - if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) != - ERROR_SUCCESS) { - fprintf(stderr, "cannot open reg key %S: %ld\n", key, err); - ret = -1; - } else { - for (ret = -1, i = 0; 1; i++) { - DWORD subkey_size = sizeof(subkey), type, len = sizeof(value); - if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL, - NULL) != ERROR_SUCCESS) { - break; - } - if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS && - ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value, - &len) == ERROR_SUCCESS && - value[0] != '\0') || - (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value, - &len) == ERROR_SUCCESS && - value[0] != '\0'))) { - /* - * See https://github.com/cesanta/mongoose/issues/176 - * The value taken from the registry can be empty, a single - * IP address, or multiple IP addresses separated by comma. - * If it's empty, check the next interface. - * If it's multiple IP addresses, take the first one. - */ - wchar_t *comma = wcschr(value, ','); - if (comma != NULL) { - *comma = '\0'; - } - /* %S will convert wchar_t -> char */ - snprintf(name, name_len, "%S", value); - ret = 0; - RegCloseKey(hSub); - break; - } - } - RegCloseKey(hKey); - } -#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME) - FILE *fp; - char line[512]; - - if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) { - ret = -1; - } else { - /* Try to figure out what nameserver to use */ - for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) { - unsigned int a, b, c, d; - if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) { - snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d); - ret = 0; - break; - } - } - (void) fclose(fp); - } -#else - snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER); -#endif /* _WIN32 */ - - return ret; -} - -int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) { -#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME) - /* TODO(mkm) cache /etc/hosts */ - FILE *fp; - char line[1024]; - char *p; - char alias[256]; - unsigned int a, b, c, d; - int len = 0; - - if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) { - return -1; - } - - for (; fgets(line, sizeof(line), fp) != NULL;) { - if (line[0] == '#') continue; - - if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) { - /* TODO(mkm): handle ipv6 */ - continue; - } - for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) { - if (strcmp(alias, name) == 0) { - usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d); - fclose(fp); - return 0; - } - } - } - - fclose(fp); -#else - (void) name; - (void) usa; -#endif - - return -1; -} - -static void mg_resolve_async_eh(struct mg_connection *nc, int ev, - void *data MG_UD_ARG(void *user_data)) { - time_t now = (time_t) mg_time(); - struct mg_resolve_async_request *req; - struct mg_dns_message *msg; - int first = 0; -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = nc->user_data; -#endif - - if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, user_data)); - - req = (struct mg_resolve_async_request *) user_data; - - if (req == NULL) { - return; - } - - switch (ev) { - case MG_EV_CONNECT: - /* don't depend on timer not being at epoch for sending out first req */ - first = 1; - /* fallthrough */ - case MG_EV_POLL: - if (req->retries > req->max_retries) { - req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - } - if (first || now - req->last_time >= req->timeout) { - mg_send_dns_query(nc, req->name, req->query); - req->last_time = now; - req->retries++; - } - break; - case MG_EV_RECV: - msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg)); - if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 && - msg->num_answers > 0) { - req->callback(msg, req->data, MG_RESOLVE_OK); - nc->user_data = NULL; - MG_FREE(req); - } else { - req->err = MG_RESOLVE_NO_ANSWERS; - } - MG_FREE(msg); - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_SEND: - /* - * If a send error occurs, prevent closing of the connection by the core. - * We will retry after timeout. - */ - nc->flags &= ~MG_F_CLOSE_IMMEDIATELY; - mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len); - break; - case MG_EV_TIMER: - req->err = MG_RESOLVE_TIMEOUT; - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - /* If we got here with request still not done, fire an error callback. */ - if (req != NULL) { - char addr[32]; - mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP); -#ifdef MG_LOG_DNS_FAILURES - LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr)); -#endif - req->callback(NULL, req->data, req->err); - nc->user_data = NULL; - MG_FREE(req); - } - break; - } -} - -int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data) { - struct mg_resolve_async_opts opts; - memset(&opts, 0, sizeof(opts)); - return mg_resolve_async_opt(mgr, name, query, cb, data, opts); -} - -int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, - mg_resolve_callback_t cb, void *data, - struct mg_resolve_async_opts opts) { - struct mg_resolve_async_request *req; - struct mg_connection *dns_nc; - const char *nameserver = opts.nameserver; - char dns_server_buff[17], nameserver_url[26]; - - if (nameserver == NULL) { - nameserver = mgr->nameserver; - } - - DBG(("%s %d %p", name, query, opts.dns_conn)); - - /* resolve with DNS */ - req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req)); - if (req == NULL) { - return -1; - } - - strncpy(req->name, name, sizeof(req->name)); - req->name[sizeof(req->name) - 1] = '\0'; - - req->query = query; - req->callback = cb; - req->data = data; - /* TODO(mkm): parse defaults out of resolve.conf */ - req->max_retries = opts.max_retries ? opts.max_retries : 2; - req->timeout = opts.timeout ? opts.timeout : 5; - - /* Lazily initialize dns server */ - if (nameserver == NULL) { - if (mg_get_ip_address_of_nameserver(dns_server_buff, - sizeof(dns_server_buff)) != -1) { - nameserver = dns_server_buff; - } else { - nameserver = MG_DEFAULT_NAMESERVER; - } - } - - snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver); - - dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL)); - if (dns_nc == NULL) { - MG_FREE(req); - return -1; - } - dns_nc->user_data = req; - if (opts.dns_conn != NULL) { - *opts.dns_conn = dns_nc; - } - - return 0; -} - -void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) { - MG_FREE((char *) mgr->nameserver); - mgr->nameserver = NULL; - if (nameserver != NULL) { - mgr->nameserver = strdup(nameserver); - } -} - -#endif /* MG_ENABLE_ASYNC_RESOLVER */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_coap.c" -#endif -/* - * Copyright (c) 2015 Cesanta Software Limited - * All rights reserved - * This software is dual-licensed: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 as - * published by the Free Software Foundation. For the terms of this - * license, see . - * - * You are free to use this software under the terms of the GNU General - * Public License, but WITHOUT ANY WARRANTY; without even the implied - * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * Alternatively, you can license this software under a commercial - * license, as set out in . - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_coap.h" */ - -#if MG_ENABLE_COAP - -void mg_coap_free_options(struct mg_coap_message *cm) { - while (cm->options != NULL) { - struct mg_coap_option *next = cm->options->next; - MG_FREE(cm->options); - cm->options = next; - } -} - -struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm, - uint32_t number, char *value, - size_t len) { - struct mg_coap_option *new_option = - (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option)); - - new_option->number = number; - new_option->value.p = value; - new_option->value.len = len; - - if (cm->options == NULL) { - cm->options = cm->optiomg_tail = new_option; - } else { - /* - * A very simple attention to help clients to compose options: - * CoAP wants to see options ASC ordered. - * Could be change by using sort in coap_compose - */ - if (cm->optiomg_tail->number <= new_option->number) { - /* if option is already ordered just add it */ - cm->optiomg_tail = cm->optiomg_tail->next = new_option; - } else { - /* looking for appropriate position */ - struct mg_coap_option *current_opt = cm->options; - struct mg_coap_option *prev_opt = 0; - - while (current_opt != NULL) { - if (current_opt->number > new_option->number) { - break; - } - prev_opt = current_opt; - current_opt = current_opt->next; - } - - if (prev_opt != NULL) { - prev_opt->next = new_option; - new_option->next = current_opt; - } else { - /* insert new_option to the beginning */ - new_option->next = cm->options; - cm->options = new_option; - } - } - } - - return new_option; -} - -/* - * Fills CoAP header in mg_coap_message. - * - * Helper function. - */ -static char *coap_parse_header(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - if (io->len < sizeof(uint32_t)) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; - return NULL; - } - - /* - * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version - * number. Implementations of this specification MUST set this field - * to 1 (01 binary). Other values are reserved for future versions. - * Messages with unknown version numbers MUST be silently ignored. - */ - if (((uint8_t) *ptr >> 6) != 1) { - cm->flags |= MG_COAP_IGNORE; - return NULL; - } - - /* - * Type (T): 2-bit unsigned integer. Indicates if this message is of - * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or - * Reset (3). - */ - cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4; - cm->flags |= MG_COAP_MSG_TYPE_FIELD; - - /* - * Token Length (TKL): 4-bit unsigned integer. Indicates the length of - * the variable-length Token field (0-8 bytes). Lengths 9-15 are - * reserved, MUST NOT be sent, and MUST be processed as a message - * format error. - */ - cm->token.len = *ptr & 0x0F; - if (cm->token.len > 8) { - cm->flags |= MG_COAP_FORMAT_ERROR; - return NULL; - } - - ptr++; - - /* - * Code: 8-bit unsigned integer, split into a 3-bit class (most - * significant bits) and a 5-bit detail (least significant bits) - */ - cm->code_class = (uint8_t) *ptr >> 5; - cm->code_detail = *ptr & 0x1F; - cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD); - - ptr++; - - /* Message ID: 16-bit unsigned integer in network byte order. */ - cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1); - cm->flags |= MG_COAP_MSG_ID_FIELD; - - ptr += 2; - - return ptr; -} - -/* - * Fills token information in mg_coap_message. - * - * Helper function. - */ -static char *coap_get_token(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - if (cm->token.len != 0) { - if (ptr + cm->token.len > io->buf + io->len) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; - return NULL; - } else { - cm->token.p = ptr; - ptr += cm->token.len; - cm->flags |= MG_COAP_TOKEN_FIELD; - } - } - - return ptr; -} - -/* - * Returns Option Delta or Length. - * - * Helper function. - */ -static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) { - int ret = 0; - - if (*opt_info == 13) { - /* - * 13: An 8-bit unsigned integer follows the initial byte and - * indicates the Option Delta/Length minus 13. - */ - if (ptr < io->buf + io->len) { - *opt_info = (uint8_t) *ptr + 13; - ret = sizeof(uint8_t); - } else { - ret = -1; /* LCOV_EXCL_LINE */ - } - } else if (*opt_info == 14) { - /* - * 14: A 16-bit unsigned integer in network byte order follows the - * initial byte and indicates the Option Delta/Length minus 269. - */ - if (ptr + sizeof(uint8_t) < io->buf + io->len) { - *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269; - ret = sizeof(uint16_t); - } else { - ret = -1; /* LCOV_EXCL_LINE */ - } - } - - return ret; -} - -/* - * Fills options in mg_coap_message. - * - * Helper function. - * - * General options format: - * +---------------+---------------+ - * | Option Delta | Option Length | 1 byte - * +---------------+---------------+ - * \ Option Delta (extended) \ 0-2 bytes - * +-------------------------------+ - * / Option Length (extended) \ 0-2 bytes - * +-------------------------------+ - * \ Option Value \ 0 or more bytes - * +-------------------------------+ - */ -static char *coap_get_options(char *ptr, struct mbuf *io, - struct mg_coap_message *cm) { - uint16_t prev_opt = 0; - - if (ptr == io->buf + io->len) { - /* end of packet, ok */ - return NULL; - } - - /* 0xFF is payload marker */ - while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) { - uint16_t option_delta, option_lenght; - int optinfo_len; - - /* Option Delta: 4-bit unsigned integer */ - option_delta = ((uint8_t) *ptr & 0xF0) >> 4; - /* Option Length: 4-bit unsigned integer */ - option_lenght = *ptr & 0x0F; - - if (option_delta == 15 || option_lenght == 15) { - /* - * 15: Reserved for future use. If the field is set to this value, - * it MUST be processed as a message format error - */ - cm->flags |= MG_COAP_FORMAT_ERROR; - break; - } - - ptr++; - - /* check for extended option delta */ - optinfo_len = coap_get_ext_opt(ptr, io, &option_delta); - if (optinfo_len == -1) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += optinfo_len; - - /* check or extended option lenght */ - optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght); - if (optinfo_len == -1) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += optinfo_len; - - /* - * Instead of specifying the Option Number directly, the instances MUST - * appear in order of their Option Numbers and a delta encoding is used - * between them. - */ - option_delta += prev_opt; - - mg_coap_add_option(cm, option_delta, ptr, option_lenght); - - prev_opt = option_delta; - - if (ptr + option_lenght > io->buf + io->len) { - cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */ - break; /* LCOV_EXCL_LINE */ - } - - ptr += option_lenght; - } - - if ((cm->flags & MG_COAP_ERROR) != 0) { - mg_coap_free_options(cm); - return NULL; - } - - cm->flags |= MG_COAP_OPTIOMG_FIELD; - - if (ptr == io->buf + io->len) { - /* end of packet, ok */ - return NULL; - } - - ptr++; - - return ptr; -} - -uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) { - char *ptr; - - memset(cm, 0, sizeof(*cm)); - - if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) { - return cm->flags; - } - - if ((ptr = coap_get_token(ptr, io, cm)) == NULL) { - return cm->flags; - } - - if ((ptr = coap_get_options(ptr, io, cm)) == NULL) { - return cm->flags; - } - - /* the rest is payload */ - cm->payload.len = io->len - (ptr - io->buf); - if (cm->payload.len != 0) { - cm->payload.p = ptr; - cm->flags |= MG_COAP_PAYLOAD_FIELD; - } - - return cm->flags; -} - -/* - * Calculates extended size of given Opt Number/Length in coap message. - * - * Helper function. - */ -static size_t coap_get_ext_opt_size(uint32_t value) { - int ret = 0; - - if (value >= 13 && value <= 0xFF + 13) { - ret = sizeof(uint8_t); - } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { - ret = sizeof(uint16_t); - } - - return ret; -} - -/* - * Splits given Opt Number/Length into base and ext values. - * - * Helper function. - */ -static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) { - int ret = 0; - - if (value < 13) { - *base = value; - } else if (value >= 13 && value <= 0xFF + 13) { - *base = 13; - *ext = value - 13; - ret = sizeof(uint8_t); - } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) { - *base = 14; - *ext = value - 269; - ret = sizeof(uint16_t); - } - - return ret; -} - -/* - * Puts uint16_t (in network order) into given char stream. - * - * Helper function. - */ -static char *coap_add_uint16(char *ptr, uint16_t val) { - *ptr = val >> 8; - ptr++; - *ptr = val & 0x00FF; - ptr++; - return ptr; -} - -/* - * Puts extended value of Opt Number/Length into given char stream. - * - * Helper function. - */ -static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) { - if (len == sizeof(uint8_t)) { - *ptr = (char) val; - ptr++; - } else if (len == sizeof(uint16_t)) { - ptr = coap_add_uint16(ptr, val); - } - - return ptr; -} - -/* - * Verifies given mg_coap_message and calculates message size for it. - * - * Helper function. - */ -static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm, - size_t *len) { - struct mg_coap_option *opt; - uint32_t prev_opt_number; - - *len = 4; /* header */ - if (cm->msg_type > MG_COAP_MSG_MAX) { - return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD; - } - if (cm->token.len > 8) { - return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD; - } - if (cm->code_class > 7) { - return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD; - } - if (cm->code_detail > 31) { - return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD; - } - - *len += cm->token.len; - if (cm->payload.len != 0) { - *len += cm->payload.len + 1; /* ... + 1; add payload marker */ - } - - opt = cm->options; - prev_opt_number = 0; - while (opt != NULL) { - *len += 1; /* basic delta/length */ - *len += coap_get_ext_opt_size(opt->number - prev_opt_number); - *len += coap_get_ext_opt_size((uint32_t) opt->value.len); - /* - * Current implementation performs check if - * option_number > previous option_number and produces an error - * TODO(alashkin): write design doc with limitations - * May be resorting is more suitable solution. - */ - if ((opt->next != NULL && opt->number > opt->next->number) || - opt->value.len > 0xFFFF + 269 || - opt->number - prev_opt_number > 0xFFFF + 269) { - return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD; - } - *len += opt->value.len; - prev_opt_number = opt->number; - opt = opt->next; - } - - return 0; -} - -uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) { - struct mg_coap_option *opt; - uint32_t res, prev_opt_number; - size_t prev_io_len, packet_size; - char *ptr; - - res = coap_calculate_packet_size(cm, &packet_size); - if (res != 0) { - return res; - } - - /* saving previous lenght to handle non-empty mbuf */ - prev_io_len = io->len; - if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR; - ptr = io->buf + prev_io_len; - - /* - * since cm is verified, it is possible to use bits shift operator - * without additional zeroing of unused bits - */ - - /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */ - *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len); - ptr++; - - /* code class: 3 bits, code detail: 5 bits */ - *ptr = (cm->code_class << 5) | (cm->code_detail); - ptr++; - - ptr = coap_add_uint16(ptr, cm->msg_id); - - if (cm->token.len != 0) { - memcpy(ptr, cm->token.p, cm->token.len); - ptr += cm->token.len; - } - - opt = cm->options; - prev_opt_number = 0; - while (opt != NULL) { - uint8_t delta_base = 0, length_base = 0; - uint16_t delta_ext = 0, length_ext = 0; - - size_t opt_delta_len = - coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext); - size_t opt_lenght_len = - coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext); - - *ptr = (delta_base << 4) | length_base; - ptr++; - - ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len); - ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len); - - if (opt->value.len != 0) { - memcpy(ptr, opt->value.p, opt->value.len); - ptr += opt->value.len; - } - - prev_opt_number = opt->number; - opt = opt->next; - } - - if (cm->payload.len != 0) { - *ptr = (char) -1; - ptr++; - memcpy(ptr, cm->payload.p, cm->payload.len); - } - - return 0; -} - -uint32_t mg_coap_send_message(struct mg_connection *nc, - struct mg_coap_message *cm) { - struct mbuf packet_out; - uint32_t compose_res; - - mbuf_init(&packet_out, 0); - compose_res = mg_coap_compose(cm, &packet_out); - if (compose_res != 0) { - return compose_res; /* LCOV_EXCL_LINE */ - } - - mg_send(nc, packet_out.buf, (int) packet_out.len); - mbuf_free(&packet_out); - - return 0; -} - -uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) { - struct mg_coap_message cm; - memset(&cm, 0, sizeof(cm)); - cm.msg_type = MG_COAP_MSG_ACK; - cm.msg_id = msg_id; - - return mg_coap_send_message(nc, &cm); -} - -static void coap_handler(struct mg_connection *nc, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &nc->recv_mbuf; - struct mg_coap_message cm; - uint32_t parse_res; - - memset(&cm, 0, sizeof(cm)); - - nc->handler(nc, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: - parse_res = mg_coap_parse(io, &cm); - if ((parse_res & MG_COAP_IGNORE) == 0) { - if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) { - /* - * Since we support UDP only - * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR - */ - cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */ - } /* LCOV_EXCL_LINE */ - nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, - &cm MG_UD_ARG(user_data)); - } - - mg_coap_free_options(&cm); - mbuf_remove(io, io->len); - break; - } -} -/* - * Attach built-in CoAP event handler to the given connection. - * - * The user-defined event handler will receive following extra events: - * - * - MG_EV_COAP_CON - * - MG_EV_COAP_NOC - * - MG_EV_COAP_ACK - * - MG_EV_COAP_RST - */ -int mg_set_protocol_coap(struct mg_connection *nc) { - /* supports UDP only */ - if ((nc->flags & MG_F_UDP) == 0) { - return -1; - } - - nc->proto_handler = coap_handler; - - return 0; -} - -#endif /* MG_ENABLE_COAP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_sntp.c" -#endif -/* - * Copyright (c) 2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "mg_internal.h" */ -/* Amalgamated: #include "mg_sntp.h" */ -/* Amalgamated: #include "mg_util.h" */ - -#if MG_ENABLE_SNTP - -#define SNTP_TIME_OFFSET 2208988800 - -#ifndef SNTP_TIMEOUT -#define SNTP_TIMEOUT 10 -#endif - -#ifndef SNTP_ATTEMPTS -#define SNTP_ATTEMPTS 3 -#endif - -static uint64_t mg_get_sec(uint64_t val) { - return (val & 0xFFFFFFFF00000000) >> 32; -} - -static uint64_t mg_get_usec(uint64_t val) { - uint64_t tmp = (val & 0x00000000FFFFFFFF); - tmp *= 1000000; - tmp >>= 32; - return tmp; -} - -static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) { - uint64_t tmp; - tmp = mg_get_sec(val); - tmp -= SNTP_TIME_OFFSET; - tv->tv_sec = tmp; - tv->tv_usec = mg_get_usec(val); -} - -static void mg_get_ntp_ts(const char *ntp, uint64_t *val) { - uint32_t tmp; - memcpy(&tmp, ntp, sizeof(tmp)); - tmp = ntohl(tmp); - *val = (uint64_t) tmp << 32; - memcpy(&tmp, ntp + 4, sizeof(tmp)); - tmp = ntohl(tmp); - *val |= tmp; -} - -void mg_sntp_send_request(struct mg_connection *c) { - uint8_t buf[48] = {0}; - /* - * header - 8 bit: - * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version), - * mode (3 bit) - 3 (client) - */ - buf[0] = (3 << 6) | (4 << 3) | 3; - -/* - * Next fields should be empty in client request - * stratum, 8 bit - * poll interval, 8 bit - * rrecision, 8 bit - * root delay, 32 bit - * root dispersion, 32 bit - * ref id, 32 bit - * ref timestamp, 64 bit - * originate Timestamp, 64 bit - * receive Timestamp, 64 bit -*/ - -/* - * convert time to sntp format (sntp starts from 00:00:00 01.01.1900) - * according to rfc868 it is 2208988800L sec - * this information is used to correct roundtrip delay - * but if local clock is absolutely broken (and doesn't work even - * as simple timer), it is better to disable it -*/ -#ifndef MG_SNTP_NO_DELAY_CORRECTION - uint32_t sec; - sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET)); - memcpy(&buf[40], &sec, sizeof(sec)); -#endif - - mg_send(c, buf, sizeof(buf)); -} - -#ifndef MG_SNTP_NO_DELAY_CORRECTION -static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) { - /* roundloop delay = (T4 - T1) - (T3 - T2) */ - uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) - - (mg_get_sec(t1) * 1000000 + mg_get_usec(t1)); - uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) - - (mg_get_sec(t2) * 1000000 + mg_get_usec(t2)); - - return (d1 > d2) ? d1 - d2 : 0; -} -#endif - -MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len, - struct mg_sntp_message *msg) { - uint8_t hdr; - uint64_t trsm_ts_T3, delay = 0; - int mode; - struct timeval tv; - - if (len < 48) { - return -1; - } - - hdr = buf[0]; - - if ((hdr & 0x38) >> 3 != 4) { - /* Wrong version */ - return -1; - } - - mode = hdr & 0x7; - if (mode != 4 && mode != 5) { - /* Not a server reply */ - return -1; - } - - memset(msg, 0, sizeof(*msg)); - - msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */ - - mg_get_ntp_ts(&buf[40], &trsm_ts_T3); - -#ifndef MG_SNTP_NO_DELAY_CORRECTION - { - uint64_t orig_ts_T1, recv_ts_T2; - mg_get_ntp_ts(&buf[24], &orig_ts_T1); - mg_get_ntp_ts(&buf[32], &recv_ts_T2); - delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3); - } -#endif - - mg_ntp_to_tv(trsm_ts_T3, &tv); - - msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0); - - return 0; -} - -static void mg_sntp_handler(struct mg_connection *c, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { - struct mbuf *io = &c->recv_mbuf; - struct mg_sntp_message msg; - - c->handler(c, ev, ev_data MG_UD_ARG(user_data)); - - switch (ev) { - case MG_EV_RECV: { - if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) { - DBG(("Invalid SNTP packet received (%d)", (int) io->len)); - c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data)); - } else { - c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data)); - } - - mbuf_remove(io, io->len); - break; - } - } -} - -int mg_set_protocol_sntp(struct mg_connection *c) { - if ((c->flags & MG_F_UDP) == 0) { - return -1; - } - - c->proto_handler = mg_sntp_handler; - - return 0; -} - -struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, - MG_CB(mg_event_handler_t event_handler, - void *user_data), - const char *sntp_server_name) { - struct mg_connection *c = NULL; - char url[100], *p_url = url; - const char *proto = "", *port = "", *tmp; - - /* If port is not specified, use default (123) */ - tmp = strchr(sntp_server_name, ':'); - if (tmp != NULL && *(tmp + 1) == '/') { - tmp = strchr(tmp + 1, ':'); - } - - if (tmp == NULL) { - port = ":123"; - } - - /* Add udp:// if needed */ - if (strncmp(sntp_server_name, "udp://", 6) != 0) { - proto = "udp://"; - } - - mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port); - - c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data)); - - if (c == NULL) { - goto cleanup; - } - - mg_set_protocol_sntp(c); - -cleanup: - if (p_url != url) { - MG_FREE(p_url); - } - - return c; -} - -struct sntp_data { - mg_event_handler_t hander; - int count; -}; - -static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev, - void *ev_data MG_UD_ARG(void *user_data)) { -#if !MG_ENABLE_CALLBACK_USERDATA - void *user_data = c->user_data; -#endif - struct sntp_data *sd = (struct sntp_data *) user_data; - - switch (ev) { - case MG_EV_CONNECT: - if (*(int *) ev_data != 0) { - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - break; - } - /* fallthrough */ - case MG_EV_TIMER: - if (sd->count <= SNTP_ATTEMPTS) { - mg_sntp_send_request(c); - mg_set_timer(c, mg_time() + 10); - sd->count++; - } else { - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - } - break; - case MG_SNTP_MALFORMED_REPLY: - mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_SNTP_REPLY: - mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data); - c->flags |= MG_F_CLOSE_IMMEDIATELY; - break; - case MG_EV_CLOSE: - MG_FREE(user_data); - c->user_data = NULL; - break; - } -} - -struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr, - mg_event_handler_t event_handler, - const char *sntp_server_name) { - struct mg_connection *c; - struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd)); - if (sd == NULL) { - return NULL; - } - - c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd), - sntp_server_name); - if (c == NULL) { - MG_FREE(sd); - return NULL; - } - - sd->hander = event_handler; -#if !MG_ENABLE_CALLBACK_USERDATA - c->user_data = sd; -#endif - - return c; -} - -#endif /* MG_ENABLE_SNTP */ -#ifdef MG_MODULE_LINES -#line 1 "mongoose/src/mg_socks.c" -#endif -/* - * Copyright (c) 2017 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SOCKS - -/* Amalgamated: #include "mg_socks.h" */ -/* Amalgamated: #include "mg_internal.h" */ - -/* - * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake - * - * +----+----------+----------+ - * |VER | NMETHODS | METHODS | - * +----+----------+----------+ - * | 1 | 1 | 1 to 255 | - * +----+----------+----------+ - */ -static void mg_socks5_handshake(struct mg_connection *c) { - struct mbuf *r = &c->recv_mbuf; - if (r->buf[0] != MG_SOCKS_VERSION) { - c->flags |= MG_F_CLOSE_IMMEDIATELY; - } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) { - /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */ - unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE}; - int i; - for (i = 2; i < r->buf[1] + 2; i++) { - /* TODO(lsm): support other auth methods */ - if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i]; - } - mbuf_remove(r, 2 + r->buf[1]); - mg_send(c, reply, sizeof(reply)); - c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */ - } -} - -static void disband(struct mg_connection *c) { - struct mg_connection *c2 = (struct mg_connection *) c->user_data; - if (c2 != NULL) { - c2->flags |= MG_F_SEND_AND_CLOSE; - c2->user_data = NULL; - } - c->flags |= MG_F_SEND_AND_CLOSE; - c->user_data = NULL; -} - -static void relay_data(struct mg_connection *c) { - struct mg_connection *c2 = (struct mg_connection *) c->user_data; - if (c2 != NULL) { - mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len); - mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len); - } else { - c->flags |= MG_F_SEND_AND_CLOSE; - } -} - -static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_CLOSE) { - disband(c); - } else if (ev == MG_EV_RECV) { - relay_data(c); - } else if (ev == MG_EV_CONNECT) { - int res = *(int *) ev_data; - if (res != 0) LOG(LL_ERROR, ("connect error: %d", res)); - } -} - -static void mg_socks5_connect(struct mg_connection *c, const char *addr) { - struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler); - serv->user_data = c; - c->user_data = serv; -} - -/* - * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4 - * - * +----+-----+-------+------+----------+----------+ - * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | - * +----+-----+-------+------+----------+----------+ - * | 1 | 1 | X'00' | 1 | Variable | 2 | - * +----+-----+-------+------+----------+----------+ - */ -static void mg_socks5_handle_request(struct mg_connection *c) { - struct mbuf *r = &c->recv_mbuf; - unsigned char *p = (unsigned char *) r->buf; - unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS; - int ver, cmd, atyp; - char addr[300]; - - if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */ - ver = p[0]; - cmd = p[1]; - atyp = p[3]; - - /* TODO(lsm): support other commands */ - if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) { - reply = MG_SOCKS_CMD_NOT_SUPPORTED; - } else if (atyp == MG_SOCKS_ADDR_IPV4) { - addr_len = 4; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7], - p[8] << 8 | p[9]); - mg_socks5_connect(c, addr); - } else if (atyp == MG_SOCKS_ADDR_IPV6) { - addr_len = 16; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", - p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9], - p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15], - p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]); - mg_socks5_connect(c, addr); - } else if (atyp == MG_SOCKS_ADDR_DOMAIN) { - addr_len = p[4] + 1; - if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */ - snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5, - p[4 + addr_len] << 8 | p[4 + addr_len + 1]); - mg_socks5_connect(c, addr); - } else { - reply = MG_SOCKS_ADDR_NOT_SUPPORTED; - } - - /* - * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5 - * - * +----+-----+-------+------+----------+----------+ - * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | - * +----+-----+-------+------+----------+----------+ - * | 1 | 1 | X'00' | 1 | Variable | 2 | - * +----+-----+-------+------+----------+----------+ - */ - { - unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0}; - mg_send(c, buf, sizeof(buf)); - } - mg_send(c, r->buf + 3, addr_len + 1 + 2); - - mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */ - c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */ -} - -static void socks_handler(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_RECV) { - if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c); - if (c->flags & MG_SOCKS_HANDSHAKE_DONE && - !(c->flags & MG_SOCKS_CONNECT_DONE)) { - mg_socks5_handle_request(c); - } - if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c); - } else if (ev == MG_EV_CLOSE) { - disband(c); - } - (void) ev_data; -} - -void mg_set_protocol_socks(struct mg_connection *c) { - c->proto_handler = socks_handler; -} -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/cc3200/cc3200_libc.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if CS_PLATFORM == CS_P_CC3200 - -/* Amalgamated: #include "common/mg_mem.h" */ -#include -#include - -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#define CONSOLE_UART UARTA0_BASE - -#ifdef __TI_COMPILER_VERSION__ -int asprintf(char **strp, const char *fmt, ...) { - va_list ap; - int len; - - *strp = MG_MALLOC(BUFSIZ); - if (*strp == NULL) return -1; - - va_start(ap, fmt); - len = vsnprintf(*strp, BUFSIZ, fmt, ap); - va_end(ap); - - if (len > 0) { - *strp = MG_REALLOC(*strp, len + 1); - if (*strp == NULL) return -1; - } - - if (len >= BUFSIZ) { - va_start(ap, fmt); - len = vsnprintf(*strp, len + 1, fmt, ap); - va_end(ap); - } - - return len; -} - -#if MG_TI_NO_HOST_INTERFACE -time_t HOSTtime() { - struct timeval tp; - gettimeofday(&tp, NULL); - return tp.tv_sec; -} -#endif - -#endif /* __TI_COMPILER_VERSION__ */ - -void fprint_str(FILE *fp, const char *str) { - while (*str != '\0') { - if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r'); - MAP_UARTCharPut(CONSOLE_UART, *str++); - } -} - -void _exit(int status) { - fprint_str(stderr, "_exit\n"); - /* cause an unaligned access exception, that will drop you into gdb */ - *(int *) 1 = status; - while (1) - ; /* avoid gcc warning because stdlib abort() has noreturn attribute */ -} - -void _not_implemented(const char *what) { - fprint_str(stderr, what); - fprint_str(stderr, " is not implemented\n"); - _exit(42); -} - -int _kill(int pid, int sig) { - (void) pid; - (void) sig; - _not_implemented("_kill"); - return -1; -} - -int _getpid() { - fprint_str(stderr, "_getpid is not implemented\n"); - return 42; -} - -int _isatty(int fd) { - /* 0, 1 and 2 are TTYs. */ - return fd < 2; -} - -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/msp432/msp432_libc.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if CS_PLATFORM == CS_P_MSP432 - -#include -#include - -int gettimeofday(struct timeval *tp, void *tzp) { - uint32_t ticks = Clock_getTicks(); - tp->tv_sec = ticks / 1000; - tp->tv_usec = (ticks % 1000) * 1000; - return 0; -} - -#endif /* CS_PLATFORM == CS_P_MSP432 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/nrf5/nrf5_libc.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \ - defined(__ARMCC_VERSION) -int gettimeofday(struct timeval *tp, void *tzp) { - /* TODO */ - tp->tv_sec = 0; - tp->tv_usec = 0; - return 0; -} -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs_slfs.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ - -#if defined(MG_FS_SLFS) - -#include -#ifndef __TI_COMPILER_VERSION__ -#include -#include -#endif - -#define MAX_OPEN_SLFS_FILES 8 - -/* Indirect libc interface - same functions, different names. */ -int fs_slfs_open(const char *pathname, int flags, mode_t mode); -int fs_slfs_close(int fd); -ssize_t fs_slfs_read(int fd, void *buf, size_t count); -ssize_t fs_slfs_write(int fd, const void *buf, size_t count); -int fs_slfs_stat(const char *pathname, struct stat *s); -int fs_slfs_fstat(int fd, struct stat *s); -off_t fs_slfs_lseek(int fd, off_t offset, int whence); -int fs_slfs_unlink(const char *filename); -int fs_slfs_rename(const char *from, const char *to); - -void fs_slfs_set_new_file_size(const char *name, size_t size); - -#endif /* defined(MG_FS_SLFS) */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs_slfs.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -/* Standard libc interface to TI SimpleLink FS. */ - -#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) - -/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */ - -#include - -#if CS_PLATFORM == CS_P_CC3200 -#include -#endif - -/* Amalgamated: #include "common/cs_dbg.h" */ -/* Amalgamated: #include "common/mg_mem.h" */ - -#if SL_MAJOR_VERSION_NUM < 2 -int slfs_open(const unsigned char *fname, uint32_t flags) { - _i32 fh; - _i32 r = sl_FsOpen(fname, flags, NULL /* token */, &fh); - return (r < 0 ? r : fh); -} -#else /* SL_MAJOR_VERSION_NUM >= 2 */ -int slfs_open(const unsigned char *fname, uint32_t flags) { - return sl_FsOpen(fname, flags, NULL /* token */); -} -#endif - -/* From sl_fs.c */ -int set_errno(int e); -const char *drop_dir(const char *fname, bool *is_slfs); - -/* - * With SLFS, you have to pre-declare max file size. Yes. Really. - * 64K should be enough for everyone. Right? - */ -#ifndef FS_SLFS_MAX_FILE_SIZE -#define FS_SLFS_MAX_FILE_SIZE (64 * 1024) -#endif - -struct sl_file_size_hint { - char *name; - size_t size; -}; - -struct sl_fd_info { - _i32 fh; - _off_t pos; - size_t size; -}; - -static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES]; -static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES]; - -static int sl_fs_to_errno(_i32 r) { - DBG(("SL error: %d", (int) r)); - switch (r) { - case SL_FS_OK: - return 0; - case SL_ERROR_FS_FILE_NAME_EXIST: - return EEXIST; - case SL_ERROR_FS_WRONG_FILE_NAME: - return EINVAL; - case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX: - case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE: - return ENOSPC; - case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM: - return ENOMEM; - case SL_ERROR_FS_FILE_NOT_EXISTS: - return ENOENT; - case SL_ERROR_FS_NOT_SUPPORTED: - return ENOTSUP; - } - return ENXIO; -} - -int fs_slfs_open(const char *pathname, int flags, mode_t mode) { - int fd; - for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) { - if (s_sl_fds[fd].fh <= 0) break; - } - if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM); - struct sl_fd_info *fi = &s_sl_fds[fd]; - - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - - _u32 am = 0; - fi->size = (size_t) -1; - int rw = (flags & 3); - size_t new_size = FS_SLFS_MAX_FILE_SIZE; - if (rw == O_RDONLY) { - SlFsFileInfo_t sl_fi; - _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); - if (r == SL_FS_OK) { - fi->size = SL_FI_FILE_SIZE(sl_fi); - } - am = SL_FS_READ; - } else { - if (!(flags & O_TRUNC) || (flags & O_APPEND)) { - // FailFS files cannot be opened for append and will be truncated - // when opened for write. - return set_errno(ENOTSUP); - } - if (flags & O_CREAT) { - size_t i; - for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { - if (s_sl_file_size_hints[i].name != NULL && - strcmp(s_sl_file_size_hints[i].name, pathname) == 0) { - new_size = s_sl_file_size_hints[i].size; - MG_FREE(s_sl_file_size_hints[i].name); - s_sl_file_size_hints[i].name = NULL; - break; - } - } - am = FS_MODE_OPEN_CREATE(new_size, 0); - } else { - am = SL_FS_WRITE; - } - } - fi->fh = slfs_open((_u8 *) pathname, am); - LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x) sz %u = %d", pathname, (int) am, - (unsigned int) new_size, (int) fi->fh)); - int r; - if (fi->fh >= 0) { - fi->pos = 0; - r = fd; - } else { - r = set_errno(sl_fs_to_errno(fi->fh)); - } - return r; -} - -int fs_slfs_close(int fd) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0); - LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r)); - s_sl_fds[fd].fh = -1; - return set_errno(sl_fs_to_errno(r)); -} - -ssize_t fs_slfs_read(int fd, void *buf, size_t count) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE. - */ - if (fi->pos == fi->size) return 0; - _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count); - DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, - (int) r)); - if (r >= 0) { - fi->pos += r; - return r; - } - return set_errno(sl_fs_to_errno(r)); -} - -ssize_t fs_slfs_write(int fd, const void *buf, size_t count) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count); - DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count, - (int) r)); - if (r >= 0) { - fi->pos += r; - return r; - } - return set_errno(sl_fs_to_errno(r)); -} - -int fs_slfs_stat(const char *pathname, struct stat *s) { - SlFsFileInfo_t sl_fi; - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi); - if (r == SL_FS_OK) { - s->st_mode = S_IFREG | 0666; - s->st_nlink = 1; - s->st_size = SL_FI_FILE_SIZE(sl_fi); - return 0; - } - return set_errno(sl_fs_to_errno(r)); -} - -int fs_slfs_fstat(int fd, struct stat *s) { - struct sl_fd_info *fi = &s_sl_fds[fd]; - if (fi->fh <= 0) return set_errno(EBADF); - s->st_mode = 0666; - s->st_mode = S_IFREG | 0666; - s->st_nlink = 1; - s->st_size = fi->size; - return 0; -} - -off_t fs_slfs_lseek(int fd, off_t offset, int whence) { - if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF); - switch (whence) { - case SEEK_SET: - s_sl_fds[fd].pos = offset; - break; - case SEEK_CUR: - s_sl_fds[fd].pos += offset; - break; - case SEEK_END: - return set_errno(ENOTSUP); - } - return 0; -} - -int fs_slfs_unlink(const char *pathname) { - /* - * Apply path manipulations again, in case we got here directly - * (via TI libc's "add_device"). - */ - pathname = drop_dir(pathname, NULL); - return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0))); -} - -int fs_slfs_rename(const char *from, const char *to) { - return set_errno(ENOTSUP); -} - -void fs_slfs_set_new_file_size(const char *name, size_t size) { - int i; - for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) { - if (s_sl_file_size_hints[i].name == NULL) { - DBG(("File size hint: %s %d", name, (int) size)); - s_sl_file_size_hints[i].name = strdup(name); - s_sl_file_size_hints[i].size = size; - break; - } - } -} - -#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_fs.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \ - (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS)) - -int set_errno(int e) { - errno = e; - return (e == 0 ? 0 : -1); -} - -const char *drop_dir(const char *fname, bool *is_slfs) { - if (is_slfs != NULL) { - *is_slfs = (strncmp(fname, "SL:", 3) == 0); - if (*is_slfs) fname += 3; - } - /* Drop "./", if any */ - if (fname[0] == '.' && fname[1] == '/') { - fname += 2; - } - /* - * Drop / if it is the only one in the path. - * This allows use of /pretend/directories but serves /file.txt as normal. - */ - if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) { - fname++; - } - return fname; -} - -#if !defined(MG_FS_NO_VFS) - -#include -#include -#include -#include -#include -#ifdef __TI_COMPILER_VERSION__ -#include -#endif - -/* Amalgamated: #include "common/cs_dbg.h" */ -/* Amalgamated: #include "common/platform.h" */ - -#ifdef CC3200_FS_SPIFFS -/* Amalgamated: #include "cc3200_fs_spiffs.h" */ -#endif - -#ifdef MG_FS_SLFS -/* Amalgamated: #include "sl_fs_slfs.h" */ -#endif - -#define NUM_SYS_FDS 3 -#define SPIFFS_FD_BASE 10 -#define SLFS_FD_BASE 100 - -#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE) -#if CS_PLATFORM == CS_P_CC3200 -#include -#include -#include -#include -#include -#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c); -#else -#define MG_UART_WRITE(fd, buf, len) -#endif /* CS_PLATFORM == CS_P_CC3200 */ -#endif /* !MG_UART_CHAR_PUT */ - -enum fd_type { - FD_INVALID, - FD_SYS, -#ifdef CC3200_FS_SPIFFS - FD_SPIFFS, -#endif -#ifdef MG_FS_SLFS - FD_SLFS -#endif -}; -static int fd_type(int fd) { - if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS; -#ifdef CC3200_FS_SPIFFS - if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) { - return FD_SPIFFS; - } -#endif -#ifdef MG_FS_SLFS - if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) { - return FD_SLFS; - } -#endif - return FD_INVALID; -} - -#if MG_TI_NO_HOST_INTERFACE -int open(const char *pathname, unsigned flags, int mode) { -#else -int _open(const char *pathname, int flags, mode_t mode) { -#endif - int fd = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - if (is_sl) { -#ifdef MG_FS_SLFS - fd = fs_slfs_open(fname, flags, mode); - if (fd >= 0) fd += SLFS_FD_BASE; -#endif - } else { -#ifdef CC3200_FS_SPIFFS - fd = fs_spiffs_open(fname, flags, mode); - if (fd >= 0) fd += SPIFFS_FD_BASE; -#endif - } - LOG(LL_DEBUG, - ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname)); - return fd; -} - -int _stat(const char *pathname, struct stat *st) { - int res = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - memset(st, 0, sizeof(*st)); - /* Simulate statting the root directory. */ - if (fname[0] == '\0' || strcmp(fname, ".") == 0) { - st->st_ino = 0; - st->st_mode = S_IFDIR | 0777; - st->st_nlink = 1; - st->st_size = 0; - return 0; - } - if (is_sl) { -#ifdef MG_FS_SLFS - res = fs_slfs_stat(fname, st); -#endif - } else { -#ifdef CC3200_FS_SPIFFS - res = fs_spiffs_stat(fname, st); -#endif - } - LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname)); - return res; -} - -#if MG_TI_NO_HOST_INTERFACE -int close(int fd) { -#else -int _close(int fd) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: - r = set_errno(EACCES); - break; -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_close(fd - SPIFFS_FD_BASE); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_close(fd - SLFS_FD_BASE); - break; -#endif - } - DBG(("close(%d) = %d", fd, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -off_t lseek(int fd, off_t offset, int whence) { -#else -off_t _lseek(int fd, off_t offset, int whence) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: - r = set_errno(ESPIPE); - break; -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence); - break; -#endif - } - DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r)); - return r; -} - -int _fstat(int fd, struct stat *s) { - int r = -1; - memset(s, 0, sizeof(*s)); - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - /* Create barely passable stats for STD{IN,OUT,ERR}. */ - memset(s, 0, sizeof(*s)); - s->st_ino = fd; - s->st_mode = S_IFCHR | 0666; - r = 0; - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_fstat(fd - SLFS_FD_BASE, s); - break; -#endif - } - DBG(("fstat(%d) = %d", fd, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -int read(int fd, char *buf, unsigned count) { -#else -ssize_t _read(int fd, void *buf, size_t count) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - if (fd != 0) { - r = set_errno(EACCES); - break; - } - /* Should we allow reading from stdin = uart? */ - r = set_errno(ENOTSUP); - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count); - break; -#endif - } - DBG(("read(%d, %u) = %d", fd, count, r)); - return r; -} - -#if MG_TI_NO_HOST_INTERFACE -int write(int fd, const char *buf, unsigned count) { -#else -ssize_t _write(int fd, const void *buf, size_t count) { -#endif - int r = -1; - switch (fd_type(fd)) { - case FD_INVALID: - r = set_errno(EBADF); - break; - case FD_SYS: { - if (fd == 0) { - r = set_errno(EACCES); - break; - } -#ifdef MG_UART_WRITE - MG_UART_WRITE(fd, buf, count); -#elif defined(MG_UART_CHAR_PUT) - { - size_t i; - for (i = 0; i < count; i++) { - const char c = ((const char *) buf)[i]; - if (c == '\n') MG_UART_CHAR_PUT(fd, '\r'); - MG_UART_CHAR_PUT(fd, c); - } - } -#endif - r = count; - break; - } -#ifdef CC3200_FS_SPIFFS - case FD_SPIFFS: - r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count); - break; -#endif -#ifdef MG_FS_SLFS - case FD_SLFS: - r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count); - break; -#endif - } - return r; -} - -/* - * On Newlib we override rename directly too, because the default - * implementation using _link and _unlink doesn't work for us. - */ -#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) -int rename(const char *frompath, const char *topath) { - int r = -1; - bool is_sl_from, is_sl_to; - const char *from = drop_dir(frompath, &is_sl_from); - const char *to = drop_dir(topath, &is_sl_to); - if (is_sl_from || is_sl_to) { - set_errno(ENOTSUP); - } else { -#ifdef CC3200_FS_SPIFFS - r = fs_spiffs_rename(from, to); -#endif - } - DBG(("rename(%s, %s) = %d", from, to, r)); - return r; -} -#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */ - -#if MG_TI_NO_HOST_INTERFACE -int unlink(const char *pathname) { -#else -int _unlink(const char *pathname) { -#endif - int r = -1; - bool is_sl; - const char *fname = drop_dir(pathname, &is_sl); - if (is_sl) { -#ifdef MG_FS_SLFS - r = fs_slfs_unlink(fname); -#endif - } else { -#ifdef CC3200_FS_SPIFFS - r = fs_spiffs_unlink(fname); -#endif - } - DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname)); - return r; -} - -#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */ -DIR *opendir(const char *dir_name) { - DIR *r = NULL; - bool is_sl; - drop_dir(dir_name, &is_sl); - if (is_sl) { - r = NULL; - set_errno(ENOTSUP); - } else { - r = fs_spiffs_opendir(dir_name); - } - DBG(("opendir(%s) = %p", dir_name, r)); - return r; -} - -struct dirent *readdir(DIR *dir) { - struct dirent *res = fs_spiffs_readdir(dir); - DBG(("readdir(%p) = %p", dir, res)); - return res; -} - -int closedir(DIR *dir) { - int res = fs_spiffs_closedir(dir); - DBG(("closedir(%p) = %d", dir, res)); - return res; -} - -int rmdir(const char *path) { - return fs_spiffs_rmdir(path); -} - -int mkdir(const char *path, mode_t mode) { - (void) path; - (void) mode; - /* for spiffs supports only root dir, which comes from mongoose as '.' */ - return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR; -} -#endif - -int sl_fs_init(void) { - int ret = 1; -#ifdef __TI_COMPILER_VERSION__ -#ifdef MG_FS_SLFS -#pragma diag_push -#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \ - */ - ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read, - fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink, - fs_slfs_rename) == 0); -#pragma diag_pop -#endif -#endif - return ret; -} - -#endif /* !defined(MG_FS_NO_VFS) */ -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \ - defined(MG_FS_SPIFFS)) */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_socket.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_NET_IF == MG_NET_IF_SIMPLELINK - -#include -#include - -/* Amalgamated: #include "common/platform.h" */ - -const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) { - int res; - struct in_addr *in = (struct in_addr *) src; - if (af != AF_INET) { - errno = ENOTSUP; - return NULL; - } - res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0), - SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2), - SL_IPV4_BYTE(in->s_addr, 3)); - return res > 0 ? dst : NULL; -} - -char *inet_ntoa(struct in_addr n) { - static char a[16]; - return (char *) inet_ntop(AF_INET, &n, a, sizeof(a)); -} - -int inet_pton(int af, const char *src, void *dst) { - uint32_t a0, a1, a2, a3; - uint8_t *db = (uint8_t *) dst; - if (af != AF_INET) { - errno = ENOTSUP; - return 0; - } - if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) { - return 0; - } - *db = a3; - *(db + 1) = a2; - *(db + 2) = a1; - *(db + 3) = a0; - return 1; -} - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_mg_task.c" -#endif -#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) - -/* Amalgamated: #include "mg_task.h" */ - -#include - -enum mg_q_msg_type { - MG_Q_MSG_CB, -}; -struct mg_q_msg { - enum mg_q_msg_type type; - void (*cb)(struct mg_mgr *mgr, void *arg); - void *arg; -}; -static OsiMsgQ_t s_mg_q; -static void mg_task(void *arg); - -bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) { - if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) { - return false; - } - if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size, - (void *) mg_init, priority, NULL) != OSI_OK) { - return false; - } - return true; -} - -static void mg_task(void *arg) { - struct mg_mgr mgr; - mg_init_cb mg_init = (mg_init_cb) arg; - mg_mgr_init(&mgr, NULL); - mg_init(&mgr); - while (1) { - struct mg_q_msg msg; - mg_mgr_poll(&mgr, 1); - if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue; - switch (msg.type) { - case MG_Q_MSG_CB: { - msg.cb(&mgr, msg.arg); - } - } - } -} - -void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) { - struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg}; - osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT); -} - -#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \ - */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_net_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ -#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ - -/* Amalgamated: #include "mongoose/src/net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_ENABLE_NET_IF_SIMPLELINK -#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK -#endif - -extern const struct mg_iface_vtable mg_simplelink_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_net_if.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */ - -#if MG_ENABLE_NET_IF_SIMPLELINK - -/* Amalgamated: #include "mongoose/src/internal.h" */ -/* Amalgamated: #include "mongoose/src/util.h" */ - -#define MG_TCP_RECV_BUFFER_SIZE 1024 -#define MG_UDP_RECV_BUFFER_SIZE 1500 - -static sock_t mg_open_listening_socket(struct mg_connection *nc, - union socket_address *sa, int type, - int proto); - -void mg_set_non_blocking_mode(sock_t sock) { - SlSockNonblocking_t opt; -#if SL_MAJOR_VERSION_NUM < 2 - opt.NonblockingEnabled = 1; -#else - opt.NonBlockingEnabled = 1; -#endif - sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt)); -} - -static int mg_is_error(int n) { - return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN); -} - -void mg_sl_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - int proto = 0; - if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; - sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto); - if (sock < 0) { - nc->err = sock; - goto out; - } - mg_sock_set(nc, sock); -#if MG_ENABLE_SSL - nc->err = sl_set_ssl_opts(sock, nc); - if (nc->err != 0) goto out; -#endif - nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin)); -out: - DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr), - ntohs(sa->sin.sin_port), nc->sock, proto, nc->err)); -} - -void mg_sl_if_connect_udp(struct mg_connection *nc) { - sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) { - nc->err = sock; - return; - } - mg_sock_set(nc, sock); - nc->err = 0; -} - -int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { - int proto = 0; - if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET; - sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto); - if (sock < 0) return sock; - mg_sock_set(nc, sock); - return 0; -} - -int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { - sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0); - if (sock == INVALID_SOCKET) return (errno ? errno : 1); - mg_sock_set(nc, sock); - return 0; -} - -void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_sl_if_recved(struct mg_connection *nc, size_t len) { - (void) nc; - (void) len; -} - -int mg_sl_if_create_conn(struct mg_connection *nc) { - (void) nc; - return 1; -} - -void mg_sl_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - /* For UDP, only close outgoing sockets or listeners. */ - if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) { - sl_Close(nc->sock); - } - nc->sock = INVALID_SOCKET; -} - -static int mg_accept_conn(struct mg_connection *lc) { - struct mg_connection *nc; - union socket_address sa; - socklen_t sa_len = sizeof(sa); - sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len); - if (sock < 0) { - DBG(("%p: failed to accept: %d", lc, sock)); - return 0; - } - nc = mg_if_accept_new_conn(lc); - if (nc == NULL) { - sl_Close(sock); - return 0; - } - DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr), - ntohs(sa.sin.sin_port))); - mg_sock_set(nc, sock); - if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE; - mg_if_accept_tcp_cb(nc, &sa, sa_len); - return 1; -} - -/* 'sa' must be an initialized address to bind to */ -static sock_t mg_open_listening_socket(struct mg_connection *nc, - union socket_address *sa, int type, - int proto) { - int r; - socklen_t sa_len = - (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6); - sock_t sock = sl_Socket(sa->sa.sa_family, type, proto); - if (sock < 0) return sock; - if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean; - if (type != SOCK_DGRAM) { -#if MG_ENABLE_SSL - if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean; -#endif - if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean; - } - mg_set_non_blocking_mode(sock); -clean: - if (r < 0) { - sl_Close(sock); - sock = r; - } - return sock; -} - -static void mg_write_to_socket(struct mg_connection *nc) { - struct mbuf *io = &nc->send_mbuf; - int n = 0; - - if (nc->flags & MG_F_UDP) { - n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa, - sizeof(nc->sa.sin)); - DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno, - inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port))); - } else { - n = (int) sl_Send(nc->sock, io->buf, io->len, 0); - DBG(("%p %d bytes -> %d", nc, n, nc->sock)); - } - - if (n > 0) { - mg_if_sent_cb(nc, n); - } else if (n < 0 && mg_is_error(n)) { - /* Something went wrong, drop the connection. */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) { - size_t avail; - if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0; - avail = conn->recv_mbuf_limit - conn->recv_mbuf.len; - return avail > max ? max : avail; -} - -static void mg_handle_tcp_read(struct mg_connection *conn) { - int n = 0; - char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE); - - if (buf == NULL) { - DBG(("OOM")); - return; - } - - n = (int) sl_Recv(conn->sock, buf, - recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0); - DBG(("%p %d bytes <- %d", conn, n, conn->sock)); - if (n > 0) { - mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */); - } else { - MG_FREE(buf); - } - if (n == 0) { - /* Orderly shutdown of the socket, try flushing output. */ - conn->flags |= MG_F_SEND_AND_CLOSE; - } else if (mg_is_error(n)) { - conn->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -static void mg_handle_udp_read(struct mg_connection *nc) { - char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE); - if (buf == NULL) return; - union socket_address sa; - socklen_t sa_len = sizeof(sa); - int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0, - (SlSockAddr_t *) &sa, &sa_len); - DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - if (n > 0) { - mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len); - } else { - MG_FREE(buf); - } -} - -#define _MG_F_FD_CAN_READ 1 -#define _MG_F_FD_CAN_WRITE 1 << 1 -#define _MG_F_FD_ERROR 1 << 2 - -void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) { - DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, - fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); - - if (nc->flags & MG_F_CONNECTING) { - if (nc->flags & MG_F_UDP || nc->err != SL_ERROR_BSD_EALREADY) { - mg_if_connect_cb(nc, nc->err); - } else { - /* In SimpleLink, to get status of non-blocking connect() we need to wait - * until socket is writable and repeat the call to sl_Connect again, - * which will now return the real status. */ - if (fd_flags & _MG_F_FD_CAN_WRITE) { - nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin)); - DBG(("%p conn res=%d", nc, nc->err)); - if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY || - /* TODO(rojer): Provide API to set the date for verification. */ - nc->err == SL_ERROR_BSD_ESECDATEERROR -#if SL_MAJOR_VERSION_NUM >= 2 - /* Per SWRU455, this error does not mean verification failed, - * it only means that the cert used is not present in the trusted - * root CA catalog. Which is perfectly fine. */ - || - nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA -#endif - ) { - nc->err = 0; - } - if (nc->flags & MG_F_SSL && nc->err == 0) { - nc->flags |= MG_F_SSL_HANDSHAKE_DONE; - } - mg_if_connect_cb(nc, nc->err); - } - } - /* Ignore read/write in further processing, we've handled it. */ - fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE); - } - - if (fd_flags & _MG_F_FD_CAN_READ) { - if (nc->flags & MG_F_UDP) { - mg_handle_udp_read(nc); - } else { - if (nc->flags & MG_F_LISTENING) { - mg_accept_conn(nc); - } else { - mg_handle_tcp_read(nc); - } - } - } - - if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { - if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) { - mg_write_to_socket(nc); - } - - if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) { - mg_if_poll(nc, now); - } - mg_if_timer(nc, now); - } - - DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags, - (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len)); -} - -/* Associate a socket to a connection. */ -void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) { - mg_set_non_blocking_mode(sock); - nc->sock = sock; - DBG(("%p %d", nc, sock)); -} - -void mg_sl_if_init(struct mg_iface *iface) { - (void) iface; - DBG(("%p using sl_Select()", iface->mgr)); -} - -void mg_sl_if_free(struct mg_iface *iface) { - (void) iface; -} - -void mg_sl_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_sl_if_remove_conn(struct mg_connection *nc) { - (void) nc; -} - -time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - double now = mg_time(); - double min_timer; - struct mg_connection *nc, *tmp; - struct SlTimeval_t tv; - SlFdSet_t read_set, write_set, err_set; - sock_t max_fd = INVALID_SOCKET; - int num_fds, num_ev = 0, num_timers = 0; - - SL_SOCKET_FD_ZERO(&read_set); - SL_SOCKET_FD_ZERO(&write_set); - SL_SOCKET_FD_ZERO(&err_set); - - /* - * Note: it is ok to have connections with sock == INVALID_SOCKET in the list, - * e.g. timer-only "connections". - */ - min_timer = 0; - for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) { - tmp = nc->next; - - if (nc->sock != INVALID_SOCKET) { - num_fds++; - - if (!(nc->flags & MG_F_WANT_WRITE) && - nc->recv_mbuf.len < nc->recv_mbuf_limit && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) { - SL_SOCKET_FD_SET(nc->sock, &read_set); - if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; - } - - if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) || - (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) { - SL_SOCKET_FD_SET(nc->sock, &write_set); - SL_SOCKET_FD_SET(nc->sock, &err_set); - if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock; - } - } - - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - } - - /* - * If there is a timer to be fired earlier than the requested timeout, - * adjust the timeout. - */ - if (num_timers > 0) { - double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */; - if (timer_timeout_ms < timeout_ms) { - timeout_ms = timer_timeout_ms; - } - } - if (timeout_ms < 0) timeout_ms = 0; - - tv.tv_sec = timeout_ms / 1000; - tv.tv_usec = (timeout_ms % 1000) * 1000; - - if (num_fds > 0) { - num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv); - } - - now = mg_time(); - DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, - num_fds, timeout_ms)); - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - int fd_flags = 0; - if (nc->sock != INVALID_SOCKET) { - if (num_ev > 0) { - fd_flags = - (SL_SOCKET_FD_ISSET(nc->sock, &read_set) && - (!(nc->flags & MG_F_UDP) || nc->listener == NULL) - ? _MG_F_FD_CAN_READ - : 0) | - (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE - : 0) | - (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0); - } - /* SimpleLink does not report UDP sockets as writable. */ - if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) { - fd_flags |= _MG_F_FD_CAN_WRITE; - } - } - tmp = nc->next; - mg_mgr_handle_conn(nc, fd_flags, now); - } - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || - (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { - mg_close_conn(nc); - } - } - - return now; -} - -void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - /* SimpleLink does not provide a way to get socket's peer address after - * accept or connect. Address should have been preserved in the connection, - * so we do our best here by using it. */ - if (remote) memcpy(sa, &nc->sa, sizeof(*sa)); -} - -void sl_restart_cb(struct mg_mgr *mgr) { - /* - * SimpleLink has been restarted, meaning all sockets have been invalidated. - * We try our best - we'll restart the listeners, but for outgoing - * connections we have no option but to terminate. - */ - struct mg_connection *nc; - for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { - if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */ - if (nc->flags & MG_F_LISTENING) { - DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa) - : mg_sl_if_listen_tcp(nc, &nc->sa)); - if (res == 0) continue; - /* Well, we tried and failed. Fall through to closing. */ - } - nc->sock = INVALID_SOCKET; - DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr), - ntohs(nc->sa.sin.sin_port))); - /* TODO(rojer): Outgoing UDP? */ - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - } -} - -/* clang-format off */ -#define MG_SL_IFACE_VTABLE \ - { \ - mg_sl_if_init, \ - mg_sl_if_free, \ - mg_sl_if_add_conn, \ - mg_sl_if_remove_conn, \ - mg_sl_if_poll, \ - mg_sl_if_listen_tcp, \ - mg_sl_if_listen_udp, \ - mg_sl_if_connect_tcp, \ - mg_sl_if_connect_udp, \ - mg_sl_if_tcp_send, \ - mg_sl_if_udp_send, \ - mg_sl_if_recved, \ - mg_sl_if_create_conn, \ - mg_sl_if_destroy_conn, \ - mg_sl_if_sock_set, \ - mg_sl_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_SIMPLELINK -const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/simplelink/sl_ssl_if.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK - -/* Amalgamated: #include "common/mg_mem.h" */ - -#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX -#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:" -#endif - -#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \ - (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1) - -struct mg_ssl_if_ctx { - char *ssl_cert; - char *ssl_key; - char *ssl_ca_cert; - char *ssl_server_name; -}; - -void mg_ssl_if_init() { -} - -enum mg_ssl_if_result mg_ssl_if_conn_init( - struct mg_connection *nc, const struct mg_ssl_if_conn_params *params, - const char **err_msg) { - struct mg_ssl_if_ctx *ctx = - (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx)); - if (ctx == NULL) { - MG_SET_PTRPTR(err_msg, "Out of memory"); - return MG_SSL_ERROR; - } - nc->ssl_if_data = ctx; - - if (params->cert != NULL || params->key != NULL) { - if (params->cert != NULL && params->key != NULL) { - ctx->ssl_cert = strdup(params->cert); - ctx->ssl_key = strdup(params->key); - } else { - MG_SET_PTRPTR(err_msg, "Both cert and key are required."); - return MG_SSL_ERROR; - } - } - if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) { - ctx->ssl_ca_cert = strdup(params->ca_cert); - } - /* TODO(rojer): cipher_suites. */ - if (params->server_name != NULL) { - ctx->ssl_server_name = strdup(params->server_name); - } - return MG_SSL_OK; -} - -void mg_ssl_if_conn_close_notify(struct mg_connection *nc) { - /* Nothing to do */ - (void) nc; -} - -void mg_ssl_if_conn_free(struct mg_connection *nc) { - struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - if (ctx == NULL) return; - nc->ssl_if_data = NULL; - MG_FREE(ctx->ssl_cert); - MG_FREE(ctx->ssl_key); - MG_FREE(ctx->ssl_ca_cert); - MG_FREE(ctx->ssl_server_name); - memset(ctx, 0, sizeof(*ctx)); - MG_FREE(ctx); -} - -bool pem_to_der(const char *pem_file, const char *der_file) { - bool ret = false; - FILE *pf = NULL, *df = NULL; - bool writing = false; - pf = fopen(pem_file, "r"); - if (pf == NULL) goto clean; - remove(der_file); - fs_slfs_set_new_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, - 2048); - df = fopen(der_file, "w"); - if (df == NULL) goto clean; - while (1) { - char pem_buf[70]; - char der_buf[48]; - if (!fgets(pem_buf, sizeof(pem_buf), pf)) break; - if (writing) { - if (strstr(pem_buf, "-----END ") != NULL) { - ret = true; - break; - } - int l = 0; - while (!isspace((unsigned int) pem_buf[l])) l++; - int der_len = 0; - cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf), - der_buf, &der_len); - if (der_len <= 0) break; - if (fwrite(der_buf, 1, der_len, df) != der_len) break; - } else if (strstr(pem_buf, "-----BEGIN ") != NULL) { - writing = true; - } - } - -clean: - if (pf != NULL) fclose(pf); - if (df != NULL) { - fclose(df); - if (!ret) remove(der_file); - } - return ret; -} - -#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS) -/* If the file's extension is .pem, convert it to DER format and put on SLFS. */ -static char *sl_pem2der(const char *pem_file) { - const char *pem_ext = strstr(pem_file, ".pem"); - if (pem_ext == NULL || *(pem_ext + 4) != '\0') { - return strdup(pem_file); - } - char *der_file = NULL; - /* DER file must be located on SLFS, add prefix. */ - int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der", - (int) (pem_ext - pem_file), pem_file); - if (der_file == NULL) return NULL; - bool result = false; - cs_stat_t st; - if (mg_stat(der_file, &st) != 0) { - result = pem_to_der(pem_file, der_file); - LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result)); - } else { - /* File exists, assume it's already been converted. */ - result = true; - } - if (result) { - /* Strip the SL: prefix we added since NWP does not expect it. */ - memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, - l - 2 /* including \0 */); - } else { - MG_FREE(der_file); - der_file = NULL; - } - return der_file; -} -#else -static char *sl_pem2der(const char *pem_file) { - return strdup(pem_file); -} -#endif - -int sl_set_ssl_opts(int sock, struct mg_connection *nc) { - int err; - const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data; - DBG(("%p ssl ctx: %p", nc, ctx)); - - if (ctx != NULL) { - DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"), - (ctx->ssl_key ? ctx->ssl_cert : "-"), - (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"), - (ctx->ssl_server_name ? ctx->ssl_server_name : "-"))); - if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) { - char *ssl_cert = sl_pem2der(ctx->ssl_cert); - char *ssl_key = sl_pem2der(ctx->ssl_key); - if (ssl_cert != NULL && ssl_key != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert, - strlen(ssl_cert)); - LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err)); - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key, - strlen(ssl_key)); - LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err)); - } else { - err = -1; - } - MG_FREE(ssl_cert); - MG_FREE(ssl_key); - if (err != 0) return err; - } - if (ctx->ssl_ca_cert != NULL) { - if (ctx->ssl_ca_cert[0] != '\0') { - char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert); - if (ssl_ca_cert != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert, - strlen(ssl_ca_cert)); - LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err)); - } else { - err = -1; - } - MG_FREE(ssl_ca_cert); - if (err != 0) return err; - } - } - if (ctx->ssl_server_name != NULL) { - err = sl_SetSockOpt(sock, SL_SOL_SOCKET, - SL_SO_SECURE_DOMAIN_NAME_VERIFICATION, - ctx->ssl_server_name, strlen(ctx->ssl_server_name)); - DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err)); - /* Domain name verificationw as added in a NWP service pack, older - * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do - * about it, - * so we ignore the error. */ - if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err; - } - } - return 0; -} - -#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_net_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ -#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ - -#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL -#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -#endif - -#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL - -#include - -extern const struct mg_iface_vtable mg_lwip_iface_vtable; - -struct mg_lwip_conn_state { - struct mg_connection *nc; - struct mg_connection *lc; - union { - struct tcp_pcb *tcp; - struct udp_pcb *udp; - } pcb; - err_t err; - size_t num_sent; /* Number of acknowledged bytes to be reported to the core */ - struct pbuf *rx_chain; /* Chain of incoming data segments. */ - size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */ - /* Last SSL write size, for retries. */ - int last_ssl_write_size; - /* Whether MG_SIG_RECV is already pending for this connection */ - int recv_pending : 1; - /* Whether the connection is about to close, just `rx_chain` needs to drain */ - int draining_rx_chain : 1; -}; - -enum mg_sig_type { - MG_SIG_CONNECT_RESULT = 1, - MG_SIG_RECV = 2, - MG_SIG_CLOSE_CONN = 3, - MG_SIG_TOMBSTONE = 4, - MG_SIG_ACCEPT = 5, -}; - -void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc); - -/* To be implemented by the platform. */ -void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr); - -#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ - -#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_net_if.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL - -/* Amalgamated: #include "common/mg_mem.h" */ - -#include -#include -#include -#include -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 -#include /* For tcp_seg */ -#else -#include -#endif -#include - -/* Amalgamated: #include "common/cs_dbg.h" */ - -/* - * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip, - * even older have nothing. - */ -#ifndef ip_2_ip4 -#ifdef ipX_2_ip -#define ip_2_ip4(addr) ipX_2_ip(addr) -#else -#define ip_2_ip4(addr) (addr) -#endif -#endif - -/* - * Depending on whether Mongoose is compiled with ipv6 support, use right - * lwip functions - */ -#if MG_ENABLE_IPV6 -#define TCP_NEW tcp_new_ip6 -#define TCP_BIND tcp_bind_ip6 -#define UDP_BIND udp_bind_ip6 -#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x)) -#define SET_ADDR(dst, src) \ - memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \ - sizeof((dst)->sin6.sin6_addr.s6_addr)) -#else -#define TCP_NEW tcp_new -#define TCP_BIND tcp_bind -#define UDP_BIND udp_bind -#define IPADDR_NTOA ipaddr_ntoa -#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr -#endif - -#if NO_SYS -#define tcpip_callback(fn, arg) (fn)(arg) -typedef void (*tcpip_callback_fn)(void *arg); -#endif - -void mg_lwip_ssl_do_hs(struct mg_connection *nc); -void mg_lwip_ssl_send(struct mg_connection *nc); -void mg_lwip_ssl_recv(struct mg_connection *nc); - -void mg_lwip_if_init(struct mg_iface *iface); -void mg_lwip_if_free(struct mg_iface *iface); -void mg_lwip_if_add_conn(struct mg_connection *nc); -void mg_lwip_if_remove_conn(struct mg_connection *nc); -time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms); - -#if defined(RTOS_SDK) || defined(ESP_PLATFORM) -extern void mgos_lock(); -extern void mgos_unlock(); -#else -#define mgos_lock() -#define mgos_unlock() -#endif - -static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p); - -#if LWIP_TCP_KEEPALIVE -void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, - int interval, int count) { - if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) { - return; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (idle > 0 && interval > 0 && count > 0) { - tpcb->keep_idle = idle * 1000; - tpcb->keep_intvl = interval * 1000; - tpcb->keep_cnt = count; - tpcb->so_options |= SOF_KEEPALIVE; - } else { - tpcb->so_options &= ~SOF_KEEPALIVE; - } -} -#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE) -#warning LWIP TCP keepalive is disabled. Please consider enabling it. -#endif /* LWIP_TCP_KEEPALIVE */ - -static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)), - tpcb->remote_port, err)); - if (nc == NULL) { - tcp_abort(tpcb); - return ERR_ARG; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - cs->err = err; -#if LWIP_TCP_KEEPALIVE - if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6); -#endif - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return ERR_OK; -} - -static void mg_lwip_tcp_error_cb(void *arg, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p conn error %d", nc, err)); - if (nc == NULL) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - cs->pcb.tcp = NULL; /* Has already been deallocated */ - if (nc->flags & MG_F_CONNECTING) { - cs->err = err; - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } -} - -static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, - struct pbuf *p, err_t err) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err)); - if (p == NULL) { - if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->rx_chain != NULL) { - /* - * rx_chain still contains non-consumed data, don't close the - * connection - */ - cs->draining_rx_chain = 1; - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - } else { - /* Tombstoned connection, do nothing. */ - } - return ERR_OK; - } else if (nc == NULL) { - tcp_abort(tpcb); - return ERR_ARG; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - /* - * If we get a chain of more than one segment at once, we need to bump - * refcount on the subsequent bufs to make them independent. - */ - if (p->next != NULL) { - struct pbuf *q = p->next; - for (; q != NULL; q = q->next) pbuf_ref(q); - } - mgos_lock(); - if (cs->rx_chain == NULL) { - cs->rx_offset = 0; - } else if (pbuf_clen(cs->rx_chain) >= 4) { - /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX - * will be completely blocked. We already have at least 4 in the chain, - * this one is, so we have to make a copy and release this one. */ - struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); - if (np != NULL) { - pbuf_copy(np, p); - pbuf_free(p); - p = np; - } - } - mgos_unlock(); - mg_lwip_recv_common(nc, p); - return ERR_OK; -} - -static void mg_lwip_consume_rx_chain_tcp(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->rx_chain == NULL) return; -#if MG_ENABLE_SSL - if (nc->flags & MG_F_SSL) { - if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { - mg_lwip_ssl_recv(nc); - } else { - mg_lwip_ssl_do_hs(nc); - } - return; - } -#endif - mgos_lock(); - while (cs->rx_chain != NULL && nc->recv_mbuf.len < nc->recv_mbuf_limit) { - struct pbuf *seg = cs->rx_chain; - - size_t seg_len = (seg->len - cs->rx_offset); - size_t buf_avail = (nc->recv_mbuf_limit - nc->recv_mbuf.len); - size_t len = MIN(seg_len, buf_avail); - - char *data = (char *) MG_MALLOC(len); - if (data == NULL) { - mgos_unlock(); - DBG(("OOM")); - return; - } - pbuf_copy_partial(seg, data, len, cs->rx_offset); - cs->rx_offset += len; - if (cs->rx_offset == cs->rx_chain->len) { - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - cs->rx_offset = 0; - } - mgos_unlock(); - mg_if_recv_tcp_cb(nc, data, len, 1 /* own */); - mgos_lock(); - } - mgos_unlock(); -} - -static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) { - mg_lwip_consume_rx_chain_tcp(nc); - - if (nc->send_mbuf.len > 0) { - mg_lwip_mgr_schedule_poll(nc->mgr); - } -} - -static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, - u16_t num_sent) { - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked)); - if (nc == NULL) return ERR_OK; - if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) && - nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - return ERR_OK; -} - -struct mg_lwip_if_connect_tcp_ctx { - struct mg_connection *nc; - const union socket_address *sa; -}; - -static void mg_lwip_if_connect_tcp_tcpip(void *arg) { - struct mg_lwip_if_connect_tcp_ctx *ctx = - (struct mg_lwip_if_connect_tcp_ctx *) arg; - struct mg_connection *nc = ctx->nc; - const union socket_address *sa = ctx->sa; - - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = TCP_NEW(); - cs->pcb.tcp = tpcb; - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - tcp_arg(tpcb, nc); - tcp_err(tpcb, mg_lwip_tcp_error_cb); - tcp_sent(tpcb, mg_lwip_tcp_sent_cb); - tcp_recv(tpcb, mg_lwip_tcp_recv_cb); - cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */); - DBG(("%p tcp_bind = %d", nc, cs->err)); - if (cs->err != ERR_OK) { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return; - } - cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb); - DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err)); - if (cs->err != ERR_OK) { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - return; - } -} - -void mg_lwip_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_connect_tcp_tcpip, &ctx); -} - -/* - * Lwip included in the SDKs for nRF5x chips has different type for the - * callback of `udp_recv()` - */ -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 -static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, - const ip_addr_t *addr, u16_t port) -#else -static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, - ip_addr_t *addr, u16_t port) -#endif -{ - struct mg_connection *nc = (struct mg_connection *) arg; - DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len)); - /* Put address in a separate pbuf and tack it onto the packet. */ - struct pbuf *sap = - pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM); - if (sap == NULL) { - pbuf_free(p); - return; - } - union socket_address *sa = (union socket_address *) sap->payload; -#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105 - sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr; -#else - sa->sin.sin_addr.s_addr = addr->addr; -#endif - sa->sin.sin_port = htons(port); - /* Logic in the recv handler requires that there be exactly one data pbuf. */ - p = pbuf_coalesce(p, PBUF_RAW); - pbuf_chain(sap, p); - mg_lwip_recv_common(nc, sap); - (void) pcb; -} - -static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - mgos_lock(); - if (cs->rx_chain == NULL) { - cs->rx_chain = p; - } else { - pbuf_chain(cs->rx_chain, p); - } - if (!cs->recv_pending) { - cs->recv_pending = 1; - mg_lwip_post_signal(MG_SIG_RECV, nc); - } - mgos_unlock(); -} - -static void mg_lwip_handle_recv_udp(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - /* - * For UDP, RX chain consists of interleaved address and packet bufs: - * Address pbuf followed by exactly one data pbuf (recv_cb took care of that). - */ - while (cs->rx_chain != NULL) { - struct pbuf *sap = cs->rx_chain; - struct pbuf *p = sap->next; - cs->rx_chain = pbuf_dechain(p); - size_t data_len = p->len; - char *data = (char *) MG_MALLOC(data_len); - if (data != NULL) { - pbuf_copy_partial(p, data, data_len, 0); - pbuf_free(p); - mg_if_recv_udp_cb(nc, data, data_len, - (union socket_address *) sap->payload, sap->len); - pbuf_free(sap); - } else { - pbuf_free(p); - pbuf_free(sap); - } - } -} - -static void mg_lwip_if_connect_udp_tcpip(void *arg) { - struct mg_connection *nc = (struct mg_connection *) arg; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct udp_pcb *upcb = udp_new(); - cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */); - DBG(("%p udp_bind %p = %d", nc, upcb, cs->err)); - if (cs->err == ERR_OK) { - udp_recv(upcb, mg_lwip_udp_recv_cb, nc); - cs->pcb.udp = upcb; - } else { - udp_remove(upcb); - } - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); -} - -void mg_lwip_if_connect_udp(struct mg_connection *nc) { - tcpip_callback(mg_lwip_if_connect_udp_tcpip, nc); -} - -void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) { - union socket_address sa; - SET_ADDR(&sa, &tpcb->remote_ip); - sa.sin.sin_port = htons(tpcb->remote_port); - mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin)); -} - -static void tcp_close_tcpip(void *arg) { - tcp_close((struct tcp_pcb *) arg); -} - -void mg_lwip_handle_accept(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->pcb.tcp == NULL) return; -#if MG_ENABLE_SSL - if (cs->lc->flags & MG_F_SSL) { - if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) { - LOG(LL_ERROR, ("SSL error")); - tcpip_callback(tcp_close_tcpip, cs->pcb.tcp); - } - } else -#endif - { - mg_lwip_accept_conn(nc, cs->pcb.tcp); - } -} - -static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) { - struct mg_connection *lc = (struct mg_connection *) arg, *nc; - struct mg_lwip_conn_state *lcs, *cs; - struct tcp_pcb_listen *lpcb; - LOG(LL_DEBUG, - ("%p conn %p from %s:%u", lc, newtpcb, - IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port)); - if (lc == NULL) { - tcp_abort(newtpcb); - return ERR_ABRT; - } - lcs = (struct mg_lwip_conn_state *) lc->sock; - lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp; -#if TCP_LISTEN_BACKLOG - tcp_accepted(lpcb); -#endif - nc = mg_if_accept_new_conn(lc); - if (nc == NULL) { - tcp_abort(newtpcb); - return ERR_ABRT; - } - cs = (struct mg_lwip_conn_state *) nc->sock; - cs->lc = lc; - cs->pcb.tcp = newtpcb; - /* We need to set up callbacks before returning because data may start - * arriving immediately. */ - tcp_arg(newtpcb, nc); - tcp_err(newtpcb, mg_lwip_tcp_error_cb); - tcp_sent(newtpcb, mg_lwip_tcp_sent_cb); - tcp_recv(newtpcb, mg_lwip_tcp_recv_cb); -#if LWIP_TCP_KEEPALIVE - mg_lwip_set_keepalive_params(nc, 60, 10, 6); -#endif - mg_lwip_post_signal(MG_SIG_ACCEPT, nc); - (void) err; - (void) lpcb; - return ERR_OK; -} - -struct mg_lwip_if_listen_ctx { - struct mg_connection *nc; - union socket_address *sa; - int ret; -}; - -static void mg_lwip_if_listen_tcp_tcpip(void *arg) { - struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; - struct mg_connection *nc = ctx->nc; - union socket_address *sa = ctx->sa; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = TCP_NEW(); - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - cs->err = TCP_BIND(tpcb, ip, port); - DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); - if (cs->err != ERR_OK) { - tcp_close(tpcb); - ctx->ret = -1; - return; - } - tcp_arg(tpcb, nc); - tpcb = tcp_listen(tpcb); - cs->pcb.tcp = tpcb; - tcp_accept(tpcb, mg_lwip_accept_cb); - ctx->ret = 0; -} - -int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { - struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_listen_tcp_tcpip, &ctx); - return ctx.ret; -} - -static void mg_lwip_if_listen_udp_tcpip(void *arg) { - struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg; - struct mg_connection *nc = ctx->nc; - union socket_address *sa = ctx->sa; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct udp_pcb *upcb = udp_new(); - ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr; - u16_t port = ntohs(sa->sin.sin_port); - cs->err = UDP_BIND(upcb, ip, port); - DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err)); - if (cs->err != ERR_OK) { - udp_remove(upcb); - ctx->ret = -1; - } else { - udp_recv(upcb, mg_lwip_udp_recv_cb, nc); - cs->pcb.udp = upcb; - ctx->ret = 0; - } -} - -int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { - struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa}; - tcpip_callback(mg_lwip_if_listen_udp_tcpip, &ctx); - return ctx.ret; -} - -struct mg_lwip_tcp_write_ctx { - struct mg_connection *nc; - const void *data; - uint16_t len; - int ret; -}; - -static void tcp_output_tcpip(void *arg) { - tcp_output((struct tcp_pcb *) arg); -} - -static void mg_lwip_tcp_write_tcpip(void *arg) { - struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg; - struct mg_connection *nc = ctx->nc; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = cs->pcb.tcp; - size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf)); - size_t unsent, unacked; - if (len == 0) { - DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen, - tpcb->unsent, tpcb->unacked)); - tcpip_callback(tcp_output_tcpip, tpcb); - ctx->ret = 0; - return; - } - unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); - unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); -/* - * On ESP8266 we only allow one TCP segment in flight at any given time. - * This may increase latency and reduce efficiency of tcp windowing, - * but memory is scarce and precious on that platform so we do this to - * reduce footprint. - */ -#if CS_PLATFORM == CS_P_ESP8266 - if (unacked > 0) { - ctx->ret = 0; - return; - } - len = MIN(len, (TCP_MSS - unsent)); -#endif - cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY); - unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0); - unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0); - DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked)); - if (cs->err != ERR_OK) { - /* - * We ignore ERR_MEM because memory will be freed up when the data is sent - * and we'll retry. - */ - ctx->ret = (cs->err == ERR_MEM ? 0 : -1); - return; - } - ctx->ret = len; -} - -static int mg_lwip_tcp_write(struct mg_connection *nc, const void *data, - uint16_t len) { - struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = data, .len = len}; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (tpcb == NULL) { - return -1; - } - tcpip_callback(mg_lwip_tcp_write_tcpip, &ctx); - return ctx.ret; -} - -struct udp_sendto_ctx { - struct udp_pcb *upcb; - struct pbuf *p; - ip_addr_t *ip; - uint16_t port; - int ret; -}; - -static void udp_sendto_tcpip(void *arg) { - struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg; - ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port); -} - -static int mg_lwip_udp_send(struct mg_connection *nc, const void *data, - uint16_t len) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (cs->pcb.udp == NULL) { - /* - * In case of UDP, this usually means, what - * async DNS resolve is still in progress and connection - * is not ready yet - */ - DBG(("%p socket is not connected", nc)); - return -1; - } - struct udp_pcb *upcb = cs->pcb.udp; - struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); -#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6 - ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0}; -#else - ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr}; -#endif - u16_t port = ntohs(nc->sa.sin.sin_port); - if (p == NULL) { - DBG(("OOM")); - return 0; - } - memcpy(p->payload, data, len); - struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port}; - tcpip_callback(udp_sendto_tcpip, &ctx); - cs->err = ctx.ret; - pbuf_free(p); - return (cs->err == ERR_OK ? len : -1); -} - -static void mg_lwip_send_more(struct mg_connection *nc) { - int num_sent = 0; - if (nc->sock == INVALID_SOCKET) return; - if (nc->flags & MG_F_UDP) { - num_sent = mg_lwip_udp_send(nc, nc->send_mbuf.buf, nc->send_mbuf.len); - DBG(("%p mg_lwip_udp_send %u = %d", nc, nc->send_mbuf.len, num_sent)); - } else { - num_sent = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len); - DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_sent)); - } - if (num_sent == 0) return; - if (num_sent > 0) { - mg_if_sent_cb(nc, num_sent); - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } -} - -void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); - mg_lwip_mgr_schedule_poll(nc->mgr); -} - -void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); - mg_lwip_mgr_schedule_poll(nc->mgr); -} - -struct tcp_recved_ctx { - struct tcp_pcb *tpcb; - size_t len; -}; - -void tcp_recved_tcpip(void *arg) { - struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg; - tcp_recved(ctx->tpcb, ctx->len); -} - -void mg_lwip_if_recved(struct mg_connection *nc, size_t len) { - if (nc->flags & MG_F_UDP) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) { - DBG(("%p invalid socket", nc)); - return; - } - DBG(("%p %p %u %u", nc, cs->pcb.tcp, len, - (cs->rx_chain ? cs->rx_chain->tot_len : 0))); - struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = len}; -#if MG_ENABLE_SSL - if (!(nc->flags & MG_F_SSL)) { - tcpip_callback(tcp_recved_tcpip, &ctx); - } else { - /* Currently SSL acknowledges data immediately. - * TODO(rojer): Find a way to propagate mg_lwip_if_recved. */ - } -#else - tcpip_callback(tcp_recved_tcpip, &ctx); -#endif - mbuf_trim(&nc->recv_mbuf); -} - -int mg_lwip_if_create_conn(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = - (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs)); - if (cs == NULL) return 0; - cs->nc = nc; - nc->sock = (intptr_t) cs; - return 1; -} - -static void udp_remove_tcpip(void *arg) { - udp_remove((struct udp_pcb *) arg); -} - -void mg_lwip_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (!(nc->flags & MG_F_UDP)) { - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (tpcb != NULL) { - tcp_arg(tpcb, NULL); - DBG(("%p tcp_close %p", nc, tpcb)); - tcp_arg(tpcb, NULL); - tcpip_callback(tcp_close_tcpip, tpcb); - } - while (cs->rx_chain != NULL) { - struct pbuf *seg = cs->rx_chain; - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - } - memset(cs, 0, sizeof(*cs)); - MG_FREE(cs); - } else if (nc->listener == NULL) { - /* Only close outgoing UDP pcb or listeners. */ - struct udp_pcb *upcb = cs->pcb.udp; - if (upcb != NULL) { - DBG(("%p udp_remove %p", nc, upcb)); - tcpip_callback(udp_remove_tcpip, upcb); - } - memset(cs, 0, sizeof(*cs)); - MG_FREE(cs); - } - nc->sock = INVALID_SOCKET; -} - -void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - memset(sa, 0, sizeof(*sa)); - if (nc == NULL || nc->sock == INVALID_SOCKET) return; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->flags & MG_F_UDP) { - struct udp_pcb *upcb = cs->pcb.udp; - if (remote) { - memcpy(sa, &nc->sa, sizeof(*sa)); - } else if (upcb != NULL) { - sa->sin.sin_port = htons(upcb->local_port); - SET_ADDR(sa, &upcb->local_ip); - } - } else { - struct tcp_pcb *tpcb = cs->pcb.tcp; - if (remote) { - memcpy(sa, &nc->sa, sizeof(*sa)); - } else if (tpcb != NULL) { - sa->sin.sin_port = htons(tpcb->local_port); - SET_ADDR(sa, &tpcb->local_ip); - } - } -} - -void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) { - nc->sock = sock; -} - -/* clang-format off */ -#define MG_LWIP_IFACE_VTABLE \ - { \ - mg_lwip_if_init, \ - mg_lwip_if_free, \ - mg_lwip_if_add_conn, \ - mg_lwip_if_remove_conn, \ - mg_lwip_if_poll, \ - mg_lwip_if_listen_tcp, \ - mg_lwip_if_listen_udp, \ - mg_lwip_if_connect_tcp, \ - mg_lwip_if_connect_udp, \ - mg_lwip_if_tcp_send, \ - mg_lwip_if_udp_send, \ - mg_lwip_if_recved, \ - mg_lwip_if_create_conn, \ - mg_lwip_if_destroy_conn, \ - mg_lwip_if_sock_set, \ - mg_lwip_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL -const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL - -#ifndef MG_SIG_QUEUE_LEN -#define MG_SIG_QUEUE_LEN 32 -#endif - -struct mg_ev_mgr_lwip_signal { - int sig; - struct mg_connection *nc; -}; - -struct mg_ev_mgr_lwip_data { - struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]; - int sig_queue_len; - int start_index; -}; - -void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) nc->iface->data; - mgos_lock(); - if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) { - mgos_unlock(); - return; - } - int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN; - md->sig_queue[end_index].sig = sig; - md->sig_queue[end_index].nc = nc; - md->sig_queue_len++; - mg_lwip_mgr_schedule_poll(nc->mgr); - mgos_unlock(); -} - -void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data; - while (md->sig_queue_len > 0) { - mgos_lock(); - int sig = md->sig_queue[md->start_index].sig; - struct mg_connection *nc = md->sig_queue[md->start_index].nc; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN; - md->sig_queue_len--; - mgos_unlock(); - if (nc->iface == NULL || nc->mgr == NULL) continue; - switch (sig) { - case MG_SIG_CONNECT_RESULT: { -#if MG_ENABLE_SSL - if (cs->err == 0 && (nc->flags & MG_F_SSL) && - !(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) { - mg_lwip_ssl_do_hs(nc); - } else -#endif - { - mg_if_connect_cb(nc, cs->err); - } - break; - } - case MG_SIG_CLOSE_CONN: { - nc->flags |= MG_F_SEND_AND_CLOSE; - mg_close_conn(nc); - break; - } - case MG_SIG_RECV: { - cs->recv_pending = 0; - if (nc->flags & MG_F_UDP) { - mg_lwip_handle_recv_udp(nc); - } else { - mg_lwip_handle_recv_tcp(nc); - } - break; - } - case MG_SIG_TOMBSTONE: { - break; - } - case MG_SIG_ACCEPT: { - mg_lwip_handle_accept(nc); - break; - } - } - } -} - -void mg_lwip_if_init(struct mg_iface *iface) { - LOG(LL_INFO, ("%p Mongoose init", iface)); - iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data)); -} - -void mg_lwip_if_free(struct mg_iface *iface) { - MG_FREE(iface->data); - iface->data = NULL; -} - -void mg_lwip_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_lwip_if_remove_conn(struct mg_connection *nc) { - struct mg_ev_mgr_lwip_data *md = - (struct mg_ev_mgr_lwip_data *) nc->iface->data; - /* Walk the queue and null-out further signals for this conn. */ - for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) { - if (md->sig_queue[i].nc == nc) { - md->sig_queue[i].sig = MG_SIG_TOMBSTONE; - } - } -} - -time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - int n = 0; - double now = mg_time(); - struct mg_connection *nc, *tmp; - double min_timer = 0; - int num_timers = 0; -#if 0 - DBG(("begin poll @%u", (unsigned int) (now * 1000))); -#endif - mg_ev_mgr_lwip_process_signals(mgr); - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - tmp = nc->next; - n++; - if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || - ((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) && - (nc->send_mbuf.len == 0))) { - mg_close_conn(nc); - continue; - } - mg_if_poll(nc, now); - mg_if_timer(nc, now); -#if MG_ENABLE_SSL - if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL && - cs->pcb.tcp->state == ESTABLISHED) { - if (((nc->flags & MG_F_WANT_WRITE) || - ((nc->send_mbuf.len > 0) && - (nc->flags & MG_F_SSL_HANDSHAKE_DONE))) && - cs->pcb.tcp->snd_buf > 0) { - /* Can write more. */ - if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { - if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc); - } else { - mg_lwip_ssl_do_hs(nc); - } - } - if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) { - if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) { - if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc); - } else { - mg_lwip_ssl_do_hs(nc); - } - } - } else -#endif /* MG_ENABLE_SSL */ - { - if (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING)) { - mg_lwip_send_more(nc); - } - } - if (nc->sock != INVALID_SOCKET && - !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL && - cs->pcb.tcp->unsent != NULL) { - tcpip_callback(tcp_output_tcpip, cs->pcb.tcp); - } - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - - if (nc->sock != INVALID_SOCKET) { - /* Try to consume data from cs->rx_chain */ - mg_lwip_consume_rx_chain_tcp(nc); - - /* - * If the connection is about to close, and rx_chain is finally empty, - * send the MG_SIG_CLOSE_CONN signal - */ - if (cs->draining_rx_chain && cs->rx_chain == NULL) { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } - } - } -#if 0 - DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms", - (unsigned int) (now * 1000), n, num_timers, - (unsigned int) (min_timer * 1000), timeout_ms)); -#endif - (void) timeout_ms; - return now; -} - -uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) { - struct mg_connection *nc; - double now; - double min_timer = 0; - int num_timers = 0; - mg_ev_mgr_lwip_process_signals(mgr); - for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - if (nc->ev_timer_time > 0) { - if (num_timers == 0 || nc->ev_timer_time < min_timer) { - min_timer = nc->ev_timer_time; - } - num_timers++; - } - if (nc->send_mbuf.len > 0 -#if MG_ENABLE_SSL - || (nc->flags & MG_F_WANT_WRITE) -#endif - ) { - int can_send = 0; - /* We have stuff to send, but can we? */ - if (nc->flags & MG_F_UDP) { - /* UDP is always ready for sending. */ - can_send = (cs->pcb.udp != NULL); - } else { - can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0); - } - /* We want and can send, request a poll immediately. */ - if (can_send) return 0; - } - } - uint32_t timeout_ms = ~0; - now = mg_time(); - if (num_timers > 0) { - /* If we have a timer that is past due, do a poll ASAP. */ - if (min_timer < now) return 0; - double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */; - if (timer_timeout_ms < timeout_ms) { - timeout_ms = timer_timeout_ms; - } - } - return timeout_ms; -} - -#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/lwip/mg_lwip_ssl_if.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL - -/* Amalgamated: #include "common/mg_mem.h" */ -/* Amalgamated: #include "common/cs_dbg.h" */ - -#include -#include - -#ifndef MG_LWIP_SSL_IO_SIZE -#define MG_LWIP_SSL_IO_SIZE 1024 -#endif - -#ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif - -void mg_lwip_ssl_do_hs(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - int server_side = (nc->listener != NULL); - enum mg_ssl_if_result res; - if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return; - res = mg_ssl_if_handshake(nc); - DBG(("%p %lu %d %d", nc, nc->flags, server_side, res)); - if (res != MG_SSL_OK) { - if (res == MG_SSL_WANT_WRITE) { - nc->flags |= MG_F_WANT_WRITE; - cs->err = 0; - } else if (res == MG_SSL_WANT_READ) { - /* - * Nothing to do in particular, we are callback-driven. - * What we definitely do not need anymore is SSL reading (nothing left). - */ - nc->flags &= ~MG_F_WANT_READ; - cs->err = 0; - } else { - cs->err = res; - if (server_side) { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } else { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - } - } - } else { - cs->err = 0; - nc->flags &= ~MG_F_WANT_WRITE; - /* - * Handshake is done. Schedule a read immediately to consume app data - * which may already be waiting. - */ - nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ); - if (server_side) { - mg_lwip_accept_conn(nc, cs->pcb.tcp); - } else { - mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc); - } - } -} - -void mg_lwip_ssl_send(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) { - DBG(("%p invalid socket", nc)); - return; - } - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - /* It's ok if the buffer is empty. Return value of 0 may also be valid. */ - int len = cs->last_ssl_write_size; - if (len == 0) { - len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len); - } - int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len); - DBG(("%p SSL_write %u = %d", nc, len, ret)); - if (ret > 0) { - mg_if_sent_cb(nc, ret); - cs->last_ssl_write_size = 0; - } else if (ret < 0) { - /* This is tricky. We must remember the exact data we were sending to retry - * exactly the same send next time. */ - cs->last_ssl_write_size = len; - } - if (ret == len) { - nc->flags &= ~MG_F_WANT_WRITE; - } else if (ret == MG_SSL_WANT_WRITE) { - nc->flags |= MG_F_WANT_WRITE; - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - } -} - -void mg_lwip_ssl_recv(struct mg_connection *nc) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - /* Don't deliver data before connect callback */ - if (nc->flags & MG_F_CONNECTING) return; - while (nc->recv_mbuf.len < nc->recv_mbuf_limit) { - char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE); - if (buf == NULL) return; - int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE); - DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret)); - if (ret <= 0) { - MG_FREE(buf); - if (ret == MG_SSL_WANT_WRITE) { - nc->flags |= MG_F_WANT_WRITE; - return; - } else if (ret == MG_SSL_WANT_READ) { - /* - * Nothing to do in particular, we are callback-driven. - * What we definitely do not need anymore is SSL reading (nothing left). - */ - nc->flags &= ~MG_F_WANT_READ; - cs->err = 0; - return; - } else { - mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc); - return; - } - } else { - mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */); - } - } -} - -#ifdef KR_VERSION - -ssize_t kr_send(int fd, const void *buf, size_t len) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd; - int ret = mg_lwip_tcp_write(cs->nc, buf, len); - DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret)); - if (ret == 0) ret = KR_IO_WOULDBLOCK; - return ret; -} - -ssize_t kr_recv(int fd, void *buf, size_t len) { - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd; - struct pbuf *seg = cs->rx_chain; - if (seg == NULL) { - DBG(("%u - nothing to read", len)); - return KR_IO_WOULDBLOCK; - } - size_t seg_len = (seg->len - cs->rx_offset); - DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len)); - len = MIN(len, seg_len); - pbuf_copy_partial(seg, buf, len, cs->rx_offset); - cs->rx_offset += len; - tcp_recved(cs->pcb.tcp, len); - if (cs->rx_offset == cs->rx_chain->len) { - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - cs->rx_offset = 0; - } - return len; -} - -#elif MG_SSL_IF == MG_SSL_IF_MBEDTLS - -int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) { - struct mg_connection *nc = (struct mg_connection *) ctx; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - int ret = mg_lwip_tcp_write(cs->nc, buf, len); - if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE; - LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret)); - return ret; -} - -int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) { - struct mg_connection *nc = (struct mg_connection *) ctx; - struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock; - struct pbuf *seg = cs->rx_chain; - if (seg == NULL) { - DBG(("%u - nothing to read", len)); - return MBEDTLS_ERR_SSL_WANT_READ; - } - size_t seg_len = (seg->len - cs->rx_offset); - DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len)); - mgos_lock(); - len = MIN(len, seg_len); - pbuf_copy_partial(seg, buf, len, cs->rx_offset); - cs->rx_offset += len; - /* TCP PCB may be NULL if connection has already been closed - * but we still have data to deliver to SSL. */ - if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len); - if (cs->rx_offset == cs->rx_chain->len) { - cs->rx_chain = pbuf_dechain(cs->rx_chain); - pbuf_free(seg); - cs->rx_offset = 0; - } - mgos_unlock(); - LOG(LL_DEBUG, ("%p <- %d", nc, (int) len)); - return len; -} - -#endif - -#endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/wince/wince_libc.c" -#endif -/* - * Copyright (c) 2016 Cesanta Software Limited - * All rights reserved - */ - -#ifdef WINCE - -const char *strerror(int err) { - /* - * TODO(alashkin): there is no strerror on WinCE; - * look for similar wce_xxxx function - */ - static char buf[10]; - snprintf(buf, sizeof(buf), "%d", err); - return buf; -} - -int open(const char *filename, int oflag, int pmode) { - /* - * TODO(alashkin): mg_open function is not used in mongoose - * but exists in documentation as utility function - * Shall we delete it at all or implement for WinCE as well? - */ - DebugBreak(); - return 0; /* for compiler */ -} - -int _wstati64(const wchar_t *path, cs_stat_t *st) { - DWORD fa = GetFileAttributesW(path); - if (fa == INVALID_FILE_ATTRIBUTES) { - return -1; - } - memset(st, 0, sizeof(*st)); - if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) { - HANDLE h; - FILETIME ftime; - st->st_mode |= _S_IFREG; - h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (h == INVALID_HANDLE_VALUE) { - return -1; - } - st->st_size = GetFileSize(h, NULL); - GetFileTime(h, NULL, NULL, &ftime); - st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime + - ((uint64_t) ftime.dwHighDateTime << 32)) / - 10000000.0) - - 11644473600); - CloseHandle(h); - } else { - st->st_mode |= _S_IFDIR; - } - return 0; -} - -/* Windows CE doesn't have neither gmtime nor strftime */ -static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) { - FILETIME ft; - SYSTEMTIME systime; - if (t != NULL) { - uint64_t filetime = (*t + 11644473600) * 10000000; - ft.dwLowDateTime = filetime & 0xFFFFFFFF; - ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32; - FileTimeToSystemTime(&ft, &systime); - } else { - GetSystemTime(&systime); - } - /* There is no PRIu16 in WinCE SDK */ - snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear, - (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour, - (int) systime.wMinute, (int) systime.wSecond); -} - -#endif -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/pic32/pic32_net_if.h" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ -#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ - -/* Amalgamated: #include "mongoose/src/net_if.h" */ - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -#ifndef MG_ENABLE_NET_IF_PIC32 -#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32 -#endif - -extern const struct mg_iface_vtable mg_pic32_iface_vtable; - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/pic32/pic32_net_if.c" -#endif -/* - * Copyright (c) 2014-2016 Cesanta Software Limited - * All rights reserved - */ - -#if MG_ENABLE_NET_IF_PIC32 - -int mg_pic32_if_create_conn(struct mg_connection *nc) { - (void) nc; - return 1; -} - -void mg_pic32_if_recved(struct mg_connection *nc, size_t len) { - (void) nc; - (void) len; -} - -void mg_pic32_if_add_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_pic32_if_init(struct mg_iface *iface) { - (void) iface; - (void) mg_get_errno(); /* Shutup compiler */ -} - -void mg_pic32_if_free(struct mg_iface *iface) { - (void) iface; -} - -void mg_pic32_if_remove_conn(struct mg_connection *nc) { - (void) nc; -} - -void mg_pic32_if_destroy_conn(struct mg_connection *nc) { - if (nc->sock == INVALID_SOCKET) return; - /* For UDP, only close outgoing sockets or listeners. */ - if (!(nc->flags & MG_F_UDP)) { - /* Close TCP */ - TCPIP_TCP_Close((TCP_SOCKET) nc->sock); - } else if (nc->listener == NULL) { - /* Only close outgoing UDP or listeners. */ - TCPIP_UDP_Close((UDP_SOCKET) nc->sock); - } - - nc->sock = INVALID_SOCKET; -} - -int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) { - nc->sock = TCPIP_UDP_ServerOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), - sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); - if (nc->sock == INVALID_SOCKET) { - return -1; - } - return 0; -} - -void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, - size_t len) { - mbuf_append(&nc->send_mbuf, buf, len); -} - -int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) { - nc->sock = TCPIP_TCP_ServerOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), - sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin); - memcpy(&nc->sa, sa, sizeof(*sa)); - if (nc->sock == INVALID_SOCKET) { - return -1; - } - return 0; -} - -static int mg_accept_conn(struct mg_connection *lc) { - struct mg_connection *nc; - TCP_SOCKET_INFO si; - union socket_address sa; - - nc = mg_if_accept_new_conn(lc); - - if (nc == NULL) { - return 0; - } - - nc->sock = lc->sock; - nc->flags &= ~MG_F_LISTENING; - - if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) { - return 0; - } - - if (si.addressType == IP_ADDRESS_TYPE_IPV4) { - sa.sin.sin_family = AF_INET; - sa.sin.sin_port = htons(si.remotePort); - sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val; - } else { - /* TODO(alashkin): do something with _potential_ IPv6 */ - memset(&sa, 0, sizeof(sa)); - } - - mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa)); - - return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0; -} - -char *inet_ntoa(struct in_addr in) { - static char addr[17]; - snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1, - (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3, - (int) in.S_un.S_un_b.s_b4); - return addr; -} - -static void mg_handle_send(struct mg_connection *nc) { - uint16_t bytes_written = 0; - if (nc->flags & MG_F_UDP) { - if (!TCPIP_UDP_RemoteBind( - (UDP_SOCKET) nc->sock, - nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - return; - } - bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0); - if (bytes_written >= nc->send_mbuf.len) { - if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock, - (uint8_t *) nc->send_mbuf.buf, - nc->send_mbuf.len) != nc->send_mbuf.len) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_written = 0; - } - } - } else { - bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock); - if (bytes_written != 0) { - if (bytes_written > nc->send_mbuf.len) { - bytes_written = nc->send_mbuf.len; - } - if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock, - (uint8_t *) nc->send_mbuf.buf, - bytes_written) != bytes_written) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_written = 0; - } - } - } - - mg_if_sent_cb(nc, bytes_written); -} - -static void mg_handle_recv(struct mg_connection *nc) { - uint16_t bytes_read = 0; - uint8_t *buf = NULL; - if (nc->flags & MG_F_UDP) { - bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock); - if (bytes_read != 0 && - (nc->recv_mbuf_limit == -1 || - nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) { - buf = (uint8_t *) MG_MALLOC(bytes_read); - if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) != - bytes_read) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - bytes_read = 0; - MG_FREE(buf); - } - } - } else { - bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock); - if (bytes_read != 0) { - if (nc->recv_mbuf_limit != -1 && - nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) { - bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len; - } - buf = (uint8_t *) MG_MALLOC(bytes_read); - if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) != - bytes_read) { - nc->flags |= MG_F_CLOSE_IMMEDIATELY; - MG_FREE(buf); - bytes_read = 0; - } - } - } - - if (bytes_read != 0) { - mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */); - } -} - -time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) { - struct mg_mgr *mgr = iface->mgr; - double now = mg_time(); - struct mg_connection *nc, *tmp; - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - - if (nc->flags & MG_F_CONNECTING) { - /* processing connections */ - if (nc->flags & MG_F_UDP || - TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { - mg_if_connect_cb(nc, 0); - } - } else if (nc->flags & MG_F_LISTENING) { - if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) { - /* accept new connections */ - mg_accept_conn(nc); - } - } else { - if (nc->send_mbuf.len != 0) { - mg_handle_send(nc); - } - - if (nc->recv_mbuf_limit == -1 || - nc->recv_mbuf.len < nc->recv_mbuf_limit) { - mg_handle_recv(nc); - } - } - } - - for (nc = mgr->active_connections; nc != NULL; nc = tmp) { - tmp = nc->next; - if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) || - (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) { - mg_close_conn(nc); - } - } - - return now; -} - -void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) { - nc->sock = sock; -} - -void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, - union socket_address *sa) { - /* TODO(alaskin): not implemented yet */ -} - -void mg_pic32_if_connect_tcp(struct mg_connection *nc, - const union socket_address *sa) { - nc->sock = TCPIP_TCP_ClientOpen( - sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4 - : IP_ADDRESS_TYPE_IPV6, - ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin); - nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; -} - -void mg_pic32_if_connect_udp(struct mg_connection *nc) { - nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL); - nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0; -} - -/* clang-format off */ -#define MG_PIC32_IFACE_VTABLE \ - { \ - mg_pic32_if_init, \ - mg_pic32_if_free, \ - mg_pic32_if_add_conn, \ - mg_pic32_if_remove_conn, \ - mg_pic32_if_poll, \ - mg_pic32_if_listen_tcp, \ - mg_pic32_if_listen_udp, \ - mg_pic32_if_connect_tcp, \ - mg_pic32_if_connect_udp, \ - mg_pic32_if_tcp_send, \ - mg_pic32_if_udp_send, \ - mg_pic32_if_recved, \ - mg_pic32_if_create_conn, \ - mg_pic32_if_destroy_conn, \ - mg_pic32_if_sock_set, \ - mg_pic32_if_get_conn_addr, \ - } -/* clang-format on */ - -const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE; -#if MG_NET_IF == MG_NET_IF_PIC32 -const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE; -#endif - -#endif /* MG_ENABLE_NET_IF_PIC32 */ -#ifdef MG_MODULE_LINES -#line 1 "common/platforms/windows/windows_direct.c" -#endif -/* - * Copyright (c) 2017 Cesanta Software Limited - * All rights reserved - */ - -#ifdef _WIN32 - -int rmdir(const char *dirname) { - return _rmdir(dirname); -} - -unsigned int sleep(unsigned int seconds) { - Sleep(seconds * 1000); - return 0; -} - -#endif /* _WIN32 */ Index: plugins/htmlinterface/torrentlistgenerator.h =================================================================== --- plugins/htmlinterface/torrentlistgenerator.h +++ plugins/htmlinterface/torrentlistgenerator.h @@ -45,17 +45,12 @@ TorrentListGenerator(CoreInterface* core); virtual ~TorrentListGenerator(); - void get(char ** str_p, int * size); - virtual void post(char * json); - // virtual void post(HttpClientHandler* hdlr, const QHttpRequestHeader& hdr, const QByteArray& data); - + QByteArray get(); + virtual void post(QString json); private: CoreInterface* core; TorrentInterface * getTorrentFromHash(QString hash); - const static SHA1Hash * QStringToSHA1Hash(QString qString); - Uint8 static char2int(char input); - void static hex2bin(const char * src, Uint8 * target); }; Index: plugins/htmlinterface/torrentlistgenerator.cpp =================================================================== --- plugins/htmlinterface/torrentlistgenerator.cpp +++ plugins/htmlinterface/torrentlistgenerator.cpp @@ -22,6 +22,7 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ +#include #include #include #include @@ -33,6 +34,7 @@ #include "torrentlistgenerator.h" #include #include +#include #include using namespace bt; @@ -51,132 +53,161 @@ } - void TorrentListGenerator::get(char ** str_p, int * size) + QByteArray TorrentListGenerator::get() { kt::QueueManager* qman = core->getQueueManager(); kt::QueueManager::iterator i = qman->begin(); - QJsonArray array = QJsonArray(); + QJsonArray array; while (i != qman->end()) { bt::TorrentInterface* ti = *i; const bt::TorrentStats& s = ti->getStats(); - QJsonObject json = QJsonObject() ; - json.insert(QString::fromLocal8Bit("name"), ti->getDisplayName()); - json.insert(QString::fromLocal8Bit("infoHash"), ti->getInfoHash().toString()); - json.insert(QString::fromLocal8Bit("status"), s.status); - json.insert(QString::fromLocal8Bit("timeAdded"), s.time_added.toMSecsSinceEpoch()); - json.insert(QString::fromLocal8Bit("bytesDownloaded"), (double) s.bytes_downloaded); - json.insert(QString::fromLocal8Bit("bytesUploaded"), (double) s.bytes_uploaded); - json.insert(QString::fromLocal8Bit("totalBytes"), (double) s.total_bytes); - json.insert(QString::fromLocal8Bit("totalBytesToDownload"), (double) s.total_bytes_to_download); - json.insert(QString::fromLocal8Bit("downloadRate"), (double) s.download_rate); - json.insert(QString::fromLocal8Bit("uploadRate"), (double) s.upload_rate); - json.insert(QString::fromLocal8Bit("numPeers"), (double) s.num_peers); - json.insert(QString::fromLocal8Bit("seeders"), (double) s.seeders_connected_to); - json.insert(QString::fromLocal8Bit("seedersTotal"), (double) s.seeders_total); - json.insert(QString::fromLocal8Bit("leechers"), (double) s.leechers_connected_to); - json.insert(QString::fromLocal8Bit("leechersTotal"), (double) s.leechers_total); - json.insert(QString::fromLocal8Bit("running"), s.running); - json.insert(QString::fromLocal8Bit("numFiles"), (double) ti->getNumFiles()); + QJsonObject json; + json.insert(QString::fromLatin1("name"), ti->getDisplayName()); + json.insert(QString::fromLatin1("infoHash"), ti->getInfoHash().toString()); + json.insert(QString::fromLatin1("status"), s.status); + json.insert(QString::fromLatin1("timeAdded"), s.time_added.toMSecsSinceEpoch()); + json.insert(QString::fromLatin1("bytesDownloaded"), (double) s.bytes_downloaded); + json.insert(QString::fromLatin1("bytesUploaded"), (double) s.bytes_uploaded); + json.insert(QString::fromLatin1("totalBytes"), (double) s.total_bytes); + json.insert(QString::fromLatin1("totalBytesToDownload"), (double) s.total_bytes_to_download); + json.insert(QString::fromLatin1("downloadRate"), (double) s.download_rate); + json.insert(QString::fromLatin1("uploadRate"), (double) s.upload_rate); + json.insert(QString::fromLatin1("numPeers"), (double) s.num_peers); + json.insert(QString::fromLatin1("seeders"), (double) s.seeders_connected_to); + json.insert(QString::fromLatin1("seedersTotal"), (double) s.seeders_total); + json.insert(QString::fromLatin1("leechers"), (double) s.leechers_connected_to); + json.insert(QString::fromLatin1("leechersTotal"), (double) s.leechers_total); + json.insert(QString::fromLatin1("running"), s.running); + json.insert(QString::fromLatin1("numFiles"), (double) ti->getNumFiles()); array.append(json); i++; } - QJsonObject message = QJsonObject(); - message.insert(QString::fromLocal8Bit("torrents"), array); - QJsonDocument doc = QJsonDocument(message); - *str_p = doc.toJson().data(); - *size = doc.toJson().size(); + QJsonObject message; + message.insert(QString::fromLatin1("torrents"), array); + return QJsonDocument(message).toJson(); } - void TorrentListGenerator::post(char * json) { - QJsonDocument doc = QJsonDocument::fromJson(QByteArray((const char *) json)); + void TorrentListGenerator::post(QString json) + { + QJsonDocument doc = QJsonDocument::fromJson(json.toLatin1()); QMap qJson = doc.toVariant().toMap(); QString action = qJson[QString::fromLatin1("type")].toString(); - if (action.isEmpty() || action.isNull()) { + if (action.isEmpty()) + { return; } - if (action == QString::fromLatin1("magnet")) { + if (action == QString::fromLatin1("magnet")) + { QString magnet = qJson[QString::fromLatin1("magnet")].toString(); - if (magnet.isEmpty() || magnet.isNull()) { + if (magnet.isEmpty()) + { return; } - core->loadSilently(QUrl(magnet), QString()); + QUrl url = QUrl(magnet); + if (!url.isValid()) + { + return; + } + core->loadSilently(url, QString()); return; } QString hash = qJson[QString::fromLatin1("hash")].toString(); - if (hash.isEmpty() || hash.isNull()) { + if (hash.isEmpty()) + { return; } TorrentInterface * ti = getTorrentFromHash(hash); - if (action == QString::fromLatin1("start")) { - if (ti->getStats().paused) { + if (action == QString::fromLatin1("start")) + { + if (ti->getStats().paused) + { ti->unpause(); - } else { + } + else + { ti->start(); } } - if (action == QString::fromLatin1("pause")) { - ti->pause(); + else if (action == QString::fromLatin1("stop")) + { + core->stop(ti); } - if (action == QString::fromLatin1("remove")) { + else if (action == QString::fromLatin1("remove")) + { core->remove(ti, false); } } - const SHA1Hash * TorrentListGenerator::QStringToSHA1Hash(QString qString) { - Uint8 hashNum[20] = {}; - hex2bin((const char *) qString.toLatin1().data(), hashNum); + /** + * From: https://github.com/KDE/libktorrent/blob/master/src/dht/tests/keytest.cpp + */ + static Uint8 HexCharToUint8(char c) + { + if (c >= 'a' && c <= 'f') + return 10 + (c - 'a'); + else if (c >= 'A' && c <= 'F') + return 10 + (c - 'A'); + else if (c >= '0' && c <= '9') + return c - '0'; + else + return 0; + } + + /** + * Based on: https://github.com/KDE/libktorrent/blob/master/src/dht/tests/keytest.cpp + */ + static Uint8 * HashFromHexString(QString & str) + { + bt::Uint8 * result = new Uint8[20]; + std::fill(result, result + 20, 0); + + QString s = str.toLower(); + if (s.size() % 2 != 0) + { + s.prepend(QChar::fromLatin1('0')); + } + + int j = 19; + + for (int i = s.size() - 1; i >= 0; i -= 2) + { + char left = s[i - 1].toLatin1(); + char right = s[i].toLatin1(); + result[j--] = (HexCharToUint8(left) << 4) | HexCharToUint8(right); + } + return result; + } + + static const SHA1Hash * QStringToSHA1Hash(QString qString) { + Uint8 * hashNum = HashFromHexString(qString); const SHA1Hash * hash = new SHA1Hash(hashNum); + delete hashNum; return hash; } - - TorrentInterface * TorrentListGenerator::getTorrentFromHash(QString qHash) { + + TorrentInterface * TorrentListGenerator::getTorrentFromHash(QString qHash) + { const SHA1Hash * hash = QStringToSHA1Hash(qHash); kt::QueueManager* qman = core->getQueueManager(); kt::QueueManager::iterator i = qman->begin(); while (i != qman->end()) { bt::TorrentInterface* ti = *i; - const bt::TorrentStats& s = ti->getStats(); - if (ti->getInfoHash() == *hash) { + if (ti->getInfoHash() == *hash) + { + delete hash; return ti; } i++; } + delete hash; return NULL; } - - /** - * Shameless ripped from: https://stackoverflow.com/a/17261928/313273 - */ - Uint8 TorrentListGenerator::char2int(char input) - { - if(input >= '0' && input <= '9') - return (Uint8) input - '0'; - if(input >= 'A' && input <= 'F') - return (Uint8) input - 'A' + 10; - if(input >= 'a' && input <= 'f') - return (Uint8) input - 'a' + 10; - throw std::invalid_argument("Invalid input string"); - } - - /** - * Shamelessly ripped from: https://stackoverflow.com/a/17261928/313273 - * This function assumes src to be a zero terminated sanitized string with - * an even number of [0-9a-f] characters, and target to be sufficiently large. - */ - void TorrentListGenerator::hex2bin(const char * src, Uint8 * target) - { - while(*src && src[1]) - { - *(target++) = char2int(*src) * 16 + char2int(src[1]); - src += 2; - } - } } Index: plugins/htmlinterface/webserver.h =================================================================== --- plugins/htmlinterface/webserver.h +++ plugins/htmlinterface/webserver.h @@ -25,10 +25,9 @@ #include #include +#include #include "torrentlistgenerator.h" -#include "mongoose.h" - namespace kt { class WebServer : public QObject @@ -39,14 +38,21 @@ ~WebServer(); public slots: void process(); - static void httpeventhandler(struct mg_connection * c, int ev, void * ev_data); signals: void finished(); void error(QString err); private: - struct mg_mgr mgr; + static int answer_to_connection(void *cls, struct MHD_Connection *connection, + const char *url, const char *method, + const char *version, const char *upload_data, + size_t *upload_data_size, void **con_cls); + struct MHD_Daemon *daemon; CoreInterface * core; static TorrentListGenerator * listGenerator; + static QString sessionToken; + static const char * makeCookie(); + static const char * cookie; + static bool checkForToken(MHD_Connection * connection); }; } Index: plugins/htmlinterface/webserver.cpp =================================================================== --- plugins/htmlinterface/webserver.cpp +++ plugins/htmlinterface/webserver.cpp @@ -21,13 +21,18 @@ #include #include "webserver.h" -using namespace std; - #include +#include +#include #include #include #include #include +#include +#include +#define GET 0 +#define POST 1 +#define POSTBUFFERSIZE 65536 using namespace std; @@ -39,66 +44,166 @@ WebServer::~WebServer() { + MHD_stop_daemon (daemon); + delete listGenerator; } + static QMimeDatabase mimeDatabase; + + static QString BASE_DIRECTORY = QString::fromLatin1("/usr/share/ktorrent/html/"); + TorrentListGenerator * WebServer::listGenerator; - - void WebServer::process() + + QString WebServer::sessionToken; + + const char * WebServer::cookie; + + static int respond404(MHD_Connection * connection) { - listGenerator = new TorrentListGenerator(core); - struct mg_connection *c; + int ret; + struct MHD_Response *response; - mg_mgr_init(&mgr, NULL); - c = mg_bind(&mgr, "8880", WebServer::httpeventhandler); - mg_set_protocol_http_websocket(c); - while (true) { - mg_mgr_poll(&mgr, 1000); - } + const char * message = "404: The requested resource was not found."; + + response = MHD_create_response_from_buffer (strlen(message), (void *) message, MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); + MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html"); + MHD_destroy_response (response); + return ret; } - void WebServer::httpeventhandler(struct mg_connection * c, int ev, void * ev_data) { - if (ev == MG_EV_HTTP_REQUEST) - { - struct mg_serve_http_opts opts; + static int respond500(MHD_Connection * connection) + { + int ret; + struct MHD_Response *response; - memset(&opts, 0, sizeof(opts)); // Reset all options to defaults - opts.document_root = "/usr/share/ktorrent/html/"; - - struct http_message * message = (struct http_message *) ev_data; + const char * message = "500: An internal server error has occured."; - char * method = new char[message->method.len + 1]; - strncpy(method, message->method.p, message->method.len); - method[message->method.len] = '\0'; + response = MHD_create_response_from_buffer (strlen(message), (void *) message, MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); + MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html"); + MHD_destroy_response (response); + return ret; + } - char * uri = new char[message->uri.len + 1]; - strncpy(uri, message->uri.p, message->uri.len); - uri[message->uri.len] = '\0'; + struct Json + { + QString json; + bool firstPass; + }; + + int WebServer::answer_to_connection(void * cls, struct MHD_Connection * connection, + const char * url, const char * method, + const char * version, const char * upload_data, + size_t * upload_data_size, void ** con_cls) + { + int ret; + struct MHD_Response *response; - if (strcmp(uri, "/ktorrentdata") == 0 && strcmp(method, "GET") == 0) + if (strcmp("/ktorrentdata", url) == 0 && strcmp("GET", method) == 0) + { + QByteArray json = listGenerator->get(); + response = MHD_create_response_from_buffer (json.size(), (void *) json.data(), + MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response (connection, MHD_HTTP_OK, response); + MHD_destroy_response (response); + return ret; + } + if (strcmp("/ktorrentaction", url) == 0 && strcmp("POST", method) == 0) + { + Json * json; + if (*con_cls == NULL) { - char * json = NULL; - int size; - listGenerator->get(&json, &size); - mg_send_head(c, 200, size, "Content-Type: application/json\nAccess-Control-Allow-Origin: *"); - mg_printf(c, "%s", json); - return; + json = new Json(); + *con_cls = (void *) json; + json->firstPass = true; } - if (strcmp(uri, "/ktorrentaction") == 0) + else { - char * body = new char[message->body.len + 1]; - strncpy(body, message->body.p, message->body.len); - body[message->body.len] = '\0'; + json = (Json *) *con_cls; + } - if (strcmp(method, "POST") == 0) { - listGenerator->post(body); + if (json->firstPass) { + json->firstPass = false; + return MHD_YES; + } + if (*upload_data_size > 0 && !json->firstPass) + { + QString qJson = QString::fromLatin1(upload_data, *upload_data_size); + json->json.append(qJson); + if (checkForToken(connection)) + { + listGenerator->post(json->json); } - const char * validation = "{\"status\":\"Request received.\"}"; - int len = strlen(validation); - mg_send_head(c, 200, len, "Content-Type: application/json\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Headers: X-ACCESS_TOKEN, Access-Control-Allow-Origin, Authorization, Origin, x-requested-with, Content-Type, Content-Range, Content-Disposition, Content-Description\nAccess-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS"); - mg_printf(c, "%s", validation); - return; + *upload_data_size = 0; + return MHD_YES; } - mg_serve_http(c, (struct http_message *) ev_data, opts); + const char * validation = "{\"status\":\"Request received.\"}"; + response = MHD_create_response_from_buffer(strlen(validation), (void *) validation, + MHD_RESPMEM_PERSISTENT); + MHD_add_response_header(response, "Content-Type", "application/json"); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + return ret; + } + struct stat sbuf; + int fd; + if (0 == strcmp(url, "/") || 0 == strcmp(url, "/index")) + { + url = "index.html"; + } + QString qUrl = QString::fromLatin1(url); + const char * file = (BASE_DIRECTORY + qUrl).toLatin1().data(); + if ((-1 == (fd = open(file, O_RDONLY))) || (0 != fstat(fd, &sbuf))) + { + return respond404(connection); + } + response = MHD_create_response_from_fd_at_offset64(sbuf.st_size, fd, 0); + const char * mimeType = mimeDatabase.mimeTypeForFile(qUrl).name().toLatin1().data(); + MHD_add_response_header(response, "Content-Type", mimeType); + MHD_add_response_header(response, "Set-Cookie", makeCookie()); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response (response); + return ret; + } + + static void request_completed (void *cls, struct MHD_Connection *connection, + void **con_cls, enum MHD_RequestTerminationCode toe) + { + Json * json = (Json *) *con_cls; + + delete json; + } + + void WebServer::process() + { + listGenerator = new TorrentListGenerator(core); + sessionToken = QUuid::createUuid().toString(); + cookie = makeCookie(); + + daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, 8880, NULL, NULL, + &answer_to_connection, NULL, + MHD_OPTION_NOTIFY_COMPLETED, request_completed, + NULL, MHD_OPTION_END); + } + + const char * WebServer::makeCookie() + { + QString tempString = QString::fromLatin1("token=") + sessionToken; + return tempString.toLatin1().data(); + } + + bool WebServer::checkForToken(MHD_Connection * connection) + { + const char * token = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "session-Token"); + if (token == NULL) + { + return false; + } + if (strcmp(token, sessionToken.toLatin1().data()) == 0) + { + return true; } + return false; } } Index: plugins/infowidget/ktorrent_infowidget.desktop =================================================================== --- plugins/infowidget/ktorrent_infowidget.desktop +++ plugins/infowidget/ktorrent_infowidget.desktop @@ -1,7 +1,5 @@ [Desktop Entry] Name=Information Widget -Name[ar]=ودجة المعلومات -Name[ast]=Widget d'información Name[bg]=Джаджа с данни Name[bs]=Widget podataka Name[ca]=Estri d'informació @@ -51,8 +49,6 @@ Name[zh_CN]=信息部件 Name[zh_TW]=資訊元件 Comment=Displays general information about a torrent in several tabs -Comment[ar]=تعرض معلومات عامة عن أحد السّيول في عدّة ألسنة -Comment[ast]=Amuesa información xeneral tocante a un torrent en delles llingüetes Comment[bg]=Показване на различни данни за торентите в няколко подпрозореца Comment[bs]=Prikazuje opšte podatke o torentu u nekoliko kartica Comment[ca]=Mostra informació general quant a un torrent en diverses pestanyes @@ -67,7 +63,7 @@ Comment[fi]=Näyttää eri välilehdillä yleistietoja torrentista Comment[fr]=Affiche des informations générales sur un torrent dans plusieurs onglets Comment[ga]=Breiseán a thaispeánann eolas ginearálta maidir le torrent i gcluaisíní éagsúla -Comment[gl]=Mostrar información sobre un torrente en varias lapelas. +Comment[gl]=Mostrar información acerca dun torrente en varias lapelas. Comment[hu]=Általános információk megjelenítése több lapon egy torrentről Comment[is]=Birtir í nokkrum flipum almennar upplýsingar um torrent straum Comment[it]=Visualizza in diverse schede informazioni generali sul torrent @@ -105,7 +101,7 @@ X-KDE-PluginInfo-Author=Joris Guisson, Ivan Vasic X-KDE-PluginInfo-Email=joris.guisson@gmail.com, ivasic@gmail.com X-KDE-PluginInfo-Name=InfoWidgetPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=true Icon=kt-info-widget Index: plugins/ipfilter/ktorrent_ipfilter.desktop =================================================================== --- plugins/ipfilter/ktorrent_ipfilter.desktop +++ plugins/ipfilter/ktorrent_ipfilter.desktop @@ -1,6 +1,5 @@ [Desktop Entry] Name=IP Filter -Name[ast]=Peñera d'IPs Name[bg]=Филтър по IP Name[bs]=IP filter Name[ca]=Filtre d'IP @@ -27,10 +26,8 @@ Name[ko]=IP 필터 Name[lt]=IP filtras Name[lv]=IP filtrs -Name[nb]=IP-filter Name[nds]=IP-Filter Name[nl]=IP-filter -Name[nn]=IP-filter Name[pl]=Filtr IP Name[pt]=Filtro de IPs Name[pt_BR]=Filtro de IP @@ -52,7 +49,6 @@ Name[zh_CN]=IP 过滤器 Name[zh_TW]=IP 過濾 Comment=Filter IP addresses through a blocklist -Comment[ast]=Peñera direiciones IP pente un llistáu de bloquéu Comment[bg]=Филтриране на IP-адресите с черен списък Comment[bs]=Filtrirajte IP adrese kroz listu blokiranja Comment[ca]=Filtra les adreces IP a través d'una llista de bloqueig @@ -77,10 +73,8 @@ Comment[ko]=차단 목록으로 IP 주소 필터링 Comment[lt]=Filtruoti IP adresus per blocklist'ą Comment[lv]=Filtrē IP adreses ar bloķēšanas saraksta palīdzību -Comment[nb]=Filtrer IP-adresser gjennom en svarteliste Comment[nds]=IP-Adressen över en Blockeerlist filtern Comment[nl]=Filter IP-adressen via een blokkeerlijst -Comment[nn]=Filtrer IP-adresser gjennom ei blokkeringsliste Comment[pl]=Filtrowanie adresów IP z wykorzystaniem spisu blokowanych adresów Comment[pt]=Filtra os endereços IP através de uma lista de bloqueios Comment[pt_BR]=Filtra os endereços IP através de uma lista de bloqueio @@ -105,7 +99,7 @@ X-KDE-PluginInfo-Author=Joris Guisson, Ivan Vasic X-KDE-PluginInfo-Email=joris.guisson@gmail.com, ivasic@gmail.com X-KDE-PluginInfo-Name=IPFilterPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=view-filter Index: plugins/logviewer/ktorrent_logviewer.desktop =================================================================== --- plugins/logviewer/ktorrent_logviewer.desktop +++ plugins/logviewer/ktorrent_logviewer.desktop @@ -1,10 +1,5 @@ [Desktop Entry] Name=Log Viewer -Name[ar]=عارض السّجلات -<<<<<<< HEAD -======= -Name[ast]=Visor de rexistros ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Name[bg]=Преглед на дневника Name[bs]=Prikazivač dnevnika Name[ca]=Visor del registre @@ -57,7 +52,6 @@ Name[zh_CN]=日志查看器 Name[zh_TW]=紀錄檢視器 Comment=Displays the logging output -Comment[ast]=Amuesa la salida del rexistru Comment[bg]=Показване на изхода от дневника Comment[bs]=Prikazuje upise dnevnika Comment[ca]=Mostra la sortida del registre @@ -110,7 +104,7 @@ X-KDE-PluginInfo-Author=Joris Guisson, Ivan Vasic X-KDE-PluginInfo-Email=joris.guisson@gmail.com, ivasic@gmail.com X-KDE-PluginInfo-Name=LogViewerPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=utilities-log-viewer Index: plugins/magnetgenerator/ktorrent_magnetgenerator.desktop =================================================================== --- plugins/magnetgenerator/ktorrent_magnetgenerator.desktop +++ plugins/magnetgenerator/ktorrent_magnetgenerator.desktop @@ -1,9 +1,8 @@ [Desktop Entry] Name=Magnet Generator -Name[ast]=Xenerador de magnets Name[bs]=Generator magneta -Name[ca]=Generador de magnet -Name[ca@valencia]=Generador de magnet +Name[ca]=Generador de «magnet» +Name[ca@valencia]=Generador de «magnet» Name[cs]=Generátor Magnet Name[da]=Magnet-generator Name[de]=Magnet-Generator @@ -45,11 +44,9 @@ Name[zh_CN]=磁力链生成器 Name[zh_TW]=Magnet 產生器 Comment=Generates magnet links -Comment[ar]=تولّد وصلات ممغنطة -Comment[ast]=Xenera enllaces magnet Comment[bs]=Stvara magnetske veze -Comment[ca]=Genera enllaços magnet -Comment[ca@valencia]=Genera enllaços magnet +Comment[ca]=Genera enllaços «magnet» +Comment[ca@valencia]=Genera enllaços «magnet» Comment[cs]=Generuje odkazy magnet Comment[da]=Genererer magnet-links Comment[de]=Erzeugt Magnet-Verknüpfungen @@ -95,7 +92,7 @@ X-KDE-PluginInfo-Author=Jonas Lundqvist X-KDE-PluginInfo-Email=jonas@gannon.se X-KDE-PluginInfo-Name=MagnetGeneratorPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=kt-magnet Index: plugins/mediaplayer/ktorrent_mediaplayer.desktop =================================================================== --- plugins/mediaplayer/ktorrent_mediaplayer.desktop +++ plugins/mediaplayer/ktorrent_mediaplayer.desktop @@ -1,10 +1,5 @@ [Desktop Entry] Name=Media Player -Name[ar]=مشغّل الوسائط -<<<<<<< HEAD -======= -Name[ast]=Reproctor de medios ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Name[bg]=Медиен плеър Name[bs]=Izvođač medija Name[ca]=Reproductor multimèdia @@ -58,11 +53,6 @@ Name[zh_CN]=媒体播放器 Name[zh_TW]=媒體播放器 Comment=Phonon-based media player -Comment[ar]=مشغّل وسائط يعتمد «فنون» -<<<<<<< HEAD -======= -Comment[ast]=Reproductor de medios basáu en Phonon ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Comment[bg]=Програма за преглед на мултимедия на основата на Phonon Comment[bs]=Medija plejer zasnovan na Fononu Comment[ca]=Reproductor de suports basat en el Phonon @@ -116,7 +106,7 @@ X-KDE-PluginInfo-Author=Joris Guisson X-KDE-PluginInfo-Email=joris.guisson@gmail.com X-KDE-PluginInfo-Name=MediaPlayerPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=applications-multimedia Index: plugins/scanfolder/ktorrent_scanfolder.desktop =================================================================== --- plugins/scanfolder/ktorrent_scanfolder.desktop +++ plugins/scanfolder/ktorrent_scanfolder.desktop @@ -1,10 +1,9 @@ [Desktop Entry] Name=Scan Folder -Name[ast]=Escaniar carpeta Name[bg]=Претърсване на директория Name[bs]=Pretraga direktorija -Name[ca]=Explora les carpetes -Name[ca@valencia]=Explora les carpetes +Name[ca]=Exploració de carpetes +Name[ca@valencia]=Exploració de carpetes Name[cs]=Procházení složek Name[da]=Scan mappe Name[de]=Ordner durchsuchen @@ -54,8 +53,8 @@ Comment=Scan folders for torrent files and load them Comment[bg]=Претърсване на директории за торент-файлове за добавяне Comment[bs]=Pretraži direktorije i učitaj torent datoteke iz njih -Comment[ca]=Explora les carpetes cercant fitxers torrent i els carrega -Comment[ca@valencia]=Explora les carpetes cercant fitxers torrent i els carrega +Comment[ca]=Explora les carpetes cercant fitxers «torrent» i els carrega +Comment[ca@valencia]=Explora les carpetes cercant fitxers «torrent» i els carrega Comment[cs]=Vyhledávat ve složkách a načítat torrenty Comment[da]=Scan mapper efter torrent-filer og indlæs dem Comment[de]=Ordner nach Torrent-Dateien durchsuchen und diese laden @@ -66,7 +65,7 @@ Comment[fi]=Etsii kansiosta torrent-tiedostoja ja lataa ne Comment[fr]=Analyse des dossiers pour rechercher des fichiers de torrents et pour les charger Comment[ga]=Lorg comhaid torrent i bhfillteáin agus luchtaigh iad -Comment[gl]=Examina cartafoles na busca de ficheiros torrent e os carga. +Comment[gl]=Examina cartafoles na busca de torrentes e os carga. Comment[hu]=Mappák figyelése és a torrentfájlok betöltése Comment[is]=Leita að torrent straumaskrám í möppum og hleður þeim inn Comment[it]=Analizza le cartelle alla ricerca di torrent e procede al loro caricamento @@ -104,7 +103,7 @@ X-KDE-PluginInfo-Author=Joris Guisson, Ivan Vasic X-KDE-PluginInfo-Email=joris.guisson@gmail.com, ivasic@gmail.com X-KDE-PluginInfo-Name=ScanFolderPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=folder-open Index: plugins/scripting/ktorrent_scripting.desktop =================================================================== --- plugins/scripting/ktorrent_scripting.desktop +++ plugins/scripting/ktorrent_scripting.desktop @@ -2,8 +2,8 @@ Name=Scripting Name[bg]=Скриптиране Name[bs]=Skriptovanje -Name[ca]=Crea scripts -Name[ca@valencia]=Crea scripts +Name[ca]=Creació de scripts +Name[ca@valencia]=Creació de scripts Name[cs]=Skriptování Name[da]=Scripting Name[de]=Skripte @@ -50,11 +50,10 @@ Name[zh_CN]=脚本 Name[zh_TW]=文稿 Comment=Enables Kross scripting support -Comment[ast]=Activa'l sofitu pa scripts Kross Comment[bg]=Включване на поддръжка на скриптиране на Kross Comment[bs]=Omogućava podršku za skriptovanje Krosom -Comment[ca]=Habilita l'ús per a crear scripts del Kross -Comment[ca@valencia]=Habilita l'ús per a crear scripts del Kross +Comment[ca]=Habilita l'ús per crear scripts del Kross +Comment[ca@valencia]=Habilita l'ús per crear scripts del Kross Comment[cs]=Podpora skriptování Kross Comment[da]=Aktiverer understøttelse af Kross-scripting Comment[de]=Aktiviert die Unterstützung für Kross-Skripte @@ -103,7 +102,7 @@ X-KDE-PluginInfo-Author=Joris Guisson X-KDE-PluginInfo-Email=joris.guisson@gmail.com X-KDE-PluginInfo-Name=ScriptingPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=text-x-script Index: plugins/scripting/scripts/auto_remove/auto_remove.desktop =================================================================== --- plugins/scripting/scripts/auto_remove/auto_remove.desktop +++ plugins/scripting/scripts/auto_remove/auto_remove.desktop @@ -1,7 +1,5 @@ [Desktop Entry] Name=Automatic Remove -Name[ar]=الإزالة الآليّة -Name[ast]=Desaniciu automáticu Name[bg]=Автоматично премахване Name[bs]=Automatsko uklanjanje Name[ca]=Supressió automàtica @@ -51,11 +49,10 @@ Name[zh_CN]=自动移除 Name[zh_TW]=自動移除 Comment=Script to automatically remove torrents when they finish downloading or seeding -Comment[ar]=سكربت لإزالة السّيول آليًّا عندما ينتهي تنزيلها أو تزويدها Comment[bg]=Скрипт за автоматично премахване на торенти при приключване с изтеглянето или разпръскването им Comment[bs]=Skripta za automatsko uklanjanje torenata nakon što završe preuzimanje ili sijanje -Comment[ca]=Script per a suprimir automàticament els torrents quan s'han acabat de baixar o sembrar -Comment[ca@valencia]=Script per a suprimir automàticament els torrents quan s'han acabat de baixar o sembrar +Comment[ca]=Script per a suprimir automàticament els «torrent» quan han acabat de baixar o sembrar +Comment[ca@valencia]=Script per a suprimir automàticament els «torrent» quan han acabat de baixar o sembrar Comment[cs]=Skript, který automaticky odstraní torrenty pokud dokončily stahování nebo sdílení Comment[da]=Script til automatisk at fjerne torrents når de er færdige med at downloade eller seede Comment[de]=Skript zum automatischen Entfernen von Torrents, wenn sie vollständig hoch- oder heruntergeladen sind @@ -102,7 +99,7 @@ Icon=kt-remove X-KTorrent-Script-Author=Joris Guisson X-KTorrent-Script-Email=joris.guisson@gmail.com -X-KTorrent-Script-Website=http://kde.org/applications/internet/ktorrent/ +X-KTorrent-Script-Website=http://ktorrent.org/ X-KTorrent-Script-License=GPL X-KTorrent-Script-File=auto_remove.py Index: plugins/scripting/scripts/email_notifications/email_notifications.desktop =================================================================== --- plugins/scripting/scripts/email_notifications/email_notifications.desktop +++ plugins/scripting/scripts/email_notifications/email_notifications.desktop @@ -1,11 +1,9 @@ [Desktop Entry] Name=E-Mail Notifications -Name[ar]=إخطارات البريد الإلكترونيّ -Name[ast]=Avisos per corréu Name[bg]=Уведомления по е-поща Name[bs]=Obavještenja E-poštom -Name[ca]=Notificacions per correu electrònic -Name[ca@valencia]=Notificacions per correu electrònic +Name[ca]=Notificacions de correu electrònic +Name[ca@valencia]=Notificacions de correu electrònic Name[cs]=Upozornění e-mailem Name[da]=E-mail-bekendtgørelser Name[de]=E-Mail-Benachrichtigungen @@ -52,7 +50,6 @@ Name[zh_CN]=电子邮件通知 Name[zh_TW]=電子郵件通知 Comment=Script to notify you of events via e-mail -Comment[ar]=سكربت لإخطارك بالأحداث عبر البريد الإلكترونيّ Comment[bg]=Скрипт за уведомяване за събития по електронната поща Comment[bs]=Skripta koja vas obavještava o dešavanjima putem e-pošte Comment[ca]=Script per a notificar els esdeveniments via correu electrònic @@ -67,7 +64,7 @@ Comment[fi]=Sähköpostitse tapahtumista tiedottava skripti Comment[fr]=Script pour vous avertir d'évènements par courrier électronique Comment[ga]=Script a chuireann teagmhais in iúl duit trí ríomhphost -Comment[gl]=Un script para notificarlle por correo os eventos. +Comment[gl]=Un script para notificarlle por correo os sucesos. Comment[hu]=Értesítés az eseményekről e-mailen keresztül Comment[is]=Skrifta til að láta þig vita að uppákomum með tölvupósti Comment[it]=Script per notificare gli eventi usando messaggi di posta @@ -104,7 +101,7 @@ Icon=mail-send X-KTorrent-Script-Author=Joris Guisson X-KTorrent-Script-Email=joris.guisson@gmail.com -X-KTorrent-Script-Website=http://kde.org/applications/internet/ktorrent/ +X-KTorrent-Script-Website=http://ktorrent.org/ X-KTorrent-Script-License=GPL X-KTorrent-Script-File=email_notifications.py Index: plugins/shutdown/ktorrent_shutdown.desktop =================================================================== --- plugins/shutdown/ktorrent_shutdown.desktop +++ plugins/shutdown/ktorrent_shutdown.desktop @@ -1,10 +1,5 @@ [Desktop Entry] Name=Shutdown -Name[ar]=الإطفاء -<<<<<<< HEAD -======= -Name[ast]=Apagar ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Name[bg]=Изключване Name[bs]=Ugasi Name[ca]=Aturada @@ -58,15 +53,10 @@ Name[zh_CN]=关机 Name[zh_TW]=關機 Comment=Allows you to shutdown your computer when torrents finish -Comment[ar]=تسمح لك بإطفاء الحاسوب عند انتهاء السّيول -<<<<<<< HEAD -======= -Comment[ast]=Pertmítete apagar l'ordeandor cuando finen los torrents ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Comment[bg]=Позволява ви да изключите компютъра си след като приключат торентите Comment[bs]=Dozvoljava gašenje vašeg računara kada torenti završe -Comment[ca]=Permet aturar l'ordinador en finalitzar els torrents -Comment[ca@valencia]=Permet aturar l'ordinador en finalitzar els torrents +Comment[ca]=Permet aturar l'ordinador en finalitzar els torrent +Comment[ca@valencia]=Permet aturar l'ordinador en finalitzar els torrent Comment[cs]=Umožní vypnutí počítače po dokončení stahování torrentu Comment[da]=Lader dig lukke din computer ned når torrents er færdige Comment[de]=Ermöglicht es, den Rechner herunterzufahren, wenn die Torrents abgeschlossen wurden @@ -115,7 +105,7 @@ X-KDE-PluginInfo-Author=Joris Guisson X-KDE-PluginInfo-Email=joris.guisson@gmail.com X-KDE-PluginInfo-Name=ShutdownPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=system-shutdown Index: plugins/stats/ktorrent_stats.desktop =================================================================== --- plugins/stats/ktorrent_stats.desktop +++ plugins/stats/ktorrent_stats.desktop @@ -1,8 +1,6 @@ [Desktop Entry] Type=Service Name=Statistics -Name[ar]=الإحصائيّات -Name[ast]=Estadístiques Name[bg]=Статистики Name[bs]=Statistike Name[ca]=Estadístiques @@ -58,8 +56,8 @@ Comment=Shows statistics about torrents in several graphs Comment[bg]=Показване на статистика на торентите в няколко графики Comment[bs]=Prikazuje statistiku o torentima u nekoliko grafikona -Comment[ca]=Mostra les estadístiques sobre els torrents en diverses gràfiques -Comment[ca@valencia]=Mostra les estadístiques sobre els torrents en diverses gràfiques +Comment[ca]=Mostra les estadístiques sobre els torrent en diverses gràfiques +Comment[ca@valencia]=Mostra les estadístiques sobre els torrent en diverses gràfiques Comment[cs]=Zobrazení statistiky o torrentech v několika grafech Comment[da]=Viser statistik om torrents i flere grafer Comment[de]=Zeigt Statistiken über Torrents in mehreren Diagrammen @@ -107,7 +105,7 @@ X-KDE-PluginInfo-Author=Krzysztof Kundzicz X-KDE-PluginInfo-Email=athantor@gmail.com X-KDE-PluginInfo-Name=StatsPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=view-statistics Index: plugins/syndication/ktorrent_syndication.desktop =================================================================== --- plugins/syndication/ktorrent_syndication.desktop +++ plugins/syndication/ktorrent_syndication.desktop @@ -1,6 +1,5 @@ [Desktop Entry] Name=Syndication -Name[ast]=Sindicación Name[bg]=Синдикиране Name[bs]=Spajanje u sindikat Name[ca]=Sindicació @@ -51,8 +50,8 @@ Comment=Syndication plugin for KTorrent, supporting RSS and Atom feeds Comment[bg]=Приставка за синдикиране на KTorrent, поддържаща емисии RSS и ATOM Comment[bs]=Priključak za spajanje u sindikat za KTorent, koji podržava RSS i atom dovode -Comment[ca]=Connector de sindicació per al KTorrent, permet canals RSS i Atom -Comment[ca@valencia]=Connector de sindicació per al KTorrent, permet canals RSS i Atom +Comment[ca]=Connector de sindicació per al KTorrent, que permet canals RSS i Atom +Comment[ca@valencia]=Connector de sindicació per al KTorrent, que permet canals RSS i Atom Comment[cs]=Modul pro publikování pro KTorrent podporující RSS a kanály Atom Comment[da]=Syndikeringsplugin til KTorrent, understøtter RSS- og Atom-feeds Comment[de]=Syndizierungsmodul für KTorrent mit Unterstützung für RSS- und Atom-Nachrichtenquellen @@ -102,7 +101,7 @@ X-KDE-PluginInfo-Author=Joris Guisson X-KDE-PluginInfo-Email=joris.guisson@gmail.com X-KDE-PluginInfo-Name=SyndicationPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=application-rss+xml Index: plugins/upnp/ktorrent_upnp.desktop =================================================================== --- plugins/upnp/ktorrent_upnp.desktop +++ plugins/upnp/ktorrent_upnp.desktop @@ -1,6 +1,5 @@ [Desktop Entry] Name=UPnP -Name[ast]=UPnP Name[bg]=UPnP Name[bs]=UPnP Name[ca]=UPnP @@ -53,11 +52,10 @@ Name[zh_CN]=UPnP Name[zh_TW]=UPnP Comment=Forward ports using UPnP -Comment[ast]=Redireiciona puertos usando UPnP Comment[bg]=Пренасочване на портове с UPnP Comment[bs]=Proslijedi priključke koristeći UPnP -Comment[ca]=Rediregeix els ports usant UPnP -Comment[ca@valencia]=Rediregeix els ports usant UPnP +Comment[ca]=Redirecció de ports usant UPnP +Comment[ca@valencia]=Redirecció de ports usant UPnP Comment[cs]=Předávání portů pomocí UPnP Comment[da]=Åbning af porte via UPnP Comment[de]=Port-Weiterleitung unter Verwendung von UPnP @@ -106,7 +104,7 @@ X-KDE-PluginInfo-Author=Joris Guisson, Ivan Vasic X-KDE-PluginInfo-Email=joris.guisson@gmail.com, ivasic@gmail.com X-KDE-PluginInfo-Name=UPnPPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=kt-upnp Index: plugins/webinterface/ktwebinterfaceplugin.desktop =================================================================== --- plugins/webinterface/ktwebinterfaceplugin.desktop +++ plugins/webinterface/ktwebinterfaceplugin.desktop @@ -1,10 +1,5 @@ [Desktop Entry] Name=Web Interface -Name[ar]=واجهة الوبّ -<<<<<<< HEAD -======= -Name[ast]=Interfaz web ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Name[bg]=Уеб-интефейс Name[bs]=Web sučelje Name[ca]=Interfície web @@ -58,11 +53,6 @@ Name[zh_CN]=网页界面 Name[zh_TW]=網頁介面 Comment=Allows control of KTorrent via a web interface -Comment[ar]=تتيح لك التّحكّم ب‍«سيولك» عبر واجهة وبّ -<<<<<<< HEAD -======= -Comment[ast]=Permite'l control de KTorrent per un interfaz web ->>>>>>> cbdbeeea1a92eda031ab1e4e62545ce055aed845 Comment[bg]=Включване на управление на KTorrent през уеб-интерфейс Comment[bs]=Dozvoljava upravljanje KTorentom putem web sučelja Comment[ca]=Permet controlar el KTorrent via una interfície web @@ -115,7 +105,7 @@ X-KDE-PluginInfo-Author=Diego R. Brogna X-KDE-PluginInfo-Email=dierbro@gmail.com X-KDE-PluginInfo-Name=WebInterfacePlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=network-server Index: plugins/zeroconf/ktorrent_zeroconf.desktop =================================================================== --- plugins/zeroconf/ktorrent_zeroconf.desktop +++ plugins/zeroconf/ktorrent_zeroconf.desktop @@ -1,6 +1,5 @@ [Desktop Entry] Name=Zeroconf -Name[ast]=Zeroconf Name[bg]=Zeroconf Name[bs]=Zeroconf Name[ca]=Zeroconf @@ -52,11 +51,10 @@ Name[zh_CN]=ZeroConf Name[zh_TW]=ZeroConf Comment=Discover peers on the local network using the Zeroconf protocol -Comment[ast]=Descubre pares na rede llocal usando'l protocolu Zeroconf Comment[bg]=Откриване на потребители в локалната мрежа чрез протокола "Zeroconf" Comment[bs]=Otkrivajte vršnjake na lokalnoj mreži koristeći Zeroconf protokol -Comment[ca]=Descobreix els parells a la xarxa local usant el protocol Zeroconf -Comment[ca@valencia]=Descobreix els parells a la xarxa local usant el protocol Zeroconf +Comment[ca]=Descobriment de parells a la xarxa local usant el protocol Zeroconf +Comment[ca@valencia]=Descobriment de parells a la xarxa local usant el protocol Zeroconf Comment[cs]=Hledání protějšků na lokální síti s pomocí protokolu Zeroconf Comment[da]=Find peers på lokalnetværket via zeroconf-protokollen Comment[de]=Gegenstellen im lokalen Netzwerk unter Verwendung des Zeroconf-Protokolls auffinden @@ -105,7 +103,7 @@ X-KDE-PluginInfo-Author=Lesly Weyts, Kevin Andre and Joris Guisson X-KDE-PluginInfo-Email=joris.guisson@gmail.com X-KDE-PluginInfo-Name=ZeroconfPlugin -X-KDE-PluginInfo-Website=http://kde.org/applications/internet/ktorrent/ +X-KDE-PluginInfo-Website=http://ktorrent.org/ X-KDE-PluginInfo-License=GPL X-KDE-PluginInfo-EnabledByDefault=false Icon=preferences-plugin