textsearch: support for case insensitive searching
[safe/jmp/linux-2.6] / lib / textsearch.c
1 /*
2  * lib/textsearch.c     Generic text search interface
3  *
4  *              This program is free software; you can redistribute it and/or
5  *              modify it under the terms of the GNU General Public License
6  *              as published by the Free Software Foundation; either version
7  *              2 of the License, or (at your option) any later version.
8  *
9  * Authors:     Thomas Graf <tgraf@suug.ch>
10  *              Pablo Neira Ayuso <pablo@netfilter.org>
11  *
12  * ==========================================================================
13  *
14  * INTRODUCTION
15  *
16  *   The textsearch infrastructure provides text searching facitilies for
17  *   both linear and non-linear data. Individual search algorithms are
18  *   implemented in modules and chosen by the user.
19  *
20  * ARCHITECTURE
21  *
22  *      User
23  *     +----------------+
24  *     |        finish()|<--------------(6)-----------------+
25  *     |get_next_block()|<--------------(5)---------------+ |
26  *     |                |                     Algorithm   | |
27  *     |                |                    +------------------------------+
28  *     |                |                    |  init()   find()   destroy() |
29  *     |                |                    +------------------------------+
30  *     |                |       Core API           ^       ^          ^
31  *     |                |      +---------------+  (2)     (4)        (8)
32  *     |             (1)|----->| prepare()     |---+       |          |
33  *     |             (3)|----->| find()/next() |-----------+          |
34  *     |             (7)|----->| destroy()     |----------------------+
35  *     +----------------+      +---------------+
36  *  
37  *   (1) User configures a search by calling _prepare() specifying the
38  *       search parameters such as the pattern and algorithm name.
39  *   (2) Core requests the algorithm to allocate and initialize a search
40  *       configuration according to the specified parameters.
41  *   (3) User starts the search(es) by calling _find() or _next() to
42  *       fetch subsequent occurrences. A state variable is provided
43  *       to the algorithm to store persistent variables.
44  *   (4) Core eventually resets the search offset and forwards the find()
45  *       request to the algorithm.
46  *   (5) Algorithm calls get_next_block() provided by the user continously
47  *       to fetch the data to be searched in block by block.
48  *   (6) Algorithm invokes finish() after the last call to get_next_block
49  *       to clean up any leftovers from get_next_block. (Optional)
50  *   (7) User destroys the configuration by calling _destroy().
51  *   (8) Core notifies the algorithm to destroy algorithm specific
52  *       allocations. (Optional)
53  *
54  * USAGE
55  *
56  *   Before a search can be performed, a configuration must be created
57  *   by calling textsearch_prepare() specifying the searching algorithm,
58  *   the pattern to look for and flags. As a flag, you can set TS_IGNORECASE
59  *   to perform case insensitive matching. But it might slow down
60  *   performance of algorithm, so you should use it at own your risk.
61  *   The returned configuration may then be used for an arbitary
62  *   amount of times and even in parallel as long as a separate struct
63  *   ts_state variable is provided to every instance.
64  *
65  *   The actual search is performed by either calling textsearch_find_-
66  *   continuous() for linear data or by providing an own get_next_block()
67  *   implementation and calling textsearch_find(). Both functions return
68  *   the position of the first occurrence of the patern or UINT_MAX if
69  *   no match was found. Subsequent occurences can be found by calling
70  *   textsearch_next() regardless of the linearity of the data.
71  *
72  *   Once you're done using a configuration it must be given back via
73  *   textsearch_destroy.
74  *
75  * EXAMPLE
76  *
77  *   int pos;
78  *   struct ts_config *conf;
79  *   struct ts_state state;
80  *   const char *pattern = "chicken";
81  *   const char *example = "We dance the funky chicken";
82  *
83  *   conf = textsearch_prepare("kmp", pattern, strlen(pattern),
84  *                             GFP_KERNEL, TS_AUTOLOAD);
85  *   if (IS_ERR(conf)) {
86  *       err = PTR_ERR(conf);
87  *       goto errout;
88  *   }
89  *
90  *   pos = textsearch_find_continuous(conf, &state, example, strlen(example));
91  *   if (pos != UINT_MAX)
92  *       panic("Oh my god, dancing chickens at %d\n", pos);
93  *
94  *   textsearch_destroy(conf);
95  * ==========================================================================
96  */
97
98 #include <linux/module.h>
99 #include <linux/types.h>
100 #include <linux/string.h>
101 #include <linux/init.h>
102 #include <linux/rcupdate.h>
103 #include <linux/err.h>
104 #include <linux/textsearch.h>
105
106 static LIST_HEAD(ts_ops);
107 static DEFINE_SPINLOCK(ts_mod_lock);
108
109 static inline struct ts_ops *lookup_ts_algo(const char *name)
110 {
111         struct ts_ops *o;
112
113         rcu_read_lock();
114         list_for_each_entry_rcu(o, &ts_ops, list) {
115                 if (!strcmp(name, o->name)) {
116                         if (!try_module_get(o->owner))
117                                 o = NULL;
118                         rcu_read_unlock();
119                         return o;
120                 }
121         }
122         rcu_read_unlock();
123
124         return NULL;
125 }
126
127 /**
128  * textsearch_register - register a textsearch module
129  * @ops: operations lookup table
130  *
131  * This function must be called by textsearch modules to announce
132  * their presence. The specified &@ops must have %name set to a
133  * unique identifier and the callbacks find(), init(), get_pattern(),
134  * and get_pattern_len() must be implemented.
135  *
136  * Returns 0 or -EEXISTS if another module has already registered
137  * with same name.
138  */
139 int textsearch_register(struct ts_ops *ops)
140 {
141         int err = -EEXIST;
142         struct ts_ops *o;
143
144         if (ops->name == NULL || ops->find == NULL || ops->init == NULL ||
145             ops->get_pattern == NULL || ops->get_pattern_len == NULL)
146                 return -EINVAL;
147
148         spin_lock(&ts_mod_lock);
149         list_for_each_entry(o, &ts_ops, list) {
150                 if (!strcmp(ops->name, o->name))
151                         goto errout;
152         }
153
154         list_add_tail_rcu(&ops->list, &ts_ops);
155         err = 0;
156 errout:
157         spin_unlock(&ts_mod_lock);
158         return err;
159 }
160
161 /**
162  * textsearch_unregister - unregister a textsearch module
163  * @ops: operations lookup table
164  *
165  * This function must be called by textsearch modules to announce
166  * their disappearance for examples when the module gets unloaded.
167  * The &ops parameter must be the same as the one during the
168  * registration.
169  *
170  * Returns 0 on success or -ENOENT if no matching textsearch
171  * registration was found.
172  */
173 int textsearch_unregister(struct ts_ops *ops)
174 {
175         int err = 0;
176         struct ts_ops *o;
177
178         spin_lock(&ts_mod_lock);
179         list_for_each_entry(o, &ts_ops, list) {
180                 if (o == ops) {
181                         list_del_rcu(&o->list);
182                         goto out;
183                 }
184         }
185
186         err = -ENOENT;
187 out:
188         spin_unlock(&ts_mod_lock);
189         return err;
190 }
191
192 struct ts_linear_state
193 {
194         unsigned int    len;
195         const void      *data;
196 };
197
198 static unsigned int get_linear_data(unsigned int consumed, const u8 **dst,
199                                     struct ts_config *conf,
200                                     struct ts_state *state)
201 {
202         struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
203
204         if (likely(consumed < st->len)) {
205                 *dst = st->data + consumed;
206                 return st->len - consumed;
207         }
208
209         return 0;
210 }
211
212 /**
213  * textsearch_find_continuous - search a pattern in continuous/linear data
214  * @conf: search configuration
215  * @state: search state
216  * @data: data to search in
217  * @len: length of data
218  *
219  * A simplified version of textsearch_find() for continuous/linear data.
220  * Call textsearch_next() to retrieve subsequent matches.
221  *
222  * Returns the position of first occurrence of the pattern or
223  * %UINT_MAX if no occurrence was found.
224  */ 
225 unsigned int textsearch_find_continuous(struct ts_config *conf,
226                                         struct ts_state *state,
227                                         const void *data, unsigned int len)
228 {
229         struct ts_linear_state *st = (struct ts_linear_state *) state->cb;
230
231         conf->get_next_block = get_linear_data;
232         st->data = data;
233         st->len = len;
234
235         return textsearch_find(conf, state);
236 }
237
238 /**
239  * textsearch_prepare - Prepare a search
240  * @algo: name of search algorithm
241  * @pattern: pattern data
242  * @len: length of pattern
243  * @gfp_mask: allocation mask
244  * @flags: search flags
245  *
246  * Looks up the search algorithm module and creates a new textsearch
247  * configuration for the specified pattern. Upon completion all
248  * necessary refcnts are held and the configuration must be put back
249  * using textsearch_put() after usage.
250  *
251  * Note: The format of the pattern may not be compatible between
252  *       the various search algorithms.
253  *
254  * Returns a new textsearch configuration according to the specified
255  * parameters or a ERR_PTR(). If a zero length pattern is passed, this
256  * function returns EINVAL.
257  */
258 struct ts_config *textsearch_prepare(const char *algo, const void *pattern,
259                                      unsigned int len, gfp_t gfp_mask, int flags)
260 {
261         int err = -ENOENT;
262         struct ts_config *conf;
263         struct ts_ops *ops;
264         
265         if (len == 0)
266                 return ERR_PTR(-EINVAL);
267
268         ops = lookup_ts_algo(algo);
269 #ifdef CONFIG_KMOD
270         /*
271          * Why not always autoload you may ask. Some users are
272          * in a situation where requesting a module may deadlock,
273          * especially when the module is located on a NFS mount.
274          */
275         if (ops == NULL && flags & TS_AUTOLOAD) {
276                 request_module("ts_%s", algo);
277                 ops = lookup_ts_algo(algo);
278         }
279 #endif
280
281         if (ops == NULL)
282                 goto errout;
283
284         conf = ops->init(pattern, len, gfp_mask, flags);
285         if (IS_ERR(conf)) {
286                 err = PTR_ERR(conf);
287                 goto errout;
288         }
289
290         conf->ops = ops;
291         return conf;
292
293 errout:
294         if (ops)
295                 module_put(ops->owner);
296                 
297         return ERR_PTR(err);
298 }
299
300 /**
301  * textsearch_destroy - destroy a search configuration
302  * @conf: search configuration
303  *
304  * Releases all references of the configuration and frees
305  * up the memory.
306  */
307 void textsearch_destroy(struct ts_config *conf)
308 {
309         if (conf->ops) {
310                 if (conf->ops->destroy)
311                         conf->ops->destroy(conf);
312                 module_put(conf->ops->owner);
313         }
314
315         kfree(conf);
316 }
317
318 EXPORT_SYMBOL(textsearch_register);
319 EXPORT_SYMBOL(textsearch_unregister);
320 EXPORT_SYMBOL(textsearch_prepare);
321 EXPORT_SYMBOL(textsearch_find_continuous);
322 EXPORT_SYMBOL(textsearch_destroy);