pax_global_header00006660000000000000000000000064147546253760014535gustar00rootroot0000000000000052 comment=eb71e9bc8fb2f191d225b13209549227bc6f13a0 fts-xapian-1.9.1/000077500000000000000000000000001475462537600136175ustar00rootroot00000000000000fts-xapian-1.9.1/.gitignore000066400000000000000000000016521475462537600156130ustar00rootroot00000000000000# http://www.gnu.org/software/automake Makefile.in /ar-lib /mdate-sh /py-compile /test-driver /ylwrap .deps/ .dirstamp # http://www.gnu.org/software/autoconf autom4te.cache /autoscan.log /autoscan-*.log /aclocal.m4 /compile /config.guess /config.h.in /config.log /config.status /config.sub /configure /configure.scan /depcomp /install-sh /missing /stamp-h1 /stamp-h2 /stamp.h # https://www.gnu.org/software/libtool/ /ltmain.sh /libtool # http://www.gnu.org/software/texinfo /texinfo.tex # http://www.gnu.org/software/m4/ m4/libtool.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4 m4/lt~obsolete.m4 # Generated Makefile # (meta build system like autotools, # can automatically generate from config.status script # (which is called by configure script)) Makefile configure~ /dummy-config.h /dummy-config.h.in /dummy-config.h.in~ /fts-xapian-config.h /run-test.sh /PACKAGES/RPM/fedora src/*.o src/*.lo src/*.la src/.libs/** fts-xapian-1.9.1/AUTHORS000066400000000000000000000001001475462537600146560ustar00rootroot00000000000000Joan Moreau via dovecot fts-xapian-1.9.1/COPYING000066400000000000000000000634631475462537600146660ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, see . Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Moe Ghoul, President of Vice That's all there is to it! fts-xapian-1.9.1/Makefile.am000066400000000000000000000001241475462537600156500ustar00rootroot00000000000000SUBDIRS = src PACKAGE_VERSION = "1.9.1" VERSION = "1.9.1" ACLOCAL_AMFLAGS = -I m4 fts-xapian-1.9.1/README.md000066400000000000000000000123571475462537600151060ustar00rootroot00000000000000FTS Xapian plugin for Dovecot ============================= What is this? ------------- This project intends to provide a straightforward, simple and maintenance free, way to configure FTS plugin for [Dovecot](https://github.com/dovecot/), leveraging the efforts by the [Xapian.org](https://xapian.org/) team. This effort came after Dovecot team decided to deprecate "fts_squat" included in the dovecot core, and due to the complexity of the Solr plugin capabilitles, unneeded for most users. If you feel donating, kindly use Paypal : moreaujoan@gmail.com Debugging/Support ----------------- Please submit requests/bugs via the [GitHub issue tracker](https://github.com/grosjo/fts-xapian/issues). A Matrix Room exists also at : #xapian-dovecot:matrix.grosjo.net Availability in major distributions ----------------------------------- THis plugin is readly available in major distributions under the name "dovecot-fts-xapian" - Archlinux : https://archlinux.org/packages/?q=dovecot-fts-xapian - Debian : https://packages.debian.org/bookworm/dovecot-fts-xapian - Fedora : https://src.fedoraproject.org/rpms/dovecot-fts-xapian Configuration - dovecot.conf file --------------------------------- You need to setup LMTP properly with your SMTP server. Kindly refer to: - For Postfix : https://doc.dovecot.org/2.3/configuration_manual/howto/postfix_dovecot_lmtp/ - For Exim : https://doc.dovecot.org/2.3/configuration_manual/howto/dovecot_lmtp_exim/ Update your dovecot.conf file with something similar to: *VERSION 2.3.x* ``` (...) protocols = imap pop3 sieve lmtp mail_plugins = (...) fts fts_xapian plugin { fts = xapian fts_xapian = verbose=0 fts_autoindex = yes fts_enforced = yes (...) } service indexer-worker { # Increase vsz_limit to 2GB or above. # Or 0 if you have rather large memory usable on your server, which is preferred for performance) vsz_limit = 2G # This one must be 0 process_limit = 0 } (...) ``` *VERSION 2.4.x* ``` (...) protocols = imap pop3 sieve lmtp mail_plugins = (...) fts fts_xapian fts_autoindex = yes language "en" { default = yes } // Note : the 'language' settings is set mandatory by dovecot // but has totally NO impact on FTS Xapian module fts xapian { // Note : All variables are optional verbose = 0 maxthreads = 4 lowmemory = 500 partial = 3 } (...) ``` Configuration options -------------------------------- | Option | Optional | Description | Possible values | Default value | |----------------|----------|---------------------------------|-----------------------------------------------------|---------------| | partial | yes | Minimum size of search keyword | 3 or above | 3 | | verbose | yes | Logs verbosity | 0 (silent), 1 (verbose) or 2 (debug) | 0 | | lowmemory | yes | Memory limit before disk commit | 0 (default, meaning 300MB), or set value (in MB) | 0 | | maxthreads | yes | Maximum number of threads | 0 (default, hardware limit), or value above 2 | 0 | Index updating ------------------------------ Just restart Dovecot: ```sh sudo service restart dovecot ``` You shall put in a cron the following command (daily for instance) to cleanup indexes : ```sh doveadm fts optimize -A ``` Building yourself - Prerequisites ---------------------------------- You are going to need the following things to get this going: ``` * Dovecot 2.2.x (or above) * Xapian 1.2.x (or above) * ICU 50.x (or above) * SQlite 3.x ``` You will need to configure properly [Users Home Directories](https://doc.dovecot.org/2.3/configuration_manual/home_directories_for_virtual_users/) in dovecot configuration Building yourself - Installing the Dovecot plugin ----------------------------- First install the following packages, or equivalent for your operating system. ``` Ubuntu: apt-get build-dep dovecot-core apt-get install dovecot-dev git libxapian-dev libicu-dev libsqlite3-dev autoconf automake libtool pkg-config Archlinux: pacman -S dovecot pacman -S xapian-core icu git sqlite FreeBSD: pkg install xapian-core pkg install xapian-bindings pkg install icu pkg install git Fedora: dnf install sqlite-devel libicu-devel xapian-core-devel dnf install dovecot-devel git ``` Clone this project: ``` git clone https://github.com/grosjo/fts-xapian cd fts-xapian ``` Compile and install the plugin. ``` autoupdate autoreconf -vi ./configure --with-dovecot=/path/to/dovecot make sudo make install ``` Note: if your system is quite old, you may change gnu++20 by gnu++11 in src/Makefile.in Replace /path/to/dovecot by the actual path to 'dovecot-config'. Type 'locate dovecot-config' in a shell to figure this out. On ArchLinux , it is /usr/lib/dovecot. For specific configuration, you may have to 'export PKG_CONFIG_PATH=...'. To check that, type 'pkg-config --cflags-only-I icu-uc icu-io icu-i18n', it shall return no error. The module will be placed into the module directory of your dovecot configuration ------ Thanks to Aki Tuomi , Stephan Bosch , Paul Hecker fts-xapian-1.9.1/configure.ac000066400000000000000000000103151475462537600161050ustar00rootroot00000000000000AC_INIT([Dovecot FTS Xapian],[1.9.1],[jom@grosjo.net],[dovecot-fts-xapian]) AC_CONFIG_AUX_DIR([.]) AC_CONFIG_SRCDIR([src]) AC_CONFIG_MACRO_DIR([m4]) # Autoheader is not needed and does more harm than good for this package # However, it is tightly integrated in autoconf/automake and therefore it is # difficult not to use it. As a workaround we give autoheader a dummy config # header to chew on and we handle the real config header ourselves. AC_CONFIG_HEADERS([dummy-config.h fts-xapian-config.h]) AM_INIT_AUTOMAKE([no-define foreign tar-ustar]) AM_MAINTAINER_MODE AC_PROG_CC AC_PROG_CPP AC_PROG_CXX LT_INIT PKG_PROG_PKG_CONFIG DC_DOVECOT DC_DOVECOT_MODULEDIR LIBDOVECOT_INCLUDE="$LIBDOVECOT_INCLUDE" CFLAGS="$CFLAGS $EXTRA_CFLAGS $DOVECOT_FLAGS -O2" LIBS="$DOVECOT_LIBS" BINARY_LDFLAGS="$PIE_LDFLAGS $RELRO_LDFLAGS" BINARY_CFLAGS="$PIE_CFLAGS" AC_SUBST(LIBDOVECOT_INCLUDE) PKG_PROG_PKG_CONFIG() # check and set $PKG_CONFIG PKG_CHECK_MODULES([ICU_UC], [icu-uc >= 50], [have_icu_uc=true], [have_icu_uc=false]) PKG_CHECK_MODULES([ICU_I18N], [icu-i18n >= 50], [have_icu_i18n=true], [have_icu_i18n=false]) if !($have_icu_uc && $have_icu_i18n); then AC_MSG_ERROR([icu 50 or higher is required, but was not found.]) fi ICU_LDFLAGS=$($PKG_CONFIG --libs-only-L icu-uc | sed 's/-L//g') ICU_LIBS=$($PKG_CONFIG --libs icu-uc icu-io icu-i18n) ICU_CFLAGS=$($PKG_CONFIG --cflags-only-I icu-uc icu-io icu-i18n) ICU_INCLUDE=$($PKG_CONFIG --variable=includedir icu-uc) AC_MSG_CHECKING([for fts_mail_user_init]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([[ #include "$dovecot_pkgincludedir/config.h" #include "$dovecot_pkgincludedir/lib.h" #include "$dovecot_pkgincludedir/mail-user.h" #include "$dovecot_pkgincludedir/fts-user.h" int f() { void *ptr = &fts_mail_user_init; (void)ptr; return 0; } ]])], [ AC_MSG_RESULT([yes]) ],[ AC_MSG_RESULT([no]) AC_MSG_ERROR([fts_mail_user_init not found dovecot headers are not installed correctly]) ]) AC_MSG_CHECKING([whether fts_mail_user_init has 2, 3 or 4 args]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([[ #include "$dovecot_pkgincludedir/config.h" #include "$dovecot_pkgincludedir/lib.h" #include "$dovecot_pkgincludedir/mail-user.h" #include "$dovecot_pkgincludedir/fts-user.h" void f(struct mail_user *s, const char **error) { fts_mail_user_init(s, NULL, 0, error); } ]])], [ AC_MSG_RESULT([4]) USERINIT_ARGS="-DFTS_DOVECOT24=1" ],[ AC_COMPILE_IFELSE( [AC_LANG_PROGRAM([[ #include "$dovecot_pkgincludedir/config.h" #include "$dovecot_pkgincludedir/lib.h" #include "$dovecot_pkgincludedir/mail-user.h" #include "$dovecot_pkgincludedir/fts-user.h" void f(struct mail_user *s, const char **error) { fts_mail_user_init(s, 0, error); } ]])], [ AC_MSG_RESULT([3]) USERINIT_ARGS="-DFTS_MAIL_USER_INIT_THREE_ARGS=1" ],[ AC_MSG_RESULT([no]) USERINIT_ARGS="" ]) ]) AC_SUBST(ICU_CFLAGS) AC_SUBST(ICU_LIBS) AC_SUBST(ICU_INCLUDE) AC_SUBST(ICU_LDFLAGS) AC_SUBST(USERINIT_ARGS) PKG_CHECK_MODULES([SQLITE], [sqlite3], [have_sqlite=true], [have_sqlite=false]); if !($have_sqlite); then AC_MSG_ERROR([SQLite is required, but was not found.]) fi AC_CHECK_PROG(XAPIAN_CONFIG,xapian-config,xapian-config,no) AM_CONDITIONAL(HAVE_XAPIAN,test "x$XAPIAN_CONFIG" != "xno") AS_IF([test "x$XAPIAN_CONFIG" = "xno"],[ AC_MSG_ERROR([ *** xapian could not be found; please install it *** e.g., in debian/ubuntu the package would be 'libxapian-dev' *** If you compiled it yourself, you should ensure that xapian-config *** is in your PATH.])], [XAPIAN_VERSION=$($XAPIAN_CONFIG --version | sed -e 's/.* //')]) XAPIAN_CXXFLAGS="$($XAPIAN_CONFIG --cxxflags)" XAPIAN_LIBS="$($XAPIAN_CONFIG --libs)" AC_SUBST(XAPIAN_CXXFLAGS) AC_SUBST(XAPIAN_LIBS) if test "$DOVECOT_INSTALLED" != "yes"; then DOVECOT_FTS_PLUGIN="$abs_dovecotdir/src/plugins/fts/lib20_fts_plugin.la" else DOVECOT_FTS_PLUGIN="$dovecot_installed_moduledir/lib20_fts_plugin.la" fi AC_SUBST(DOVECOT_FTS_PLUGIN) AC_CONFIG_FILES([ Makefile src/Makefile stamp.h]) AC_OUTPUT fts-xapian-1.9.1/contrib/000077500000000000000000000000001475462537600152575ustar00rootroot00000000000000fts-xapian-1.9.1/contrib/conf.d/000077500000000000000000000000001475462537600164265ustar00rootroot00000000000000fts-xapian-1.9.1/contrib/conf.d/90-fts.conf000066400000000000000000000011071475462537600203160ustar00rootroot00000000000000mail_plugins = $mail_plugins fts fts_xapian plugin { fts = xapian fts_xapian = partial=3 full=20 verbose=0 fts_autoindex = yes fts_enforced = yes fts_autoindex_exclude = \Trash fts_decoder = decode2text } service indexer-worker { # Increase vsz_limit to 2GB or above. # Or 0 if you have rather large memory usable on your server, which is preferred for performance) vsz_limit = 2G } service decode2text { executable = script /usr/libexec/dovecot/decode2text.sh user = dovecot unix_listener decode2text { mode = 0666 } } fts-xapian-1.9.1/contrib/systemd/000077500000000000000000000000001475462537600167475ustar00rootroot00000000000000fts-xapian-1.9.1/contrib/systemd/dovecot-fts-optimize.service.in000066400000000000000000000003101475462537600250230ustar00rootroot00000000000000[Unit] Description=Optimize Dovecot FTS Index Requires=dovecot.service After=dovecot.service [Service] Type=oneshot ExecStart=@@prefix@@/doveadm fts optimize -A [Install] WantedBy=multi-user.target fts-xapian-1.9.1/contrib/systemd/dovecot-fts-optimize.timer.in000066400000000000000000000002101475462537600245020ustar00rootroot00000000000000[Unit] Description=Optimize Dovecot FTS Index [Timer] OnCalendar=@@index_frequency@@ Persistent=true [Install] WantedBy=timers.target fts-xapian-1.9.1/fts-xapian-config.h.in000066400000000000000000000001201475462537600177030ustar00rootroot00000000000000#define FTS_XAPIAN_NAME "Dovecot FTS Xapian" #define FTS_XAPIAN_VERSION "1.9.1" fts-xapian-1.9.1/m4/000077500000000000000000000000001475462537600141375ustar00rootroot00000000000000fts-xapian-1.9.1/m4/dovecot.m4000066400000000000000000000477771475462537600160720ustar00rootroot00000000000000dnl dovecot.m4 - Check presence of dovecot -*-Autoconf-*- dnl dnl Copyright (C) 2010 Dennis Schridde dnl dnl This file is free software; the authors give dnl unlimited permission to copy and/or distribute it, with or without dnl modifications, as long as this notice is preserved. # serial 41 dnl dnl Check for support for D_FORTIFY_SOURCE=2 dnl AC_DEFUN([AC_CC_D_FORTIFY_SOURCE],[ AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) AS_IF([test "$enable_hardening" = yes], [ case "$host" in *) gl_COMPILER_OPTION_IF([-O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2], [ CFLAGS="$CFLAGS -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2" ], [], [AC_LANG_PROGRAM()] ) ;; esac ]) ]) dnl * gcc specific options AC_DEFUN([DC_DOVECOT_CFLAGS],[ m4_version_prereq(2.70, [AC_PROG_CC], [AC_PROG_CC_C99]) AS_IF([test "$ac_prog_cc_stdc" = "c89" || test "$ac_prog_cc_std" = "no" || test "$ac_cv_prog_cc_c99" = "no"], [ AC_MSG_ERROR(C99 capable compiler required) ]) AC_MSG_CHECKING([Which $CC -std flag to use]) old_cflags=$CFLAGS std= for mystd in gnu11 gnu99 c11 c99; do CFLAGS="-std=$mystd" AC_COMPILE_IFELSE([AC_LANG_PROGRAM() ], [ CFLAGS="$CFLAGS $old_cflags" std=$mystd break ], [ CFLAGS="$old_cflags" ]) done AC_MSG_RESULT($std) AS_IF([test "x$ac_cv_c_compiler_gnu" = "xyes"], [ dnl -Wcast-qual -Wcast-align -Wconversion -Wunreachable-code # too many warnings dnl -Wstrict-prototypes -Wredundant-decls # may give warnings in some systems dnl -Wmissing-format-attribute -Wmissing-noreturn -Wwrite-strings # a couple of warnings CFLAGS="$CFLAGS -Wall -W -Wmissing-prototypes -Wmissing-declarations -Wpointer-arith -Wchar-subscripts -Wformat=2 -Wbad-function-cast" AS_IF([test "$have_clang" = "yes"], [ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 3) # error new clang #endif ]], [[]])],[],[ dnl clang 3.3+ unfortunately this gives warnings with hash.h CFLAGS="$CFLAGS -Wno-duplicate-decl-specifier" ]) ], [ dnl This is simply to avoid warning when building strftime() wrappers.. CFLAGS="$CFLAGS -fno-builtin-strftime" ]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #if __GNUC__ < 4 # error old gcc #endif ]], [[]])],[ dnl gcc4 CFLAGS="$CFLAGS -Wstrict-aliasing=2" ],[]) ]) ]) AC_DEFUN([AC_LD_WHOLE_ARCHIVE], [ LD_WHOLE_ARCHIVE= LD_NO_WHOLE_ARCHIVE= AC_MSG_CHECKING([for linker option to include whole archive]) ld_help="`$CC -Wl,-help 2>&1`" case "$ld_help" in *"--whole-archive"*) LD_WHOLE_ARCHIVE="--whole-archive" LD_NO_WHOLE_ARCHIVE="--no-whole-archive" ;; esac AS_IF([test "x$LD_WHOLE_ARCHIVE" != "x"], [AC_MSG_RESULT([-Wl,$LD_WHOLE_ARCHIVE])], [AC_MSG_RESULT([not supported])] ) AC_SUBST([LD_WHOLE_ARCHIVE]) AC_SUBST([LD_NO_WHOLE_ARCHIVE]) AM_CONDITIONAL([HAVE_WHOLE_ARCHIVE], [test "x$LD_WHOLE_ARCHIVE" != "x"]) ]) dnl dnl Check for -z now and -z relro linker flags dnl dnl Copyright (C) 2013 Red Hat, Inc. dnl dnl This library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public dnl License as published by the Free Software Foundation; either dnl version 2.1 of the License, or (at your option) any later version. dnl dnl This library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with this library. If not, see dnl . dnl AC_DEFUN([AC_LD_RELRO],[ RELRO_LDFLAGS= AS_IF([test "$enable_hardening" = yes], [ AC_MSG_CHECKING([for how to force completely read-only GOT table]) ld_help=`$CC -Wl,-help 2>&1` case $ld_help in *"-z relro"*) RELRO_LDFLAGS="-Wl,-z -Wl,relro" ;; esac case $ld_help in *"-z now"*) RELRO_LDFLAGS="$RELRO_LDFLAGS -Wl,-z -Wl,now" ;; esac AS_IF([test "x$RELRO_LDFLAGS" != "x"], [AC_MSG_RESULT([$RELRO_LDFLAGS])], [AC_MSG_RESULT([unknown])] ) ]) AC_SUBST([RELRO_LDFLAGS]) ]) dnl dnl Check for support for position independent executables dnl dnl Copyright (C) 2013 Red Hat, Inc. dnl dnl This library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public dnl License as published by the Free Software Foundation; either dnl version 2.1 of the License, or (at your option) any later version. dnl dnl This library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with this library. If not, see dnl . dnl AC_DEFUN([AC_CC_PIE],[ AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) PIE_CFLAGS= PIE_LDFLAGS= AS_IF([test "$enable_hardening" = yes], [ OLD_CFLAGS=$CFLAGS case "$host" in *-*-mingw* | *-*-msvc* | *-*-cygwin* ) ;; dnl All code is position independent on Win32 target *) CFLAGS="-fPIE -DPIE" gl_COMPILER_OPTION_IF([-pie], [ PIE_CFLAGS="-fPIE -DPIE" PIE_LDFLAGS="-pie" ], [ dnl some versions of clang require -Wl,-pie instead of -pie gl_COMPILER_OPTION_IF([[-Wl,-pie]], [ PIE_CFLAGS="-fPIE -DPIE" PIE_LDFLAGS="-Wl,-pie" ], [AC_MSG_RESULT([not supported])], [AC_LANG_PROGRAM()] ) ], [AC_LANG_PROGRAM()] ) esac CFLAGS=$OLD_CFLAGS ]) AC_SUBST([PIE_CFLAGS]) AC_SUBST([PIE_LDFLAGS]) ]) dnl dnl Check for support for Retpoline dnl AC_DEFUN([AC_CC_RETPOLINE],[ AC_ARG_WITH(retpoline, AS_HELP_STRING([--with-retpoline=], [Retpoline mitigation choice (default: keep)]), with_retpoline=$withval, with_retpoline=keep) AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) AS_IF([test "$enable_hardening" = yes], [ case "$host" in *) gl_COMPILER_OPTION_IF([-mfunction-return=$with_retpoline], [CFLAGS="$CFLAGS -mfunction-return=$with_retpoline"], [], [AC_LANG_PROGRAM()] ) gl_COMPILER_OPTION_IF([-mindirect-branch=$with_retpoline], [ CFLAGS="$CFLAGS -mindirect-branch=$with_retpoline" ], [], [AC_LANG_PROGRAM()] ) esac ]) ]) dnl dnl Check for support for -fstack-protector or -strong dnl AC_DEFUN([AC_CC_F_STACK_PROTECTOR],[ AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) AS_IF([test "$enable_hardening" = yes], [ case "$host" in *) gl_COMPILER_OPTION_IF([-fstack-protector-strong], [ CFLAGS="$CFLAGS -fstack-protector-strong" ], [ gl_COMPILER_OPTION_IF([-fstack-protector], [ CFLAGS="$CFLAGS -fstack-protector" ], [], [AC_LANG_PROGRAM()]) ], [AC_LANG_PROGRAM()] ) esac ]) ]) AC_DEFUN([DC_DOVECOT_MODULEDIR],[ AC_ARG_WITH(moduledir, [ --with-moduledir=DIR Base directory for dynamically loadable modules], [moduledir="$withval"], [moduledir="\$(libdir)/dovecot"] ) AC_SUBST(moduledir) ]) AC_DEFUN([DC_PLUGIN_DEPS],[ _plugin_deps=yes AC_MSG_CHECKING([whether OS supports plugin dependencies]) case "$host_os" in darwin*) dnl OSX loads the plugins twice, which breaks stuff _plugin_deps=no ;; esac AC_MSG_RESULT([$_plugin_deps]) AM_CONDITIONAL([DOVECOT_PLUGIN_DEPS], [test "x$_plugin_deps" = "xyes"]) unset _plugin_deps ]) AC_DEFUN([DC_DOVECOT_TEST_WRAPPER],[ AC_REQUIRE_AUX_FILE([run-test.sh.in]) AC_ARG_VAR([VALGRIND], [Path to valgrind]) AC_PATH_PROG(VALGRIND, valgrind, reject) AS_IF([test "$VALGRIND" != reject], [ RUN_TEST='$(LIBTOOL) execute $(SHELL) $(top_builddir)/build-aux/run-test.sh' ], [ RUN_TEST='' ]) AC_SUBST(RUN_TEST) ]) dnl Substitute every var in the given comma separated list AC_DEFUN([AX_SUBST_L],[ m4_foreach([__var__], [$@], [AC_SUBST(__var__)]) ]) AC_DEFUN([DC_DOVECOT_HARDENING],[ AC_ARG_ENABLE(hardening, AS_HELP_STRING([--enable-hardening=yes], [Enable various hardenings (default: yes)]), enable_hardening=$enableval, enable_hardening=yes) AC_MSG_CHECKING([Whether to enable hardening]) AC_MSG_RESULT([$enable_hardening]) AC_CC_PIE AC_CC_F_STACK_PROTECTOR AC_CC_D_FORTIFY_SOURCE AC_CC_RETPOLINE AC_LD_RELRO DOVECOT_WANT_UBSAN ]) AC_DEFUN([DC_DOVECOT_FUZZER],[ AC_ARG_WITH(fuzzer, AS_HELP_STRING([--with-fuzzer=clang], [Build with clang fuzzer (default: no)]), with_fuzzer=$withval, with_fuzzer=no) AS_IF([test x$with_fuzzer = xclang], [ CFLAGS="$CFLAGS -fsanitize=fuzzer-no-link" # use $LIB_FUZZING_ENGINE for linking if it exists FUZZER_LDFLAGS=${LIB_FUZZING_ENGINE--fsanitize=fuzzer} # May need to use CXXLINK for linking, which wants sources to # be compiled with -fPIE FUZZER_CPPFLAGS='$(AM_CPPFLAGS) -fPIE -DPIE' ], [test x$with_fuzzer != xno], [ AC_MSG_ERROR([Unknown fuzzer $with_fuzzer]) ]) AC_SUBST([FUZZER_CPPFLAGS]) AC_SUBST([FUZZER_LDFLAGS]) AM_CONDITIONAL([USE_FUZZER], [test "x$with_fuzzer" != "xno"]) ]) AC_DEFUN([DC_DOVECOT],[ AC_ARG_WITH(dovecot, [ --with-dovecot=DIR Dovecot base directory], [ dovecotdir="$withval" ], [ dc_prefix=$prefix test "x$dc_prefix" = xNONE && dc_prefix=$ac_default_prefix dovecotdir="$dc_prefix/lib/dovecot" ] ) AC_ARG_WITH(dovecot-install-dirs, [AS_HELP_STRING([--with-dovecot-install-dirs], [Use install directories configured for Dovecot (default)])], AS_IF([test x$withval = xno], [ use_install_dirs=no ], [ use_install_dirs=yes ]), use_install_dirs=yes) AC_MSG_CHECKING([for "$dovecotdir/dovecot-config"]) AS_IF([test -f "$dovecotdir/dovecot-config"], [ AC_MSG_RESULT([$dovecotdir/dovecot-config]) ], [ AC_MSG_RESULT([not found]) AC_MSG_NOTICE([]) AC_MSG_NOTICE([Use --with-dovecot=DIR to provide the path to the dovecot-config file.]) AC_MSG_ERROR([dovecot-config not found]) ]) old=`pwd` cd $dovecotdir abs_dovecotdir=`pwd` cd $old DISTCHECK_CONFIGURE_FLAGS="--with-dovecot=$abs_dovecotdir --without-dovecot-install-dirs" dnl Make sure dovecot-config doesn't accidentically override flags ORIG_CFLAGS="$CFLAGS" ORIG_LDFLAGS="$LDFLAGS" ORIG_BINARY_CFLAGS="$BINARY_CFLAGS" ORIG_BINARY_LDFLAGS="$BINARY_LDFLAGS" eval `$GREP -i '^dovecot_[[a-z_]]*=' "$dovecotdir"/dovecot-config` eval `$GREP '^LIBDOVECOT[[A-Z0-9_]]*=' "$dovecotdir"/dovecot-config` CFLAGS="$ORIG_CFLAGS" LDFLAGS="$ORIG_LDFLAGS" BINARY_CFLAGS="$ORIG_BINARY_CFLAGS" BINARY_LDFLAGS="$ORIG_BINARY_LDFLAGS" dovecot_installed_moduledir="$dovecot_moduledir" AS_IF([test "$use_install_dirs" = "no"], [ dnl the main purpose of these is to fix make distcheck for plugins dnl other than that, they don't really make much sense dovecot_pkgincludedir='$(pkgincludedir)' dovecot_pkglibdir='$(pkglibdir)' dovecot_pkglibexecdir='$(libexecdir)/dovecot' dovecot_docdir='$(docdir)' dovecot_moduledir='$(moduledir)' dovecot_statedir='$(statedir)' ]) CC_CLANG CC_STRICT_BOOL DC_DOVECOT_CFLAGS DC_DOVECOT_HARDENING AX_SUBST_L([DISTCHECK_CONFIGURE_FLAGS], [dovecotdir], [dovecot_moduledir], [dovecot_installed_moduledir], [dovecot_pkgincludedir], [dovecot_pkglibexecdir], [dovecot_pkglibdir], [dovecot_docdir], [dovecot_statedir]) AX_SUBST_L([DOVECOT_INSTALLED], [DOVECOT_CFLAGS], [DOVECOT_LIBS], [DOVECOT_SSL_LIBS], [DOVECOT_SQL_LIBS], [DOVECOT_LDAP_LIBS], [DOVECOT_COMPRESS_LIBS], [DOVECOT_BINARY_CFLAGS], [DOVECOT_BINARY_LDFLAGS]) AX_SUBST_L([LIBDOVECOT], [LIBDOVECOT_LOGIN], [LIBDOVECOT_SQL], [LIBDOVECOT_LDAP], [LIBDOVECOT_OPENSSL], [LIBDOVECOT_COMPRESS], [LIBDOVECOT_LDA], [LIBDOVECOT_STORAGE], [LIBDOVECOT_DSYNC], [LIBDOVECOT_LIBLANG]) AX_SUBST_L([LIBDOVECOT_DEPS], [LIBDOVECOT_LOGIN_DEPS], [LIBDOVECOT_SQL_DEPS], [LIBDOVECOT_LDAP_DEPS], [LIBDOVECOT_OPENSSL_DEPS], [LIBDOVECOT_COMPRESS_DEPS], [LIBDOVECOT_LDA_DEPS], [LIBDOVECOT_STORAGE_DEPS], [LIBDOVECOT_DSYNC_DEPS], [LIBDOVECOT_LIBLANG_DEPS]) AX_SUBST_L([LIBDOVECOT_INCLUDE], [LIBDOVECOT_LDA_INCLUDE], [LIBDOVECOT_AUTH_INCLUDE], [LIBDOVECOT_DOVEADM_INCLUDE], [LIBDOVECOT_SERVICE_INCLUDE], [LIBDOVECOT_STORAGE_INCLUDE], [LIBDOVECOT_LOGIN_INCLUDE], [LIBDOVECOT_SQL_INCLUDE], [LIBDOVECOT_LDAP_INCLUDE]) AX_SUBST_L([LIBDOVECOT_IMAP_LOGIN_INCLUDE], [LIBDOVECOT_CONFIG_INCLUDE], [LIBDOVECOT_IMAP_INCLUDE], [LIBDOVECOT_POP3_INCLUDE], [LIBDOVECOT_SUBMISSION_INCLUDE], [LIBDOVECOT_LMTP_INCLUDE], [LIBDOVECOT_DSYNC_INCLUDE], [LIBDOVECOT_IMAPC_INCLUDE], [LIBDOVECOT_LANG_INCLUDE]) AX_SUBST_L([LIBDOVECOT_NOTIFY_INCLUDE], [LIBDOVECOT_PUSH_NOTIFICATION_INCLUDE], [LIBDOVECOT_ACL_INCLUDE], [LIBDOVECOT_LIBLANG_INCLUDE], [LIBDOVECOT_LUA_INCLUDE]) AX_SUBST_L([DOVECOT_LUA_LIBS], [DOVECOT_LUA_CFLAGS], [LIBDOVECOT_LUA], [LIBDOVECOT_LUA_DEPS]) AS_IF([test x$DOVECOT_HAVE_MAIL_UTF8 = xyes], [ AC_DEFINE([DOVECOT_HAVE_MAIL_UTF8],,"Define if Dovecot has mail UTF-8 support") ]) AM_CONDITIONAL(DOVECOT_INSTALLED, test "$DOVECOT_INSTALLED" = "yes") DC_PLUGIN_DEPS DC_DOVECOT_TEST_WRAPPER ]) AC_DEFUN([DC_CC_WRAPPER],[ AS_IF([test "$want_shared_libs" != "yes"], [ dnl want_shared_libs=no is for internal use. the liblib.la check is for plugins AS_IF([test "$want_shared_libs" = "no" || echo "$LIBDOVECOT" | $GREP "/liblib.la" > /dev/null], [ AS_IF([test "$with_gnu_ld" = yes], [ dnl libtool can't handle using whole-archive flags, so we need to do this dnl with a CC wrapper.. shouldn't be much of a problem, since most people dnl are building with shared libs. cat > cc-wrapper.sh <<_DC_EOF #!/bin/sh if echo "\$[*]" | $GREP -- -export-dynamic > /dev/null; then # the binary uses plugins. make sure we include everything from .a libs exec $CC -Wl,--whole-archive \$[*] -Wl,--no-whole-archive else exec $CC \$[*] fi _DC_EOF chmod +x cc-wrapper.sh CC=`pwd`/cc-wrapper.sh ]) ]) ]) ]) # warnings.m4 serial 11 dnl Copyright (C) 2008-2015 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl From Simon Josefsson # gl_AS_VAR_APPEND(VAR, VALUE) # ---------------------------- # Provide the functionality of AS_VAR_APPEND if Autoconf does not have it. m4_ifdef([AS_VAR_APPEND], [m4_copy([AS_VAR_APPEND], [gl_AS_VAR_APPEND])], [m4_define([gl_AS_VAR_APPEND], [AS_VAR_SET([$1], [AS_VAR_GET([$1])$2])])]) # gl_COMPILER_OPTION_IF(OPTION, [IF-SUPPORTED], [IF-NOT-SUPPORTED], # [PROGRAM = AC_LANG_PROGRAM()]) # ----------------------------------------------------------------- # Check if the compiler supports OPTION when compiling PROGRAM. # # FIXME: gl_Warn must be used unquoted until we can assume Autoconf # 2.64 or newer. AC_DEFUN([gl_COMPILER_OPTION_IF], [AS_VAR_PUSHDEF([gl_Warn], [gl_cv_warn_[]_AC_LANG_ABBREV[]_$1])dnl AS_VAR_PUSHDEF([gl_Flags], [_AC_LANG_PREFIX[]FLAGS])dnl AS_LITERAL_IF([$1], [m4_pushdef([gl_Positive], m4_bpatsubst([$1], [^-Wno-], [-W]))], [gl_positive="$1" case $gl_positive in -Wno-*) gl_positive=-W`expr "X$gl_positive" : 'X-Wno-\(.*\)'` ;; esac m4_pushdef([gl_Positive], [$gl_positive])])dnl AC_CACHE_CHECK([whether _AC_LANG compiler handles $1], m4_defn([gl_Warn]), [ gl_save_compiler_FLAGS="$gl_Flags" gl_AS_VAR_APPEND(m4_defn([gl_Flags]), [" $gl_unknown_warnings_are_errors ]m4_defn([gl_Positive])["]) AC_LINK_IFELSE([m4_default([$4], [AC_LANG_PROGRAM([])])], [AS_VAR_SET(gl_Warn, [yes])], [AS_VAR_SET(gl_Warn, [no])]) gl_Flags="$gl_save_compiler_FLAGS" ]) AS_VAR_IF(gl_Warn, [yes], [$2], [$3]) m4_popdef([gl_Positive])dnl AS_VAR_POPDEF([gl_Flags])dnl AS_VAR_POPDEF([gl_Warn])dnl ]) # gl_UNKNOWN_WARNINGS_ARE_ERRORS # ------------------------------ # Clang doesn't complain about unknown warning options unless one also # specifies -Wunknown-warning-option -Werror. Detect this. AC_DEFUN([gl_UNKNOWN_WARNINGS_ARE_ERRORS], [gl_COMPILER_OPTION_IF([-Werror -Wunknown-warning-option], [gl_unknown_warnings_are_errors='-Wunknown-warning-option -Werror'], [gl_unknown_warnings_are_errors=])]) # gl_WARN_ADD(OPTION, [VARIABLE = WARN_CFLAGS], # [PROGRAM = AC_LANG_PROGRAM()]) # --------------------------------------------- # Adds parameter to WARN_CFLAGS if the compiler supports it when # compiling PROGRAM. For example, gl_WARN_ADD([-Wparentheses]). # # If VARIABLE is a variable name, AC_SUBST it. AC_DEFUN([gl_WARN_ADD], [AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) gl_COMPILER_OPTION_IF([$1], [gl_AS_VAR_APPEND(m4_if([$2], [], [[WARN_CFLAGS]], [[$2]]), [" $1"])], [], [$3]) m4_ifval([$2], [AS_LITERAL_IF([$2], [AC_SUBST([$2])])], [AC_SUBST([WARN_CFLAGS])])dnl ]) # Local Variables: # mode: autoconf # End: dnl * clang check AC_DEFUN([CC_CLANG],[ AC_MSG_CHECKING([whether $CC is clang 3.3+]) AS_IF([$CC -dM -E -x c /dev/null | $GREP __clang__ > /dev/null 2>&1], [ AS_VAR_SET([have_clang], [yes]) ], [ AS_VAR_SET([have_clang], [no]) ]) AC_MSG_RESULT([$have_clang]) ]) AC_DEFUN([CC_STRICT_BOOL], [ AS_IF([test $have_clang = yes], [ AC_REQUIRE([gl_UNKNOWN_WARNINGS_ARE_ERRORS]) gl_COMPILER_OPTION_IF([-Wstrict-bool], [ AC_DEFINE(HAVE_STRICT_BOOL,, [we have strict bool]) ]) ]) ]) AC_DEFUN([DOVECOT_WANT_UBSAN], [ AC_ARG_ENABLE(ubsan, AS_HELP_STRING([--enable-ubsan], [Enable undefined behaviour sanitizes (default=no)]), [want_ubsan=yes], [want_ubsan=no]) AC_MSG_CHECKING([whether we want undefined behaviour sanitizer]) AC_MSG_RESULT([$want_ubsan]) AS_IF([test x$want_ubsan = xyes], [ san_flags="" gl_COMPILER_OPTION_IF([-fsanitize=undefined], [ san_flags="$san_flags -fsanitize=undefined -fno-sanitize=function,vptr" AC_DEFINE([HAVE_FSANITIZE_UNDEFINED], [1], [Define if your compiler has -fsanitize=undefined]) ]) gl_COMPILER_OPTION_IF([-fno-sanitize=nonnull-attribute], [ san_flags="$san_flags -fno-sanitize=nonnull-attribute" AC_DEFINE([HAVE_FNO_SANITIZE_NONNULL_ATTRIBUTE], [1], [Define if your compiler has -fno-sanitize=nonnull-attribute]) ]) gl_COMPILER_OPTION_IF([-fsanitize=implicit-integer-truncation], [ san_flags="$san_flags -fsanitize=implicit-integer-truncation" AC_DEFINE([HAVE_FSANITIZE_IMPLICIT_INTEGER_TRUNCATION], [1], [Define if your compiler has -fsanitize=implicit-integer-truncation]) ]) gl_COMPILER_OPTION_IF([-fsanitize=local-bounds], [ san_flags="$san_flags -fsanitize=local-bounds" AC_DEFINE([HAVE_FSANITIZE_LOCAL_BOUNDS], [1], [Define if your compiler has -fsanitize=local-bounds]) ]) gl_COMPILER_OPTION_IF([-fsanitize=integer], [ san_flags="$san_flags -fsanitize=integer" AC_DEFINE([HAVE_FSANITIZE_INTEGER], [1], [Define if your compiler has -fsanitize=integer]) ]) gl_COMPILER_OPTION_IF([-fsanitize=nullability], [ san_flags="$san_flags -fsanitize=nullability" AC_DEFINE([HAVE_FSANITIZE_NULLABILITY], [1], [Define if your compiler has -fsanitize=nullability]) ]) AS_IF([test "$san_flags" != "" ], [ EXTRA_CFLAGS="$EXTRA_CFLAGS $san_flags -U_FORTIFY_SOURCE -g -ggdb3 -O0 -fno-omit-frame-pointer" AC_DEFINE([HAVE_UNDEFINED_SANITIZER], [1], [Define if your compiler supports undefined sanitizers]) ], [ AC_MSG_ERROR([No undefined sanitizer support in your compiler]) ]) san_flags="" ]) ]) fts-xapian-1.9.1/run-test.sh.in000066400000000000000000000022651475462537600163460ustar00rootroot00000000000000#!/bin/sh ## serial 2 set -eu top_srcdir="@abs_top_srcdir@" VALGRIND="@VALGRIND@" if test $# -eq 0 || test "$1" = ""; then echo "Missing target binary" >&2 exit 1 fi if test "${NOUNDEF:-}" != ""; then noundef="--undef-value-errors=no" else noundef="" fi if test "${NOCHILDREN:-}" != ""; then trace_children="--trace-children=no" else trace_children="--trace-children=yes" fi skip_path="$top_srcdir/run-test-valgrind.exclude" if test -r "$skip_path" && grep -w -q "$(basename $[1])" "$skip_path"; then NOVALGRIND=true fi if test "${NOVALGRIND:-}" != ""; then "$@" ret=$? else test_out="test.out~$$" trap "rm -f $test_out" 0 1 2 3 15 supp_path="$top_srcdir/run-test-valgrind.supp" ret=0 if test -r "$supp_path"; then $VALGRIND -q $trace_children --error-exitcode=213 --leak-check=full --gen-suppressions=all --suppressions="$supp_path" --log-file=$test_out $noundef "$@" || ret=$? else $VALGRIND -q $trace_children --error-exitcode=213 --leak-check=full --gen-suppressions=all --log-file=$test_out $noundef "$@" || ret=$? fi if test -s $test_out; then cat $test_out ret=1 fi fi if test $ret != 0; then echo "Failed to run: $@" >&2 fi exit $ret fts-xapian-1.9.1/src/000077500000000000000000000000001475462537600144065ustar00rootroot00000000000000fts-xapian-1.9.1/src/Makefile.am000066400000000000000000000015141475462537600164430ustar00rootroot00000000000000AM_CPPFLAGS = -O2 \ $(LIBDOVECOT_INCLUDE) \ $(LIBDOVECOT_STORAGE_INCLUDE) \ $(LIBDOVECOT_DOVEADM_INCLUDE) \ $(LIBDOVECOT_LIBFTS_INCLUDE) \ $(LIBDOVECOT_FTS_INCLUDE) \ $(XAPIAN_INCLUDE) \ $(USERINIT_ARGS) \ $(ICU_CFLAGS) \ $(SQLITE_CFLAGS) AM_CXXFLAGS = -std=gnu++20 -Wall settingsdir = $(dovecot_moduledir)/settings settings_LTLIBRARIES = lib21_fts_xapian_settings.la lib21_fts_xapian_plugin_la_LDFLAGS = -module -avoid-version dovecot_module_LTLIBRARIES = lib21_fts_xapian_plugin.la lib21_fts_xapian_plugin_la_LIBADD = $(XAPIAN_LIBS) $(ICU_LIBS) $(SQLITE_LIBS) lib21_fts_xapian_settings_la_SOURCES = \ fts-xapian-settings.c lib21_fts_xapian_plugin_la_SOURCES = \ fts-xapian-plugin.c \ fts-backend-xapian.cpp \ fts-xapian-settings.c EXTRA_DIST = \ fts-backend-xapian-functions.cpp noinst_HEADERS = fts-xapian-plugin.h fts-xapian-1.9.1/src/fts-backend-xapian-functions.cpp000066400000000000000000001252051475462537600225640ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ static long fts_backend_xapian_current_time() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec * 1000 + tp.tv_usec / 1000; } static long fts_backend_xapian_get_free_memory(int verbose) // KB { char buffer[250]; char *p; struct rlimit rl; rl.rlim_cur=0; if(getrlimit(RLIMIT_AS,&rl)!=0) syslog(LOG_WARNING,"FTS Xapian: Memory limit by GETRLIMIT error: %s",strerror(errno)); long m,l = rl.rlim_cur; FILE *f; if(l<1) { if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Memory limit not available from getrlimit (probably vsz_limit not set"); #if defined(__FreeBSD__) || defined(__NetBSD__) u_int page_size; uint_size uint_size = sizeof(page_size); sysctlbyname("vm.stats.vm.v_page_size", &page_size, &uint_size, NULL, 0); struct vmtotal vmt; size_t vmt_size = sizeof(vmt); sysctlbyname("vm.vmtotal", &vmt, &vmt_size, NULL, 0); m = vmt.t_free * page_size / 1024.0f; #else f=fopen("/proc/meminfo","r"); if(f==NULL) return -1024; m=0; while(!feof(f)) { if ( fgets (buffer , 200 , f) == NULL ) break; p = strstr(buffer,"MemAvailable:"); if(p!=NULL) { m=atol(p+13); break; } } fclose(f); #endif if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Memory available from meminfo : %ld MB",(long)(m/1024.0)); } else { l = l / 1024.0f; if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Memory limit detected at %ld MB",(long)(l/1024.0f)); long pid=getpid(); sprintf(buffer,"/proc/%ld/status",pid); f=fopen(buffer,"r"); long memused=0; if(f != NULL) { while(!feof(f)) { if ( fgets (buffer , 100 , f) == NULL ) break; p = strstr(buffer,"VmSize:"); if(p!=NULL) { memused=atol(p+7); break; } } fclose(f); if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Memory used %ld MB",(long)(memused/1024.0f)); } else { if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Memory used not available from %s", buffer); memused=-1; } m = l - memused; } if(verbose>1) syslog(LOG_WARNING,"FTS Xapian: Available memory %ld MB",long(m/1024.0f)); return m; } static void fts_backend_xapian_icutostring(icu::UnicodeString *t, std::string &s) { s.clear(); t->toUTF8String(s); } static long fts_backend_xapian_icutochar_length(icu::UnicodeString *t) { std::string s; s.clear(); t->toUTF8String(s); return strlen(s.c_str()); } static bool fts_backend_xapian_clean_accents(icu::UnicodeString *t) { UErrorCode status = U_ZERO_ERROR; icu::Transliterator * accentsConverter = icu::Transliterator::createInstance("NFD; [:M:] Remove; NFC", UTRANS_FORWARD, status); if(U_FAILURE(status)) { std::string s("FTS Xapian: Can not allocate ICU translator + FreeMem="+std::to_string(long(fts_backend_xapian_get_free_memory(0)/1024.0f))+"MB"); syslog(LOG_ERR,"%s",s.c_str()); accentsConverter = NULL; return false; } accentsConverter->transliterate(*t); delete(accentsConverter); return true; } static void fts_backend_xapian_trim(icu::UnicodeString *d) { while(d->startsWith(CHAR_SPACE) || d->startsWith(CHAR_KEY)) { d->remove(0,1); } while(d->endsWith(CHAR_SPACE) || d->endsWith(CHAR_KEY)) { d->truncate(d->length()-1); } } static void fts_backend_xapian_clean(icu::UnicodeString *t) { fts_backend_xapian_clean_accents(t); t->toLower(); long k=CHARS_PB; while(k>0) { t->findAndReplace(chars_pb[k-1],CHAR_KEY); k--; } k=CHARS_SEP; while(k>0) { t->findAndReplace(chars_sep[k-1],CHAR_SPACE); k--; } fts_backend_xapian_trim(t); } static long fts_backend_xapian_clean_header(const char * hdr) { if(hdr == NULL) return -1; long l = strlen(hdr); if(l>=200) return -1; char h[200]; long i=0,j=0; while(j' ') && (hdr[j]!='"') && (hdr[j]!='\'') && (hdr[j]!='-')) { h[i]=std::tolower(hdr[j]); i++; } j++; } h[i]=0; i=0; while((i=HDRS_NB) i=-1; if(i==HDRS_NB-1) i=HDR_BODY; return i; } static void fts_backend_xapian_get_lock(struct xapian_fts_backend *backend, long verbose, const char *s) { std::unique_lock *lck; lck = new std::unique_lock(backend->mutex,std::defer_lock); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" while(!(lck->try_lock_for(std::chrono::milliseconds(1000 + std::rand() % 1000)))) { if(verbose>0) { std::string sl("FTS Xapian: Waiting unlock... ("); sl.append(s); sl.append(")"); syslog(LOG_INFO,"%s",sl.c_str()); } } #pragma GCC diagnostic pop if(verbose>0) { std::string sl("FTS Xapian: Got lock ("); sl.append(s); sl.append(")"); syslog(LOG_INFO,"%s",sl.c_str()); } backend->mutex_t = lck; } static void fts_backend_xapian_release_lock(struct xapian_fts_backend *backend, long verbose, const char *s) { if(verbose>1) { std::string sl("FTS Xapian: Releasing lock ("); sl.append(s); sl.append(")"); syslog(LOG_INFO,"%s",sl.c_str()); } if(backend->mutex_t !=NULL) { std::unique_lock *lck = backend->mutex_t; backend->mutex_t= NULL; delete(lck); } } static int fts_backend_xapian_sqlite3_vector_int(void *data, int argc, char **argv, char **azColName) { if (argc < 1) return -1; uint32_t uid = atol(argv[0]); std::vector * uids = (std::vector *) data; uids->push_back(uid); return 0; } static int fts_backend_xapian_sqlite3_vector_icu(void *data, int argc, char **argv, char **azColName) { if (argc < 1) return -1; icu::StringPiece sp(argv[0]); icu::UnicodeString * t = new icu::UnicodeString(icu::UnicodeString::fromUTF8(sp)); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: sqlite3_vector_string : Adding %s",argv[0]); std::vector * v = (std::vector *) data; v->push_back(t); return 0; } static bool fts_backend_xapian_sqlite3_dict_open(struct xapian_fts_backend *backend) { if(backend->ddb!=NULL) return TRUE; backend->dict_nb=0; if(sqlite3_open_v2(backend->dict_db,&(backend->ddb),SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,NULL) != SQLITE_OK ) { i_error("FTS Xapian: Can not open %s : %s",backend->dict_db,sqlite3_errmsg(backend->ddb)); backend->ddb = NULL; return FALSE; } char *zErrMsg = 0; if(sqlite3_exec(backend->ddb,createDictTable,NULL,0,&zErrMsg) != SQLITE_OK ) { i_error("FTS Xapian: Can not execute (%s) : %s",createDictTable,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); sqlite3_close(backend->ddb); backend->ddb = NULL; return FALSE; } zErrMsg =0; if(sqlite3_exec(backend->ddb,createDictIndexes,NULL,0,&zErrMsg) != SQLITE_OK ) { i_error("FTS Xapian: Can not execute (%s) : %s",createDictIndexes,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); sqlite3_close(backend->ddb); backend->ddb = NULL; return FALSE; } zErrMsg =0; if(sqlite3_exec(backend->ddb,createTmpTable,NULL,0,&zErrMsg) != SQLITE_OK ) { i_error("FTS Xapian: Can not execute (%s) : %s",createTmpTable,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); sqlite3_close(backend->ddb); backend->ddb = NULL; return FALSE; } return TRUE; } static int fts_backend_xapian_sqlite3_dict_add(struct xapian_fts_backend *backend, long h, icu::UnicodeString *t) { std::string sql; sql.clear(); t->toUTF8String(sql); sql=replaceTmpWord + sql + "', " + std::to_string(h) + ", " + std::to_string(sql.length()) + ");"; char * zErrMsg = 0; if(sqlite3_exec(backend->ddb,sql.c_str(),NULL,0,&zErrMsg) != SQLITE_OK ) { syslog(LOG_ERR,"FTS Xapian: Can not replace keyword (%s) : %s",sql.c_str(),zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); return 1; } backend->dict_nb++; return 0; } static bool fts_backend_xapian_sqlite3_dict_flush(struct xapian_fts_backend *backend, int verbose) { if(backend->dict_nb<1) return TRUE; long dt=fts_backend_xapian_current_time(); if(verbose>0) syslog(LOG_INFO,"FTS Xapian: Flushing Dictionnary : %ld terms",backend->dict_nb); char * zErrMsg = 0; if(sqlite3_exec(backend->ddb,flushTmpWords,NULL,0,&zErrMsg) != SQLITE_OK ) { syslog(LOG_ERR,"FTS Xapian: Can not execute (%s) : %s",flushTmpWords,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); return FALSE; } if(verbose>0) syslog(LOG_INFO,"FTS Xapian: Flushing Dictionnary : %ld terms done in %ld msec",backend->dict_nb,fts_backend_xapian_current_time()-dt); backend->dict_nb = 0; return TRUE; } class XResultSet { public: long size; Xapian::docid * data; XResultSet() { size=0; data=NULL; } ~XResultSet() { if (size>0) { i_free(data); } } void add(Xapian::docid did) { if(data==NULL) { data=(Xapian::docid *)i_malloc(sizeof(Xapian::docid)); } else { data=(Xapian::docid *)i_realloc(data,size*sizeof(Xapian::docid),(size+1)*sizeof(Xapian::docid)); } data[size]=did; size++; } }; class XQuerySet { private: long header; icu::UnicodeString * text; XQuerySet ** qs; Xapian::Query::op global_op; bool item_neg; // for the term long qsize; public: long limit; XQuerySet() { qsize=0; qs=NULL; limit=1; header=-1; text=NULL; global_op = Xapian::Query::op::OP_OR; } XQuerySet(Xapian::Query::op op, long l) { qsize=0; qs=NULL; limit=2; if(l>limit) { limit=l; } header=-1; text=NULL; global_op=op; } ~XQuerySet() { if(text!=NULL) { delete(text); text=NULL; } for(long j=0;j0) free(qs); qsize=0; qs=NULL; } void add(long uid) { std::string s = std::to_string(uid); icu::UnicodeString t(s.c_str()); add(0,&t,false); } void add(long h, icu::UnicodeString *t, bool is_neg) { if(t==NULL) return; fts_backend_xapian_clean(t); if(t->length()lastIndexOf(CHAR_SPACE); if(i>0) { if(is_neg) { q2 = new XQuerySet(Xapian::Query::OP_AND_NOT,limit); } else { q2 = new XQuerySet(Xapian::Query::OP_AND,limit); } while(i>0) { j = t->length(); r = new icu::UnicodeString(*t,i+1,j-i-1); q2->add(h,r,false); delete(r); t->truncate(i); fts_backend_xapian_trim(t); i = t->lastIndexOf(CHAR_SPACE); } q2->add(h,t,false); if(q2->count()>0) add(q2); else delete(q2); return; } if(h<0) { if(is_neg) { q2 = new XQuerySet(Xapian::Query::OP_AND_NOT,limit); } else { q2 = new XQuerySet(Xapian::Query::OP_OR,limit); } for(i=1;iadd(i,t,false); } add(q2); return; } if(text==NULL) { text=new icu::UnicodeString(*t); header=h; item_neg=is_neg; return; } q2 = new XQuerySet(Xapian::Query::OP_AND,limit); q2->add(h,t,is_neg); add(q2); } void add(XQuerySet *q2) { if(qsize<1) { qs=(XQuerySet **)malloc(sizeof(XQuerySet*)); } else { qs=(XQuerySet **)realloc(qs,(qsize+1)*sizeof(XQuerySet*)); } qs[qsize]=q2; qsize++; } int count() { int c=0; if(text!=NULL) c=1; c+=qsize; return c; } std::string get_string() { std::string s(""); if(count()<1) return s; if(text!=NULL) { if(item_neg) s.append("NOT ( "); s.append(hdrs_emails[header]); s.append(":\""); text->toUTF8String(s); s.append("\""); if(item_neg) s.append(")"); } const char * op; switch(global_op) { case Xapian::Query::OP_OR : op=" OR "; break; case Xapian::Query::OP_AND : op=" AND "; break; case Xapian::Query::OP_AND_NOT : op=" AND NOT "; break; default : op=" ERROR "; } for (int i=0;icount(); if(c<1) continue; if(s.length()>0) s.append(op); if(c>1) { s.append("("); s.append(qs[i]->get_string()); s.append(")"); } else s.append(qs[i]->get_string()); } return s; } Xapian::Query * get_query(Xapian::Database * db) { Xapian::Query * q = NULL; Xapian::Query *q2, *q3; if(text!=NULL) { std::string s(hdrs_query[header]); s.append(":\""); text->toUTF8String(s); s.append("\""); Xapian::QueryParser * qp = new Xapian::QueryParser(); for(int i=0; i< HDRS_NB-1; i++) qp->add_prefix(hdrs_query[i], hdrs_xapian[i]); qp->set_database(*db); q = new Xapian::Query(qp->parse_query(s.c_str(),Xapian::QueryParser::FLAG_DEFAULT)); delete (qp); if(item_neg) { q2 = new Xapian::Query(Xapian::Query::MatchAll); q3 = new Xapian::Query(Xapian::Query::OP_AND_NOT,*q2,*q); delete(q2); delete(q); q=q3; } } if(qsize<1) { if(q==NULL) q = new Xapian::Query(Xapian::Query::MatchNothing); return q; } if(q==NULL) { q=qs[0]->get_query(db); } else { q2 = new Xapian::Query(global_op,*q,*(qs[0]->get_query(db))); delete(q); q=q2; } for (int i=1;iget_query(db))); delete(q); q=q2; } return q; } }; class XDoc { private: std::vector * terms; std::vector * strings; std::vector * headers; struct xapian_fts_backend *backend; public: long uid; char * uterm; Xapian::Document * xdoc; long status; long status_n; long nterms,nlines,ndict; XDoc(struct xapian_fts_backend *b) { backend=b; uid=b->lastuid; std::string s="Q"+std::to_string(uid); uterm = (char*)malloc((s.length()+1)*sizeof(char)); strcpy(uterm,s.c_str()); strings = new std::vector; strings->clear(); headers = new std::vector; headers->clear(); terms = new std::vector; terms->clear(); nterms=0; nlines=0; ndict=0; xdoc=NULL; status=0; status_n=0; } ~XDoc() { for(icu::UnicodeString * t : *terms) { delete(t); } terms->clear(); delete(terms); headers->clear(); delete(headers); for(icu::UnicodeString * t : *strings) { delete(t); } strings->clear(); delete(strings); if(xdoc!=NULL) delete(xdoc); free(uterm); } std::string getDocSummary() { std::string s("Doc "); s.append(std::to_string(uid)); s.append(" uterm="); s.append(uterm); s.append(" #lines=" + std::to_string(nlines)); s.append(" #terms=" + std::to_string(nterms)); s.append(" #dict=" + std::to_string(ndict)); s.append(" status=" + std::to_string(status)); return s; } void raw_load(long h, const char *d, int32_t size, long verbose, const char * title) { icu::UnicodeString * t; { icu::StringPiece sp(d,size); t = new icu::UnicodeString(icu::UnicodeString::fromUTF8(sp)); } headers->push_back(h); strings->push_back(t); nlines++; } long terms_add(icu::UnicodeString * w,long pos, long l) { if(l==0) { terms->insert(terms->begin()+pos,new icu::UnicodeString(*w)); nterms++; return pos; } long n = std::floor(l*0.5f); int c = terms->at(pos+n)->compare(*w); // If already exist, return if(c==0) return pos; // If middle pos is lower than d, search after pos+n if(c<0) return terms_add(w,pos+n+1,l-n-1); // All other case, search before return terms_add(w,pos,n); } void terms_push(long h, icu::UnicodeString *t) { fts_backend_xapian_trim(t); unsigned long n = t->length(); long m = XAPIAN_TERM_SIZELIMIT - strlen(hdrs_xapian[h]) - 1; if(n>=fts_xapian_settings.partial) { t->truncate(m); while(fts_backend_xapian_icutochar_length(t)>=m) { t->truncate(t->length()-1); } fts_backend_xapian_sqlite3_dict_add(backend,h,t); ndict++; t->insert(0,hdrs_xapian[h]); terms_add(t,0,terms->size()); } delete(t); } bool terms_create(long verbose, const char * title) { icu::UnicodeString *t; long h; long k; while((terms->size()size()>0)) { h = headers->back(); headers->pop_back(); t = strings->back(); strings->pop_back(); fts_backend_xapian_clean(t); k = t->lastIndexOf(CHAR_SPACE); while(k>0) { terms_push(h,new icu::UnicodeString(*t,k+1)); t->truncate(k); fts_backend_xapian_trim(t); k = t->lastIndexOf(CHAR_SPACE); } terms_push(h,t); } return true; } bool doc_create(long verbose, const char * title) { if(verbose>0) syslog(LOG_INFO,"%s adding %ld terms",title,nterms); try { icu::UnicodeString *t; xdoc = new Xapian::Document(); xdoc->add_value(1,Xapian::sortable_serialise(uid)); xdoc->add_term(uterm); std::string s; long n = terms->size(); while(n>0) { n--; t=terms->back(); terms->pop_back(); fts_backend_xapian_icutostring(t,s); if(verbose>1) syslog(LOG_INFO,"%s adding terms for (%s) : %s",title,uterm,s.c_str()); xdoc->add_term(s.c_str()); delete(t); } } catch(Xapian::Error e) { return false; } return true; } }; static void fts_backend_xapian_worker(void *p); class XDocsWriter { private: XDoc * doc; long verbose, lowmemory; std::thread *t; char title[1000]; struct xapian_fts_backend *backend; public: bool started,toclose,terminated; XDocsWriter(struct xapian_fts_backend *b, long n) { backend=b; sprintf(title,"DW #%ld (%s,%s) - ",n,backend->boxname,backend->xap_db); t=NULL; doc=NULL; toclose=false; terminated=false; started=false; verbose=fts_xapian_settings.verbose; lowmemory = fts_xapian_settings.lowmemory; } bool checkDB() { if(backend->dbw != NULL) return true; backend->pending=0; try { if(verbose>0) syslog(LOG_INFO,"%sOpening DB (RW)",title); backend->dbw = new Xapian::WritableDatabase(backend->xap_db,Xapian::DB_CREATE_OR_OPEN | Xapian::DB_BACKEND_GLASS); return true; } catch(Xapian::DatabaseLockError e) { syslog(LOG_WARNING,"%sCan't lock the DB : %s - %s",title,e.get_type(),e.get_msg().c_str()); } catch(Xapian::Error e) { syslog(LOG_WARNING,"%sCan't open the DB RW : %s - %s",title,e.get_type(),e.get_msg().c_str()); } return false; } void close() { toclose=true; if(t!=NULL) { t->join(); delete(t); } t=NULL; terminated=true; } ~XDocsWriter() { close(); } std::string getSummary() { std::string s(title); s.append(" queued_docs="+std::to_string(backend->docs.size())); s.append(" dict_size="+std::to_string(backend->dict_nb)); s.append(" terminated="+std::to_string(terminated)); return s; } bool launch(const char * from) { if(verbose>0) { std::string s(title); s.append("Launching thread from "); s.append(from); syslog(LOG_INFO,"%s",s.c_str()); } try { t = new std::thread(fts_backend_xapian_worker,this); } catch(std::exception const& e) { std::string s(title); s.append("Thread error "); s.append(e.what()); syslog(LOG_ERR,"%s",s.c_str()); t = NULL; return false; } started=true; return true; } long checkMemory() { // Memory check long m = fts_backend_xapian_get_free_memory(verbose); if(verbose>1) syslog(LOG_WARNING,"%sMemory : Free = %ld MB vs %ld limit | Pendings in cache = %ld / %ld | Dict size = %ld / %ld",title,(long)(m / 1024.0f),lowmemory,backend->pending,XAPIAN_WRITING_CACHE,backend->dict_nb,XAPIAN_DICT_MAX); // First clean dictionnary if((backend->dict_nb > XAPIAN_DICT_MAX) || ((m>0) && (m<(lowmemory*1024)))) { fts_backend_xapian_sqlite3_dict_flush(backend,verbose); m = fts_backend_xapian_get_free_memory(verbose); } if((backend->dbw!=NULL) && ((backend->pending > XAPIAN_WRITING_CACHE) || ((m>0) && (m<(lowmemory*1024))))) // too little memory or too many pendings { fts_backend_xapian_get_lock(backend, verbose, title); // Repeat test because the close may have happen in another thread m = fts_backend_xapian_get_free_memory(verbose); if((backend->dbw!=NULL) && ((backend->pending > XAPIAN_WRITING_CACHE) || ((m>0) && (m<(lowmemory*1024))))) { try { if(backend->pending > XAPIAN_WRITING_CACHE) { syslog(LOG_WARNING,"%sCommitting %ld docs due to cached docs exceeded (%ld vs %ld limit)",title,backend->pending,backend->pending,XAPIAN_WRITING_CACHE); } else { syslog(LOG_WARNING,"%sCommitting %ld docs due to low free memory (%ld MB vs %ld MB)",title,backend->pending,(long)(m/1024.0f),lowmemory); } backend->dbw->close(); delete(backend->dbw); if(verbose>0) syslog(LOG_INFO,"%sClosed Xapian DB %s",title,backend->xap_db); backend->dbw = NULL; backend->pending = 0; } catch(Xapian::Error e) { syslog(LOG_ERR,"%sCan't commit DB1 : %s - %s",title,e.get_type(),e.get_msg().c_str()); } catch(std::exception const& e) { syslog(LOG_ERR,"%sCan't commit DB2 : %s",title,e.what()); } } fts_backend_xapian_release_lock(backend, verbose, title); } return m; } void worker() { long start_time = fts_backend_xapian_current_time(); XDoc *doc = NULL; long totaldocs=0; long sl=0, dt=0; while((!toclose) || (doc!=NULL)) { if(doc==NULL) { if(verbose>0) syslog(LOG_INFO,"%sSearching doc",title); fts_backend_xapian_get_lock(backend, verbose, title); if((backend->docs.size()>0) && (backend->docs.back()->status==1)) { doc = backend->docs.back(); backend->docs.pop_back(); dt=fts_backend_xapian_current_time(); } fts_backend_xapian_release_lock(backend, verbose, title); } if(doc==NULL) { sl++; if((sl>50) && (verbose>0)) { syslog(LOG_INFO,"%sNoop",title); sl=0; } std::this_thread::sleep_for(XAPIAN_SLEEP); } else if(doc->status==1) { checkMemory(); if(verbose>0) syslog(LOG_INFO,"%sPopulating stems : %s",title,doc->getDocSummary().c_str()); if(doc->terms_create(verbose,title)) { doc->status=2; doc->status_n=0; if(verbose>0) syslog(LOG_INFO,"%sPopulating stems : %ld done in %ld msec",title,doc->nterms,fts_backend_xapian_current_time()-dt); dt=fts_backend_xapian_current_time(); } else { doc->status_n++; if(verbose>0) syslog(LOG_INFO,"%sPopulating stems : Error - %s",title,doc->getDocSummary().c_str()); if(doc->status_n > XAPIAN_MAX_ERRORS) { delete(doc); doc=NULL; } } } else if(doc->status==2) { checkMemory(); if(verbose>0) syslog(LOG_INFO,"%sCreating Xapian doc : %s",title,doc->getDocSummary().c_str()); if(doc->doc_create(verbose,title)) { doc->status=3; doc->status_n=0; if(verbose>0) syslog(LOG_INFO,"%sCreating Xapian doc : Done in %ld msec",title,fts_backend_xapian_current_time()-dt); dt=fts_backend_xapian_current_time(); } else { doc->status_n++; if(verbose>0) syslog(LOG_INFO,"%sCreate document : Error",title); if(doc->status_n > XAPIAN_MAX_ERRORS) { delete(doc); doc=NULL; } } } else { if(verbose>0) syslog(LOG_INFO,"%sPushing : %s",title,doc->getDocSummary().c_str()); if(doc->nterms > 0) { checkMemory(); fts_backend_xapian_get_lock(backend, verbose, title); if(checkDB()) { try { backend->dbw->replace_document(doc->uterm,*(doc->xdoc)); backend->pending++; backend->total_docs++; delete(doc); doc=NULL; if(verbose>0) syslog(LOG_INFO,"%sPushing done in %ld msec",title,fts_backend_xapian_current_time()-dt); totaldocs++; } catch(Xapian::Error e) { syslog(LOG_ERR,"%sCan't write doc1 %s : %s - %s",title,doc->getDocSummary().c_str(),e.get_type(),e.get_msg().c_str()); } catch(std::exception const & e) { syslog(LOG_ERR,"%sCan't write doc2 %s : %s",title,doc->getDocSummary().c_str(),e.what()); } } fts_backend_xapian_release_lock(backend, verbose, title); } else { delete(doc); doc=NULL; } } } terminated=true; if(verbose>0) syslog(LOG_INFO,"%sIndexed %ld docs within %ld msec",title,totaldocs,fts_backend_xapian_current_time() - start_time); } }; static void fts_backend_xapian_worker(void *p) { XDocsWriter *xw = (XDocsWriter *)p; xw->worker(); } static bool fts_backend_xapian_open_readonly(struct xapian_fts_backend *backend, Xapian::Database ** dbr) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_open_readonly"); if((backend->xap_db == NULL) || (strlen(backend->xap_db)<1)) { i_warning("FTS Xapian: Open DB Read Only : no DB name"); return false; } try { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Opening DB (RO) %s",backend->xap_db); *dbr = new Xapian::Database(backend->xap_db,Xapian::DB_CREATE_OR_OPEN | Xapian::DB_BACKEND_GLASS); } catch(Xapian::Error e) { i_error("FTS Xapian: Can not open RO index (%s) %s : %s - %s %s ",backend->boxname,backend->xap_db,e.get_type(),e.get_msg().c_str(),e.get_error_string()); return false; } return true; } static void fts_backend_xapian_oldbox(struct xapian_fts_backend *backend) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_oldbox"); if(backend->old_guid != NULL) { /* Performance calculator*/ long dt = fts_backend_xapian_current_time() - backend->start_time; double r=0; if(dt>0) { r=backend->total_docs*1000.0; r=r/dt; } /* End Performance calculator*/ if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Done indexing '%s' (%s) (%ld msgs in %ld msec, rate: %.1f)",backend->old_boxname, backend->xap_db,backend->total_docs,dt,r); i_free(backend->old_guid); backend->old_guid = NULL; i_free(backend->old_boxname); backend->old_boxname = NULL; } if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_oldbox - done"); } static void fts_backend_xapian_close_db(Xapian::WritableDatabase * dbw,const char * dbpath,const char * boxname, long verbose) { long t; if(verbose>0) { t = fts_backend_xapian_current_time(); syslog(LOG_INFO,"FTS Xapian : Closing DB (%s,%s)",boxname,dbpath); } try { dbw->close(); delete(dbw); } catch(Xapian::Error e) { syslog(LOG_ERR, "FTS Xapian: Can't close Xapian DB (%s) %s : %s - %s %s",boxname,dbpath,e.get_type(),e.get_msg().c_str(),e.get_error_string()); } catch(std::exception const& e) { syslog(LOG_ERR, "FTS Xapian : Closing db (%s) error %s",dbpath,e.what()); } if(verbose>0) { t = fts_backend_xapian_current_time()-t; syslog(LOG_INFO,"FTS Xapian : DB (%s,%s) closed in %ld ms",boxname,dbpath,t); } } static void fts_backend_xapian_close(struct xapian_fts_backend *backend, const char * reason) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian : Closing all DWs (%s)",reason); fts_backend_xapian_get_lock(backend,fts_xapian_settings.verbose,reason); if((backend->docs.size()>0) && (backend->docs.front()->status<1)) backend->docs.front()->status=1; fts_backend_xapian_release_lock(backend,fts_xapian_settings.verbose,reason); long n=0; while(backend->docs.size()>0) { n++; if((n>50) and (fts_xapian_settings.verbose>0)) { i_info("FTS Xapian: Waiting for all pending documents (%ld) to be processed (Sleep5) with %ld threads",backend->docs.size(),backend->threads.size()); n=0; } std::this_thread::sleep_for(XAPIAN_SLEEP); } for(auto & xwr : backend->threads) { xwr->toclose=true; } XDocsWriter * xw; n=0; while(backend->threads.size()>0) { xw = backend->threads.back(); if(!(xw->started)) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian : Closing thread because not started : %s",xw->getSummary().c_str()); delete(xw); backend->threads.pop_back(); } else if(xw->terminated) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian : Closing thread because terminated : %s",xw->getSummary().c_str()); delete(xw); backend->threads.pop_back(); } else { n++; if((n>50) && (fts_xapian_settings.verbose>0)) { for(auto & xwr : backend->threads) { if((xwr!=NULL)&&(!(xwr->terminated))) i_info("FTS Xapian : Waiting (Sleep4) for thread %s",xwr->getSummary().c_str()); } n=0; } std::this_thread::sleep_for(XAPIAN_SLEEP); } } if(fts_xapian_settings.verbose>0) i_info("FTS Xapian : All DWs (%s) closed",reason); fts_backend_xapian_sqlite3_dict_flush(backend,fts_xapian_settings.verbose); sqlite3_close(backend->ddb); backend->ddb = NULL; if(backend->dbw!=NULL) { fts_backend_xapian_close_db(backend->dbw,backend->xap_db,backend->boxname,fts_xapian_settings.verbose); backend->dbw=NULL; } } XResultSet * fts_backend_xapian_query(Xapian::Database * dbx, XQuerySet * query, long limit=0) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: fts_backend_xapian_query (%s)",query->get_string().c_str()); XResultSet * set= new XResultSet(); Xapian::Query * q = query->get_query(dbx); try { Xapian::Enquire enquire(*dbx); enquire.set_query(*q); enquire.set_docid_order(Xapian::Enquire::DESCENDING); long offset=0; long pagesize=100; if(limit>0) { pagesize=std::min(pagesize,limit); } Xapian::MSet m = enquire.get_mset(0, pagesize); while(m.size()>0) { Xapian::MSetIterator i = m.begin(); while (i != m.end()) { Xapian::Document doc = i.get_document(); set->add(doc.get_docid()); i++; } offset+=pagesize; m = enquire.get_mset(offset, pagesize); } } catch(Xapian::Error e) { i_error("FTS Xapian: xapian_query %s - %s %s",e.get_type(),e.get_msg().c_str(),e.get_error_string()); } delete(q); return set; } static int fts_backend_xapian_unset_box(struct xapian_fts_backend *backend) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Unset box '%s' (%s)",backend->boxname,backend->guid); fts_backend_xapian_close(backend,"unset box"); fts_backend_xapian_oldbox(backend); if(backend->xap_db != NULL) { i_free(backend->xap_db); backend->xap_db = NULL; i_free(backend->guid); backend->guid = NULL; i_free(backend->boxname); backend->boxname = NULL; i_free(backend->exp_db); backend->exp_db = NULL; i_free(backend->dict_db); backend->dict_db = NULL; i_free(backend->version_file); backend->version_file = NULL; } return 0; } static int fts_backend_xapian_set_path(struct xapian_fts_backend *backend) { struct mail_namespace * ns = backend->backend.ns; if(ns->alias_for != NULL) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Switching namespace"); ns = ns->alias_for; } const char * path = mailbox_list_get_root_forced(ns->list, MAILBOX_LIST_PATH_TYPE_INDEX); if(backend->path != NULL) i_free(backend->path); backend->path = i_strconcat(path, "/" XAPIAN_FILE_PREFIX, static_cast(NULL)); if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Index path = %s",backend->path); struct stat sb; if(!( (stat(backend->path, &sb)==0) && S_ISDIR(sb.st_mode))) { if (mailbox_list_mkdir_root(backend->backend.ns->list, backend->path, MAILBOX_LIST_PATH_TYPE_INDEX) < 0) { i_error("FTS Xapian: can not create '%s'",backend->path); i_error("FTS Xapian: You need to set mail_uid and mail_gid in your dovecot.conf according to the user of mail_location (%s)", path); return -1; } } return 0; } static int fts_backend_xapian_set_box(struct xapian_fts_backend *backend, struct mailbox *box) { if (box == NULL) { if(backend->guid != NULL) fts_backend_xapian_unset_box(backend); if(fts_xapian_settings.verbose>0) i_warning("FTS Xapian: Box is empty"); return 0; } const char * mb; fts_mailbox_get_guid(box, &mb ); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Set box '%s' (%s)",box->name,mb); if((mb == NULL) || (strlen(mb)<3)) { i_error("FTS Xapian: Invalid box"); return -1; } if((backend->guid != NULL) && (strcmp(mb,backend->guid)==0)) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Box is unchanged"); return 0; } if(backend->guid != NULL) fts_backend_xapian_unset_box(backend); if(fts_backend_xapian_set_path(backend)<0) return -1; long current_time = fts_backend_xapian_current_time(); backend->start_time = current_time; backend->lastuid = -1; backend->guid = i_strdup(mb); backend->boxname = i_strdup(box->name); backend->xap_db = i_strdup_printf("%s/db_%s",backend->path,mb); backend->exp_db = i_strdup_printf("%s%s",backend->xap_db,suffixExp); backend->dict_db = i_strdup_printf("%s%s",backend->xap_db,suffixDict); backend->version_file = i_strdup_printf("%s_v%s",backend->xap_db,XAPIAN_PLUGIN_VERSION); struct stat sb; // Existence of current version if(!( (stat(backend->version_file, &sb)==0) && S_ISREG(sb.st_mode))) { i_info("FTS Xapian: New version of the plugin : %s for %s",XAPIAN_PLUGIN_VERSION,backend->boxname); // Deleting existing indexes std::filesystem::remove_all(backend->xap_db); for(auto& f : std::filesystem::directory_iterator(backend->path)) { if((f.is_regular_file()) && (f.path().string().find(backend->xap_db) == 0)) { if(fts_xapian_settings.verbose>0) i_warning("FTS Xapian: Deleting %s",f.path().c_str()); std::filesystem::remove(f.path()); } } // Write new version file FILE * f = fopen(backend->version_file,"w+"); fprintf(f,"%s",XAPIAN_PLUGIN_VERSION); fclose(f); } // Verify existence of Dict db if(!( (stat(backend->dict_db, &sb)==0) && S_ISREG(sb.st_mode))) { i_warning("FTS Xapian: '%s' (%s) dictionnary does not exist. Creating it",backend->boxname,backend->dict_db); if(fts_backend_xapian_sqlite3_dict_open(backend)) sqlite3_close(backend->ddb); backend->ddb = NULL; std::filesystem::remove_all(backend->xap_db); } // Verify existence of Xapian db { char * t = i_strdup_printf("%s/termlist.glass",backend->xap_db); if(!( (stat(t, &sb)==0) && S_ISREG(sb.st_mode))) { std::filesystem::remove(backend->exp_db); i_info("FTS Xapian: '%s' (%s) indexes do not exist. Initializing DB",backend->boxname,backend->xap_db); try { Xapian::WritableDatabase * db = new Xapian::WritableDatabase(backend->xap_db,Xapian::DB_CREATE_OR_OVERWRITE | Xapian::DB_BACKEND_GLASS); db->close(); delete(db); } catch(Xapian::Error e) { i_error("FTS Xapian: Can't create Xapian DB (%s) %s : %s - %s %s",backend->boxname,backend->xap_db,e.get_type(),e.get_msg().c_str(),e.get_error_string()); } } i_free(t); } // Verify existence of Exp db if(!( (stat(backend->exp_db, &sb)==0) && S_ISREG(sb.st_mode))) { i_warning("FTS Xapian: '%s' (%s) expunge does not exist. Creating it",backend->boxname,backend->exp_db); sqlite3 * db = NULL; if(sqlite3_open_v2(backend->exp_db,&db,SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,NULL) != SQLITE_OK ) { i_error("FTS Xapian: Can not open %s : %s",backend->exp_db,sqlite3_errmsg(db)); } else { char *zErrMsg = 0; if(sqlite3_exec(db,createExpTable,NULL,0,&zErrMsg) != SQLITE_OK ) { i_error("FTS Xapian: Can not execute (%s) : %s",createExpTable,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); } sqlite3_close(db); } } backend->threads.clear(); backend->total_docs =0; return 0; } static void fts_backend_xapian_build_qs(XQuerySet * qs, struct mail_search_arg *a, const char * dict=NULL) { long hdr; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_build_qs"); while(a != NULL) { switch (a->type) { case SEARCH_TEXT: hdr = -1; break; case SEARCH_BODY: hdr = 8; break; case SEARCH_HEADER: case SEARCH_HEADER_ADDRESS: case SEARCH_HEADER_COMPRESS_LWSP: if((a->hdr_field_name == NULL)||(strlen(a->hdr_field_name)<1)) { hdr = -1; break; } hdr=fts_backend_xapian_clean_header(a->hdr_field_name); if(hdr >= 0) break; default: a = a->next; continue; } if((a->value.str == NULL) || (strlen(a->value.str)<1)) { XQuerySet * q2; if(a->match_not) { q2 = new XQuerySet(Xapian::Query::OP_AND_NOT,qs->limit); } else { q2 = new XQuerySet(Xapian::Query::OP_OR,qs->limit); } fts_backend_xapian_build_qs(q2,a->value.subargs,dict); if(q2->count()>0) { qs->add(q2); } else { delete(q2); } } else if(dict != NULL) { // Find key words icu::StringPiece sp(a->value.str); icu::UnicodeString t = icu::UnicodeString::fromUTF8(sp); fts_backend_xapian_clean(&t); long j, i = t.lastIndexOf(CHAR_SPACE); unsigned long l; icu::UnicodeString *k; std::vector keys; keys.clear(); while(i>0) { j = t.length(); k = new icu::UnicodeString(t,i+1,j-i-1); l = k->length(); if(l >= fts_xapian_settings.partial) { keys.push_back(k); } else delete(k); t.truncate(i); fts_backend_xapian_trim(&t); i = t.lastIndexOf(CHAR_SPACE); } l = t.length(); if(l>=fts_xapian_settings.partial) { keys.push_back(new icu::UnicodeString (t)); } // For each key, search dictionnary sqlite3 * db = NULL; char * zErrMsg =0; if(sqlite3_open_v2(dict,&db,SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READONLY,NULL) != SQLITE_OK ) { syslog(LOG_ERR,"FTS Xapian: Can not open %s : %s",dict,sqlite3_errmsg(db)); return; } // Generate query XQuerySet * q1, *q2; if(a->match_not) { q1 = new XQuerySet(Xapian::Query::OP_AND_NOT,qs->limit); } else { q1 = new XQuerySet(Xapian::Query::OP_AND,qs->limit); } for(auto & ki : keys) { std::vector st; st.clear(); std::string sql=searchDict1; ki->toUTF8String(sql); if(hdr<0) { sql+="%'"; } else { sql+="%' and header=" + std::to_string(hdr); } sql +=searchDict2; zErrMsg =0; if(sqlite3_exec(db,sql.c_str(),fts_backend_xapian_sqlite3_vector_icu,&st,&zErrMsg) != SQLITE_OK ) { syslog(LOG_ERR,"FTS Xapian: Can not search keyword (%s) : %s",sql.c_str(),zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); } q2 = new XQuerySet(Xapian::Query::OP_OR,qs->limit); for(auto &term : st) { q2->add(hdr,term,false); delete(term); } if(q2->count()>0) { q1->add(q2); } else { delete(q2); } delete(ki); } qs->add(q1); sqlite3_close(db); } else { icu::StringPiece sp(a->value.str); icu::UnicodeString t = icu::UnicodeString::fromUTF8(sp); fts_backend_xapian_clean(&t); qs->add(hdr,&t,a->match_not); } a->match_always=true; a = a->next; } } fts-xapian-1.9.1/src/fts-backend-xapian.cpp000066400000000000000000000522541475462537600205610ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ #include #include #include #include #include #include #include #include extern "C" { #include "fts-xapian-plugin.h" } #include "fts-backend-xapian.h" #include #include #include #include #include #include #if defined(__FreeBSD__) || defined(__NetBSD__) #include #endif #include #include #include #include class XDoc; class XDocsWriter; struct xapian_fts_backend { struct fts_backend backend; char * path; char * guid; char * boxname; char * xap_db; char * exp_db; char * version_file; char * dict_db; long dict_nb; sqlite3 * ddb; Xapian::WritableDatabase * dbw; long pending; char * old_guid; char * old_boxname; std::vector docs; std::vector threads; std::timed_mutex mutex; std::unique_lock * mutex_t; unsigned int max_threads; #ifdef FTS_DOVECOT24 struct event *event; #endif long lastuid; long total_docs; long start_time; }; struct xapian_fts_backend_update_context { struct fts_backend_update_context ctx; char * tbi_field=NULL; bool isattachment=false; bool tbi_isfield; uint32_t tbi_uid=0; }; static struct fts_xapian_settings fts_xapian_settings; struct event_category event_category_fts_xapian = { .parent = &event_category_fts, .name = XAPIAN_LABEL }; #include "fts-backend-xapian-functions.cpp" static struct fts_backend *fts_backend_xapian_alloc(void) { struct xapian_fts_backend *backend; backend = i_new(struct xapian_fts_backend, 1); backend->backend = fts_backend_xapian; return &backend->backend; } static int fts_backend_xapian_init(struct fts_backend *_backend, const char **error_r) { (void)error_r; struct xapian_fts_backend *backend = (struct xapian_fts_backend *)_backend; backend->xap_db = NULL; backend->exp_db = NULL; backend->dict_db = NULL; backend->docs.clear(); backend->threads.clear(); backend->total_docs =0; backend->lastuid = -1; backend->dbw = NULL; backend->ddb = NULL; backend->guid = NULL; backend->path = NULL; backend->old_guid = NULL; backend->old_boxname = NULL; struct fts_xapian_user *fuser = FTS_XAPIAN_USER_CONTEXT(_backend->ns->user); #ifdef FTS_DOVECOT24 backend->event = event_create(_backend->event); event_add_category(backend->event, &event_category_fts_xapian); if (fts_xapian_mail_user_get(_backend->ns->user, backend->event, &fuser, error_r) < 0) { event_unref(&backend->event); return -1; } fts_xapian_settings.verbose = fuser->set->verbose; fts_xapian_settings.maxthreads = fuser->set->maxthreads; fts_xapian_settings.partial = fuser->set->partial; fts_xapian_settings.lowmemory = fuser->set->lowmemory; #else fts_xapian_settings = fuser->set; #endif if(fts_xapian_settings.maxthreads>0) { backend->max_threads=fts_xapian_settings.maxthreads; } else { backend->max_threads = std::thread::hardware_concurrency()-1; } if(backend->max_threads<2) backend->max_threads = 2; if(fts_backend_xapian_set_path(backend)<0) return -1; openlog("xapian-docswriter",0,LOG_MAIL); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Starting version %s with partial=%d verbose=%d max_threads=%u lowmemory=%d MB", XAPIAN_PLUGIN_VERSION, fts_xapian_settings.partial,fts_xapian_settings.verbose,backend->max_threads,fts_xapian_settings.lowmemory); return 0; } static void fts_backend_xapian_deinit(struct fts_backend *_backend) { struct xapian_fts_backend *backend = (struct xapian_fts_backend *)_backend; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Deinit %s)",backend->path); if(backend->guid != NULL) fts_backend_xapian_unset_box(backend); if(backend->old_guid != NULL) i_free(backend->old_guid); backend->old_guid = NULL; if(backend->old_boxname != NULL) i_free(backend->old_boxname); backend->old_boxname = NULL; if(backend->path != NULL) i_free(backend->path); backend->path = NULL; #ifdef FTS_DOVECOT24 event_unref(&backend->event); #endif i_free(backend); closelog(); } static int fts_backend_xapian_get_last_uid(struct fts_backend *_backend, struct mailbox *box, uint32_t *last_uid_r) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_get_last_uid"); struct xapian_fts_backend *backend = (struct xapian_fts_backend *)_backend; *last_uid_r = 0; if(fts_backend_xapian_set_box(backend, box) < 0) { i_error("FTS Xapian: get_last_uid: Can not select mailbox '%s'",box->name); return -1; } Xapian::Database * dbr; if(!fts_backend_xapian_open_readonly(backend, &dbr)) { i_error("FTS Xapian: GetLastUID: Can not open db RO (%s)",backend->xap_db); return 0; } try { *last_uid_r = Xapian::sortable_unserialise(dbr->get_value_upper_bound(1)); } catch(Xapian::Error e) { i_warning("FTS Xapian: fts_backend_xapian_get_last_uid for '%s' (%s)",backend->boxname,backend->guid); i_warning("FTS Xapian: %s",e.get_msg().c_str()); } dbr->close(); delete(dbr); if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Get last UID of %s (%s) = %d",backend->boxname,backend->guid,*last_uid_r); return 0; } static struct fts_backend_update_context * fts_backend_xapian_update_init(struct fts_backend *_backend) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_update_context"); struct xapian_fts_backend_update_context *ctx; ctx = i_new(struct xapian_fts_backend_update_context, 1); ctx->ctx.backend = _backend; return &ctx->ctx; } static int fts_backend_xapian_update_deinit(struct fts_backend_update_context *_ctx) { struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; struct xapian_fts_backend *backend = (struct xapian_fts_backend *)ctx->ctx.backend; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_update_deinit (%s)",backend->path); i_free(ctx); return 0; } static void fts_backend_xapian_update_set_mailbox(struct fts_backend_update_context *_ctx, struct mailbox *box) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_update_set_mailbox"); struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; struct xapian_fts_backend *backend = (struct xapian_fts_backend *)ctx->ctx.backend; fts_backend_xapian_set_box(backend, box); } static void fts_backend_xapian_update_expunge(struct fts_backend_update_context *_ctx, uint32_t uid) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_update_expunge"); struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; struct xapian_fts_backend *backend = (struct xapian_fts_backend *)ctx->ctx.backend; sqlite3 * expdb = NULL; if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Opening expunge DB(%s)",backend->exp_db); if(sqlite3_open_v2(backend->exp_db,&expdb,SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE,NULL)) { i_error("FTS Xapian: Expunging UID=%d : Can not open %s",uid,backend->exp_db); return; } char *zErrMsg = 0; char * u = i_strdup_printf(replaceExpUID,uid); if(sqlite3_exec(expdb,u,NULL,0,&zErrMsg) != SQLITE_OK) { i_error("FTS Xapian: Expunging (3) UID=%d : Can not add UID : %s",uid,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); } i_free(u); sqlite3_close(expdb); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian : Expunge done"); } static bool fts_backend_xapian_update_set_build_key(struct fts_backend_update_context *_ctx, const struct fts_backend_build_key *key) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_update_set_build_key"); struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; struct xapian_fts_backend *backend = (struct xapian_fts_backend *)ctx->ctx.backend; ctx->tbi_isfield=false; ctx->tbi_uid=0; ctx->tbi_field=NULL; if(backend->guid == NULL) { if(fts_xapian_settings.verbose>0) i_warning("FTS Xapian: Build key %s with no mailbox",key->hdr_name); return FALSE; } if((backend->old_guid == NULL) || (strcmp(backend->old_guid,backend->guid)!=0)) { fts_backend_xapian_oldbox(backend); backend->old_guid = i_strdup(backend->guid); backend->old_boxname = i_strdup(backend->boxname); } const char * type = key->body_content_type; const char * disposition = key->body_content_disposition; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: New part (Header=%s,Type=%s,Disposition=%s)",key->hdr_name,type,disposition); // Verify content-type if(key->type == FTS_BACKEND_BUILD_KEY_BODY_PART_BINARY) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Skipping binary part of type '%s'",type); return FALSE; } if((type != NULL) && (strncmp(type,"text",4)!=0) && ((disposition==NULL) || ((strstr(disposition,"filename=")==NULL) && (strstr(disposition,"attachment")==NULL)))) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Non-binary & non-text part of type '%s'",type); return FALSE; } if(!fts_backend_xapian_sqlite3_dict_open(backend)) return FALSE; // Verify content-disposition ctx->isattachment=false; if((disposition != NULL) && ((strstr(disposition,"filename=")!=NULL) || (strstr(disposition,"attachment")!=NULL))) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Found part as attachment of type '%s' and disposition '%s'",type,disposition); ctx->isattachment=true; } long field = HDR_BODY; if(key->hdr_name!=NULL) { field = fts_backend_xapian_clean_header(key->hdr_name); if(field<0) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: Unknown header '%s' of part",key->hdr_name); return FALSE; } if(field<1) field=HDR_BODY; } switch (key->type) { case FTS_BACKEND_BUILD_KEY_HDR: case FTS_BACKEND_BUILD_KEY_MIME_HDR: ctx->tbi_isfield=true; ctx->tbi_uid=key->uid; break; case FTS_BACKEND_BUILD_KEY_BODY_PART: ctx->tbi_isfield=false; ctx->tbi_uid=key->uid; break; case FTS_BACKEND_BUILD_KEY_BODY_PART_BINARY: default: return FALSE; } ctx->tbi_field = i_strdup_printf("%ld",field); if((ctx->tbi_uid>0) && (ctx->tbi_uid != backend->lastuid)) { std::string s("FTS Xapian: New doc incoming (#"); s.append(std::to_string(ctx->tbi_uid)+")"); if(fts_xapian_settings.verbose>0) i_info("%s",s.c_str()); if(backend->threads.size() < backend->max_threads ) { XDocsWriter * x = new XDocsWriter(backend,backend->threads.size()+1); x->launch(s.c_str()); backend->threads.push_back(x); } long n = backend->threads.size(); while(n>0) { n--; if(!(backend->threads.at(n)->started)) { backend->threads[n]->launch("Relaunch post error"); } } fts_backend_xapian_get_lock(backend, fts_xapian_settings.verbose, s.c_str()); { if(backend->lastuid>0) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Previous doc ready to index (#%ld)",backend->lastuid); backend->docs.front()->status=1; } backend->lastuid = ctx->tbi_uid; backend->docs.insert(backend->docs.begin(),new XDoc(backend)); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Start indexing #%ld (%s) : Queue size = %ld",backend->lastuid, backend->boxname,backend->docs.size()); } fts_backend_xapian_release_lock(backend, fts_xapian_settings.verbose, s.c_str()); if(backend->docs.size() > (XAPIAN_WRITING_CACHE * 2) ) { n=0; while (backend->docs.size() > XAPIAN_WRITING_CACHE ) { n++; if(n>50) { if (fts_xapian_settings.verbose>0) i_info("FTS Xapian: Waiting for queue to be absorbed (pending=%ld)",backend->docs.size()); n=0; } std::this_thread::sleep_for(XAPIAN_SLEEP); } } } return TRUE; } static void fts_backend_xapian_update_unset_build_key(struct fts_backend_update_context *_ctx) { struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_update_unset_build_key"); if(ctx->tbi_field!=NULL) { i_free(ctx->tbi_field); } ctx->tbi_uid=0; ctx->tbi_field=NULL; } static int fts_backend_xapian_refresh(struct fts_backend * _backend) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_refresh"); return 0; } static int fts_backend_xapian_update_build_more(struct fts_backend_update_context *_ctx, const unsigned char *data, size_t size) { struct xapian_fts_backend_update_context *ctx = (struct xapian_fts_backend_update_context *)_ctx; struct xapian_fts_backend *backend = (struct xapian_fts_backend *) ctx->ctx.backend; if(ctx->tbi_uid<1) return 0; if(strlen(ctx->tbi_field)<1) return 0; if(data == NULL) return 0; const char * d = (const char *) data; if(strlen(d)<(unsigned long)fts_xapian_settings.partial) return 0; long h = atol(ctx->tbi_field); backend->docs.front()->raw_load(h,d,size,fts_xapian_settings.verbose,"fts_backend_xapian_index"); return 0; } static int fts_backend_xapian_optimize(struct fts_backend *_backend) { struct xapian_fts_backend *backend = (struct xapian_fts_backend *) _backend; if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_optimize '%s'",backend->path); struct stat sb; if(!( (stat(backend->path, &sb)==0) && S_ISDIR(sb.st_mode))) { i_error("FTS Xapian: Optimize(0) Index folder inexistent"); return -1; } Xapian::WritableDatabase * db = NULL; sqlite3 * expdb = NULL; DIR* dirp = opendir(backend->path); struct dirent * dp; std::string s; uint32_t uid; int ret=0; std::vector uids; uids.clear(); char *zErrMsg = 0; XResultSet * result = NULL; Xapian::docid docid =0; while ((dp = readdir(dirp)) != NULL) { s = dp->d_name; if((dp->d_type == DT_REG) && s.starts_with("db_") && s.ends_with(suffixExp) ) { uids.clear(); i_info("FTS Xapian: Optimize (1) : Checking expunges from %s",dp->d_name); if(sqlite3_open_v2(dp->d_name,&expdb,SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE,NULL) == SQLITE_OK) { if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Optimize (2) : Executing %s",selectExpUIDs); if(sqlite3_exec(expdb,selectExpUIDs,fts_backend_xapian_sqlite3_vector_int,&uids,&zErrMsg) != SQLITE_OK) { i_error("FTS Xapian: Optimize (3) : Can not select IDs (%s) : %s",selectExpUIDs,zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); ret =-1; } s = s.substr(0,s.length()-strlen(suffixExp)); if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Optimize (4) : Opening Xapian DB (%s)",s.c_str()); try { bool ok=false; while(!ok) { try { db = new Xapian::WritableDatabase(s.c_str(),Xapian::DB_CREATE_OR_OPEN | Xapian::DB_BACKEND_GLASS); ok=true; } catch(Xapian::Error e) { i_warning("FTS Xapian: Retrying opening DB : %s - %s %s",e.get_type(),e.get_msg().c_str(),e.get_error_string()); std::this_thread::sleep_for(XAPIAN_SLEEP); } } long c=0; for(uint32_t n=0;n0) i_info("FTS Xapian: Optimize (5) Removing DOC UID=%d",uid); XQuerySet * xq = new XQuerySet(); xq->add(uid); result=fts_backend_xapian_query(db,xq,1); docid=0; if((result!=NULL) && (result->size>0)) { try { docid = result->data[0]; if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Optimize (5) Removing DOC UID=%d DOCID=%d",uid,docid); db->delete_document(docid); c++; if(c>XAPIAN_WRITING_CACHE) { i_info("FTS Xapian: Flushing changes on disk"); db->commit(); c=0; } } catch(Xapian::Error e) { i_error("FTS Xapian: Optimize (6) %s",e.get_msg().c_str()); } } else if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Optimize UID=%d (DOCID=%d) inexistent",uid,docid); if(result!=NULL) { delete(result); result=NULL; } delete(xq); char * u = i_strdup_printf(deleteExpUID,uid); if (sqlite3_exec(expdb,u,NULL,0,&zErrMsg) != SQLITE_OK ) { i_error("FTS Xapian : Optimize Sqlite error: %s",zErrMsg); if(zErrMsg!=NULL) sqlite3_free(zErrMsg); } i_free(u); } if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Optimize - Closing DB %s",s.c_str()); fts_backend_xapian_close_db(db,s.c_str(),"fts_optimize",fts_xapian_settings.verbose); } catch(Xapian::Error e) { i_error("FTS Xapian: Optimize (7) %s",e.get_msg().c_str()); } sqlite3_close(expdb); } } } closedir(dirp); return ret; } static int fts_backend_xapian_rescan(struct fts_backend *_backend) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_rescan"); struct xapian_fts_backend *backend = (struct xapian_fts_backend *) _backend; struct stat sb; if(!( (stat(backend->path, &sb)==0) && S_ISDIR(sb.st_mode))) { i_error("FTS Xapian: Index folder (%s) inexistent",backend->path); return -1; } std::error_code errorCode; if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: Rescan by deleting %s",backend->path); std::filesystem::remove_all(backend->path,errorCode); return 0; } static int fts_backend_xapian_lookup(struct fts_backend *_backend, struct mailbox *box, struct mail_search_arg *args, enum fts_lookup_flags flags, struct fts_result *result) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_lookup"); struct xapian_fts_backend *backend = (struct xapian_fts_backend *) _backend; if(fts_backend_xapian_set_box(backend, box)<0) return -1; long current_time = fts_backend_xapian_current_time(); Xapian::Database * dbr; i_array_init(&(result->maybe_uids),0); i_array_init(&(result->scores),0); if(!fts_backend_xapian_open_readonly(backend, &dbr)) { i_array_init(&(result->definite_uids),0); return 0; } XQuerySet * qs; if((flags & FTS_LOOKUP_FLAG_AND_ARGS) != 0) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: FLAG=AND"); qs = new XQuerySet(Xapian::Query::OP_AND,fts_xapian_settings.partial); } else { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: FLAG=OR"); qs = new XQuerySet(Xapian::Query::OP_OR,fts_xapian_settings.partial); } fts_backend_xapian_build_qs(qs,args,backend->dict_db); XResultSet * r=fts_backend_xapian_query(dbr,qs); long n=r->size; if(fts_xapian_settings.verbose>0) { i_info("FTS Xapian: Query '%s' -> %ld results",qs->get_string().c_str(),n); } i_array_init(&(result->definite_uids),r->size); uint32_t uid; for(long i=0;iget_document(r->data[i]).get_value(1)); seq_range_array_add(&result->definite_uids, uid); } catch(Xapian::Error e) { i_error("FTS Xapian: %s",e.get_msg().c_str()); } } delete(r); delete(qs); dbr->close(); delete(dbr); /* Performance calc */ if(fts_xapian_settings.verbose>0) i_info("FTS Xapian: %ld results in %ld ms",n,fts_backend_xapian_current_time() - current_time); return 0; } static int fts_backend_xapian_lookup_multi(struct fts_backend *_backend, struct mailbox *const boxes[], struct mail_search_arg *args, enum fts_lookup_flags flags, struct fts_multi_result *result) { if(fts_xapian_settings.verbose>1) i_info("FTS Xapian: fts_backend_xapian_lookup_multi"); ARRAY(struct fts_result) box_results; struct fts_result *box_result; int i; p_array_init(&box_results, result->pool, 0); for (i = 0; boxes[i] != NULL; i++) { box_result = array_append_space(&box_results); box_result->box = boxes[i]; if(fts_backend_xapian_lookup(_backend, boxes[i], args, flags, box_result)<0) { void* p=&box_results; p_free(result->pool, p); return -1; } } array_append_zero(&box_results); result->box_results = array_idx_modifiable(&box_results, 0); return 0; } struct fts_backend fts_backend_xapian = { .name = "xapian", .flags = FTS_BACKEND_FLAG_BUILD_FULL_WORDS, .v = { .alloc = fts_backend_xapian_alloc, .init = fts_backend_xapian_init, .deinit = fts_backend_xapian_deinit, .get_last_uid = fts_backend_xapian_get_last_uid, .update_init = fts_backend_xapian_update_init, .update_deinit = fts_backend_xapian_update_deinit, .update_set_mailbox = fts_backend_xapian_update_set_mailbox, .update_expunge = fts_backend_xapian_update_expunge, .update_set_build_key = fts_backend_xapian_update_set_build_key, .update_unset_build_key = fts_backend_xapian_update_unset_build_key, .update_build_more = fts_backend_xapian_update_build_more, .refresh = fts_backend_xapian_refresh, .rescan = fts_backend_xapian_rescan, .optimize = fts_backend_xapian_optimize, .can_lookup = fts_backend_default_can_lookup, .lookup = fts_backend_xapian_lookup, .lookup_multi = fts_backend_xapian_lookup_multi, } }; fts-xapian-1.9.1/src/fts-backend-xapian.h000066400000000000000000000053531475462537600202240ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ #ifndef FTS_XAPIAN_BACKEND_H #define FTS_XAPIAN_BACKEND_H #define XAPIAN_SLEEP std::chrono::milliseconds(200) // Ressources limits #define XAPIAN_TERM_SIZELIMIT 245L // Hard limit of Xapian library #define XAPIAN_MAXTERMS_PERDOC 50000L // Nb of keywords max per email #define XAPIAN_WRITING_CACHE 5000L // Max nb of emails processed in cache #define XAPIAN_DICT_MAX 60000L // Max nb of terms in the dict #define XAPIAN_MAX_ERRORS 1024L #define XAPIAN_MAX_SEC_WAIT 15L #define HDRS_NB 11 static const char * hdrs_emails[HDRS_NB] = { "uid", "subject", "from", "to", "cc", "bcc", "messageid", "listid", "body", "contenttype", "" }; static const char * hdrs_xapian[HDRS_NB] = { "Q", "S", "A", "XTO", "XCC", "XBCC", "XMID", "XLIST", "XBDY", "XCT", "XBDY" }; static const char * hdrs_query[HDRS_NB] = { "a", "b", "c", "d", "d", "e", "f", "g", "h", "i", "h" }; #define HDR_BODY 8L static const char * createExpTable = "CREATE TABLE IF NOT EXISTS expunges(ID INTEGER PRIMARY KEY NOT NULL);"; static const char * selectExpUIDs = "select ID from expunges;"; static const char * replaceExpUID = "replace into expunges values (%d);"; static const char * deleteExpUID = "delete from expunges where ID=%d;"; static const char * suffixExp = "_exp.db"; static const char * createDictTable = "CREATE TABLE IF NOT EXISTS dict (keyword TEXT COLLATE NOCASE, header INTEGER, len INTEGER, UNIQUE(keyword,header));"; static const char * createDictIndexes = "CREATE INDEX IF NOT EXISTS dict_len ON dict (len); CREATE INDEX IF NOT EXISTS dict_h ON dict(header); CREATE INDEX IF NOT EXISTS dict_t ON dict(keyword);"; static const char * createTmpTable = "ATTACH DATABASE ':memory:' AS work; CREATE TABLE work.dict (keyword TEXT COLLATE NOCASE, header INTEGER, len INTEGER, UNIQUE(keyword,header) ); CREATE INDEX IF NOT EXISTS work.dict_h ON dict(header)"; static const char * replaceTmpWord ="INSERT OR IGNORE INTO work.dict VALUES('"; static const char * flushTmpWords = "BEGIN TRANSACTION; INSERT OR IGNORE INTO main.dict SELECT keyword, header, len FROM work.dict; DELETE FROM work.dict; COMMIT;"; static const char * searchDict1 = "SELECT keyword FROM dict WHERE keyword like '%"; static const char * searchDict2 = " ORDER BY len LIMIT 100"; static const char * suffixDict = "_dict.db"; #define CHAR_KEY "_" #define CHAR_SPACE " " #define CHARS_PB 21 static const char * chars_pb[] = { "<", ">", ".", "-", "@", "&", "%", "*", "|", "`", "#", "^", "\\", "'", "/", "~", "[", "]", "{", "}", "-" }; #define CHARS_SEP 16 static const char * chars_sep[] = { "\"", "\r", "\n", "\t", ",", ":", ";", "(", ")", "?", "!", "¿", "¡", "\u00A0", "‘", "“" }; #endif fts-xapian-1.9.1/src/fts-xapian-plugin.c000066400000000000000000000120771475462537600201270ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ #include "fts-xapian-plugin.h" const char *fts_xapian_plugin_version = DOVECOT_ABI_VERSION; struct fts_xapian_user_module fts_xapian_user_module = MODULE_CONTEXT_INIT(&mail_user_module_register); static void fts_xapian_mail_user_deinit(struct mail_user *user) { #if ((DOVECOT_VERSION_MINOR > 2) || (DOVECOT_VERSION_MAJOR > 2) || (FTS_DOVECOT24 > 0)) struct fts_xapian_user *fuser = FTS_XAPIAN_USER_CONTEXT_REQUIRE(user); #else struct fts_xapian_user *fuser = FTS_XAPIAN_USER_CONTEXT(user); #endif #ifdef FTS_DOVECOT24 settings_free(fuser->set); #else fts_mail_user_deinit(user); #endif fuser->module_ctx.super.deinit(user); } #ifdef FTS_DOVECOT24 int fts_xapian_mail_user_get(struct mail_user *user, struct event *event, struct fts_xapian_user **fuser_r, const char **error_r) { struct fts_xapian_user *fuser = FTS_XAPIAN_USER_CONTEXT_REQUIRE(user); struct fts_xapian_settings *set; if (settings_get(event, &fts_xapian_setting_parser_info, 0, &set, error_r) < 0) { return -1; } /* Reference the user even when fuser is already initialized */ if (fts_mail_user_init(user, event, FALSE, error_r) < 0) { settings_free(set); return -1; } if (fuser->set == NULL) fuser->set = set; else settings_free(set); *fuser_r = fuser; return 0; } static void fts_xapian_mail_user_created(struct mail_user *user) { struct fts_xapian_user *fuser; struct mail_user_vfuncs *v = user->vlast; fuser = p_new(user->pool, struct fts_xapian_user, 1); fuser->module_ctx.super = *v; user->vlast = &fuser->module_ctx.super; v->deinit = fts_xapian_mail_user_deinit; MODULE_CONTEXT_SET(user, fts_xapian_user_module, fuser); } #else static void fts_xapian_mail_user_created(struct mail_user *user) { const char *error; struct mail_user_vfuncs *v = user->vlast; struct fts_xapian_user *fuser; fuser = p_new(user->pool, struct fts_xapian_user, 1); fuser->set.verbose = 0; fuser->set.lowmemory = XAPIAN_MIN_RAM; fuser->set.partial = XAPIAN_DEFAULT_PARTIAL; fuser->set.maxthreads = 0; const char * env = mail_user_plugin_getenv(user, XAPIAN_LABEL); if (env == NULL) { i_warning("FTS Xapian: missing configuration - Using default values"); } else { long len; const char *const *tmp; for (tmp = t_strsplit_spaces(env, " "); *tmp != NULL; tmp++) { if (strncmp(*tmp, "partial=",8)==0) { len=atol(*tmp + 8); if(len<3) { i_error("FTS Xapian: 'partial' parameter is incorrect (%ld). Try 'partial=%ld'",len,XAPIAN_DEFAULT_PARTIAL); len=XAPIAN_DEFAULT_PARTIAL; } fuser->set.partial = len; } else if (strncmp(*tmp,"verbose=",8)==0) { len=atol(*tmp + 8); if(len>0) { fuser->set.verbose = len; } } else if (strncmp(*tmp,"lowmemory=",10)==0) { len=atol(*tmp + 10); if(len>0) { fuser->set.lowmemory = len; } } else if (strncmp(*tmp,"maxthreads=",11)==0) { len=atol(*tmp + 11); if(len>0) { fuser->set.maxthreads = len; } } else if (strncmp(*tmp,"attachments=",12)==0) { // Legacy } else if (strncmp(*tmp,"full=",5)==0) { // Legacy } else if (strncmp(*tmp,"detach=",7)==0) { // Legacy } else { i_error("FTS Xapian: Invalid setting: %s", *tmp); } } } #ifdef FTS_MAIL_USER_INIT_THREE_ARGS if (fts_mail_user_init(user, FALSE, &error) < 0) #else if (fts_mail_user_init(user, &error) < 0) #endif { if ( fuser->set.verbose > 0 ) i_warning("FTS Xapian: %s", error); } fuser->module_ctx.super = *v; user->vlast = &fuser->module_ctx.super; v->deinit = fts_xapian_mail_user_deinit; MODULE_CONTEXT_SET(user, fts_xapian_user_module, fuser); } #endif static struct mail_storage_hooks fts_xapian_mail_storage_hooks = { .mail_user_created = fts_xapian_mail_user_created }; void fts_xapian_plugin_init(struct module *module ATTR_UNUSED) { fts_backend_register(&fts_backend_xapian); mail_storage_hooks_add(module, &fts_xapian_mail_storage_hooks); } void fts_xapian_plugin_deinit(void) { fts_backend_unregister(fts_backend_xapian.name); mail_storage_hooks_remove(&fts_xapian_mail_storage_hooks); } const char *fts_xapian_plugin_dependencies[] = { "fts", NULL }; fts-xapian-1.9.1/src/fts-xapian-plugin.h000066400000000000000000000042021475462537600201230ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ #ifndef FTS_XAPIAN_PLUGIN_H #define FTS_XAPIAN_PLUGIN_H #include "config.h" #include "lib.h" #include "mail-user.h" #include "fts-api.h" #include "fts-user.h" #include "mail-search.h" #include "mail-storage-private.h" #include "restrict-process-size.h" #include "mail-storage-hooks.h" #include "module-context.h" #include "fts-api-private.h" #include "master-service.h" #ifdef FTS_DOVECOT24 #include "fts-settings.h" #include "settings-parser.h" #include "settings.h" #endif #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__) #include #include #endif #include #define XAPIAN_PLUGIN_VERSION "1.9.1" #define XAPIAN_LABEL "fts_xapian" // Main parameters #define XAPIAN_FILE_PREFIX "xapian-indexes" // Locations of indexes #define XAPIAN_MIN_RAM 300L // MB #define XAPIAN_DEFAULT_PARTIAL 3L struct fts_xapian_settings { #ifdef FTS_DOVECOT24 pool_t pool; #endif unsigned int verbose; unsigned int lowmemory; unsigned int partial; unsigned int maxthreads; }; struct fts_xapian_user { union mail_user_module_context module_ctx; #ifdef FTS_DOVECOT24 struct fts_xapian_settings *set; #else struct fts_xapian_settings set; #endif }; #define FTS_XAPIAN_USER_CONTEXT(obj) (struct fts_xapian_user *)MODULE_CONTEXT(obj, fts_xapian_user_module) #if ((DOVECOT_VERSION_MINOR > 2) || (DOVECOT_VERSION_MAJOR > 2) || (FTS_DOVECOT24 > 0)) #define FTS_XAPIAN_USER_CONTEXT_REQUIRE(obj) MODULE_CONTEXT_REQUIRE(obj, fts_xapian_user_module) #endif extern const char *fts_xapian_plugin_dependencies[]; extern MODULE_CONTEXT_DEFINE(fts_xapian_user_module, &mail_user_module_register); extern struct fts_backend fts_backend_xapian; #ifdef FTS_DOVECOT24 int fts_xapian_mail_user_get(struct mail_user *user, struct event *event, struct fts_xapian_user **fuser_r, const char **error_r); extern const struct setting_parser_info fts_xapian_setting_parser_info; #endif void fts_xapian_plugin_init(struct module *module); void fts_xapian_plugin_deinit(void); #endif fts-xapian-1.9.1/src/fts-xapian-settings.c000066400000000000000000000024161475462537600204650ustar00rootroot00000000000000/* Copyright (c) 2019 Joan Moreau , see the included COPYING file */ #ifdef FTS_DOVECOT24 #include "lib.h" #include "settings.h" #include "settings-parser.h" #include "fts-xapian-plugin.h" #undef DEF #define DEF(type, name) \ SETTING_DEFINE_STRUCT_##type(XAPIAN_LABEL"_"#name, name, struct fts_xapian_settings) static const struct setting_define fts_xapian_setting_defines[] = { DEF(UINT, verbose), DEF(UINT, lowmemory), DEF(UINT, partial), DEF(UINT, maxthreads), SETTING_DEFINE_LIST_END }; static const struct fts_xapian_settings fts_xapian_default_settings = { .verbose = 0, .lowmemory = XAPIAN_MIN_RAM, .partial = XAPIAN_DEFAULT_PARTIAL, .maxthreads = 0, }; const struct setting_parser_info fts_xapian_setting_parser_info = { .name = XAPIAN_LABEL, .defines = fts_xapian_setting_defines, .defaults = &fts_xapian_default_settings, .struct_size = sizeof(struct fts_xapian_settings), .pool_offset1 = 1 + offsetof(struct fts_xapian_settings, pool), }; const char *fts_xapian_settings_version = DOVECOT_ABI_VERSION; const struct setting_parser_info *fts_xapian_settings_set_infos[] = { &fts_xapian_setting_parser_info, NULL, }; #endif fts-xapian-1.9.1/stamp.h.in000066400000000000000000000000001475462537600155070ustar00rootroot00000000000000