author | Sergey Poznyakoff <gray@gnu.org.ua> | 2013-09-11 20:15:16 (GMT) |
---|---|---|
committer | Sergey Poznyakoff <gray@gnu.org.ua> | 2013-09-13 07:13:24 (GMT) |
commit | 2cbce6f40d92d42218dd5c4c38dd9badb244dc79 (patch) (side-by-side diff) | |
tree | d19ab8c29077911dbe4817669405c19bf206078e | |
download | vmod-sql-2cbce6f40d92d42218dd5c4c38dd9badb244dc79.tar.gz vmod-sql-2cbce6f40d92d42218dd5c4c38dd9badb244dc79.tar.bz2 |
Initial commit
-rw-r--r-- | .gitignore | 28 | ||||
-rw-r--r-- | AUTHORS | 1 | ||||
-rw-r--r-- | COPYING | 674 | ||||
-rw-r--r-- | Makefile.am | 28 | ||||
-rw-r--r-- | NEWS | 0 | ||||
-rw-r--r-- | README | 0 | ||||
-rw-r--r-- | acinclude.m4 | 109 | ||||
-rwxr-xr-x | bootstrap | 7 | ||||
-rw-r--r-- | configure.ac | 189 | ||||
-rw-r--r-- | git2chg.awk | 75 | ||||
-rw-r--r-- | src/.gitignore | 2 | ||||
-rw-r--r-- | src/Makefile.am | 49 | ||||
-rw-r--r-- | src/mysql.c | 292 | ||||
-rw-r--r-- | src/pgsql.c | 201 | ||||
-rw-r--r-- | src/sql.c | 243 | ||||
-rw-r--r-- | src/vmod-sql.c | 294 | ||||
-rw-r--r-- | src/vmod-sql.h | 97 | ||||
-rw-r--r-- | src/vmod.vcc | 7 | ||||
-rw-r--r-- | src/wordsplit.c | 1624 | ||||
-rw-r--r-- | src/wordsplit.h | 159 |
20 files changed, 4079 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..506e185 --- a/dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +*.a +*.la +*.lo +*.o +*.tar.* +*~ +.deps +.emacs* +.gdbinit +.libs +ABOUT-NLS +ChangeLog +INSTALL +Makefile +Makefile.in +TAGS +aclocal.m4 +autom4te.cache/ +build-aux +config.h +config.h.in +config.log +config.status +configure +core +libtool +m4 +stamp-h1 @@ -0,0 +1 @@ +Sergey Poznyakoff <gray@gnu.org>, <gray@gnu.org.ua> @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <http://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<http://www.gnu.org/licenses/>. + + 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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/Makefile.am b/Makefile.am new file mode 100644 index 0000000..f062d1e --- a/dev/null +++ b/Makefile.am @@ -0,0 +1,28 @@ +# This file is part of vmod-sql +# Copyright (C) 2013 Sergey Poznyakoff +# +# Vmod-dbrw 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, or (at your option) +# any later version. +# +# Vmod-dbrw 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +ACLOCAL_AMFLAGS = -I m4 + +SUBDIRS = src #doc tests + +EXTRA_DIST=git2chg.awk + +.PHONY: ChangeLog +ChangeLog: + $(AM_V_GEN)if test -d .git; then \ + git log --pretty='format:%ct %an <%ae>%n%n%s%n%n%b%n' | \ + awk -f $(top_srcdir)/git2chg.awk > ChangeLog; \ + fi + diff --git a/acinclude.m4 b/acinclude.m4 new file mode 100644 index 0000000..3cefdf8 --- a/dev/null +++ b/acinclude.m4 @@ -0,0 +1,109 @@ +# Copyright (C) 2001, 2006, 2008-2012 Sergey Poznyakoff +# +# 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, 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 <http://www.gnu.org/licenses/>. + +AC_DEFUN([GR_ENABLE],[ + AC_ARG_ENABLE($1, + AC_HELP_STRING([--disable-$1], [Disable pam_$1]), + [build_$1=$enableval], + [build_$1=m4_if([$2],[],yes,m4_if([$3],[],probe,[$3]))]) + m4_pushdef([upmodname],translit($1, [a-z.-], [A-Z__])) + m4_if([$2],[],,[if test $build_$1 != no; then + $2 + test $build_$1 = probe && build_$1=no + fi]) + AM_CONDITIONAL([GR_COND_]upmodname, [test "$[]build_$1" = "yes"]) + m4_popdef([upmodname]) +]) + +dnl GR_FLUSHLEFT -- remove all whitespace at the beginning of lines +dnl This is useful for c-code which may include cpp statements +dnl +define([GR_FLUSHLEFT], + [changequote(`,')dnl +patsubst(`$1', `^[ ]+') +changequote([,])])dnl + +dnl GR_RESULT_ACTIONS -- generate shell code for the result of a test +dnl $1 -- CVAR -- cache variable to check +dnl $2 -- NAME -- if not empty, used to generate a default value TRUE: +dnl `AC_DEFINE(HAVE_NAME)' +dnl $2 -- TRUE -- what to do if the CVAR is not `no' +dnl $3 -- FALSE -- what to do otherwise; defaults to `:' +dnl +AC_DEFUN([GR_RESULT_ACTIONS], [ +[if test "$$1" != "" -a "$$1" != no; then + ]ifelse([$3], , + [AC_DEFINE(HAVE_]translit($2, [a-z ./<>], [A-Z___])[,1,[FIXME])], + [$3])[ +else + ]ifelse([$4], , [:], [$4])[ +fi]])dnl + +dnl GR_CHECK_STRUCT_FIELD -- See if a structure has a particular field +dnl $1 - NAME -- name of structure +dnl $2 - FIELD -- name of field to test +dnl $3 - INCLS -- C program text to inculde necessary files for testing +dnl $4 - TRUE -- what to do if struct NAME has FIELD; defaults to +dnl `AC_DEFINE(HAVE_NAME_FIELD)' +dnl $5 - FALSE -- what to do if not; defaults to `:' +dnl +dnl NOTE: We still don't use AC_CHECK_MEMBERS, since it has (as of +dnl autoconf 2.53) a bug which prevents it from recognizing members +dnl of aggregate type. + +AC_DEFUN([GR_CHECK_STRUCT_FIELD], [ + define([pm_CVAR], [pm_cv_struct_]translit($1_$2, [A-Z], [a-z]))dnl + AC_CACHE_CHECK([whether struct $1 has $2 field], pm_CVAR, + AC_TRY_COMPILE(GR_FLUSHLEFT([$3]), + [struct $1 pm_x; int pm_y = sizeof pm_x.$2;], + pm_CVAR[=yes], pm_CVAR[=no])) + GR_RESULT_ACTIONS(pm_CVAR, [$1_$2], [$4], [$5])dnl + undefine([pm_CVAR])])dnl + +dnl Arguments: +dnl $1 -- Library to look for +dnl $2 -- Function to check in the library +dnl $3 -- Any additional libraries that might be needed +dnl $4 -- Action to be taken when test succeeds +dnl $5 -- Action to be taken when test fails +dnl $6 -- Directories where the library may reside +AC_DEFUN([GR_CHECK_LIB], +[m4_ifval([$4], , [AH_CHECK_LIB([$1])])dnl +AS_VAR_PUSHDEF([pm_Lib], [pm_cv_lib_$1])dnl +AC_CACHE_CHECK([for $2 in -l$1], [pm_Lib], +[AS_VAR_SET([pm_Lib], [no]) + pm_check_lib_save_LIBS=$LIBS + for path in "" $6 + do + if test -n "$path"; then + pm_ldflags="-L$path -l$1 $3" + else + pm_ldflags="-l$1 $3" + fi + LIBS="$pm_ldflags $pm_check_lib_save_LIBS" + AC_LINK_IFELSE([AC_LANG_CALL([], [$2])], + [AS_VAR_SET([pm_Lib], ["$pm_ldflags"]) + break]) + done + LIBS=$pm_check_lib_save_LIBS]) +AS_IF([test "AS_VAR_GET([pm_Lib])" != no], + [m4_default([$4], [AC_DEFINE_UNQUOTED(AS_TR_CPP(HAVE_LIB$1)) + LIBS="-l$1 $LIBS" +])], + [$5])dnl +AS_VAR_POPDEF([pm_Lib])dnl +])# GR_CHECK_LIB + + diff --git a/bootstrap b/bootstrap new file mode 100755 index 0000000..89ccf31 --- a/dev/null +++ b/bootstrap @@ -0,0 +1,7 @@ +#!/bin/sh +for dir in m4 build-aux +do + test -d $dir || mkdir $dir +done +test -f ChangeLog || touch ChangeLog +autoreconf -f -i -s diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..be6e8f5 --- a/dev/null +++ b/configure.ac @@ -0,0 +1,189 @@ +# This file is part of vmod-sql -*- autoconf -*- +# Copyright (C) 2013 Sergey Poznyakoff +# +# Vmod-dbrw 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, or (at your option) +# any later version. +# +# Vmod-dbrw 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +AC_PREREQ(2.69) +AC_INIT([vmod-sql], 1.0, [gray@gnu.org]) +AC_CONFIG_AUX_DIR([build-aux]) +AC_CONFIG_MACRO_DIR([m4]) +AC_CONFIG_SRCDIR(src/vmod-sql.c) +AM_CONFIG_HEADER(config.h) + +AC_CANONICAL_SYSTEM +AC_LANG(C) + +AM_INIT_AUTOMAKE([gnu tar-ustar]) + +AC_GNU_SOURCE +AC_PROG_CC +AC_PROG_CC_STDC +if test "x$ac_cv_prog_cc_c99" = xno; then + AC_MSG_ERROR([could not find a C99 compatible compiler]) +fi +AC_PROG_CPP + +AC_PROG_INSTALL +AC_PROG_LIBTOOL +AC_PROG_MAKE_SET + +# Check for pkg-config +PKG_PROG_PKG_CONFIG + +# Checks for header files. +AC_HEADER_STDC +AC_CHECK_HEADERS([sys/stdlib.h]) + +# Check for python +AC_CHECK_PROGS(PYTHON, [python], [ + AC_MSG_ERROR([python is not found.])]) + +# Varnish source tree +AC_ARG_VAR([VARNISHSRC], [path to Varnish source tree]) +AC_ARG_WITH([varnish-source], + AC_HELP_STRING([--with-varnish-source=DIR], + [Varnish sources are located in DIR]), + [VARNISHSRC=$withval]) + +if test -z "$VARNISHSRC"; then + AC_MSG_ERROR([no Varnish source tree specified]) +fi +case "$VARNISHSRC" in +/*) ;; +*) AC_MSG_ERROR([varnish source path must be absolute pathname]) +esac + +VARNISHSRC=`cd $VARNISHSRC && pwd` +AC_CHECK_FILE([$VARNISHSRC/include/varnishapi.h], + [], + [AC_MSG_FAILURE(["$VARNISHSRC" is not a Varnish source directory])]) + +# Check that varnishtest is built in the varnish source directory +AC_CHECK_FILE([$VARNISHSRC/bin/varnishtest/varnishtest], + [], + [AC_MSG_FAILURE([cannot find "$VARNISHSRC/bin/varnishtest/varnishtest". Please build your varnish source directory])] +) + +# vmod installation dir +AC_ARG_VAR([VMODDIR], + [vmod installation directory @<:@LIBDIR/varnish/vmods@:>@]) +AC_ARG_WITH([vmod-dir], + AC_HELP_STRING([--with-vmod-dir@<:@=DIR@:>@], + [install modules to DIR; if used without arguments, install them to the varnish module directory]), + [case "$withval" in + yes) + VMODDIR=`pkg-config --variable=vmoddir varnishapi` + if test -z "$VMODDIR"; then + AC_MSG_FAILURE([cannot determine vmod installation directory]) + fi;; + /*) VMODDIR=$withval;; + *) AC_MSG_ERROR([argument to --with-vmod-dir must be absolute pathname]) + esac]) + +if test -z "$VMODDIR"; then + VMODDIR='$(libdir)/varnish/mods' +fi + +########### +# Check for SQL support +build_mysql=probe +build_pgsql=probe + +AC_ARG_WITH(mysql, + AC_HELP_STRING([--without-mysql], + [Configure to work without MySQL]), + [build_mysql=$withval]) +AC_ARG_WITH(pgsql, + AC_HELP_STRING([--without-pgsql], + [Configure to work without Postgres]), + [build_pgsql=$withval]) +AC_ARG_WITH(postgres, + AC_HELP_STRING([--without-postgres], + [Same as --without-pgsql]), + [build_pgsql=$withval]) + +GR_ENABLE(mysql, [ + GR_CHECK_LIB(mysqlclient, mysql_real_connect, "-lm", + [ AC_DEFINE(USE_SQL_MYSQL,1, + [Define this if you are going to use MySQL]) + AC_DEFINE(HAVE_LIBMYSQL,1, + [Define this if you have mysqlclient library]) + MYSQLLIBS="$pm_cv_lib_mysqlclient" + build_mysql=yes ], + [ test "$build_mysql" = yes && AC_MSG_ERROR([MySQL support cannot be built because MySQL libraries are not present]) + build_mysql=no ], + [/usr/lib/mysql /usr/local/lib/mysql])], $build_mysql) + +GR_ENABLE(pgsql, [ + GR_CHECK_LIB(pq, PQconnectStart, [], + [ save_CPPFLAGS=$CPPFLAGS + for dir in /usr/local/pgsql/include /usr/pgsql/include + do + CPPFLAGS="$save_CPPFLAGS -I$dir" + AC_CHECK_HEADER([libpq-fe.h], [break]) + CPPFLAGS="$save_CPPFLAGS" + done + if test $ac_cv_header_libpq_fe_h != yes; then + test "$build_pgsql" = yes && + AC_MSG_ERROR([PostgreSQL support cannot be built because PostgreSQL headers are not present]) + else + AC_DEFINE(USE_SQL_PGSQL,1, + [Define this if you are going to use PostgreSQL]) + AC_DEFINE(HAVE_LIBPQ,1, + [Define this if you have libpq]) + PGSQLLIBS="$pm_cv_lib_pq" + build_pgsql=yes + fi], + [ test "$build_pgsql" = yes && AC_MSG_ERROR([PostgreSQL support cannot be built because PostgreSQL libraries are not present]) + build_pgsql=no ], + [/usr/pgsql/lib /usr/local/pgsql/lib])], $build_pgsql) + +AC_SUBST(MYSQLLIBS) +AC_SUBST(PGSQLLIBS) + +AM_CONDITIONAL([USE_MYSQL],[test $build_mysql = yes]) +AM_CONDITIONAL([USE_PGSQL],[test $build_pgsql = yes]) + +AC_CONFIG_COMMANDS([status],[ +echo "" +delim="-------------------------------------------------------------------" +echo $delim | tr '-' '*' +echo "Backends to build:" +res= +for module in mysql pgsql +do + eval enable=\${build_$module} + str=`echo ${module}" yes" | sed 's/./-/g'` + dstr=`echo $delim | sed "s/^$str//" | tr '-' '.'` + echo ${module}$dstr $enable + res="$res$enable" +done +echo $delim | tr '-' '*' +case "$res" in +*yes*) ;; +*) + AC_MSG_ERROR([Nothing to build?]) +esac +],[ +build_pgsql=$build_pgsql +build_mysql=$build_mysql]) + + +dnl FIXME: tests/Makefile +dnl FIXME: doc/Makefile +AC_CONFIG_FILES([ + Makefile + src/Makefile +]) +AC_OUTPUT + diff --git a/git2chg.awk b/git2chg.awk new file mode 100644 index 0000000..1e75254 --- a/dev/null +++ b/git2chg.awk @@ -0,0 +1,75 @@ +# This file is part of grecs +# Copyright (C) 2007, 2009-2012 Sergey Poznyakoff +# +# Grecs 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, or (at your option) +# any later version. +# +# Grecs 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 Grecs. If not, see <http://www.gnu.org/licenses/>. + +BEGIN { + if (since) + split(since,since_a,"-") +} + +function timeok(t, a) { + if (!since) + return 1 + split(t,a,"-") + if (a[1] < since_a[1]) + return 0 + if (a[1] > since_a[1]) + return 1 + if (a[2] < since_a[2]) + return 0 + if (a[2] > since_a[2]) + return 1 + return a[3] > since_a[3] +} + +/^[0-9]+ .* +<[^>]+>/ { + s = strftime("%F", $1) + if (!timeok(s)) + exit + sub(/^[0-9]+ +/,"") + if (s == datestr && author == $0) + next + datestr = s + author = $0 + if (runlen) { runlen = 0; print "" } + printf("%s %s\n", datestr, author) + next +} +/^Signed-off-by:/ { next } +/^<unknown>$/ { next } +NF==0 { + runlen++ + next +} +{ if (runlen) { runlen = 0; print "" } + print "\t" $0 } + +END { + if (append) { + print "" + while ((getline < append) > 0) { + if (match($0, /^Local *Variables:/)) + break + print + } + } + print "\f" + # Make sure Emacs won't recognize this line: + print "Local", "Variables:" + print "mode: change-log" + print "version-control: never" + print "buffer-read-only: t" + print "End:" +} diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..7f6e438 --- a/dev/null +++ b/src/.gitignore @@ -0,0 +1,2 @@ +vcc_if.c +vcc_if.h diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..b7232fd --- a/dev/null +++ b/src/Makefile.am @@ -0,0 +1,49 @@ +# This file is part of vmod-sql +# Copyright (C) 2013 Sergey Poznyakoff +# +# Vmod-dbrw 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, or (at your option) +# any later version. +# +# Vmod-dbrw 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. + +AM_CPPFLAGS = -I$(VARNISHSRC)/include -I$(VARNISHSRC) + +vmoddir = $(VMODDIR) +vmod_LTLIBRARIES = libvmod_sql.la + +libvmod_sql_la_LDFLAGS = -module -export-dynamic -avoid-version +libvmod_sql_la_LIBADD=@MYSQLLIBS@ @PGSQLLIBS@ + +libvmod_sql_la_SOURCES = \ + sql.c\ + vmod-sql.c\ + vmod-sql.h\ + vcc_if.c vcc_if.h\ + wordsplit.h\ + wordsplit.c + +if USE_MYSQL + libvmod_sql_la_SOURCES += mysql.c +endif + +if USE_PGSQL + libvmod_sql_la_SOURCES += pgsql.c +endif + +BUILT_SOURCES = vcc_if.c vcc_if.h + +vcc_if.c vcc_if.h: $(VARNISHSRC)/lib/libvmod_std/vmod.py $(top_srcdir)/src/vmod.vcc + @PYTHON@ $(VARNISHSRC)/lib/libvmod_std/vmod.py $(top_srcdir)/src/vmod.vcc + +EXTRA_DIST = vmod.vcc + +CLEANFILES = $(builddir)/vcc_if.c $(builddir)/vcc_if.h + diff --git a/src/mysql.c b/src/mysql.c new file mode 100644 index 0000000..1b941bf --- a/dev/null +++ b/src/mysql.c @@ -0,0 +1,292 @@ +/* This file is part of vmod-sql + Copyright (C) 2013 Sergey Poznyakoff + + Vmod-sql 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, or (at your option) + any later version. + + Vmod-sql 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +*/ +#include "vmod-sql.h" +#include <mysql/mysql.h> +#include <mysql/errmsg.h> +#include <mysql/mysqld_error.h> + +struct vmod_mysql_data +{ + MYSQL *mysql; + MYSQL_RES *result; + char *buffer; + size_t bufsize; +}; + + +static void +check_errno(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + + switch (mysql_errno(mp->mysql)) { + case CR_SERVER_GONE_ERROR: + case CR_SERVER_LOST: + case ER_SERVER_SHUTDOWN: + case ER_ABORTING_CONNECTION: + i_modsql_error("query failed: %s", mysql_error(mp->mysql)); + i_modsql_disconnect(conn); + if (conn->state == state_error) { + conn->state = state_disabled; + i_modsql_error("disabling MySQL connection"); + } + break; + case ER_UNKNOWN_COM_ERROR: + case ER_ACCESS_DENIED_ERROR: + case ER_BAD_DB_ERROR: + case ER_WRONG_DB_NAME: + case ER_BAD_FIELD_ERROR: + case ER_BAD_HOST_ERROR: + case ER_BAD_TABLE_ERROR: + case ER_WRONG_FIELD_SPEC: + case ER_PARSE_ERROR: + case ER_EMPTY_QUERY: + case ER_FIELD_SPECIFIED_TWICE: + case ER_NO_SUCH_TABLE: + case ER_NOT_ALLOWED_COMMAND: + i_modsql_error("query failed: %s", mysql_error(mp->mysql)); + } +} + +/* ************************************************************************* */ +/* Interface routines */ + +static int +s_mysql_init(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = calloc(1, sizeof (*mp)); + if (!mp) { + i_modsql_error("not enough memory"); + return -1; + } + conn->data = mp; + return 0; +} + +static void +s_mysql_destroy(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + free(mp->buffer); + free(mp->mysql); + free(mp); + conn->data = NULL; +} + + +static int +s_mysql_connect(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + char *host, *socket_name = NULL; + char *s; + int port = 0; + + mp->mysql = malloc(sizeof(MYSQL)); + if (!mp->mysql) { + i_modsql_error("not enough memory"); + conn->state = state_disabled; + return -1; + } + + mysql_init(mp->mysql); + + host = i_modsql_findparam(conn->param, "server"); + if (host && host[0] == '/') { + host = "localhost"; + socket_name = host; + } + + s = i_modsql_findparam(conn->param, "port"); + if (s) + port = atoi(s); + + s = i_modsql_findparam(conn->param, "config"); + if (s) + mysql_options(mp->mysql, MYSQL_READ_DEFAULT_FILE, s); + + s = i_modsql_findparam(conn->param, "group"); + if (s) + mysql_options(mp->mysql, MYSQL_READ_DEFAULT_GROUP, s); + + s = i_modsql_findparam(conn->param, "cacert"); + if (s) + mysql_ssl_set(mp->mysql, NULL, NULL, s, NULL, NULL); + debug(conn, 1, ("connecting to database")); + if (!mysql_real_connect(mp->mysql, + host, + i_modsql_findparam(conn->param, "user"), + i_modsql_findparam(conn->param, "password"), + i_modsql_findparam(conn->param, "database"), + port, + socket_name, + CLIENT_MULTI_RESULTS)) { + i_modsql_error("cannot connect: %s", mysql_error(mp->mysql)); + return -1; + } + debug(conn, 1, ("connected to database")); + + return 0; +} + +static int +s_mysql_disconnect(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + mysql_close(mp->mysql); + return 0; +} + +static int +s_mysql_query(struct vmod_sql_connection *conn, const char *query) +{ + struct vmod_mysql_data *mp = conn->data; + int rc; + int i; + MYSQL *mysql; + + for (i = 0; i < 10; i++) { + mysql = mp->mysql; + rc = mysql_query(mysql, query); + if (rc) { + check_errno(conn); + if (conn->state != state_init) + return -1; + i_modsql_connect(conn); + if (conn->state != state_connected) + return -1; + continue; + } + mp->result = mysql_store_result(mp->mysql); + if (mp->result) { + conn->state = state_result; + rc = 0; + } else if (mysql_field_count(mp->mysql)) { + i_modsql_error("cannot store result: %s", + mysql_error(mp->mysql)); + conn->state = state_error; + rc = 1; + } else + rc = 0; + break; + } + return rc; +} + +static int +s_mysql_free_result(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + mysql_free_result(mp->result); + mp->result = NULL; + return 0; +} + +static unsigned +s_mysql_num_fields(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + return mysql_num_fields(mp->result); +} + +static unsigned +s_mysql_num_tuples(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + return mysql_num_rows(mp->result); +} + +static const char * +s_mysql_get_column(struct vmod_sql_connection *conn, size_t nrow, size_t ncol) +{ + struct vmod_mysql_data *mp = conn->data; + MYSQL_ROW row; + + if (nrow >= mysql_num_rows(mp->result) || + ncol >= mysql_num_fields (mp->result)) + return NULL; + + mysql_data_seek(mp->result, nrow); + row = mysql_fetch_row(mp->result); + if (!row) + return NULL; + return row[ncol]; +} + +static char * +s_mysql_escape(struct vmod_sql_connection *conn, const char *arg) +{ + struct vmod_mysql_data *mp = conn->data; + size_t len, size; + char *p; + + switch (conn->state) { + case state_connected: + case state_result: + break; + + case state_error: + case state_init: + if (i_modsql_connect(conn)) + return NULL; + break; + + default: + return NULL; + } + + len = strlen(arg); + size = 2 * len + 1; + if (mp->bufsize < size) { + p = realloc(mp->buffer, size); + if (!p) { + i_modsql_error("not enough memory"); + return NULL; + } + mp->buffer = p; + mp->bufsize = size; + } + + mysql_real_escape_string(mp->mysql, mp->buffer, arg, len); + + p = strdup(mp->buffer); + if (!p) + i_modsql_error("not enough memory"); + return p; +} + +long +s_mysql_affected_rows(struct vmod_sql_connection *conn) +{ + struct vmod_mysql_data *mp = conn->data; + return mysql_affected_rows(mp->mysql); +} + +struct vmod_sql_backend i_modsql_mysql_backend = { + "mysql", + s_mysql_init, + s_mysql_destroy, + s_mysql_connect, + s_mysql_disconnect, + s_mysql_escape, + s_mysql_query, + s_mysql_num_tuples, + s_mysql_num_fields, + s_mysql_free_result, + s_mysql_get_column, + s_mysql_affected_rows +}; diff --git a/src/pgsql.c b/src/pgsql.c new file mode 100644 index 0000000..865526e --- a/dev/null +++ b/src/pgsql.c @@ -0,0 +1,201 @@ +/* This file is part of vmod-sql + Copyright (C) 2013 Sergey Poznyakoff + + Vmod-sql 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, or (at your option) + any later version. + + Vmod-sql 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +*/ +#include "vmod-sql.h" +#include <string.h> +#include <libpq-fe.h> + +#define ISSPACE(c) ((c) == ' ' || (c) == '\t') + +static char * +chop(char *str) +{ + int len; + + if (!str) + return NULL; + for (len = strlen(str); len > 0 && ISSPACE(str[len-1]); len--) + ; + str[len] = 0; + return str; +} + +struct vmod_pgsql_data +{ + PGconn *pgconn; + PGresult *res; +}; + +static int +s_pgsql_init(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = calloc (1, sizeof (*dp)); + if (!dp) + return ENOMEM; + conn->data = dp; + return 0; +} + +static void +s_pgsql_destroy(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + free(dp); + conn->data = NULL; +} + +static int +s_pgsql_connect(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + + dp->pgconn = PQsetdbLogin(i_modsql_findparam(conn->param, "server"), + i_modsql_findparam(conn->param, "port"), + i_modsql_findparam(conn->param, "options"), + NULL, + i_modsql_findparam(conn->param, "database"), + i_modsql_findparam(conn->param, "user"), + i_modsql_findparam(conn->param, "password")); + + if (PQstatus(dp->pgconn) == CONNECTION_BAD) { + i_modsql_error("connection to the database failed: %s", + PQerrorMessage(dp->pgconn)); + PQfinish(dp->pgconn); + dp->pgconn = NULL; + return 1; + } + + return 0; +} + +static int +s_pgsql_disconnect(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + PQfinish(dp->pgconn); + return 0; +} + +static int +s_pgsql_query(struct vmod_sql_connection *conn, const char *query) +{ + struct vmod_pgsql_data *dp = conn->data; + ExecStatusType stat; + + dp->res = PQexec(dp->pgconn, query); + stat = PQresultStatus(dp->res); + + if (stat == PGRES_TUPLES_OK) + conn->state = state_result; + else if (stat != PGRES_COMMAND_OK) { + i_modsql_error("query failed: %s", PQerrorMessage(dp->pgconn)); + i_modsql_error("the failed query was: %s", query); + if (dp->res) { + PQclear(dp->res); + dp->res = NULL; + } + return 1; + } + return 0; +} + +static int +s_pgsql_free_result(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + + PQclear(dp->res); + dp->res = NULL; + + return 0; +} + +static unsigned +s_pgsql_num_fields(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + if (!dp->res) + return 0; + return PQnfields(dp->res); +} + +static unsigned +s_pgsql_num_tuples(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + if (!dp->res) + return 0; + return PQntuples(dp->res); +} + +static const char * +s_pgsql_get_column(struct vmod_sql_connection *conn, size_t nrow, size_t ncol) +{ + struct vmod_pgsql_data *dp = conn->data; + + if (!dp->res) + return NULL; + return chop(PQgetvalue(dp->res, nrow, ncol)); +} + +static char * +s_pgsql_escape(struct vmod_sql_connection *conn, const char *ustr) +{ + char *str, *q; + const unsigned char *p; + size_t len = strlen(ustr); +#define ESCAPABLE_CHAR "\\'\"" + + for (p = (const unsigned char *) ustr; *p; p++) { + if (strchr(ESCAPABLE_CHAR, *p)) + len++; + } + + str = malloc(len + 1); + if (!str) + return NULL; + + for (p = (const unsigned char *) ustr, q = str; *p; p++) { + if (strchr(ESCAPABLE_CHAR, *p)) + *q++ = '\\'; + *q++ = *p; + } + *q = 0; + return str; +} + +long +s_pgsql_affected_rows(struct vmod_sql_connection *conn) +{ + struct vmod_pgsql_data *dp = conn->data; + return strtol(PQcmdTuples(dp->res), NULL, 0); +} + + +struct vmod_sql_backend i_modsql_pgsql_backend = { + "pgsql", + s_pgsql_init, + s_pgsql_destroy, + s_pgsql_connect, + s_pgsql_disconnect, + s_pgsql_escape, + s_pgsql_query, + s_pgsql_num_tuples, + s_pgsql_num_fields, + s_pgsql_free_result, + s_pgsql_get_column, + s_pgsql_affected_rows +}; diff --git a/src/sql.c b/src/sql.c new file mode 100644 index 0000000..2bf8bc6 --- a/dev/null +++ b/src/sql.c @@ -0,0 +1,243 @@ +/* This file is part of vmod-sql + Copyright (C) 2013 Sergey Poznyakoff + + Vmod-sql 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, or (at your option) + any later version. + + Vmod-sql 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +*/ +#include "vmod-sql.h" +#include <pthread.h> +#include <assert.h> + +#define CONN_ASSERT(conn) do { \ + if (!(conn)->backend) \ + return; \ + if ((conn)->state == state_disabled) \ + return; \ + } while(0) + +#define CONN_ASSERT_VAL(conn,v) do { \ + if (!(conn)->backend) \ + return v; \ + if ((conn)->state == state_disabled) \ + return v; \ + } while(0) + +int +i_modsql_init(struct vmod_sql_connection *conn) +{ + CONN_ASSERT_VAL(conn, 1); + debug(conn, 3, ("i_modsql_init called")); + if (conn->backend->be_init) + return conn->backend->be_init(conn); + return 0; +} + +static void +argv_free(char **argv) +{ + if (!argv) + return; + while (*argv) { + free(*argv); + ++*argv; + } +} + +void +i_modsql_destroy(struct vmod_sql_connection *conn) +{ + CONN_ASSERT(conn); + debug(conn, 5, ("i_modsql_destroy: state=%d", conn->state)); + do { + switch (conn->state) { + case state_init: + break; + case state_result: + i_modsql_free_result(conn); + break; + case state_connected: + i_modsql_disconnect(conn); + break; + default: + /* Force destroy */ + conn->state = state_init; + } + } while (conn->state != state_init); + if (conn->backend->be_destroy) + return conn->backend->be_destroy(conn); + argv_free(conn->param); + conn->backend = NULL; +} + +int +i_modsql_connect(struct vmod_sql_connection *conn) +{ + CONN_ASSERT_VAL(conn, 1); + debug(conn, 5, ("sql_connect: state=%d", conn->state)); + switch (conn->state) { + case state_init: + break; + case state_connected: + case state_result: + return 0; + case state_error: + i_modsql_disconnect(conn); + if (conn->state != state_init) + return 1; + break; + case state_disabled: + return 1; + } + assert(conn->backend->be_connect); + if (conn->backend->be_connect(conn)) + return 1; + debug(conn, 5, ("sql_connect: success")); + conn->state = state_connected; + return 0; +} + +int +i_modsql_create_connection(struct vmod_sql_backend *be, const char *ps, + char **param) +{ + struct vmod_sql_connection conn; + int i; + const char *s; + + conn.state = state_init; + conn.data = NULL; + conn.param = param; + conn.backend = be; + conn.param_str = strdup(ps); + + s = i_modsql_findparam(param, "debug"); + conn.debug_level = s ? atoi(s) : 0; + + if (i_modsql_init(&conn)) + return -1; + + if (i_modsql_connect(&conn)) + return -1; + + i = i_modsql_conntab_alloc(&conn); + if (i == -1) { + i_modsql_disconnect(&conn); + i_modsql_destroy(&conn); + } + + return i; +} + +void +i_modsql_disconnect(struct vmod_sql_connection *conn) +{ + CONN_ASSERT(conn); + debug(conn, 5, ("i_modsql_disconnect: state=%d", conn->state)); + assert(conn->backend->be_disconnect); + if (conn->backend->be_disconnect(conn) == 0) + conn->state = state_init; +} + +char * +i_modsql_escape(struct vmod_sql_connection *conn, const char *input) +{ + CONN_ASSERT_VAL(conn, NULL); + debug(conn, 5, ("i_modsql_escape: state=%d; input=%s", + conn->state, input)); + if (conn->backend->be_escape) + return conn->backend->be_escape(conn, input); + return strdup(input); +} + +int +i_modsql_query(struct vmod_sql_connection *conn, const char *input) +{ + CONN_ASSERT_VAL(conn, 1); + debug(conn, 1, ("state=%d, query=%s", conn->state, input)); + do { + switch (conn->state) { + case state_init: + if (i_modsql_connect(conn) || + conn->state != state_connected) + return 1; + break; + + case state_connected: + break; + + case state_result: + i_modsql_free_result(conn); + break; + + case state_error: + i_modsql_disconnect(conn); + if (conn->state != state_init) + return 1; + break; + + default: + return 1; + } + } while (conn->state != state_connected); + if (conn->backend->be_query(conn, input) == 0) + return 0; + return 1; +} + +unsigned +i_modsql_num_tuples(struct vmod_sql_connection *conn) +{ + CONN_ASSERT_VAL(conn, 0); + assert(conn->backend->be_num_tuples); + return conn->backend->be_num_tuples(conn); +} + +unsigned +i_modsql_num_fields(struct vmod_sql_connection *conn) +{ + CONN_ASSERT_VAL(conn, 0); + assert(conn->backend->be_num_fields); + return conn->backend->be_num_fields(conn); +} + +void +i_modsql_free_result(struct vmod_sql_connection *conn) +{ + CONN_ASSERT(conn); + if (conn->backend->be_free_result) { + if (conn->backend->be_free_result(conn)) + return; + } + conn->state = state_connected; +} + +const char * +i_modsql_get_column(struct vmod_sql_connection *conn, unsigned row, + unsigned col) +{ + CONN_ASSERT_VAL(conn, NULL); + assert(conn->backend->sql_get_column); + if (conn->state != state_result) + return NULL; + return conn->backend->sql_get_column(conn, row, col); +} + +long +i_modsql_affected_rows(struct vmod_sql_connection *conn) +{ + CONN_ASSERT_VAL(conn, 0); + assert(conn->backend->be_affected_rows); + if (conn->state != state_connected) + return 0; + return conn->backend->be_affected_rows(conn); +} diff --git a/src/vmod-sql.c b/src/vmod-sql.c new file mode 100644 index 0000000..119fa25 --- a/dev/null +++ b/src/vmod-sql.c @@ -0,0 +1,294 @@ +/* This file is part of vmod-sql + Copyright (C) 2013 Sergey Poznyakoff + + Vmod-sql 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, or (at your option) + any later version. + + Vmod-sql 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +*/ +#include "vmod-sql.h" +#include <stdarg.h> +#include "wordsplit.h" +#include "vrt.h" +#include "vcc_if.h" +#include "bin/varnishd/cache.h" + +static pthread_once_t thread_once = PTHREAD_ONCE_INIT; +static pthread_key_t thread_key; + +void +i_modsql_debug(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vsyslog(LOG_DAEMON|LOG_DEBUG, fmt, ap); + va_end(ap); +} + +void +i_modsql_error(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vsyslog(LOG_DAEMON|LOG_ERR, fmt, ap); + va_end(ap); +} + +struct vmod_sql_connection * +i_modsql_conntab_get(int n) +{ + struct vmod_sql_connection *conntab = pthread_getspecific(thread_key); + if (n < 0 || n > MAXCONN || !conntab || !conntab[n].backend) + return NULL; + return conntab + n; +} + +int +i_modsql_conntab_alloc(struct vmod_sql_connection *cp) +{ + int i; + struct vmod_sql_connection *conntab = pthread_getspecific(thread_key); + if (!conntab) { + conntab = calloc(MAXCONN, sizeof(conntab[0])); + AN(conntab); + AZ(pthread_setspecific(thread_key, conntab)); + } + + for (i = 0; i < MAXCONN; i++) { + if (conntab[i].backend == NULL) { + conntab[i] = *cp; + return i; + } + } + return -1; +} + +static int +i_modsql_conntab_find(const char *bkname, const char *param_str) +{ + int i; + struct vmod_sql_connection *conntab = pthread_getspecific(thread_key); + if (!conntab) + return -1; + for (i = 0; i < MAXCONN; i++) { + if (conntab[i].backend && + strcmp(conntab[i].backend->name, bkname) == 0 && + strcmp(conntab[i].param_str, param_str) == 0) { + return i; + } + } + return -1; +} + + +static void +conn_free(void *f) +{ + struct vmod_sql_connection *conntab = pthread_getspecific(thread_key); + if (conntab) { + struct vmod_sql_connection *cp; + for (cp = conntab; cp < conntab + MAXCONN; cp++) { + if (cp->state != state_init) { + i_modsql_disconnect(cp); + i_modsql_destroy(cp); + } + } + } + free(conntab); +} + +static void +make_key() +{ + pthread_key_create(&thread_key, conn_free); +} + +int +module_init(struct vmod_priv *priv, const struct VCL_conf *vclconf) +{ + pthread_once(&thread_once, make_key); + return 0; +} + +char * +i_modsql_findparam(char **params, char *name) +{ + char *p, *q; + + while (*params) { + p = *params++; + for (q = name; *p && *q && *p == *q; p++, q++); + if (*q == 0 && *p == '=') + return p+1; + } + return NULL; +} + + +static struct vmod_sql_backend *bcktab[] = { +#ifdef USE_SQL_MYSQL + &i_modsql_mysql_backend, +#endif +#ifdef USE_SQL_PGSQL + &i_modsql_pgsql_backend, +#endif + NULL +}; + +static struct vmod_sql_backend * +find_backend(const char *name) +{ + int i; + + for (i = 0; bcktab[i]; i++) { + if (strcmp(bcktab[i]->name, name) == 0) + return bcktab[i]; + } + return NULL; +} + +int +vmod_connect(struct sess *sp, struct vmod_priv *priv, const char *bkname, + const char *param) +{ + struct wordsplit ws; + struct vmod_sql_backend *be; + int n; + + n = i_modsql_conntab_find(bkname, param); + if (n != -1) + return n; + ws.ws_delim = ";"; + if (wordsplit(param, &ws, + WRDSF_NOVAR | WRDSF_NOCMD | WRDSF_QUOTE | + WRDSF_CESCAPES | + WRDSF_DELIM)) { + i_modsql_error("cannot split string `%s': %s", + param, wordsplit_strerror(&ws)); + return -1; + } + + /* Select backend */ + be = find_backend(bkname); + if (!be) { + i_modsql_error("unsupported backend: %s", bkname); + wordsplit_free(&ws); + return -1; + } + + n = i_modsql_create_connection(be, param, ws.ws_wordv); + ws.ws_wordc = 0; + ws.ws_wordv = NULL; + wordsplit_free(&ws); + return n; +} + +void +vmod_connect_init(struct sess *sp, struct vmod_priv *priv, const char *bkname, + const char *param) +{ + AZ(vmod_connect(sp, priv, bkname, param)); +} + +static struct vmod_sql_connection * +runquery(struct sess *sp, int n, const char *query, const char *arg) +{ + struct vmod_sql_connection *cp; + struct wordsplit ws, wsenv; + int i, rc; + + cp = i_modsql_conntab_get(n); + if (!cp) + return NULL; + debug(cp, 2, ("runquery(%s) begin", arg)); + + if (cp->state != state_connected) + return NULL; + + debug(cp, 2, ("runquery: splitting arg")); + wsenv.ws_delim = ";"; + if (wordsplit(arg, &wsenv, WRDSF_NOVAR|WRDSF_NOCMD|WRDSF_DELIM)) { + i_modsql_error("cannot split string `%s': %s", + arg, wordsplit_strerror(&wsenv)); + return NULL; + } + + if (cp->backend->be_escape) { + debug(cp, 2, ("escaping variables")); + for (i = 0; i < wsenv.ws_wordc; i++) { + char *p = i_modsql_escape(cp, wsenv.ws_wordv[i]); + if (!p) { + i_modsql_error("cannot expand argument"); + wordsplit_free(&wsenv); + return NULL; + } + free(wsenv.ws_wordv[i]); + wsenv.ws_wordv[i] = p; + debug(cp, 3, ("%d: %s",i,p)); + } + } + + debug(cp, 2, ("expanding query")); + ws.ws_env = (const char **)wsenv.ws_wordv; + rc = wordsplit(query, &ws, + WRDSF_NOCMD | WRDSF_QUOTE | + WRDSF_NOSPLIT | + WRDSF_ENV | WRDSF_UNDEF); + if (rc) { + i_modsql_error("cannot expand query `%s': %s", + query, wordsplit_strerror(&ws)); + wordsplit_free(&wsenv); + return NULL; + } + + rc = i_modsql_query(cp, ws.ws_wordv[0]); + wordsplit_free(&ws); + wordsplit_free(&wsenv); + + return cp; +} + +unsigned +vmod_query(struct sess *sp, struct vmod_priv *priv, int cd, const char *query, + const char *arg) +{ + return !runquery(sp, cd, query, arg); +} + +const char * +vmod_result(struct sess *sp, struct vmod_priv *priv, int cd, int row, int col) +{ + struct vmod_sql_connection *cp; + const char *s; + + cp = i_modsql_conntab_get(cd); + if (!cp) + return NULL; + + s = i_modsql_get_column(cp, row, col); + + if (!s) + return NULL; + return WS_Dup(sp->ws, s); +} + +int +vmod_affected(struct sess *sp, struct vmod_priv *priv, int cd) +{ + struct vmod_sql_connection *cp; + + cp = i_modsql_conntab_get(cd); + if (!cp) + return 0; + return i_modsql_affected_rows(cp); +} + + diff --git a/src/vmod-sql.h b/src/vmod-sql.h new file mode 100644 index 0000000..7daff7a --- a/dev/null +++ b/src/vmod-sql.h @@ -0,0 +1,97 @@ +/* This file is part of vmod-sql + Copyright (C) 2013 Sergey Poznyakoff + + Vmod-sql 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, or (at your option) + any later version. + + Vmod-sql 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 vmod-sql. If not, see <http://www.gnu.org/licenses/>. +*/ +#include <config.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> +#include <syslog.h> +#include <regex.h> +#include <pthread.h> + +struct vmod_sql_connection; + +struct vmod_sql_backend { + char *name; + + int (*be_init) (struct vmod_sql_connection *); + void (*be_destroy) (struct vmod_sql_connection *); + int (*be_connect) (struct vmod_sql_connection *); + int (*be_disconnect) (struct vmod_sql_connection *); + char *(*be_escape) (struct vmod_sql_connection *, const char *); + int (*be_query) (struct vmod_sql_connection *, const char *); + unsigned (*be_num_tuples) (struct vmod_sql_connection *); + unsigned (*be_num_fields) (struct vmod_sql_connection *); + int (*be_free_result) (struct vmod_sql_connection *); + const char *(*sql_get_column)(struct vmod_sql_connection *, + unsigned, unsigned); + long (*be_affected_rows)(struct vmod_sql_connection *); +}; + +enum { + state_init, + state_connected, + state_result, + state_error, + state_disabled +}; + +#ifndef MAXCONN +# define MAXCONN 16 +#endif + +struct vmod_sql_connection { + int state; /* Connection state */ + int debug_level; + struct vmod_sql_backend *backend; /* Pointer to the backend */ + char *param_str; + char **param; + void *data; /* Backend-specific data */ +}; + +void i_modsql_debug(const char *fmt, ...); +void i_modsql_error(const char *fmt, ...); + +#define debug(c,n,a) do { if ((c)->debug_level>=(n)) i_modsql_debug a; } while (0) + +#ifdef USE_SQL_MYSQL +struct vmod_sql_backend i_modsql_mysql_backend; +#endif +#ifdef USE_SQL_PGSQL +struct vmod_sql_backend i_modsql_pgsql_backend; +#endif + +char *i_modsql_findparam(char **params, char *name); + +struct vmod_sql_connection *i_modsql_conntab_get(int n); +int i_modsql_conntab_alloc(struct vmod_sql_connection *cp); + +int i_modsql_create_connection(struct vmod_sql_backend *be, + const char *param_str, char **param); + +int i_modsql_init(struct vmod_sql_connection *); +int i_modsql_connect(struct vmod_sql_connection *pd); +void i_modsql_disconnect(struct vmod_sql_connection *pd); +char *i_modsql_escape(struct vmod_sql_connection *pd, const char *input); +int i_modsql_query(struct vmod_sql_connection *pd, const char *input); +unsigned i_modsql_num_tuples(struct vmod_sql_connection *pd); +unsigned i_modsql_num_fields(struct vmod_sql_connection *pd); +void i_modsql_free_result(struct vmod_sql_connection *pd); +void i_modsql_destroy(struct vmod_sql_connection *conn); +const char *i_modsql_get_column(struct vmod_sql_connection *pd, + unsigned row, unsigned col); +long i_modsql_affected_rows(struct vmod_sql_connection *conn); + diff --git a/src/vmod.vcc b/src/vmod.vcc new file mode 100644 index 0000000..46d4bdf --- a/dev/null +++ b/src/vmod.vcc @@ -0,0 +1,7 @@ +Module sql +Init module_init +Function INT connect(PRIV_VCL, STRING, STRING) +Function VOID connect_init(PRIV_VCL, STRING, STRING) +Function BOOL query(PRIV_VCL, INT, STRING, STRING) +Function STRING result(PRIV_VCL, INT, INT, INT) +Function INT affected(PRIV_VCL, INT) diff --git a/src/wordsplit.c b/src/wordsplit.c new file mode 100644 index 0000000..9047369 --- a/dev/null +++ b/src/wordsplit.c @@ -0,0 +1,1624 @@ +/* wordsplit - a word splitter + Copyright (C) 2009-2012 Sergey Poznyakoff + + 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 <http://www.gnu.org/licenses/>. */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include <errno.h> +#include <ctype.h> +#include <unistd.h> +#include <stdlib.h> +#include <string.h> +#include <stdio.h> +#include <stdarg.h> + +#if ENABLE_NLS +# include <gettext.h> +#else +# define gettext(msgid) msgid +#endif +#define _(msgid) gettext (msgid) +#define N_(msgid) msgid + +#include <wordsplit.h> + +#define ISWS(c) ((c)==' '||(c)=='\t'||(c)=='\n') +#define ISDELIM(ws,c) \ + (strchr ((ws)->ws_delim, (c)) != NULL) +#define ISPUNCT(c) (strchr("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",(c))!=NULL) +#define ISUPPER(c) ('A' <= ((unsigned) (c)) && ((unsigned) (c)) <= 'Z') +#define ISLOWER(c) ('a' <= ((unsigned) (c)) && ((unsigned) (c)) <= 'z') +#define ISALPHA(c) (ISUPPER(c) || ISLOWER(c)) +#define ISDIGIT(c) ('0' <= ((unsigned) (c)) && ((unsigned) (c)) <= '9') +#define ISXDIGIT(c) (strchr("abcdefABCDEF", c)!=NULL) +#define ISALNUM(c) (ISALPHA(c) || ISDIGIT(c)) +#define ISPRINT(c) (' ' <= ((unsigned) (c)) && ((unsigned) (c)) <= 127) + +#define ALLOC_INIT 128 +#define ALLOC_INCR 128 + +static void +_wsplt_alloc_die (struct wordsplit *wsp) +{ + wsp->ws_error (_("memory exhausted")); + abort (); +} + +static void +_wsplt_error (const char *fmt, ...) +{ + va_list ap; + + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + fputc ('\n', stderr); +} + +static void wordsplit_free_nodes (struct wordsplit *); + +static int +_wsplt_nomem (struct wordsplit *wsp) +{ + errno = ENOMEM; + wsp->ws_errno = WRDSE_NOSPACE; + if (wsp->ws_flags & WRDSF_ENOMEMABRT) + wsp->ws_alloc_die (wsp); + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + if (!(wsp->ws_flags & WRDSF_REUSE)) + wordsplit_free (wsp); + wordsplit_free_nodes (wsp); + return wsp->ws_errno; +} + +static void +wordsplit_init0 (struct wordsplit *wsp) +{ + if (wsp->ws_flags & WRDSF_REUSE) + { + if (!(wsp->ws_flags & WRDSF_APPEND)) + wordsplit_free_words (wsp); + } + else + { + wsp->ws_wordv = NULL; + wsp->ws_wordc = 0; + wsp->ws_wordn = 0; + } + + wsp->ws_errno = 0; + wsp->ws_head = wsp->ws_tail = NULL; +} + +static int +wordsplit_init (struct wordsplit *wsp, const char *input, size_t len, + int flags) +{ + wsp->ws_flags = flags; + + if (!(wsp->ws_flags & WRDSF_ALLOC_DIE)) + wsp->ws_alloc_die = _wsplt_alloc_die; + if (!(wsp->ws_flags & WRDSF_ERROR)) + wsp->ws_error = _wsplt_error; + + if (!(wsp->ws_flags & WRDSF_NOVAR) + && !(wsp->ws_flags & (WRDSF_ENV | WRDSF_GETVAR))) + { + errno = EINVAL; + wsp->ws_errno = WRDSE_USAGE; + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + return wsp->ws_errno; + } + + if (!(wsp->ws_flags & WRDSF_NOCMD)) + { + errno = EINVAL; + wsp->ws_errno = WRDSE_NOSUPP; + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + return wsp->ws_errno; + } + + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + if (!(wsp->ws_flags & WRDSF_DEBUG)) + { + if (wsp->ws_flags & WRDSF_ERROR) + wsp->ws_debug = wsp->ws_error; + else if (wsp->ws_flags & WRDSF_SHOWERR) + wsp->ws_debug = _wsplt_error; + else + wsp->ws_flags &= ~WRDSF_SHOWDBG; + } + } + + wsp->ws_input = input; + wsp->ws_len = len; + + if (!(wsp->ws_flags & WRDSF_DOOFFS)) + wsp->ws_offs = 0; + + if (!(wsp->ws_flags & WRDSF_DELIM)) + wsp->ws_delim = " \t\n"; + + if (!(wsp->ws_flags & WRDSF_COMMENT)) + wsp->ws_comment = NULL; + + if (!(wsp->ws_flags & WRDSF_CLOSURE)) + wsp->ws_closure = NULL; + + wsp->ws_endp = 0; + + wordsplit_init0 (wsp); + + return 0; +} + +static int +alloc_space (struct wordsplit *wsp, size_t count) +{ + size_t offs = (wsp->ws_flags & WRDSF_DOOFFS) ? wsp->ws_offs : 0; + char **ptr; + size_t newalloc; + + if (wsp->ws_wordv == NULL) + { + newalloc = offs + count > ALLOC_INIT ? count : ALLOC_INIT; + ptr = calloc (newalloc, sizeof (ptr[0])); + } + else if (wsp->ws_wordn < offs + wsp->ws_wordc + count) + { + newalloc = offs + wsp->ws_wordc + + (count > ALLOC_INCR ? count : ALLOC_INCR); + ptr = realloc (wsp->ws_wordv, newalloc * sizeof (ptr[0])); + } + else + return 0; + + if (ptr) + { + wsp->ws_wordn = newalloc; + wsp->ws_wordv = ptr; + } + else + return _wsplt_nomem (wsp); + return 0; +} + + +/* Node state flags */ +#define _WSNF_NULL 0x01 /* null node (a noop) */ +#define _WSNF_WORD 0x02 /* node contains word in v.word */ +#define _WSNF_QUOTE 0x04 /* text is quoted */ +#define _WSNF_NOEXPAND 0x08 /* text is not subject to expansion */ +#define _WSNF_JOIN 0x10 /* node must be joined with the next node */ +#define _WSNF_SEXP 0x20 /* is a sed expression */ + +#define _WSNF_EMPTYOK 0x0100 /* special flag indicating that + wordsplit_add_segm must add the + segment even if it is empty */ + +struct wordsplit_node +{ + struct wordsplit_node *prev; /* Previous element */ + struct wordsplit_node *next; /* Next element */ + int flags; /* Node flags */ + union + { + struct + { + size_t beg; /* Start of word in ws_input */ + size_t end; /* End of word in ws_input */ + } segm; + char *word; + } v; +}; + +static const char * +wsnode_flagstr (int flags) +{ + static char retbuf[6]; + char *p = retbuf; + + if (flags & _WSNF_WORD) + *p++ = 'w'; + else if (flags & _WSNF_NULL) + *p++ = 'n'; + else + *p++ = '-'; + if (flags & _WSNF_QUOTE) + *p++ = 'q'; + else + *p++ = '-'; + if (flags & _WSNF_NOEXPAND) + *p++ = 'E'; + else + *p++ = '-'; + if (flags & _WSNF_JOIN) + *p++ = 'j'; + else + *p++ = '-'; + if (flags & _WSNF_SEXP) + *p++ = 's'; + else + *p++ = '-'; + *p = 0; + return retbuf; +} + +static const char * +wsnode_ptr (struct wordsplit *wsp, struct wordsplit_node *p) +{ + if (p->flags & _WSNF_NULL) + return ""; + else if (p->flags & _WSNF_WORD) + return p->v.word; + else + return wsp->ws_input + p->v.segm.beg; +} + +static size_t +wsnode_len (struct wordsplit_node *p) +{ + if (p->flags & _WSNF_NULL) + return 0; + else if (p->flags & _WSNF_WORD) + return strlen (p->v.word); + else + return p->v.segm.end - p->v.segm.beg; +} + +static int +wsnode_new (struct wordsplit *wsp, struct wordsplit_node **pnode) +{ + struct wordsplit_node *node = calloc (1, sizeof (*node)); + if (!node) + return _wsplt_nomem (wsp); + *pnode = node; + return 0; +} + +static void +wsnode_free (struct wordsplit_node *p) +{ + if (p->flags & _WSNF_WORD) + free (p->v.word); + free (p); +} + +static void +wsnode_append (struct wordsplit *wsp, struct wordsplit_node *node) +{ + node->next = NULL; + node->prev = wsp->ws_tail; + if (wsp->ws_tail) + wsp->ws_tail->next = node; + else + wsp->ws_head = node; + wsp->ws_tail = node; +} + +static void +wsnode_remove (struct wordsplit *wsp, struct wordsplit_node *node) +{ + struct wordsplit_node *p; + + p = node->prev; + if (p) + { + p->next = node->next; + if (!node->next) + p->flags &= ~_WSNF_JOIN; + } + else + wsp->ws_head = node->next; + + p = node->next; + if (p) + p->prev = node->prev; + else + wsp->ws_tail = node->prev; + + node->next = node->prev = NULL; +} + +static void +wsnode_insert (struct wordsplit *wsp, struct wordsplit_node *node, + struct wordsplit_node *anchor, int before) +{ + if (!wsp->ws_head) + { + node->next = node->prev = NULL; + wsp->ws_head = wsp->ws_tail = node; + } + else if (before) + { + if (anchor->prev) + wsnode_insert (wsp, node, anchor->prev, 0); + else + { + node->prev = NULL; + node->next = anchor; + anchor->prev = node; + wsp->ws_head = node; + } + } + else + { + struct wordsplit_node *p; + + p = anchor->next; + if (p) + p->prev = node; + else + wsp->ws_tail = node; + node->next = p; + node->prev = anchor; + anchor->next = node; + } +} + +static int +wordsplit_add_segm (struct wordsplit *wsp, size_t beg, size_t end, int flg) +{ + struct wordsplit_node *node; + int rc; + + if (end == beg && !(flg & _WSNF_EMPTYOK)) + return 0; + rc = wsnode_new (wsp, &node); + if (rc) + return rc; + node->flags = flg & ~(_WSNF_WORD | _WSNF_EMPTYOK); + node->v.segm.beg = beg; + node->v.segm.end = end; + wsnode_append (wsp, node); + return 0; +} + +static void +wordsplit_free_nodes (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + + for (p = wsp->ws_head; p;) + { + struct wordsplit_node *next = p->next; + wsnode_free (p); + p = next; + } + wsp->ws_head = wsp->ws_tail = NULL; +} + +static void +wordsplit_dump_nodes (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + int n = 0; + + for (p = wsp->ws_head, n = 0; p; p = p->next, n++) + { + if (p->flags & _WSNF_WORD) + wsp->ws_debug ("%4d: %p: %#04x (%s):%s;", + n, p, p->flags, wsnode_flagstr (p->flags), p->v.word); + else + wsp->ws_debug ("%4d: %p: %#04x (%s):%.*s;", + n, p, p->flags, wsnode_flagstr (p->flags), + (int) (p->v.segm.end - p->v.segm.beg), + wsp->ws_input + p->v.segm.beg); + } +} + +static int +coalesce_segment (struct wordsplit *wsp, struct wordsplit_node *node) +{ + struct wordsplit_node *p, *end; + size_t len = 0; + char *buf, *cur; + int stop; + + for (p = node; p && (p->flags & _WSNF_JOIN); p = p->next) + { + len += wsnode_len (p); + } + if (p) + len += wsnode_len (p); + end = p; + + buf = malloc (len + 1); + if (!buf) + return _wsplt_nomem (wsp); + cur = buf; + + p = node; + for (stop = 0; !stop;) + { + struct wordsplit_node *next = p->next; + const char *str = wsnode_ptr (wsp, p); + size_t slen = wsnode_len (p); + + memcpy (cur, str, slen); + cur += slen; + if (p != node) + { + wsnode_remove (wsp, p); + stop = p == end; + wsnode_free (p); + } + p = next; + } + + *cur = 0; + + node->flags &= ~_WSNF_JOIN; + + if (node->flags & _WSNF_WORD) + free (node->v.word); + else + node->flags |= _WSNF_WORD; + node->v.word = buf; + return 0; +} + +static int +wsnode_quoteremoval (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + void (*uqfn) (char *, const char *, size_t) = + (wsp->ws_flags & WRDSF_CESCAPES) ? + wordsplit_c_unquote_copy : wordsplit_sh_unquote_copy; + + for (p = wsp->ws_head; p; p = p->next) + { + const char *str = wsnode_ptr (wsp, p); + size_t slen = wsnode_len (p); + int unquote; + + if (wsp->ws_flags & WRDSF_QUOTE) + { + unquote = !(p->flags & _WSNF_NOEXPAND); + } + else + unquote = 0; + + if (unquote) + { + if (!(p->flags & _WSNF_WORD)) + { + char *newstr = malloc (slen + 1); + if (!newstr) + return _wsplt_nomem (wsp); + memcpy (newstr, str, slen); + newstr[slen] = 0; + p->v.word = newstr; + p->flags |= _WSNF_WORD; + } + + if (wsp->ws_flags & WRDSF_ESCAPE) + wordsplit_general_unquote_copy (p->v.word, str, slen, + wsp->ws_escape); + else + uqfn (p->v.word, str, slen); + } + } + return 0; +} + +static int +wsnode_coalesce (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + + for (p = wsp->ws_head; p; p = p->next) + { + if (p->flags & _WSNF_JOIN) + if (coalesce_segment (wsp, p)) + return 1; + } + return 0; +} + +static int +wordsplit_finish (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + size_t n; + + n = 0; + + for (p = wsp->ws_head; p; p = p->next) + n++; + + if (alloc_space (wsp, n + 1)) + return 1; + + for (p = wsp->ws_head; p; p = p->next) + { + const char *str = wsnode_ptr (wsp, p); + size_t slen = wsnode_len (p); + char *newstr = malloc (slen + 1); + + /* Assign newstr first, even if it is NULL. This way + wordsplit_free will work even if we return + nomem later. */ + wsp->ws_wordv[wsp->ws_offs + wsp->ws_wordc] = newstr; + if (!newstr) + return _wsplt_nomem (wsp); + memcpy (newstr, str, slen); + newstr[slen] = 0; + + wsp->ws_wordc++; + + } + wsp->ws_wordv[wsp->ws_offs + wsp->ws_wordc] = NULL; + return 0; +} + + +/* Variable expansion */ +static int +node_split_prefix (struct wordsplit *wsp, + struct wordsplit_node **ptail, + struct wordsplit_node *node, + size_t beg, size_t len, int flg) +{ + struct wordsplit_node *newnode; + + if (len == 0) + return 0; + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + if (node->flags & _WSNF_WORD) + { + const char *str = wsnode_ptr (wsp, node); + char *newstr = malloc (len + 1); + if (!newstr) + return _wsplt_nomem (wsp); + memcpy (newstr, str + beg, len); + newstr[len] = 0; + newnode->flags = _WSNF_WORD; + newnode->v.word = newstr; + } + else + { + newnode->v.segm.beg = node->v.segm.beg + beg; + newnode->v.segm.end = newnode->v.segm.beg + len; + } + newnode->flags |= flg; + *ptail = newnode; + return 0; +} + +static int +find_closing_cbrace (const char *str, size_t i, size_t len, size_t * poff) +{ + enum + { st_init, st_squote, st_dquote } state = st_init; + size_t level = 1; + + for (; i < len; i++) + { + switch (state) + { + case st_init: + switch (str[i]) + { + case '{': + level++; + break; + + case '}': + if (--level == 0) + { + *poff = i; + return 0; + } + break; + + case '"': + state = st_dquote; + break; + + case '\'': + state = st_squote; + break; + } + break; + + case st_squote: + if (str[i] == '\'') + state = st_init; + break; + + case st_dquote: + if (str[i] == '\\') + i++; + else if (str[i] == '"') + state = st_init; + break; + } + } + return 1; +} + +static const char * +wordsplit_find_env (struct wordsplit *wsp, const char *name, size_t len) +{ + size_t i; + + if (!(wsp->ws_flags & WRDSF_ENV)) + return NULL; + + if (wsp->ws_flags & WRDSF_ENV_KV) + { + /* A key-value pair environment */ + for (i = 0; wsp->ws_env[i]; i++) + { + size_t elen = strlen (wsp->ws_env[i]); + if (elen == len && memcmp (wsp->ws_env[i], name, elen) == 0) + return wsp->ws_env[i + 1]; + /* Skip the value. Break the loop if it is NULL. */ + i++; + if (wsp->ws_env[i] == NULL) + break; + } + } + else + { + /* Usual (A=B) environment. */ + for (i = 0; wsp->ws_env[i]; i++) + { + size_t j; + const char *var = wsp->ws_env[i]; + + for (j = 0; j < len; j++) + if (name[j] != var[j]) + break; + if (j == len && var[j] == '=') + return var + j + 1; + } + } + return NULL; +} + +static int +expvar (struct wordsplit *wsp, const char *str, size_t len, + struct wordsplit_node **ptail, const char **pend, int flg) +{ + size_t i = 0; + const char *defstr = NULL; + const char *value; + const char *vptr; + struct wordsplit_node *newnode; + const char *start = str - 1; + + if (ISALPHA (str[0]) || str[0] == '_') + { + for (i = 1; i < len; i++) + if (!(ISALNUM (str[i]) || str[i] == '_')) + break; + *pend = str + i - 1; + } + else if (str[0] == '{') + { + str++; + len--; + for (i = 1; i < len; i++) + if (str[i] == '}' || str[i] == ':') + break; + if (str[i] == ':') + { + size_t j; + + defstr = str + i + 1; + if (find_closing_cbrace (str, i + 1, len, &j)) + { + wsp->ws_errno = WRDSE_CBRACE; + return 1; + } + *pend = str + j; + } + else if (str[i] == '}') + { + defstr = NULL; + *pend = str + i; + } + else + { + wsp->ws_errno = WRDSE_CBRACE; + return 1; + } + } + else + { + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_WORD | flg; + newnode->v.word = malloc (3); + if (!newnode->v.word) + return _wsplt_nomem (wsp); + newnode->v.word[0] = '$'; + newnode->v.word[1] = str[0]; + newnode->v.word[2] = 0; + *pend = str; + return 0; + } + + /* Actually expand the variable */ + /* str - start of the variable name + i - its length + defstr - default replacement str */ + + vptr = wordsplit_find_env (wsp, str, i); + if (vptr) + { + value = strdup (vptr); + if (!value) + return _wsplt_nomem (wsp); + } + else if (wsp->ws_flags & WRDSF_GETVAR) + value = wsp->ws_getvar (str, i, wsp->ws_closure); + else if (wsp->ws_flags & WRDSF_UNDEF) + { + wsp->ws_errno = WRDSE_UNDEF; + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + return 1; + } + else + { + if (wsp->ws_flags & WRDSF_WARNUNDEF) + wsp->ws_error (_("warning: undefined variable `%.*s'"), (int) i, str); + if (wsp->ws_flags & WRDSF_KEEPUNDEF) + value = NULL; + else + value = ""; + } + /* FIXME: handle defstr */ + if (value) + { + if (flg & _WSNF_QUOTE) + { + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_WORD | _WSNF_NOEXPAND | flg; + newnode->v.word = strdup (value); + if (!newnode->v.word) + return _wsplt_nomem (wsp); + } + else if (*value == 0) + { + /* Empty string is a special case */ + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_NULL; + } + else + { + struct wordsplit ws; + int i; + + ws.ws_delim = wsp->ws_delim; + if (wordsplit (value, &ws, + WRDSF_NOVAR | WRDSF_NOCMD | WRDSF_DELIM | WRDSF_WS)) + { + wordsplit_free (&ws); + return 1; + } + for (i = 0; i < ws.ws_wordc; i++) + { + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_WORD | + _WSNF_NOEXPAND | + (i + 1 < ws.ws_wordc ? (flg & ~_WSNF_JOIN) : flg); + newnode->v.word = strdup (ws.ws_wordv[i]); + if (!newnode->v.word) + return _wsplt_nomem (wsp); + } + wordsplit_free (&ws); + } + } + else if (wsp->ws_flags & WRDSF_KEEPUNDEF) + { + size_t size = *pend - start + 1; + + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_WORD | _WSNF_NOEXPAND | flg; + newnode->v.word = malloc (size + 1); + if (!newnode->v.word) + return _wsplt_nomem (wsp); + memcpy (newnode->v.word, start, size); + newnode->v.word[size] = 0; + } + else + { + if (wsnode_new (wsp, &newnode)) + return 1; + wsnode_insert (wsp, newnode, *ptail, 0); + *ptail = newnode; + newnode->flags = _WSNF_NULL; + } + return 0; +} + +static int +node_expand_vars (struct wordsplit *wsp, struct wordsplit_node *node) +{ + const char *str = wsnode_ptr (wsp, node); + size_t slen = wsnode_len (node); + const char *end = str + slen; + const char *p; + size_t off = 0; + struct wordsplit_node *tail = node; + + for (p = str; p < end; p++) + { + if (*p == '\\') + { + p++; + continue; + } + if (*p == '$') + { + size_t n = p - str; + + if (tail != node) + tail->flags |= _WSNF_JOIN; + if (node_split_prefix (wsp, &tail, node, off, n, _WSNF_JOIN)) + return 1; + p++; + if (expvar (wsp, p, slen - n, &tail, &p, + node->flags & (_WSNF_JOIN | _WSNF_QUOTE))) + return 1; + off += p - str + 1; + str = p + 1; + } + } + if (p > str) + { + if (tail != node) + tail->flags |= _WSNF_JOIN; + if (node_split_prefix (wsp, &tail, node, off, p - str, + node->flags & _WSNF_JOIN)) + return 1; + } + if (tail != node) + { + wsnode_remove (wsp, node); + wsnode_free (node); + } + return 0; +} + +/* Remove NULL lists */ +static void +wsnode_nullelim (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + + for (p = wsp->ws_head; p;) + { + struct wordsplit_node *next = p->next; + if (p->flags & _WSNF_NULL) + { + wsnode_remove (wsp, p); + wsnode_free (p); + } + p = next; + } +} + +static int +wordsplit_varexp (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + + for (p = wsp->ws_head; p;) + { + struct wordsplit_node *next = p->next; + if (!(p->flags & _WSNF_NOEXPAND)) + if (node_expand_vars (wsp, p)) + return 1; + p = next; + } + + wsnode_nullelim (wsp); + return 0; +} + +/* Strip off any leading and trailing whitespace. This function is called + right after the initial scanning, therefore it assumes that every + node in the list is a text reference node. */ +static void +wordsplit_trimws (struct wordsplit *wsp) +{ + struct wordsplit_node *p; + + for (p = wsp->ws_head; p; p = p->next) + { + size_t n; + + if (p->flags & _WSNF_QUOTE) + continue; + + /* Skip leading whitespace: */ + for (n = p->v.segm.beg; n < p->v.segm.end && ISWS (wsp->ws_input[n]); + n++) + ; + p->v.segm.beg = n; + /* Trim trailing whitespace */ + for (n = p->v.segm.end; + n > p->v.segm.beg && ISWS (wsp->ws_input[n - 1]); n--); + p->v.segm.end = n; + if (p->v.segm.beg == p->v.segm.end) + p->flags |= _WSNF_NULL; + } + + wsnode_nullelim (wsp); +} + +static int +skip_sed_expr (const char *command, size_t i, size_t len) +{ + int state; + + do + { + int delim; + + if (command[i] == ';') + i++; + if (!(command[i] == 's' && i + 3 < len && ISPUNCT (command[i + 1]))) + break; + + delim = command[++i]; + state = 1; + for (i++; i < len; i++) + { + if (state == 3) + { + if (command[i] == delim || !ISALNUM (command[i])) + break; + } + else if (command[i] == '\\') + i++; + else if (command[i] == delim) + state++; + } + } + while (state == 3 && i < len && command[i] == ';'); + return i; +} + +static size_t +skip_delim (struct wordsplit *wsp) +{ + size_t start = wsp->ws_endp; + if (wsp->ws_flags & WRDSF_SQUEEZE_DELIMS) + { + if ((wsp->ws_flags & WRDSF_RETURN_DELIMS) && + ISDELIM (wsp, wsp->ws_input[start])) + { + int delim = wsp->ws_input[start]; + do + start++; + while (start < wsp->ws_len && delim == wsp->ws_input[start]); + } + else + { + do + start++; + while (start < wsp->ws_len && ISDELIM (wsp, wsp->ws_input[start])); + } + start--; + } + + if (!(wsp->ws_flags & WRDSF_RETURN_DELIMS)) + start++; + + return start; +} + +#define _WRDS_EOF 0 +#define _WRDS_OK 1 +#define _WRDS_ERR 2 + +static int +scan_qstring (struct wordsplit *wsp, size_t start, size_t * end) +{ + size_t j; + const char *command = wsp->ws_input; + size_t len = wsp->ws_len; + char q = command[start]; + + for (j = start + 1; j < len && command[j] != q; j++) + if (q == '"' && command[j] == '\\') + j++; + if (j < len && command[j] == q) + { + int flags = _WSNF_QUOTE | _WSNF_EMPTYOK; + if (q == '\'') + flags |= _WSNF_NOEXPAND; + if (wordsplit_add_segm (wsp, start + 1, j, flags)) + return _WRDS_ERR; + *end = j; + } + else + { + wsp->ws_endp = start; + wsp->ws_errno = WRDSE_QUOTE; + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + return _WRDS_ERR; + } + return 0; +} + +static int +scan_word (struct wordsplit *wsp, size_t start) +{ + size_t len = wsp->ws_len; + const char *command = wsp->ws_input; + const char *comment = wsp->ws_comment; + int join = 0; + int flags = 0; + + size_t i = start; + + if (i >= len) + { + wsp->ws_errno = WRDSE_EOF; + return _WRDS_EOF; + } + + start = i; + + if (wsp->ws_flags & WRDSF_SED_EXPR + && command[i] == 's' && i + 3 < len && ISPUNCT (command[i + 1])) + { + flags = _WSNF_SEXP; + i = skip_sed_expr (command, i, len); + } + else if (!ISDELIM (wsp, command[i])) + { + while (i < len) + { + if (comment && strchr (comment, command[i]) != NULL) + { + size_t j; + for (j = i + 1; j < len && command[j] != '\n'; j++) + ; + if (wordsplit_add_segm (wsp, start, i, 0)) + return _WRDS_ERR; + wsp->ws_endp = j; + return _WRDS_OK; + } + + if (wsp->ws_flags & WRDSF_QUOTE) + { + if (command[i] == '\\') + { + if (++i == len) + break; + i++; + continue; + } + + if (((wsp->ws_flags & WRDSF_SQUOTE) && command[i] == '\'') || + ((wsp->ws_flags & WRDSF_DQUOTE) && command[i] == '"')) + { + if (join && wsp->ws_tail) + wsp->ws_tail->flags |= _WSNF_JOIN; + if (wordsplit_add_segm (wsp, start, i, _WSNF_JOIN)) + return _WRDS_ERR; + if (scan_qstring (wsp, i, &i)) + return _WRDS_ERR; + start = i + 1; + join = 1; + } + } + + if (ISDELIM (wsp, command[i])) + break; + else + i++; + } + } + else if (wsp->ws_flags & WRDSF_RETURN_DELIMS) + { + i++; + } + else if (!(wsp->ws_flags & WRDSF_SQUEEZE_DELIMS)) + flags |= _WSNF_EMPTYOK; + + if (join && i > start && wsp->ws_tail) + wsp->ws_tail->flags |= _WSNF_JOIN; + if (wordsplit_add_segm (wsp, start, i, flags)) + return _WRDS_ERR; + wsp->ws_endp = i; + if (wsp->ws_flags & WRDSF_INCREMENTAL) + return _WRDS_EOF; + return _WRDS_OK; +} + +static char quote_transtab[] = "\\\\\"\"a\ab\bf\fn\nr\rt\tv\v"; + +int +wordsplit_c_unquote_char (int c) +{ + char *p; + + for (p = quote_transtab; *p; p += 2) + { + if (*p == c) + return p[1]; + } + return c; +} + +int +wordsplit_c_quote_char (int c) +{ + char *p; + + for (p = quote_transtab + sizeof (quote_transtab) - 2; + p > quote_transtab; p -= 2) + { + if (*p == c) + return p[-1]; + } + return -1; +} + +#define to_num(c) \ + (ISDIGIT(c) ? c - '0' : (ISXDIGIT(c) ? toupper(c) - 'A' + 10 : 255 )) + +static int +xtonum (int *pval, const char *src, int base, int cnt) +{ + int i, val; + + for (i = 0, val = 0; i < cnt; i++, src++) + { + int n = *(unsigned char *) src; + if (n > 127 || (n = to_num (n)) >= base) + break; + val = val * base + n; + } + *pval = val; + return i; +} + +size_t +wordsplit_c_quoted_length (const char *str, int quote_hex, int *quote) +{ + size_t len = 0; + + *quote = 0; + for (; *str; str++) + { + if (strchr (" \"", *str)) + *quote = 1; + + if (*str == ' ') + len++; + else if (*str == '"') + len += 2; + else if (*str != '\t' && *str != '\\' && ISPRINT (*str)) + len++; + else if (quote_hex) + len += 3; + else + { + if (wordsplit_c_quote_char (*str) != -1) + len += 2; + else + len += 4; + } + } + return len; +} + +void +wordsplit_general_unquote_copy (char *dst, const char *src, size_t n, + const char *escapable) +{ + int i; + + for (i = 0; i < n;) + { + if (src[i] == '\\' && i < n && strchr (escapable, src[i + 1])) + i++; + *dst++ = src[i++]; + } + *dst = 0; +} + +void +wordsplit_sh_unquote_copy (char *dst, const char *src, size_t n) +{ + int i; + + for (i = 0; i < n;) + { + if (src[i] == '\\') + i++; + *dst++ = src[i++]; + } + *dst = 0; +} + +void +wordsplit_c_unquote_copy (char *dst, const char *src, size_t n) +{ + int i = 0; + int c; + + while (i < n) + { + if (src[i] == '\\') + { + ++i; + if (src[i] == 'x' || src[i] == 'X') + { + if (n - i < 2) + { + *dst++ = '\\'; + *dst++ = src[i++]; + } + else + { + int off = xtonum (&c, src + i + 1, + 16, 2); + if (off == 0) + { + *dst++ = '\\'; + *dst++ = src[i++]; + } + else + { + *dst++ = c; + i += off + 1; + } + } + } + else if ((unsigned char) src[i] < 128 && ISDIGIT (src[i])) + { + if (n - i < 1) + { + *dst++ = '\\'; + *dst++ = src[i++]; + } + else + { + int off = xtonum (&c, src + i, 8, 3); + if (off == 0) + { + *dst++ = '\\'; + *dst++ = src[i++]; + } + else + { + *dst++ = c; + i += off; + } + } + } + else + *dst++ = wordsplit_c_unquote_char (src[i++]); + } + else + *dst++ = src[i++]; + } + *dst = 0; +} + +void +wordsplit_c_quote_copy (char *dst, const char *src, int quote_hex) +{ + for (; *src; src++) + { + if (*src == '"') + { + *dst++ = '\\'; + *dst++ = *src; + } + else if (*src != '\t' && *src != '\\' && ISPRINT (*src)) + *dst++ = *src; + else + { + char tmp[4]; + + if (quote_hex) + { + snprintf (tmp, sizeof tmp, "%%%02X", *(unsigned char *) src); + memcpy (dst, tmp, 3); + dst += 3; + } + else + { + int c = wordsplit_c_quote_char (*src); + *dst++ = '\\'; + if (c != -1) + *dst++ = c; + else + { + snprintf (tmp, sizeof tmp, "%03o", *(unsigned char *) src); + memcpy (dst, tmp, 3); + dst += 3; + } + } + } + } +} + +static int +wordsplit_process_list (struct wordsplit *wsp, size_t start) +{ + if (wsp->ws_flags & WRDSF_NOSPLIT) + { + /* Treat entire input as a quoted argument */ + if (wordsplit_add_segm (wsp, start, wsp->ws_len, _WSNF_QUOTE)) + return wsp->ws_errno; + } + else + { + int rc; + + while ((rc = scan_word (wsp, start)) == _WRDS_OK) + start = skip_delim (wsp); + /* Make sure tail element is not joinable */ + if (wsp->ws_tail) + wsp->ws_tail->flags &= ~_WSNF_JOIN; + if (rc == _WRDS_ERR) + return wsp->ws_errno; + } + + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + wsp->ws_debug ("Initial list:"); + wordsplit_dump_nodes (wsp); + } + + if (wsp->ws_flags & WRDSF_WS) + { + /* Trim leading and trailing whitespace */ + wordsplit_trimws (wsp); + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + wsp->ws_debug ("After WS trimming:"); + wordsplit_dump_nodes (wsp); + } + } + + /* Expand variables (FIXME: & commands) */ + if (!(wsp->ws_flags & WRDSF_NOVAR)) + { + if (wordsplit_varexp (wsp)) + { + wordsplit_free_nodes (wsp); + return wsp->ws_errno; + } + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + wsp->ws_debug ("Expanded list:"); + wordsplit_dump_nodes (wsp); + } + } + + do + { + if (wsnode_quoteremoval (wsp)) + break; + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + wsp->ws_debug ("After quote removal:"); + wordsplit_dump_nodes (wsp); + } + + if (wsnode_coalesce (wsp)) + break; + + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + wsp->ws_debug ("Coalesced list:"); + wordsplit_dump_nodes (wsp); + } + } + while (0); + return wsp->ws_errno; +} + +int +wordsplit_len (const char *command, size_t length, struct wordsplit *wsp, + int flags) +{ + int rc; + size_t start; + const char *cmdptr; + size_t cmdlen; + + if (!command) + { + if (!(flags & WRDSF_INCREMENTAL)) + return EINVAL; + + start = skip_delim (wsp); + if (wsp->ws_endp == wsp->ws_len) + { + wsp->ws_errno = WRDSE_NOINPUT; + if (wsp->ws_flags & WRDSF_SHOWERR) + wordsplit_perror (wsp); + return wsp->ws_errno; + } + + cmdptr = wsp->ws_input + wsp->ws_endp; + cmdlen = wsp->ws_len - wsp->ws_endp; + wsp->ws_flags |= WRDSF_REUSE; + wordsplit_init0 (wsp); + } + else + { + cmdptr = command; + cmdlen = length; + start = 0; + rc = wordsplit_init (wsp, cmdptr, cmdlen, flags); + if (rc) + return rc; + } + + if (wsp->ws_flags & WRDSF_SHOWDBG) + wsp->ws_debug ("Input:%.*s;", (int) cmdlen, cmdptr); + + rc = wordsplit_process_list (wsp, start); + if (rc == 0 && (flags & WRDSF_INCREMENTAL)) + { + while (!wsp->ws_head && wsp->ws_endp < wsp->ws_len) + { + start = skip_delim (wsp); + if (wsp->ws_flags & WRDSF_SHOWDBG) + { + cmdptr = wsp->ws_input + wsp->ws_endp; + cmdlen = wsp->ws_len - wsp->ws_endp; + wsp->ws_debug ("Restart:%.*s;", (int) cmdlen, cmdptr); + } + rc = wordsplit_process_list (wsp, start); + if (rc) + break; + } + } + if (rc) + { + wordsplit_free_nodes (wsp); + return rc; + } + wordsplit_finish (wsp); + wordsplit_free_nodes (wsp); + return wsp->ws_errno; +} + +int +wordsplit (const char *command, struct wordsplit *ws, int flags) +{ + return wordsplit_len (command, command ? strlen (command) : 0, ws, + flags); +} + +void +wordsplit_free_words (struct wordsplit *ws) +{ + size_t i; + + for (i = 0; i < ws->ws_wordc; i++) + { + char *p = ws->ws_wordv[ws->ws_offs + i]; + if (p) + { + free (p); + ws->ws_wordv[ws->ws_offs + i] = NULL; + } + } + ws->ws_wordc = 0; +} + +void +wordsplit_free (struct wordsplit *ws) +{ + wordsplit_free_words (ws); + free (ws->ws_wordv); + ws->ws_wordv = NULL; +} + +void +wordsplit_perror (struct wordsplit *wsp) +{ + switch (wsp->ws_errno) + { + case WRDSE_EOF: + wsp->ws_error (_("no error")); + break; + + case WRDSE_QUOTE: + wsp->ws_error (_("missing closing %c (start near #%lu)"), + wsp->ws_input[wsp->ws_endp], + (unsigned long) wsp->ws_endp); + break; + + case WRDSE_NOSPACE: + wsp->ws_error (_("memory exhausted")); + break; + + case WRDSE_NOSUPP: + wsp->ws_error (_("command substitution is not yet supported")); + break; + + case WRDSE_USAGE: + wsp->ws_error (_("invalid wordsplit usage")); + break; + + case WRDSE_CBRACE: + wsp->ws_error (_("unbalanced curly brace")); + break; + + case WRDSE_UNDEF: + wsp->ws_error (_("undefined variable")); + break; + + case WRDSE_NOINPUT: + wsp->ws_error (_("input exhausted")); + break; + + default: + wsp->ws_error (_("unknown error")); + } +} + +const char *_wordsplit_errstr[] = { + N_("no error"), + N_("missing closing quote"), + N_("memory exhausted"), + N_("command substitution is not yet supported"), + N_("invalid wordsplit usage"), + N_("unbalanced curly brace"), + N_("undefined variable"), + N_("input exhausted") +}; +int _wordsplit_nerrs = + sizeof (_wordsplit_errstr) / sizeof (_wordsplit_errstr[0]); + +const char * +wordsplit_strerror (struct wordsplit *ws) +{ + if (ws->ws_errno < _wordsplit_nerrs) + return _wordsplit_errstr[ws->ws_errno]; + return N_("unknown error"); +} diff --git a/src/wordsplit.h b/src/wordsplit.h new file mode 100644 index 0000000..8502106 --- a/dev/null +++ b/src/wordsplit.h @@ -0,0 +1,159 @@ +/* wordsplit - a word splitter + Copyright (C) 2009-2012 Sergey Poznyakoff + + 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 <http://www.gnu.org/licenses/>. */ + +#ifndef __WORDSPLIT_H +#define __WORDSPLIT_H + +#include <stddef.h> + +struct wordsplit +{ + size_t ws_wordc; + char **ws_wordv; + size_t ws_offs; + size_t ws_wordn; + int ws_flags; + const char *ws_delim; + const char *ws_comment; + const char *ws_escape; + void (*ws_alloc_die) (struct wordsplit * wsp); + void (*ws_error) (const char *, ...) + __attribute__ ((__format__ (__printf__, 1, 2))); + void (*ws_debug) (const char *, ...) + __attribute__ ((__format__ (__printf__, 1, 2))); + + const char **ws_env; + const char *(*ws_getvar) (const char *, size_t, void *); + void *ws_closure; + + const char *ws_input; + size_t ws_len; + size_t ws_endp; + int ws_errno; + struct wordsplit_node *ws_head, *ws_tail; +}; + +/* Wordsplit flags. Only 2 bits of a 32-bit word remain unused. + It is getting crowded... */ +/* Append the words found to the array resulting from a previous + call. */ +#define WRDSF_APPEND 0x00000001 +/* Insert we_offs initial NULLs in the array ws_wordv. + (These are not counted in the returned ws_wordc.) */ +#define WRDSF_DOOFFS 0x00000002 +/* Don't do command substitution. Reserved for future use. */ +#define WRDSF_NOCMD 0x00000004 +/* The parameter p resulted from a previous call to + wordsplit(), and wordsplit_free() was not called. Reuse the + allocated storage. */ +#define WRDSF_REUSE 0x00000008 +/* Print errors */ +#define WRDSF_SHOWERR 0x00000010 +/* Consider it an error if an undefined shell variable + is expanded. */ +#define WRDSF_UNDEF 0x00000020 + +/* Don't do variable expansion. */ +#define WRDSF_NOVAR 0x00000040 +/* Abort on ENOMEM error */ +#define WRDSF_ENOMEMABRT 0x00000080 +/* Trim off any leading and trailind whitespace */ +#define WRDSF_WS 0x00000100 +/* Handle single quotes */ +#define WRDSF_SQUOTE 0x00000200 +/* Handle double quotes */ +#define WRDSF_DQUOTE 0x00000400 +/* Handle quotes and escape directives */ +#define WRDSF_QUOTE (WRDSF_SQUOTE|WRDSF_DQUOTE) +/* Replace each input sequence of repeated delimiters with a single + delimiter */ +#define WRDSF_SQUEEZE_DELIMS 0x00000800 +/* Return delimiters */ +#define WRDSF_RETURN_DELIMS 0x00001000 +/* Treat sed expressions as words */ +#define WRDSF_SED_EXPR 0x00002000 +/* ws_delim field is initialized */ +#define WRDSF_DELIM 0x00004000 +/* ws_comment field is initialized */ +#define WRDSF_COMMENT 0x00008000 +/* ws_alloc_die field is initialized */ +#define WRDSF_ALLOC_DIE 0x00010000 +/* ws_error field is initialized */ +#define WRDSF_ERROR 0x00020000 +/* ws_debug field is initialized */ +#define WRDSF_DEBUG 0x00040000 +/* ws_env field is initialized */ +#define WRDSF_ENV 0x00080000 +/* ws_getvar field is initialized */ +#define WRDSF_GETVAR 0x00100000 +/* enable debugging */ +#define WRDSF_SHOWDBG 0x00200000 +/* Don't split input into words. Useful for side effects. */ +#define WRDSF_NOSPLIT 0x00400000 +/* Keep undefined variables in place, instead of expanding them to + empty string */ +#define WRDSF_KEEPUNDEF 0x00800000 +/* Warn about undefined variables */ +#define WRDSF_WARNUNDEF 0x01000000 +/* Handle C escapes */ +#define WRDSF_CESCAPES 0x02000000 + +/* ws_closure is set */ +#define WRDSF_CLOSURE 0x04000000 +/* ws_env is a Key/Value environment, i.e. the value of a variable is + stored in the element that follows its name. */ +#define WRDSF_ENV_KV 0x08000000 + +/* ws_escape is set */ +#define WRDSF_ESCAPE 0x10000000 + +/* Incremental mode */ +#define WRDSF_INCREMENTAL 0x20000000 + +#define WRDSF_DEFFLAGS \ + (WRDSF_NOVAR | WRDSF_NOCMD | \ + WRDSF_QUOTE | WRDSF_SQUEEZED_ELIMS | WRDSF_CESCAPES) + +#define WRDSE_EOF 0 +#define WRDSE_QUOTE 1 +#define WRDSE_NOSPACE 2 +#define WRDSE_NOSUPP 3 +#define WRDSE_USAGE 4 +#define WRDSE_CBRACE 5 +#define WRDSE_UNDEF 6 +#define WRDSE_NOINPUT 7 + +int wordsplit (const char *s, struct wordsplit *p, int flags); +int wordsplit_len (const char *s, size_t len, + struct wordsplit *p, int flags); +void wordsplit_free (struct wordsplit *p); +void wordsplit_free_words (struct wordsplit *ws); + +int wordsplit_c_unquote_char (int c); +int wordsplit_c_quote_char (int c); +size_t wordsplit_c_quoted_length (const char *str, int quote_hex, + int *quote); +void wordsplit_general_unquote_copy (char *dst, const char *src, size_t n, + const char *escapable); +void wordsplit_sh_unquote_copy (char *dst, const char *src, size_t n); +void wordsplit_c_unquote_copy (char *dst, const char *src, size_t n); +void wordsplit_c_quote_copy (char *dst, const char *src, int quote_hex); + +void wordsplit_perror (struct wordsplit *ws); +const char *wordsplit_strerror (struct wordsplit *ws); + + +#endif |