consistent description
[privoxy.git] / cgiedit.c
1 const char cgiedit_rcs[] = "$Id: cgiedit.c,v 1.27 2002/03/26 23:06:04 jongfoster Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/cgiedit.c,v $
5  *
6  * Purpose     :  CGI-based actionsfile editor.
7  *
8  *                Functions declared include: cgi_edit_*
9  *
10  *                NOTE: The CGIs in this file use parameter names
11  *                such as "f" and "s" which are really *BAD* choices.
12  *                However, I'm trying to save bytes in the
13  *                edit-actions-list HTML page - the standard actions
14  *                file generated a 550kbyte page, which is ridiculous.
15  *
16  *                Stick to the short names in this file for consistency.
17  *
18  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
19  *                Privoxy team. http://www.privoxy.org/
20  *
21  *                Based on the Internet Junkbuster originally written
22  *                by and Copyright (C) 1997 Anonymous Coders and
23  *                Junkbusters Corporation.  http://www.junkbusters.com
24  *
25  *                This program is free software; you can redistribute it
26  *                and/or modify it under the terms of the GNU General
27  *                Public License as published by the Free Software
28  *                Foundation; either version 2 of the License, or (at
29  *                your option) any later version.
30  *
31  *                This program is distributed in the hope that it will
32  *                be useful, but WITHOUT ANY WARRANTY; without even the
33  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
34  *                PARTICULAR PURPOSE.  See the GNU General Public
35  *                License for more details.
36  *
37  *                The GNU General Public License should be included with
38  *                this file.  If not, you can view it at
39  *                http://www.gnu.org/copyleft/gpl.html
40  *                or write to the Free Software Foundation, Inc., 59
41  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
42  *
43  * Revisions   :
44  *    $Log: cgiedit.c,v $
45  *    Revision 1.27  2002/03/26 23:06:04  jongfoster
46  *    Removing duplicate @ifs on the toggle page
47  *
48  *    Revision 1.26  2002/03/26 22:59:17  jongfoster
49  *    Fixing /toggle to display status consistently.
50  *
51  *    Revision 1.25  2002/03/26 22:29:54  swa
52  *    we have a new homepage!
53  *
54  *    Revision 1.24  2002/03/24 15:23:33  jongfoster
55  *    Name changes
56  *
57  *    Revision 1.23  2002/03/24 13:32:41  swa
58  *    name change related issues
59  *
60  *    Revision 1.22  2002/03/24 13:25:43  swa
61  *    name change related issues
62  *
63  *    Revision 1.21  2002/03/22 18:02:48  jongfoster
64  *    Fixing remote toggle
65  *
66  *    Revision 1.20  2002/03/16 20:28:34  oes
67  *    Added descriptions to the filters so users will know what they select in the cgi editor
68  *
69  *    Revision 1.19  2002/03/16 18:38:14  jongfoster
70  *    Stopping stupid or malicious users from breaking the actions
71  *    file using the web-based editor.
72  *
73  *    Revision 1.18  2002/03/16 14:57:44  jongfoster
74  *    Full support for enabling/disabling modular filters.
75  *
76  *    Revision 1.17  2002/03/16 14:26:42  jongfoster
77  *    First version of modular filters support - READ ONLY!
78  *    Fixing a double-free bug in the out-of-memory handling in map_radio().
79  *
80  *    Revision 1.16  2002/03/07 03:46:17  oes
81  *    Fixed compiler warnings
82  *
83  *    Revision 1.15  2002/03/06 22:54:35  jongfoster
84  *    Automated function-comment nitpicking.
85  *
86  *    Revision 1.14  2002/03/05 00:24:51  jongfoster
87  *    Patch to always edit the current actions file.
88  *
89  *    Revision 1.13  2002/03/04 02:07:59  david__schmidt
90  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
91  *
92  *    Revision 1.12  2002/03/03 09:18:03  joergs
93  *    Made jumbjuster work on AmigaOS again.
94  *
95  *    Revision 1.11  2002/01/23 01:03:31  jongfoster
96  *    Fixing gcc [CygWin] compiler warnings
97  *
98  *    Revision 1.10  2002/01/23 00:22:59  jongfoster
99  *    Adding new function cgi_edit_actions_section_swap(), to reorder
100  *    the actions file.
101  *
102  *    Adding get_url_spec_param() to get a validated URL pattern.
103  *
104  *    Moving edit_read_line() out of this file and into loaders.c.
105  *
106  *    Adding missing html_encode() to many CGI functions.
107  *
108  *    Moving the functions that #include actionlist.h to the end of the file,
109  *    because the Visual C++ 97 debugger gets extremely confused if you try
110  *    to debug any code that comes after them in the file.
111  *
112  *    Major optimizations in cgi_edit_actions_list() to reduce the size of
113  *    the generated HTML (down 40% from 550k to 304k), with major side-effects
114  *    throughout the editor and templates.  In particular, the length of the
115  *    URLs throughout the editor has been drastically reduced, by cutting
116  *    paramater names down to 1 character and CGI names down to 3-4
117  *    characters, by removing all non-essential CGI paramaters even at the
118  *    expense of having to re-read the actions file for the most trivial
119  *    page, and by using relative rather than absolute URLs.  This means
120  *    that this (typical example):
121  *
122  *    <a href="http://ijbswa.sourceforge.net/config/edit-actions-url-form?
123  *    filename=ijb&amp;ver=1011487572&amp;section=12&amp;pattern=13
124  *    &amp;oldval=www.oesterhelt.org%2Fdeanimate-demo">
125  *
126  *    is now this:
127  *
128  *    <a href="eau?f=ijb&amp;v=1011487572&amp;p=13">
129  *
130  *    Revision 1.9  2002/01/17 20:56:22  jongfoster
131  *    Replacing hard references to the URL of the config interface
132  *    with #defines from project.h
133  *
134  *    Revision 1.8  2001/11/30 23:35:51  jongfoster
135  *    Renaming actionsfile to ijb.action
136  *
137  *    Revision 1.7  2001/11/13 00:28:24  jongfoster
138  *    - Renaming parameters from edit-actions-for-url so that they only
139  *      contain legal JavaScript characters.  If we wanted to write
140  *      JavaScript that worked with Netscape 4, this is nessacery.
141  *      (Note that at the moment the JavaScript doesn't actually work
142  *      with Netscape 4, but now this is purely a template issue, not
143  *      one affecting code).
144  *    - Adding new CGIs for use by non-JavaScript browsers:
145  *        edit-actions-url-form
146  *        edit-actions-add-url-form
147  *        edit-actions-remove-url-form
148  *    - Fixing || bug.
149  *
150  *    Revision 1.6  2001/10/29 03:48:09  david__schmidt
151  *    OS/2 native needed a snprintf() routine.  Added one to miscutil, brackedted
152  *    by and __OS2__ ifdef.
153  *
154  *    Revision 1.5  2001/10/25 03:40:48  david__schmidt
155  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
156  *    threads to call select() simultaneously.  So, it's time to do a real, live,
157  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
158  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
159  *
160  *    Revision 1.4  2001/10/23 21:48:19  jongfoster
161  *    Cleaning up error handling in CGI functions - they now send back
162  *    a HTML error page and should never cause a FATAL error.  (Fixes one
163  *    potential source of "denial of service" attacks).
164  *
165  *    CGI actions file editor that works and is actually useful.
166  *
167  *    Ability to toggle JunkBuster remotely using a CGI call.
168  *
169  *    You can turn off both the above features in the main configuration
170  *    file, e.g. if you are running a multi-user proxy.
171  *
172  *    Revision 1.3  2001/10/14 22:12:49  jongfoster
173  *    New version of CGI-based actionsfile editor.
174  *    Major changes, including:
175  *    - Completely new file parser and file output routines
176  *    - edit-actions CGI renamed edit-actions-for-url
177  *    - All CGIs now need a filename parameter, except for...
178  *    - New CGI edit-actions which doesn't need a filename,
179  *      to allow you to start the editor up.
180  *    - edit-actions-submit now works, and now automatically
181  *      redirects you back to the main edit-actions-list handler.
182  *
183  *    Revision 1.2  2001/09/16 17:05:14  jongfoster
184  *    Removing unused #include showarg.h
185  *
186  *    Revision 1.1  2001/09/16 15:47:37  jongfoster
187  *    First version of CGI-based edit interface.  This is very much a
188  *    work-in-progress, and you can't actually use it to edit anything
189  *    yet.  You must #define FEATURE_CGI_EDIT_ACTIONS for these changes
190  *    to have any effect.
191  *
192  *
193  **********************************************************************/
194 \f
195
196 #include "config.h"
197
198 /*
199  * FIXME: Following includes copied from cgi.c - which are actually needed?
200  */
201
202 #include <stdio.h>
203 #include <stdlib.h>
204 #include <sys/types.h>
205 #include <ctype.h>
206 #include <string.h>
207 #include <assert.h>
208 #include <limits.h>
209 #include <sys/stat.h>
210
211 #ifdef _WIN32
212 #define snprintf _snprintf
213 #endif /* def _WIN32 */
214
215 #include "project.h"
216 #include "cgi.h"
217 #include "cgiedit.h"
218 #include "cgisimple.h"
219 #include "list.h"
220 #include "encode.h"
221 #include "actions.h"
222 #include "miscutil.h"
223 #include "errlog.h"
224 #include "loaders.h"
225 #include "loadcfg.h"
226 /* loadcfg.h is for g_bToggleIJB only */
227 #include "urlmatch.h"
228
229 const char cgiedit_h_rcs[] = CGIEDIT_H_VERSION;
230
231
232 #ifdef FEATURE_CGI_EDIT_ACTIONS
233
234 struct file_line
235 {
236    struct file_line * next;
237    char * raw;
238    char * prefix;
239    char * unprocessed;
240    int type;
241
242    union
243    {
244       struct action_spec action[1];
245
246       struct
247       {
248          char * name;
249          char * svalue;
250          int ivalue;
251       } setting;
252
253       /* Add more data types here... e.g.
254
255
256       struct url_spec url[1];
257
258       struct
259       {
260          struct action_spec action[1];
261          const char * name;
262       } alias;
263
264       */
265
266    } data;
267 };
268
269 #define FILE_LINE_UNPROCESSED           1
270 #define FILE_LINE_BLANK                 2
271 #define FILE_LINE_ALIAS_HEADER          3
272 #define FILE_LINE_ALIAS_ENTRY           4
273 #define FILE_LINE_ACTION                5
274 #define FILE_LINE_URL                   6
275 #define FILE_LINE_SETTINGS_HEADER       7
276 #define FILE_LINE_SETTINGS_ENTRY        8
277 #define FILE_LINE_DESCRIPTION_HEADER    9
278 #define FILE_LINE_DESCRIPTION_ENTRY    10
279
280
281 struct editable_file
282 {
283    struct file_line * lines;
284    const char * filename;     /* Full pathname - e.g. "/etc/privoxy/wibble.action" */
285    const char * identifier;   /* Filename stub - e.g. "wibble".  Use for CGI param. */
286                               /* Pre-encoded with url_encode() for ease of use. */
287    const char * version_str;  /* Last modification time, as a string.  For CGI param */
288                               /* Can be used in URL without using url_param(). */
289    unsigned version;          /* Last modification time - prevents chaos with
290                                * the browser's "back" button.  Note that this is a
291                                * time_t cast to an unsigned.  When comparing, always
292                                * cast the time_t to an unsigned, and *NOT* vice-versa.
293                                * This may lose the top few bits, but they're not
294                                * significant anyway.
295                                */
296    int newline;               /* Newline convention - one of the NEWLINE_xxx constants.
297                                * Note that changing this after the file has been
298                                * read in will cause a mess.
299                                */
300    struct file_line * parse_error; /* On parse error, this is the offending line. */
301    const char * parse_error_text;  /* On parse error, this is the problem.
302                                     * (Statically allocated) */
303 };
304
305 #define CGI_ACTION_PARAM_LEN_MAX 500
306
307 /* FIXME: Following non-static functions should be prototyped in .h or made static */
308
309 /* Functions to read and write arbitrary config files */
310 jb_err edit_read_file(struct client_state *csp,
311                       const struct map *parameters,
312                       int require_version,
313                       const char *suffix,
314                       struct editable_file **pfile);
315 jb_err edit_write_file(struct editable_file * file);
316 void   edit_free_file(struct editable_file * file);
317
318 /* Functions to read and write actions files */
319 jb_err edit_parse_actions_file(struct editable_file * file);
320 jb_err edit_read_actions_file(struct client_state *csp,
321                               struct http_response *rsp,
322                               const struct map *parameters,
323                               int require_version,
324                               struct editable_file **pfile);
325
326 /* Error handlers */
327 jb_err cgi_error_modified(struct client_state *csp,
328                           struct http_response *rsp,
329                           const char *filename);
330 jb_err cgi_error_parse(struct client_state *csp,
331                        struct http_response *rsp,
332                        struct editable_file *file);
333 jb_err cgi_error_file(struct client_state *csp,
334                       struct http_response *rsp,
335                       const char *filename);
336 jb_err cgi_error_disabled(struct client_state *csp,
337                           struct http_response *rsp);
338
339 /* Internal arbitrary config file support functions */
340 static jb_err edit_read_file_lines(FILE *fp, struct file_line ** pfile, int *newline);
341 static void edit_free_file_lines(struct file_line * first_line);
342
343 /* Internal actions file support functions */
344 static int match_actions_file_header_line(const char * line, const char * name);
345 static jb_err split_line_on_equals(const char * line, char ** pname, char ** pvalue);
346
347 /* Internal parameter parsing functions */
348 static jb_err get_file_name_param(struct client_state *csp,
349                                   const struct map *parameters,
350                                   const char *param_name,
351                                   const char *suffix,
352                                   char **pfilename,
353                                   const char **pparam);
354 static jb_err get_number_param(struct client_state *csp,
355                                const struct map *parameters,
356                                char *name,
357                                unsigned *pvalue);
358 static jb_err get_url_spec_param(struct client_state *csp,
359                                  const struct map *parameters,
360                                  const char *name,
361                                  char **pvalue);
362 static jb_err get_string_param(const struct map *parameters,
363                                const char *param_name,
364                                const char **pparam);
365
366 /* Internal actionsfile <==> HTML conversion functions */
367 static jb_err map_radio(struct map * exports,
368                         const char * optionname,
369                         const char * values,
370                         int value);
371 static jb_err actions_to_radio(struct map * exports,
372                                const struct action_spec *action);
373 static jb_err actions_from_radio(const struct map * parameters,
374                                  struct action_spec *action);
375
376
377 static jb_err map_copy_parameter_html(struct map *out,
378                                       const struct map *in,
379                                       const char *name);
380 #if 0 /* unused function */
381 static jb_err map_copy_parameter_url(struct map *out,
382                                      const struct map *in,
383                                      const char *name);
384 #endif /* unused function */
385
386 /*********************************************************************
387  *
388  * Function    :  map_copy_parameter_html
389  *
390  * Description :  Copy a CGI parameter from one map to another, HTML
391  *                encoding it.
392  *
393  * Parameters  :
394  *          1  :  out = target map
395  *          2  :  in = source map
396  *          3  :  name = name of cgi parameter to copy
397  *
398  * Returns     :  JB_ERR_OK on success
399  *                JB_ERR_MEMORY on out-of-memory
400  *                JB_ERR_CGI_PARAMS if the parameter doesn't exist
401  *                                  in the source map
402  *
403  *********************************************************************/
404 static jb_err map_copy_parameter_html(struct map *out,
405                                       const struct map *in,
406                                       const char *name)
407 {
408    const char * value;
409    jb_err err;
410
411    assert(out);
412    assert(in);
413    assert(name);
414
415    value = lookup(in, name);
416    err = map(out, name, 1, html_encode(value), 0);
417
418    if (err)
419    {
420       /* Out of memory */
421       return err;
422    }
423    else if (*value == '\0')
424    {
425       return JB_ERR_CGI_PARAMS;
426    }
427    else
428    {
429       return JB_ERR_OK;
430    }
431 }
432
433
434 #if 0 /* unused function */
435 /*********************************************************************
436  *
437  * Function    :  map_copy_parameter_html
438  *
439  * Description :  Copy a CGI parameter from one map to another, URL
440  *                encoding it.
441  *
442  * Parameters  :
443  *          1  :  out = target map
444  *          2  :  in = source map
445  *          3  :  name = name of cgi parameter to copy
446  *
447  * Returns     :  JB_ERR_OK on success
448  *                JB_ERR_MEMORY on out-of-memory
449  *                JB_ERR_CGI_PARAMS if the parameter doesn't exist
450  *                                  in the source map
451  *
452  *********************************************************************/
453 static jb_err map_copy_parameter_url(struct map *out,
454                                      const struct map *in,
455                                      const char *name)
456 {
457    const char * value;
458    jb_err err;
459
460    assert(out);
461    assert(in);
462    assert(name);
463
464    value = lookup(in, name);
465    err = map(out, name, 1, url_encode(value), 0);
466
467    if (err)
468    {
469       /* Out of memory */
470       return err;
471    }
472    else if (*value == '\0')
473    {
474       return JB_ERR_CGI_PARAMS;
475    }
476    else
477    {
478       return JB_ERR_OK;
479    }
480 }
481 #endif /* 0 - unused function */
482
483 /*********************************************************************
484  *
485  * Function    :  cgi_edit_actions_url_form
486  *
487  * Description :  CGI function that displays a form for
488  *                edit-actions-url
489  *
490  * Parameters  :
491  *          1  :  csp = Current client state (buffers, headers, etc...)
492  *          2  :  rsp = http_response data structure for output
493  *          3  :  parameters = map of cgi parameters
494  *
495  * CGI Parameters
496  *           f : (filename) Identifies the file to edit
497  *           v : (version) File's last-modified time
498  *           p : (pattern) Line number of pattern to edit
499  *
500  * Returns     :  JB_ERR_OK on success
501  *                JB_ERR_MEMORY on out-of-memory
502  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
503  *                                  specified or not valid.
504  *
505  *********************************************************************/
506 jb_err cgi_edit_actions_url_form(struct client_state *csp,
507                                  struct http_response *rsp,
508                                  const struct map *parameters)
509 {
510    struct map * exports;
511    unsigned patternid;
512    struct editable_file * file;
513    struct file_line * cur_line;
514    unsigned line_number;
515    jb_err err;
516
517    assert(csp);
518    assert(rsp);
519    assert(parameters);
520
521    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
522    {
523       return cgi_error_disabled(csp, rsp);
524    }
525
526    err = get_number_param(csp, parameters, "p", &patternid);
527    if (err)
528    {
529       return err;
530    }
531
532    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
533    if (err)
534    {
535       /* No filename specified, can't read file, modified, or out of memory. */
536       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
537    }
538
539    cur_line = file->lines;
540
541    for (line_number = 1; (cur_line != NULL) && (line_number < patternid); line_number++)
542    {
543       cur_line = cur_line->next;
544    }
545
546    if ( (cur_line == NULL)
547      || (line_number != patternid)
548      || (patternid < 1)
549      || (cur_line->type != FILE_LINE_URL))
550    {
551       /* Invalid "patternid" parameter */
552       edit_free_file(file);
553       return JB_ERR_CGI_PARAMS;
554    }
555
556    if (NULL == (exports = default_exports(csp, NULL)))
557    {
558       edit_free_file(file);
559       return JB_ERR_MEMORY;
560    }
561
562    err = map(exports, "f", 1, file->identifier, 1);
563    if (!err) err = map(exports, "v", 1, file->version_str, 1);
564    if (!err) err = map(exports, "p", 1, url_encode(lookup(parameters, "p")), 0);
565    if (!err) err = map(exports, "u", 1, html_encode(cur_line->unprocessed), 0);
566
567    edit_free_file(file);
568
569    if (err)
570    {
571       free_map(exports);
572       return err;
573    }
574
575    return template_fill_for_cgi(csp, "edit-actions-url-form", exports, rsp);
576 }
577
578
579 /*********************************************************************
580  *
581  * Function    :  cgi_edit_actions_add_url_form
582  *
583  * Description :  CGI function that displays a form for
584  *                edit-actions-url
585  *
586  * Parameters  :
587  *          1  :  csp = Current client state (buffers, headers, etc...)
588  *          2  :  rsp = http_response data structure for output
589  *          3  :  parameters = map of cgi parameters
590  *
591  * CGI Parameters :
592  *           f : (filename) Identifies the file to edit
593  *           v : (version) File's last-modified time
594  *           s : (section) Line number of section to edit
595  *
596  * Returns     :  JB_ERR_OK on success
597  *                JB_ERR_MEMORY on out-of-memory
598  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
599  *                                  specified or not valid.
600  *
601  *********************************************************************/
602 jb_err cgi_edit_actions_add_url_form(struct client_state *csp,
603                                      struct http_response *rsp,
604                                      const struct map *parameters)
605 {
606    struct map *exports;
607    jb_err err;
608
609    assert(csp);
610    assert(rsp);
611    assert(parameters);
612
613    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
614    {
615       return cgi_error_disabled(csp, rsp);
616    }
617
618    if (NULL == (exports = default_exports(csp, NULL)))
619    {
620       return JB_ERR_MEMORY;
621    }
622
623    err = map_copy_parameter_html(exports, parameters, "f");
624    if (!err) err = map_copy_parameter_html(exports, parameters, "v");
625    if (!err) err = map_copy_parameter_html(exports, parameters, "s");
626
627    if (err)
628    {
629       free_map(exports);
630       return err;
631    }
632
633    return template_fill_for_cgi(csp, "edit-actions-add-url-form", exports, rsp);
634 }
635
636
637 /*********************************************************************
638  *
639  * Function    :  cgi_edit_actions_remove_url_form
640  *
641  * Description :  CGI function that displays a form for
642  *                edit-actions-url
643  *
644  * Parameters  :
645  *          1  :  csp = Current client state (buffers, headers, etc...)
646  *          2  :  rsp = http_response data structure for output
647  *          3  :  parameters = map of cgi parameters
648  *
649  * CGI Parameters :
650  *           f : (filename) Identifies the file to edit
651  *           v : (version) File's last-modified time
652  *           p : (pattern) Line number of pattern to edit
653  *
654  * Returns     :  JB_ERR_OK on success
655  *                JB_ERR_MEMORY on out-of-memory
656  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
657  *                                  specified or not valid.
658  *
659  *********************************************************************/
660 jb_err cgi_edit_actions_remove_url_form(struct client_state *csp,
661                                      struct http_response *rsp,
662                                      const struct map *parameters)
663 {
664    struct map * exports;
665    unsigned patternid;
666    struct editable_file * file;
667    struct file_line * cur_line;
668    unsigned line_number;
669    jb_err err;
670
671    assert(csp);
672    assert(rsp);
673    assert(parameters);
674
675    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
676    {
677       return cgi_error_disabled(csp, rsp);
678    }
679
680    err = get_number_param(csp, parameters, "p", &patternid);
681    if (err)
682    {
683       return err;
684    }
685
686    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
687    if (err)
688    {
689       /* No filename specified, can't read file, modified, or out of memory. */
690       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
691    }
692
693    cur_line = file->lines;
694
695    for (line_number = 1; (cur_line != NULL) && (line_number < patternid); line_number++)
696    {
697       cur_line = cur_line->next;
698    }
699
700    if ( (cur_line == NULL)
701      || (line_number != patternid)
702      || (patternid < 1)
703      || (cur_line->type != FILE_LINE_URL))
704    {
705       /* Invalid "patternid" parameter */
706       edit_free_file(file);
707       return JB_ERR_CGI_PARAMS;
708    }
709
710    if (NULL == (exports = default_exports(csp, NULL)))
711    {
712       edit_free_file(file);
713       return JB_ERR_MEMORY;
714    }
715
716    err = map(exports, "f", 1, file->identifier, 1);
717    if (!err) err = map(exports, "v", 1, file->version_str, 1);
718    if (!err) err = map(exports, "s", 1, url_encode(lookup(parameters, "s")), 0);
719    if (!err) err = map(exports, "u", 1, html_encode(cur_line->unprocessed), 0);
720
721    edit_free_file(file);
722
723    if (err)
724    {
725       free_map(exports);
726       return err;
727    }
728
729    return template_fill_for_cgi(csp, "edit-actions-remove-url-form", exports, rsp);
730 }
731
732
733 /*********************************************************************
734  *
735  * Function    :  edit_write_file
736  *
737  * Description :  Write a complete file to disk.
738  *
739  * Parameters  :
740  *          1  :  filename = File to write to.
741  *          2  :  file = Data structure to write.
742  *
743  * Returns     :  JB_ERR_OK     on success
744  *                JB_ERR_FILE   on error writing to file.
745  *                JB_ERR_MEMORY on out of memory
746  *
747  *********************************************************************/
748 jb_err edit_write_file(struct editable_file * file)
749 {
750    FILE * fp;
751    struct file_line * cur_line;
752    struct stat statbuf[1];
753    char version_buf[22]; /* 22 = ceil(log10(2^64)) + 2 = max number of
754                             digits in time_t, assuming this is a 64-bit
755                             machine, plus null terminator, plus one
756                             for paranoia */
757
758    assert(file);
759    assert(file->filename);
760
761 #if defined(AMIGA) || defined(__OS2__)
762    if (NULL == (fp = fopen(file->filename, "w")))
763 #else
764    if (NULL == (fp = fopen(file->filename, "wt")))
765 #endif /* def AMIGA */
766    {
767       return JB_ERR_FILE;
768    }
769
770    cur_line = file->lines;
771    while (cur_line != NULL)
772    {
773       if (cur_line->raw)
774       {
775          if (fputs(cur_line->raw, fp) < 0)
776          {
777             fclose(fp);
778             return JB_ERR_FILE;
779          }
780       }
781       else
782       {
783          if (cur_line->prefix)
784          {
785             if (fputs(cur_line->prefix, fp) < 0)
786             {
787                fclose(fp);
788                return JB_ERR_FILE;
789             }
790          }
791          if (cur_line->unprocessed)
792          {
793             /* This should be a single line - sanity check. */
794             assert(NULL == strchr(cur_line->unprocessed, '\r'));
795             assert(NULL == strchr(cur_line->unprocessed, '\n'));
796
797             if (NULL != strchr(cur_line->unprocessed, '#'))
798             {
799                /* Must quote '#' characters */
800                int numhash = 0;
801                int len;
802                char * src;
803                char * dest;
804                char * str;
805
806                /* Count number of # characters, so we know length of output string */
807                src = cur_line->unprocessed;
808                while (NULL != (src = strchr(src, '#')))
809                {
810                   numhash++;
811                   src++;
812                }
813                assert(numhash > 0);
814
815                /* Allocate new memory for string */
816                len = strlen(cur_line->unprocessed);
817                if (NULL == (str = malloc((size_t) len + 1 + numhash)))
818                {
819                   /* Uh oh, just trashed file! */
820                   fclose(fp);
821                   return JB_ERR_MEMORY;
822                }
823
824                /* Loop through string from end */
825                src  = cur_line->unprocessed + len;
826                dest = str + len + numhash;
827                for ( ; len >= 0; len--)
828                {
829                   if ((*dest-- = *src--) == '#')
830                   {
831                      *dest-- = '\\';
832                      numhash--;
833                      assert(numhash >= 0);
834                   }
835                }
836                assert(numhash == 0);
837                assert(src  + 1 == cur_line->unprocessed);
838                assert(dest + 1 == str);
839
840                if (fputs(str, fp) < 0)
841                {
842                   free(str);
843                   fclose(fp);
844                   return JB_ERR_FILE;
845                }
846
847                free(str);
848             }
849             else
850             {
851                /* Can write without quoting '#' characters. */
852                if (fputs(cur_line->unprocessed, fp) < 0)
853                {
854                   fclose(fp);
855                   return JB_ERR_FILE;
856                }
857             }
858             if (fputs(NEWLINE(file->newline), fp) < 0)
859             {
860                fclose(fp);
861                return JB_ERR_FILE;
862             }
863          }
864          else
865          {
866             /* FIXME: Write data from file->data->whatever */
867             assert(0);
868          }
869       }
870       cur_line = cur_line->next;
871    }
872
873    fclose(fp);
874
875
876    /* Update the version stamp in the file structure, since we just
877     * wrote to the file & changed it's date.
878     */
879    if (stat(file->filename, statbuf) < 0)
880    {
881       /* Error, probably file not found. */
882       return JB_ERR_FILE;
883    }
884    file->version = (unsigned)statbuf->st_mtime;
885
886    /* Correct file->version_str */
887    freez(file->version_str);
888    snprintf(version_buf, 22, "%u", file->version);
889    version_buf[21] = '\0';
890    file->version_str = strdup(version_buf);
891    if (version_buf == NULL)
892    {
893       return JB_ERR_MEMORY;
894    }
895
896    return JB_ERR_OK;
897 }
898
899
900 /*********************************************************************
901  *
902  * Function    :  edit_free_file
903  *
904  * Description :  Free a complete file in memory.
905  *
906  * Parameters  :
907  *          1  :  file = Data structure to free.
908  *
909  * Returns     :  N/A
910  *
911  *********************************************************************/
912 void edit_free_file(struct editable_file * file)
913 {
914    if (!file)
915    {
916       /* Silently ignore NULL pointer */
917       return;
918    }
919
920    edit_free_file_lines(file->lines);
921    freez(file->filename);
922    freez(file->identifier);
923    freez(file->version_str);
924    file->version = 0;
925    file->parse_error_text = NULL; /* Statically allocated */
926    file->parse_error = NULL;
927
928    free(file);
929 }
930
931
932 /*********************************************************************
933  *
934  * Function    :  edit_free_file
935  *
936  * Description :  Free an entire linked list of file lines.
937  *
938  * Parameters  :
939  *          1  :  first_line = Data structure to free.
940  *
941  * Returns     :  N/A
942  *
943  *********************************************************************/
944 static void edit_free_file_lines(struct file_line * first_line)
945 {
946    struct file_line * next_line;
947
948    while (first_line != NULL)
949    {
950       next_line = first_line->next;
951       first_line->next = NULL;
952       freez(first_line->raw);
953       freez(first_line->prefix);
954       freez(first_line->unprocessed);
955       switch(first_line->type)
956       {
957          case 0: /* special case if memory zeroed */
958          case FILE_LINE_UNPROCESSED:
959          case FILE_LINE_BLANK:
960          case FILE_LINE_ALIAS_HEADER:
961          case FILE_LINE_SETTINGS_HEADER:
962          case FILE_LINE_DESCRIPTION_HEADER:
963          case FILE_LINE_DESCRIPTION_ENTRY:
964          case FILE_LINE_ALIAS_ENTRY:
965          case FILE_LINE_URL:
966             /* No data is stored for these */
967             break;
968
969          case FILE_LINE_ACTION:
970             free_action(first_line->data.action);
971             break;
972
973          case FILE_LINE_SETTINGS_ENTRY:
974             freez(first_line->data.setting.name);
975             freez(first_line->data.setting.svalue);
976             break;
977          default:
978             /* Should never happen */
979             assert(0);
980             break;
981       }
982       first_line->type = 0; /* paranoia */
983       free(first_line);
984       first_line = next_line;
985    }
986 }
987
988
989 /*********************************************************************
990  *
991  * Function    :  match_actions_file_header_line
992  *
993  * Description :  Match an actions file {{header}} line
994  *
995  * Parameters  :
996  *          1  :  line = String from file
997  *          2  :  name = Header to match against
998  *
999  * Returns     :  0 iff they match.
1000  *
1001  *********************************************************************/
1002 static int match_actions_file_header_line(const char * line, const char * name)
1003 {
1004    size_t len;
1005
1006    assert(line);
1007    assert(name);
1008
1009    /* Look for "{{" */
1010    if ((line[0] != '{') || (line[1] != '{'))
1011    {
1012       return 1;
1013    }
1014    line += 2;
1015
1016    /* Look for optional whitespace */
1017    while ( (*line == ' ') || (*line == '\t') )
1018    {
1019       line++;
1020    }
1021
1022    /* Look for the specified name (case-insensitive) */
1023    len = strlen(name);
1024    if (0 != strncmpic(line, name, len))
1025    {
1026       return 1;
1027    }
1028    line += len;
1029
1030    /* Look for optional whitespace */
1031    while ( (*line == ' ') || (*line == '\t') )
1032    {
1033       line++;
1034    }
1035
1036    /* Look for "}}" and end of string*/
1037    if ((line[0] != '}') || (line[1] != '}') || (line[2] != '\0'))
1038    {
1039       return 1;
1040    }
1041
1042    /* It matched!! */
1043    return 0;
1044 }
1045
1046
1047 /*********************************************************************
1048  *
1049  * Function    :  match_actions_file_header_line
1050  *
1051  * Description :  Match an actions file {{header}} line
1052  *
1053  * Parameters  :
1054  *          1  :  line = String from file.  Must not start with
1055  *                       whitespace (else infinite loop!)
1056  *          2  :  name = Destination for name
1057  *          2  :  name = Destination for value
1058  *
1059  * Returns     :  JB_ERR_OK     on success
1060  *                JB_ERR_MEMORY on out-of-memory
1061  *                JB_ERR_PARSE  if there's no "=" sign, or if there's
1062  *                              nothing before the "=" sign (but empty
1063  *                              values *after* the "=" sign are legal).
1064  *
1065  *********************************************************************/
1066 static jb_err split_line_on_equals(const char * line, char ** pname, char ** pvalue)
1067 {
1068    const char * name_end;
1069    const char * value_start;
1070    size_t name_len;
1071
1072    assert(line);
1073    assert(pname);
1074    assert(pvalue);
1075    assert(*line != ' ');
1076    assert(*line != '\t');
1077
1078    *pname = NULL;
1079    *pvalue = NULL;
1080
1081    value_start = strchr(line, '=');
1082    if ((value_start == NULL) || (value_start == line))
1083    {
1084       return JB_ERR_PARSE;
1085    }
1086
1087    name_end = value_start - 1;
1088
1089    /* Eat any whitespace before the '=' */
1090    while ((*name_end == ' ') || (*name_end == '\t'))
1091    {
1092       /*
1093        * we already know we must have at least 1 non-ws char
1094        * at start of buf - no need to check
1095        */
1096       name_end--;
1097    }
1098
1099    name_len = name_end - line + 1; /* Length excluding \0 */
1100    if (NULL == (*pname = (char *) malloc(name_len + 1)))
1101    {
1102       return JB_ERR_MEMORY;
1103    }
1104    strncpy(*pname, line, name_len);
1105    (*pname)[name_len] = '\0';
1106
1107    /* Eat any the whitespace after the '=' */
1108    value_start++;
1109    while ((*value_start == ' ') || (*value_start == '\t'))
1110    {
1111       value_start++;
1112    }
1113
1114    if (NULL == (*pvalue = strdup(value_start)))
1115    {
1116       free(*pname);
1117       *pname = NULL;
1118       return JB_ERR_MEMORY;
1119    }
1120
1121    return JB_ERR_OK;
1122 }
1123
1124
1125 /*********************************************************************
1126  *
1127  * Function    :  edit_parse_actions_file
1128  *
1129  * Description :  Parse an actions file in memory.
1130  *
1131  *                Passed linked list must have the "data" member
1132  *                zeroed, and must contain valid "next" and
1133  *                "unprocessed" fields.  The "raw" and "prefix"
1134  *                fields are ignored, and "type" is just overwritten.
1135  *
1136  *                Note that on error the file may have been
1137  *                partially parsed.
1138  *
1139  * Parameters  :
1140  *          1  :  file = Actions file to be parsed in-place.
1141  *
1142  * Returns     :  JB_ERR_OK     on success
1143  *                JB_ERR_MEMORY on out-of-memory
1144  *                JB_ERR_PARSE  on error
1145  *
1146  *********************************************************************/
1147 jb_err edit_parse_actions_file(struct editable_file * file)
1148 {
1149    struct file_line * cur_line;
1150    size_t len;
1151    const char * text; /* Text from a line */
1152    char * name;  /* For lines of the form name=value */
1153    char * value; /* For lines of the form name=value */
1154    struct action_alias * alias_list = NULL;
1155    jb_err err = JB_ERR_OK;
1156
1157    /* alias_list contains the aliases defined in this file.
1158     * It might be better to use the "file_line.data" fields
1159     * in the relavent places instead.
1160     */
1161
1162    cur_line = file->lines;
1163
1164    /* A note about blank line support: Blank lines should only
1165     * ever occur as the last line in the file.  This function
1166     * is more forgiving than that - FILE_LINE_BLANK can occur
1167     * anywhere.
1168     */
1169
1170    /* Skip leading blanks.  Should only happen if file is
1171     * empty (which is valid, but pointless).
1172     */
1173    while ( (cur_line != NULL)
1174         && (cur_line->unprocessed[0] == '\0') )
1175    {
1176       /* Blank line */
1177       cur_line->type = FILE_LINE_BLANK;
1178       cur_line = cur_line->next;
1179    }
1180
1181    if ( (cur_line != NULL)
1182      && (cur_line->unprocessed[0] != '{') )
1183    {
1184       /* File doesn't start with a header */
1185       file->parse_error = cur_line;
1186       file->parse_error_text = "First (non-comment) line of the file must contain a header.";
1187       return JB_ERR_PARSE;
1188    }
1189
1190    if ( (cur_line != NULL) && (0 ==
1191       match_actions_file_header_line(cur_line->unprocessed, "settings") ) )
1192    {
1193       cur_line->type = FILE_LINE_SETTINGS_HEADER;
1194
1195       cur_line = cur_line->next;
1196       while ((cur_line != NULL) && (cur_line->unprocessed[0] != '{'))
1197       {
1198          if (cur_line->unprocessed[0])
1199          {
1200             cur_line->type = FILE_LINE_SETTINGS_ENTRY;
1201
1202             err = split_line_on_equals(cur_line->unprocessed,
1203                      &cur_line->data.setting.name,
1204                      &cur_line->data.setting.svalue);
1205             if (err == JB_ERR_MEMORY)
1206             {
1207                return err;
1208             }
1209             else if (err != JB_ERR_OK)
1210             {
1211                /* Line does not contain a name=value pair */
1212                file->parse_error = cur_line;
1213                file->parse_error_text = "Expected a name=value pair on this {{description}} line, but couldn't find one.";
1214                return JB_ERR_PARSE;
1215             }
1216          }
1217          else
1218          {
1219             cur_line->type = FILE_LINE_BLANK;
1220          }
1221          cur_line = cur_line->next;
1222       }
1223    }
1224
1225    if ( (cur_line != NULL) && (0 ==
1226       match_actions_file_header_line(cur_line->unprocessed, "description") ) )
1227    {
1228       cur_line->type = FILE_LINE_DESCRIPTION_HEADER;
1229
1230       cur_line = cur_line->next;
1231       while ((cur_line != NULL) && (cur_line->unprocessed[0] != '{'))
1232       {
1233          if (cur_line->unprocessed[0])
1234          {
1235             cur_line->type = FILE_LINE_DESCRIPTION_ENTRY;
1236          }
1237          else
1238          {
1239             cur_line->type = FILE_LINE_BLANK;
1240          }
1241          cur_line = cur_line->next;
1242       }
1243    }
1244
1245    if ( (cur_line != NULL) && (0 ==
1246       match_actions_file_header_line(cur_line->unprocessed, "alias") ) )
1247    {
1248       cur_line->type = FILE_LINE_ALIAS_HEADER;
1249
1250       cur_line = cur_line->next;
1251       while ((cur_line != NULL) && (cur_line->unprocessed[0] != '{'))
1252       {
1253          if (cur_line->unprocessed[0])
1254          {
1255             /* define an alias */
1256             struct action_alias * new_alias;
1257
1258             cur_line->type = FILE_LINE_ALIAS_ENTRY;
1259
1260             err = split_line_on_equals(cur_line->unprocessed, &name, &value);
1261             if (err == JB_ERR_MEMORY)
1262             {
1263                return err;
1264             }
1265             else if (err != JB_ERR_OK)
1266             {
1267                /* Line does not contain a name=value pair */
1268                file->parse_error = cur_line;
1269                file->parse_error_text = "Expected a name=value pair on this {{alias}} line, but couldn't find one.";
1270                return JB_ERR_PARSE;
1271             }
1272
1273             if ((new_alias = zalloc(sizeof(*new_alias))) == NULL)
1274             {
1275                /* Out of memory */
1276                free(name);
1277                free(value);
1278                free_alias_list(alias_list);
1279                return JB_ERR_MEMORY;
1280             }
1281
1282             err = get_actions(value, alias_list, new_alias->action);
1283             if (err)
1284             {
1285                /* Invalid action or out of memory */
1286                free(name);
1287                free(value);
1288                free(new_alias);
1289                free_alias_list(alias_list);
1290                if (err == JB_ERR_MEMORY)
1291                {
1292                   return err;
1293                }
1294                else
1295                {
1296                   /* Line does not contain a name=value pair */
1297                   file->parse_error = cur_line;
1298                   file->parse_error_text = "This alias does not specify a valid set of actions.";
1299                   return JB_ERR_PARSE;
1300                }
1301             }
1302
1303             free(value);
1304
1305             new_alias->name = name;
1306
1307             /* add to list */
1308             new_alias->next = alias_list;
1309             alias_list = new_alias;
1310          }
1311          else
1312          {
1313             cur_line->type = FILE_LINE_BLANK;
1314          }
1315          cur_line = cur_line->next;
1316       }
1317    }
1318
1319    /* Header done, process the main part of the file */
1320    while (cur_line != NULL)
1321    {
1322       /* At this point, (cur_line->unprocessed[0] == '{') */
1323       assert(cur_line->unprocessed[0] == '{');
1324       text = cur_line->unprocessed + 1;
1325       len = strlen(text) - 1;
1326       if (text[len] != '}')
1327       {
1328          /* No closing } on header */
1329          free_alias_list(alias_list);
1330          file->parse_error = cur_line;
1331          file->parse_error_text = "Headers starting with '{' must have a "
1332             "closing bracket ('}').  Headers starting with two brackets ('{{') "
1333             "must close with two brackets ('}}').";
1334          return JB_ERR_PARSE;
1335       }
1336
1337       if (text[0] == '{')
1338       {
1339          /* An invalid {{ header.  */
1340          free_alias_list(alias_list);
1341          file->parse_error = cur_line;
1342          file->parse_error_text = "Unknown or unexpected two-bracket header.  "
1343             "Please remember that the system (two-bracket) headers must "
1344             "appear in the order {{settings}}, {{description}}, {{alias}}, "
1345             "and must appear before any actions (one-bracket) headers.  "
1346             "Also note that system headers may not be repeated.";
1347          return JB_ERR_PARSE;
1348       }
1349
1350       while ( (*text == ' ') || (*text == '\t') )
1351       {
1352          text++;
1353          len--;
1354       }
1355       while ( (len > 0)
1356            && ( (text[len - 1] == ' ')
1357              || (text[len - 1] == '\t') ) )
1358       {
1359          len--;
1360       }
1361
1362       cur_line->type = FILE_LINE_ACTION;
1363
1364       /* Remove {} and make copy */
1365       if (NULL == (value = (char *) malloc(len + 1)))
1366       {
1367          /* Out of memory */
1368          free_alias_list(alias_list);
1369          return JB_ERR_MEMORY;
1370       }
1371       strncpy(value, text, len);
1372       value[len] = '\0';
1373
1374       /* Get actions */
1375       err = get_actions(value, alias_list, cur_line->data.action);
1376       if (err)
1377       {
1378          /* Invalid action or out of memory */
1379          free(value);
1380          free_alias_list(alias_list);
1381          if (err == JB_ERR_MEMORY)
1382          {
1383             return err;
1384          }
1385          else
1386          {
1387             /* Line does not contain a name=value pair */
1388             file->parse_error = cur_line;
1389             file->parse_error_text = "This header does not specify a valid set of actions.";
1390             return JB_ERR_PARSE;
1391          }
1392       }
1393
1394       /* Done with string - it was clobbered anyway */
1395       free(value);
1396
1397       /* Process next line */
1398       cur_line = cur_line->next;
1399
1400       /* Loop processing URL patterns */
1401       while ((cur_line != NULL) && (cur_line->unprocessed[0] != '{'))
1402       {
1403          if (cur_line->unprocessed[0])
1404          {
1405             /* Could parse URL here, but this isn't currently needed */
1406
1407             cur_line->type = FILE_LINE_URL;
1408          }
1409          else
1410          {
1411             cur_line->type = FILE_LINE_BLANK;
1412          }
1413          cur_line = cur_line->next;
1414       }
1415    } /* End main while(cur_line != NULL) loop */
1416
1417    free_alias_list(alias_list);
1418
1419    return JB_ERR_OK;
1420 }
1421
1422
1423 /*********************************************************************
1424  *
1425  * Function    :  edit_read_file_lines
1426  *
1427  * Description :  Read all the lines of a file into memory.
1428  *                Handles whitespace, comments and line continuation.
1429  *
1430  * Parameters  :
1431  *          1  :  fp = File to read from.  On return, this will be
1432  *                     at EOF but it will not have been closed.
1433  *          2  :  pfile = Destination for a linked list of file_lines.
1434  *                        Will be set to NULL on error.
1435  *
1436  * Returns     :  JB_ERR_OK     on success
1437  *                JB_ERR_MEMORY on out-of-memory
1438  *
1439  *********************************************************************/
1440 jb_err edit_read_file_lines(FILE *fp, struct file_line ** pfile, int *newline)
1441 {
1442    struct file_line * first_line; /* Keep for return value or to free */
1443    struct file_line * cur_line;   /* Current line */
1444    struct file_line * prev_line;  /* Entry with prev_line->next = cur_line */
1445    jb_err rval;
1446
1447    assert(fp);
1448    assert(pfile);
1449
1450    *pfile = NULL;
1451
1452    cur_line = first_line = zalloc(sizeof(struct file_line));
1453    if (cur_line == NULL)
1454    {
1455       return JB_ERR_MEMORY;
1456    }
1457
1458    cur_line->type = FILE_LINE_UNPROCESSED;
1459
1460    rval = edit_read_line(fp, &cur_line->raw, &cur_line->prefix, &cur_line->unprocessed, newline, NULL);
1461    if (rval)
1462    {
1463       /* Out of memory or empty file. */
1464       /* Note that empty file is not an error we propogate up */
1465       free(cur_line);
1466       return ((rval == JB_ERR_FILE) ? JB_ERR_OK : rval);
1467    }
1468
1469    do
1470    {
1471       prev_line = cur_line;
1472       cur_line = prev_line->next = zalloc(sizeof(struct file_line));
1473       if (cur_line == NULL)
1474       {
1475          /* Out of memory */
1476          edit_free_file_lines(first_line);
1477          return JB_ERR_MEMORY;
1478       }
1479
1480       cur_line->type = FILE_LINE_UNPROCESSED;
1481
1482       rval = edit_read_line(fp, &cur_line->raw, &cur_line->prefix, &cur_line->unprocessed, newline, NULL);
1483       if ((rval != JB_ERR_OK) && (rval != JB_ERR_FILE))
1484       {
1485          /* Out of memory */
1486          edit_free_file_lines(first_line);
1487          return JB_ERR_MEMORY;
1488       }
1489
1490    }
1491    while (rval != JB_ERR_FILE);
1492
1493    /* EOF */
1494
1495    /* We allocated one too many - free it */
1496    prev_line->next = NULL;
1497    free(cur_line);
1498
1499    *pfile = first_line;
1500    return JB_ERR_OK;
1501 }
1502
1503
1504 /*********************************************************************
1505  *
1506  * Function    :  edit_read_file
1507  *
1508  * Description :  Read a complete file into memory.
1509  *                Handles CGI parameter parsing.  If requested, also
1510  *                checks the file's modification timestamp.
1511  *
1512  * Parameters  :
1513  *          1  :  csp = Current client state (buffers, headers, etc...)
1514  *          2  :  parameters = map of cgi parameters.
1515  *          3  :  require_version = true to check "ver" parameter.
1516  *          4  :  suffix = File extension, e.g. ".action".
1517  *          5  :  pfile = Destination for the file.  Will be set
1518  *                        to NULL on error.
1519  *
1520  * CGI Parameters :
1521  *    filename :  The name of the file to read, without the
1522  *                path or ".action" extension.
1523  *         ver :  (Only if require_version is nonzero)
1524  *                Timestamp of the actions file.  If wrong, this
1525  *                function fails with JB_ERR_MODIFIED.
1526  *
1527  * Returns     :  JB_ERR_OK     on success
1528  *                JB_ERR_MEMORY on out-of-memory
1529  *                JB_ERR_CGI_PARAMS if "filename" was not specified
1530  *                                  or is not valid.
1531  *                JB_ERR_FILE   if the file cannot be opened or
1532  *                              contains no data
1533  *                JB_ERR_MODIFIED if version checking was requested and
1534  *                                failed - the file was modified outside
1535  *                                of this CGI editor instance.
1536  *
1537  *********************************************************************/
1538 jb_err edit_read_file(struct client_state *csp,
1539                       const struct map *parameters,
1540                       int require_version,
1541                       const char *suffix,
1542                       struct editable_file **pfile)
1543 {
1544    struct file_line * lines;
1545    FILE * fp;
1546    jb_err err;
1547    char * filename;
1548    const char * identifier;
1549    struct editable_file * file;
1550    unsigned version = 0;
1551    struct stat statbuf[1];
1552    char version_buf[22];
1553    int newline = NEWLINE_UNKNOWN;
1554
1555    assert(csp);
1556    assert(parameters);
1557    assert(pfile);
1558
1559    *pfile = NULL;
1560
1561    err = get_file_name_param(csp, parameters, "f", suffix,
1562                              &filename, &identifier);
1563    if (err)
1564    {
1565       return err;
1566    }
1567
1568    if (stat(filename, statbuf) < 0)
1569    {
1570       /* Error, probably file not found. */
1571       free(filename);
1572       return JB_ERR_FILE;
1573    }
1574    version = (unsigned) statbuf->st_mtime;
1575
1576    if (require_version)
1577    {
1578       unsigned specified_version;
1579       err = get_number_param(csp, parameters, "v", &specified_version);
1580       if (err)
1581       {
1582          free(filename);
1583          return err;
1584       }
1585
1586       if (version != specified_version)
1587       {
1588          return JB_ERR_MODIFIED;
1589       }
1590    }
1591
1592 #if defined(AMIGA) || defined(__OS2__)
1593    if (NULL == (fp = fopen(filename,"r")))
1594 #else
1595    if (NULL == (fp = fopen(filename,"rt")))
1596 #endif /* def AMIGA */
1597    {
1598       free(filename);
1599       return JB_ERR_FILE;
1600    }
1601
1602    err = edit_read_file_lines(fp, &lines, &newline);
1603
1604    fclose(fp);
1605
1606    if (err)
1607    {
1608       free(filename);
1609       return err;
1610    }
1611
1612    file = (struct editable_file *) zalloc(sizeof(*file));
1613    if (err)
1614    {
1615       free(filename);
1616       edit_free_file_lines(lines);
1617       return err;
1618    }
1619
1620    file->lines = lines;
1621    file->newline = newline;
1622    file->filename = filename;
1623    file->version = version;
1624    file->identifier = url_encode(identifier);
1625
1626    if (file->identifier == NULL)
1627    {
1628       edit_free_file(file);
1629       return JB_ERR_MEMORY;
1630    }
1631
1632    /* Correct file->version_str */
1633    freez(file->version_str);
1634    snprintf(version_buf, 22, "%u", file->version);
1635    version_buf[21] = '\0';
1636    file->version_str = strdup(version_buf);
1637    if (version_buf == NULL)
1638    {
1639       edit_free_file(file);
1640       return JB_ERR_MEMORY;
1641    }
1642
1643    *pfile = file;
1644    return JB_ERR_OK;
1645 }
1646
1647
1648 /*********************************************************************
1649  *
1650  * Function    :  edit_read_actions_file
1651  *
1652  * Description :  Read a complete actions file into memory.
1653  *                Handles CGI parameter parsing.  If requested, also
1654  *                checks the file's modification timestamp.
1655  *
1656  *                If this function detects an error in the categories
1657  *                JB_ERR_FILE, JB_ERR_MODIFIED, or JB_ERR_PARSE,
1658  *                then it handles it by filling in the specified
1659  *                response structure and returning JB_ERR_FILE.
1660  *
1661  * Parameters  :
1662  *          1  :  csp = Current client state (buffers, headers, etc...)
1663  *          2  :  rsp = HTTP response.  Only filled in on error.
1664  *          2  :  parameters = map of cgi parameters.
1665  *          3  :  require_version = true to check "ver" parameter.
1666  *          4  :  pfile = Destination for the file.  Will be set
1667  *                        to NULL on error.
1668  *
1669  * CGI Parameters :
1670  *    filename :  The name of the actions file to read, without the
1671  *                path or ".action" extension.
1672  *         ver :  (Only if require_version is nonzero)
1673  *                Timestamp of the actions file.  If wrong, this
1674  *                function fails with JB_ERR_MODIFIED.
1675  *
1676  * Returns     :  JB_ERR_OK     on success
1677  *                JB_ERR_MEMORY on out-of-memory
1678  *                JB_ERR_CGI_PARAMS if "filename" was not specified
1679  *                                  or is not valid.
1680  *                JB_ERR_FILE  if the file does not contain valid data,
1681  *                             or if file cannot be opened or
1682  *                             contains no data, or if version
1683  *                             checking was requested and failed.
1684  *
1685  *********************************************************************/
1686 jb_err edit_read_actions_file(struct client_state *csp,
1687                               struct http_response *rsp,
1688                               const struct map *parameters,
1689                               int require_version,
1690                               struct editable_file **pfile)
1691 {
1692    jb_err err;
1693    struct editable_file *file;
1694
1695    assert(csp);
1696    assert(parameters);
1697    assert(pfile);
1698
1699    *pfile = NULL;
1700
1701    err = edit_read_file(csp, parameters, require_version, ".action", &file);
1702    if (err)
1703    {
1704       /* Try to handle if possible */
1705       if (err == JB_ERR_FILE)
1706       {
1707          err = cgi_error_file(csp, rsp, lookup(parameters, "f"));
1708       }
1709       else if (err == JB_ERR_MODIFIED)
1710       {
1711          err = cgi_error_modified(csp, rsp, lookup(parameters, "f"));
1712       }
1713       if (err == JB_ERR_OK)
1714       {
1715          /*
1716           * Signal to higher-level CGI code that there was a problem but we
1717           * handled it, they should just return JB_ERR_OK.
1718           */
1719          err = JB_ERR_FILE;
1720       }
1721       return err;
1722    }
1723
1724    err = edit_parse_actions_file(file);
1725    if (err)
1726    {
1727       if (err == JB_ERR_PARSE)
1728       {
1729          err = cgi_error_parse(csp, rsp, file);
1730          if (err == JB_ERR_OK)
1731          {
1732             /*
1733              * Signal to higher-level CGI code that there was a problem but we
1734              * handled it, they should just return JB_ERR_OK.
1735              */
1736             err = JB_ERR_FILE;
1737          }
1738       }
1739       edit_free_file(file);
1740       return err;
1741    }
1742
1743    *pfile = file;
1744    return JB_ERR_OK;
1745 }
1746
1747
1748 /*********************************************************************
1749  *
1750  * Function    :  get_file_name_param
1751  *
1752  * Description :  Get the name of the file to edit from the parameters
1753  *                passed to a CGI function.  This function handles
1754  *                security checks such as blocking urls containing
1755  *                "/" or ".", prepending the config file directory,
1756  *                and adding the specified suffix.
1757  *
1758  *                (This is an essential security check, otherwise
1759  *                users may be able to pass "../../../etc/passwd"
1760  *                and overwrite the password file [linux], "prn:"
1761  *                and print random data [Windows], etc...)
1762  *
1763  *                This function only allows filenames contining the
1764  *                characters '-', '_', 'A'-'Z', 'a'-'z', and '0'-'9'.
1765  *                That's probably too restrictive but at least it's
1766  *                secure.
1767  *
1768  * Parameters  :
1769  *          1  :  csp = Current client state (buffers, headers, etc...)
1770  *          2  :  parameters = map of cgi parameters
1771  *          3  :  param_name = The name of the parameter to read
1772  *          4  :  suffix = File extension, e.g. ".actions"
1773  *          5  :  pfilename = destination for full filename.  Caller
1774  *                free()s.  Set to NULL on error.
1775  *          6  :  pparam = destination for partial filename,
1776  *                suitable for use in another URL.  Allocated as part
1777  *                of the map "parameters", so don't free it.
1778  *                Set to NULL if not specified.
1779  *
1780  * Returns     :  JB_ERR_OK         on success
1781  *                JB_ERR_MEMORY     on out-of-memory
1782  *                JB_ERR_CGI_PARAMS if "filename" was not specified
1783  *                                  or is not valid.
1784  *
1785  *********************************************************************/
1786 static jb_err get_file_name_param(struct client_state *csp,
1787                                   const struct map *parameters,
1788                                   const char *param_name,
1789                                   const char *suffix,
1790                                   char **pfilename,
1791                                   const char **pparam)
1792 {
1793    const char *param;
1794    const char *s;
1795 #if 0 /* Patch to make 3.0.0 work properly. */
1796    char *name;
1797 #endif /* 0 - Patch to make 3.0.0 work properly. */
1798    char *fullpath;
1799    char ch;
1800    int len;
1801
1802    assert(csp);
1803    assert(parameters);
1804    assert(suffix);
1805    assert(pfilename);
1806    assert(pparam);
1807
1808    *pfilename = NULL;
1809    *pparam = NULL;
1810
1811    param = lookup(parameters, param_name);
1812    if (!*param)
1813    {
1814       return JB_ERR_CGI_PARAMS;
1815    }
1816
1817    *pparam = param;
1818
1819    len = strlen(param);
1820    if (len >= FILENAME_MAX)
1821    {
1822       /* Too long. */
1823       return JB_ERR_CGI_PARAMS;
1824    }
1825
1826    /* Check every character to see if it's legal */
1827    s = param;
1828    while ((ch = *s++) != '\0')
1829    {
1830       if ( ((ch < 'A') || (ch > 'Z'))
1831         && ((ch < 'a') || (ch > 'z'))
1832         && ((ch < '0') || (ch > '9'))
1833         && (ch != '-')
1834         && (ch != '_') )
1835       {
1836          /* Probable hack attempt. */
1837          return JB_ERR_CGI_PARAMS;
1838       }
1839    }
1840
1841    /*
1842     * FIXME Following is a hack to make 3.0.0 work properly.
1843     * Change "#if 0" --> "#if 1" below when we have modular action
1844     * files.
1845     *    -- Jon
1846     */
1847 #if 0 /* Patch to make 3.0.0 work properly. */
1848    /* Append extension */
1849    name = malloc(len + strlen(suffix) + 1);
1850    if (name == NULL)
1851    {
1852       return JB_ERR_MEMORY;
1853    }
1854    strcpy(name, param);
1855    strcpy(name + len, suffix);
1856
1857    /* Prepend path */
1858    fullpath = make_path(csp->config->confdir, name);
1859    free(name);
1860 #else /* 1 - Patch to make 3.0.0 work properly. */
1861    if ((csp->actions_list == NULL)
1862     || (csp->actions_list->filename == NULL))
1863    {
1864       return JB_ERR_CGI_PARAMS;
1865    }
1866
1867    fullpath = ( (csp->actions_list && csp->actions_list->filename)
1868              ? strdup(csp->actions_list->filename) : NULL);
1869 #endif /* 1 - Patch to make 3.0.0 work properly. */
1870    if (fullpath == NULL)
1871    {
1872       return JB_ERR_MEMORY;
1873    }
1874
1875    /* Success */
1876    *pfilename = fullpath;
1877
1878    return JB_ERR_OK;
1879 }
1880
1881
1882 /*********************************************************************
1883  *
1884  * Function    :  get_char_param
1885  *
1886  * Description :  Get a single-character parameter passed to a CGI
1887  *                function.
1888  *
1889  * Parameters  :
1890  *          1  :  parameters = map of cgi parameters
1891  *          2  :  param_name = The name of the parameter to read
1892  *
1893  * Returns     :  Uppercase character on success, '\0' on error.
1894  *
1895  *********************************************************************/
1896 static char get_char_param(const struct map *parameters,
1897                            const char *param_name)
1898 {
1899    char ch;
1900
1901    assert(parameters);
1902    assert(param_name);
1903
1904    ch = *(lookup(parameters, param_name));
1905    if ((ch >= 'a') && (ch <= 'z'))
1906    {
1907       ch = ch - 'a' + 'A';
1908    }
1909
1910    return ch;
1911 }
1912
1913
1914 /*********************************************************************
1915  *
1916  * Function    :  get_string_param
1917  *
1918  * Description :  Get a string paramater, to be used as an
1919  *                ACTION_STRING or ACTION_MULTI paramater.
1920  *                Validates the input to prevent stupid/malicious
1921  *                users from corrupting their action file.
1922  *
1923  * Parameters  :
1924  *          1  :  parameters = map of cgi parameters
1925  *          2  :  param_name = The name of the parameter to read
1926  *          3  :  pparam = destination for paramater.  Allocated as
1927  *                part of the map "parameters", so don't free it.
1928  *                Set to NULL if not specified.
1929  *
1930  * Returns     :  JB_ERR_OK         on success, or if the paramater
1931  *                                  was not specified.
1932  *                JB_ERR_MEMORY     on out-of-memory.
1933  *                JB_ERR_CGI_PARAMS if the paramater is not valid.
1934  *
1935  *********************************************************************/
1936 static jb_err get_string_param(const struct map *parameters,
1937                                const char *param_name,
1938                                const char **pparam)
1939 {
1940    const char *param;
1941    const char *s;
1942    char ch;
1943
1944    assert(parameters);
1945    assert(param_name);
1946    assert(pparam);
1947
1948    *pparam = NULL;
1949
1950    param = lookup(parameters, param_name);
1951    if (!*param)
1952    {
1953       return JB_ERR_OK;
1954    }
1955
1956    if (strlen(param) >= CGI_ACTION_PARAM_LEN_MAX)
1957    {
1958       /*
1959        * Too long.
1960        *
1961        * Note that the length limit is arbitrary, it just seems
1962        * sensible to limit it to *something*.  There's no
1963        * technical reason for any limit at all.
1964        */
1965       return JB_ERR_CGI_PARAMS;
1966    }
1967
1968    /* Check every character to see if it's legal */
1969    s = param;
1970    while ((ch = *s++) != '\0')
1971    {
1972       if ( ((unsigned char)ch < (unsigned char)' ')
1973         || (ch == '}') )
1974       {
1975          /* Probable hack attempt, or user accidentally used '}'. */
1976          return JB_ERR_CGI_PARAMS;
1977       }
1978    }
1979
1980    /* Success */
1981    *pparam = param;
1982
1983    return JB_ERR_OK;
1984 }
1985
1986
1987 /*********************************************************************
1988  *
1989  * Function    :  get_number_param
1990  *
1991  * Description :  Get a non-negative integer from the parameters
1992  *                passed to a CGI function.
1993  *
1994  * Parameters  :
1995  *          1  :  csp = Current client state (buffers, headers, etc...)
1996  *          2  :  parameters = map of cgi parameters
1997  *          3  :  name = Name of CGI parameter to read
1998  *          4  :  pvalue = destination for value.
1999  *                         Set to -1 on error.
2000  *
2001  * Returns     :  JB_ERR_OK         on success
2002  *                JB_ERR_MEMORY     on out-of-memory
2003  *                JB_ERR_CGI_PARAMS if the parameter was not specified
2004  *                                  or is not valid.
2005  *
2006  *********************************************************************/
2007 static jb_err get_number_param(struct client_state *csp,
2008                                const struct map *parameters,
2009                                char *name,
2010                                unsigned *pvalue)
2011 {
2012    const char *param;
2013    char ch;
2014    unsigned value;
2015
2016    assert(csp);
2017    assert(parameters);
2018    assert(name);
2019    assert(pvalue);
2020
2021    *pvalue = 0; 
2022
2023    param = lookup(parameters, name);
2024    if (!*param)
2025    {
2026       return JB_ERR_CGI_PARAMS;
2027    }
2028
2029    /* We don't use atoi because I want to check this carefully... */
2030
2031    value = 0;
2032    while ((ch = *param++) != '\0')
2033    {
2034       if ((ch < '0') || (ch > '9'))
2035       {
2036          return JB_ERR_CGI_PARAMS;
2037       }
2038
2039       ch -= '0';
2040
2041       /* Note:
2042        *
2043        * <limits.h> defines UINT_MAX
2044        *
2045        * (UINT_MAX - ch) / 10 is the largest number that
2046        *     can be safely multiplied by 10 then have ch added.
2047        */
2048       if (value > ((UINT_MAX - (unsigned)ch) / 10U))
2049       {
2050          return JB_ERR_CGI_PARAMS;
2051       }
2052
2053       value = value * 10 + ch;
2054    }
2055
2056    /* Success */
2057    *pvalue = value;
2058
2059    return JB_ERR_OK;
2060
2061 }
2062
2063
2064 /*********************************************************************
2065  *
2066  * Function    :  get_url_spec_param
2067  *
2068  * Description :  Get a URL pattern from the parameters
2069  *                passed to a CGI function.  Removes leading/trailing
2070  *                spaces and validates it.
2071  *
2072  * Parameters  :
2073  *          1  :  csp = Current client state (buffers, headers, etc...)
2074  *          2  :  parameters = map of cgi parameters
2075  *          3  :  name = Name of CGI parameter to read
2076  *          4  :  pvalue = destination for value.  Will be malloc()'d.
2077  *                         Set to NULL on error.
2078  *
2079  * Returns     :  JB_ERR_OK         on success
2080  *                JB_ERR_MEMORY     on out-of-memory
2081  *                JB_ERR_CGI_PARAMS if the parameter was not specified
2082  *                                  or is not valid.
2083  *
2084  *********************************************************************/
2085 static jb_err get_url_spec_param(struct client_state *csp,
2086                                  const struct map *parameters,
2087                                  const char *name,
2088                                  char **pvalue)
2089 {
2090    const char *orig_param;
2091    char *param;
2092    char *s;
2093    struct url_spec compiled[1];
2094    jb_err err;
2095
2096    assert(csp);
2097    assert(parameters);
2098    assert(name);
2099    assert(pvalue);
2100
2101    *pvalue = NULL;
2102
2103    orig_param = lookup(parameters, name);
2104    if (!*orig_param)
2105    {
2106       return JB_ERR_CGI_PARAMS;
2107    }
2108
2109    /* Copy and trim whitespace */
2110    param = strdup(orig_param);
2111    if (param == NULL)
2112    {
2113       return JB_ERR_MEMORY;
2114    }
2115    chomp(param);
2116
2117    /* Must be non-empty, and can't allow 1st character to be '{' */
2118    if (param[0] == '\0' || param[0] == '{')
2119    {
2120       free(param);
2121       return JB_ERR_CGI_PARAMS;
2122    }
2123
2124    /* Check for embedded newlines */
2125    for (s = param; *s != '\0'; s++)
2126    {
2127       if ((*s == '\r') || (*s == '\n'))
2128       {
2129          free(param);
2130          return JB_ERR_CGI_PARAMS;
2131       }
2132    }
2133
2134    /* Check that regex is valid */
2135    s = strdup(param);
2136    if (s == NULL)
2137    {
2138       free(param);
2139       return JB_ERR_MEMORY;
2140    }
2141    err = create_url_spec(compiled, s);
2142    free(s);
2143    if (err)
2144    {
2145       free(param);
2146       return (err == JB_ERR_MEMORY) ? JB_ERR_MEMORY : JB_ERR_CGI_PARAMS;
2147    }
2148    free_url_spec(compiled);
2149
2150    if (param[strlen(param) - 1] == '\\')
2151    {
2152       /*
2153        * Must protect trailing '\\' from becoming line continuation character.
2154        * Two methods: 1) If it's a domain only, add a trailing '/'.
2155        * 2) For path, add the do-nothing PCRE expression (?:) to the end
2156        */
2157       if (strchr(param, '/') == NULL)
2158       {
2159          err = string_append(&param, "/");
2160       }
2161       else
2162       {
2163          err = string_append(&param, "(?:)");
2164       }
2165       if (err)
2166       {
2167          return err;
2168       }
2169
2170       /* Check that the modified regex is valid */
2171       s = strdup(param);
2172       if (s == NULL)
2173       {
2174          free(param);
2175          return JB_ERR_MEMORY;
2176       }
2177       err = create_url_spec(compiled, s);
2178       free(s);
2179       if (err)
2180       {
2181          free(param);
2182          return (err == JB_ERR_MEMORY) ? JB_ERR_MEMORY : JB_ERR_CGI_PARAMS;
2183       }
2184       free_url_spec(compiled);
2185    }
2186
2187    *pvalue = param;
2188    return JB_ERR_OK;
2189 }
2190
2191 /*********************************************************************
2192  *
2193  * Function    :  map_radio
2194  *
2195  * Description :  Map a set of radio button values.  E.g. if you have
2196  *                3 radio buttons, declare them as:
2197  *                  <option type="radio" name="xyz" @xyz-a@>
2198  *                  <option type="radio" name="xyz" @xyz-b@>
2199  *                  <option type="radio" name="xyz" @xyz-c@>
2200  *                Then map one of the @xyz-?@ variables to "checked"
2201  *                and all the others to empty by calling:
2202  *                map_radio(exports, "xyz", "abc", sel)
2203  *                Where 'sel' is 'a', 'b', or 'c'.
2204  *
2205  * Parameters  :
2206  *          1  :  exports = Exports map to modify.
2207  *          2  :  optionname = name for map
2208  *          3  :  values = null-terminated list of values;
2209  *          4  :  value = Selected value.
2210  *
2211  * CGI Parameters : None
2212  *
2213  * Returns     :  JB_ERR_OK     on success
2214  *                JB_ERR_MEMORY on out-of-memory
2215  *
2216  *********************************************************************/
2217 static jb_err map_radio(struct map * exports,
2218                         const char * optionname,
2219                         const char * values,
2220                         int value)
2221 {
2222    size_t len;
2223    char * buf;
2224    char * p;
2225    char c;
2226
2227    assert(exports);
2228    assert(optionname);
2229    assert(values);
2230
2231    len = strlen(optionname);
2232    buf = malloc(len + 3);
2233    if (buf == NULL)
2234    {
2235       return JB_ERR_MEMORY;
2236    }
2237
2238    strcpy(buf, optionname);
2239    p = buf + len;
2240    *p++ = '-';
2241    p[1] = '\0';
2242
2243    while ((c = *values++) != '\0')
2244    {
2245       if (c != value)
2246       {
2247          *p = c;
2248          if (map(exports, buf, 1, "", 1))
2249          {
2250             return JB_ERR_MEMORY;
2251          }
2252       }
2253    }
2254
2255    *p = value;
2256    return map(exports, buf, 0, "checked", 1);
2257 }
2258
2259
2260 /*********************************************************************
2261  *
2262  * Function    :  cgi_error_modified
2263  *
2264  * Description :  CGI function that is called when a file is modified
2265  *                outside the CGI editor.
2266  *
2267  * Parameters  :
2268  *          1  :  csp = Current client state (buffers, headers, etc...)
2269  *          2  :  rsp = http_response data structure for output
2270  *          3  :  filename = The file that was modified.
2271  *
2272  * CGI Parameters : none
2273  *
2274  * Returns     :  JB_ERR_OK on success
2275  *                JB_ERR_MEMORY on out-of-memory error.
2276  *
2277  *********************************************************************/
2278 jb_err cgi_error_modified(struct client_state *csp,
2279                           struct http_response *rsp,
2280                           const char *filename)
2281 {
2282    struct map *exports;
2283    jb_err err;
2284
2285    assert(csp);
2286    assert(rsp);
2287    assert(filename);
2288
2289    if (NULL == (exports = default_exports(csp, NULL)))
2290    {
2291       return JB_ERR_MEMORY;
2292    }
2293
2294    err = map(exports, "f", 1, html_encode(filename), 0);
2295    if (err)
2296    {
2297       free_map(exports);
2298       return err;
2299    }
2300
2301    return template_fill_for_cgi(csp, "cgi-error-modified", exports, rsp);
2302 }
2303
2304
2305 /*********************************************************************
2306  *
2307  * Function    :  cgi_error_parse
2308  *
2309  * Description :  CGI function that is called when a file cannot
2310  *                be parsed by the CGI editor.
2311  *
2312  * Parameters  :
2313  *          1  :  csp = Current client state (buffers, headers, etc...)
2314  *          2  :  rsp = http_response data structure for output
2315  *          3  :  file = The file that was modified.
2316  *
2317  * CGI Parameters : none
2318  *
2319  * Returns     :  JB_ERR_OK on success
2320  *                JB_ERR_MEMORY on out-of-memory error.
2321  *
2322  *********************************************************************/
2323 jb_err cgi_error_parse(struct client_state *csp,
2324                        struct http_response *rsp,
2325                        struct editable_file *file)
2326 {
2327    struct map *exports;
2328    jb_err err;
2329    struct file_line *cur_line;
2330
2331    assert(csp);
2332    assert(rsp);
2333    assert(file);
2334
2335    if (NULL == (exports = default_exports(csp, NULL)))
2336    {
2337       return JB_ERR_MEMORY;
2338    }
2339
2340    err = map(exports, "f", 1, file->identifier, 1);
2341    if (!err) err = map(exports, "parse-error", 1, html_encode(file->parse_error_text), 0);
2342
2343    cur_line = file->parse_error;
2344    assert(cur_line);
2345
2346    if (!err) err = map(exports, "line-raw", 1, html_encode(cur_line->raw), 0);
2347    if (!err) err = map(exports, "line-data", 1, html_encode(cur_line->unprocessed), 0);
2348
2349    if (err)
2350    {
2351       free_map(exports);
2352       return err;
2353    }
2354
2355    return template_fill_for_cgi(csp, "cgi-error-parse", exports, rsp);
2356 }
2357
2358
2359 /*********************************************************************
2360  *
2361  * Function    :  cgi_error_file
2362  *
2363  * Description :  CGI function that is called when a file cannot be
2364  *                opened by the CGI editor.
2365  *
2366  * Parameters  :
2367  *          1  :  csp = Current client state (buffers, headers, etc...)
2368  *          2  :  rsp = http_response data structure for output
2369  *          3  :  filename = The file that was modified.
2370  *
2371  * CGI Parameters : none
2372  *
2373  * Returns     :  JB_ERR_OK on success
2374  *                JB_ERR_MEMORY on out-of-memory error.
2375  *
2376  *********************************************************************/
2377 jb_err cgi_error_file(struct client_state *csp,
2378                       struct http_response *rsp,
2379                       const char *filename)
2380 {
2381    struct map *exports;
2382    jb_err err;
2383
2384    assert(csp);
2385    assert(rsp);
2386    assert(filename);
2387
2388    if (NULL == (exports = default_exports(csp, NULL)))
2389    {
2390       return JB_ERR_MEMORY;
2391    }
2392
2393    err = map(exports, "f", 1, html_encode(filename), 0);
2394    if (err)
2395    {
2396       free_map(exports);
2397       return err;
2398    }
2399
2400    return template_fill_for_cgi(csp, "cgi-error-file", exports, rsp);
2401 }
2402
2403
2404 /*********************************************************************
2405  *
2406  * Function    :  cgi_error_bad_param
2407  *
2408  * Description :  CGI function that is called if the parameters
2409  *                (query string) for a CGI were wrong.
2410  *
2411  * Parameters  :
2412  *          1  :  csp = Current client state (buffers, headers, etc...)
2413  *          2  :  rsp = http_response data structure for output
2414  *
2415  * CGI Parameters : none
2416  *
2417  * Returns     :  JB_ERR_OK on success
2418  *                JB_ERR_MEMORY on out-of-memory error.
2419  *
2420  *********************************************************************/
2421 jb_err cgi_error_disabled(struct client_state *csp,
2422                           struct http_response *rsp)
2423 {
2424    struct map *exports;
2425
2426    assert(csp);
2427    assert(rsp);
2428
2429    if (NULL == (exports = default_exports(csp, NULL)))
2430    {
2431       return JB_ERR_MEMORY;
2432    }
2433
2434    return template_fill_for_cgi(csp, "cgi-error-disabled", exports, rsp);
2435 }
2436
2437
2438 /*********************************************************************
2439  *
2440  * Function    :  cgi_edit_actions
2441  *
2442  * Description :  CGI function that allows the user to choose which
2443  *                actions file to edit.
2444  *
2445  * Parameters  :
2446  *          1  :  csp = Current client state (buffers, headers, etc...)
2447  *          2  :  rsp = http_response data structure for output
2448  *          3  :  parameters = map of cgi parameters
2449  *
2450  * CGI Parameters : None
2451  *
2452  * Returns     :  JB_ERR_OK on success
2453  *                JB_ERR_MEMORY on out-of-memory error
2454  *
2455  *********************************************************************/
2456 jb_err cgi_edit_actions(struct client_state *csp,
2457                         struct http_response *rsp,
2458                         const struct map *parameters)
2459 {
2460
2461    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
2462    {
2463       return cgi_error_disabled(csp, rsp);
2464    }
2465
2466    /* FIXME: Incomplete */
2467    rsp->status = strdup("302 Local Redirect from Privoxy");
2468    if (rsp->status == NULL)
2469    {
2470       return JB_ERR_MEMORY;
2471    }
2472    if (enlist_unique_header(rsp->headers, "Location",
2473       CGI_PREFIX "edit-actions-list?f=default"))
2474    {
2475       free(rsp->status);
2476       rsp->status = NULL;
2477       return JB_ERR_MEMORY;
2478    }
2479
2480    return JB_ERR_OK;
2481 }
2482
2483
2484 /*********************************************************************
2485  *
2486  * Function    :  cgi_edit_actions_list
2487  *
2488  * Description :  CGI function that edits the actions list.
2489  *                FIXME: This function shouldn't FATAL ever.
2490  *                FIXME: This function doesn't check the retval of map()
2491  * Parameters  :
2492  *          1  :  csp = Current client state (buffers, headers, etc...)
2493  *          2  :  rsp = http_response data structure for output
2494  *          3  :  parameters = map of cgi parameters
2495  *
2496  * CGI Parameters : filename
2497  *
2498  * Returns     :  JB_ERR_OK     on success
2499  *                JB_ERR_MEMORY on out-of-memory
2500  *                JB_ERR_FILE   if the file cannot be opened or
2501  *                              contains no data
2502  *                JB_ERR_CGI_PARAMS if "filename" was not specified
2503  *                                  or is not valid.
2504  *
2505  *********************************************************************/
2506 jb_err cgi_edit_actions_list(struct client_state *csp,
2507                              struct http_response *rsp,
2508                              const struct map *parameters)
2509 {
2510    char * section_template;
2511    char * url_template;
2512    char * sections;
2513    char * urls;
2514    char buf[50];
2515    char * s;
2516    struct map * exports;
2517    struct map * section_exports;
2518    struct map * url_exports;
2519    struct editable_file * file;
2520    struct file_line * cur_line;
2521    unsigned line_number = 0;
2522    unsigned prev_section_line_number = ((unsigned) (-1));
2523    int url_1_2;
2524    jb_err err;
2525
2526    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
2527    {
2528       return cgi_error_disabled(csp, rsp);
2529    }
2530
2531    err = edit_read_actions_file(csp, rsp, parameters, 0, &file);
2532    if (err)
2533    {
2534       /* No filename specified, can't read file, or out of memory. */
2535       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
2536    }
2537
2538    if (NULL == (exports = default_exports(csp, NULL)))
2539    {
2540       edit_free_file(file);
2541       return JB_ERR_MEMORY;
2542    }
2543
2544    err = map(exports, "f", 1, file->identifier, 1);
2545    if (!err) err = map(exports, "v", 1, file->version_str, 1);
2546
2547    if (err)
2548    {
2549       edit_free_file(file);
2550       free_map(exports);
2551       return err;
2552    }
2553
2554    /* Should do all global exports above this point */
2555
2556    err = template_load(csp, &section_template, "edit-actions-list-section");
2557    if (err)
2558    {
2559       edit_free_file(file);
2560       free_map(exports);
2561       if (err == JB_ERR_FILE)
2562       {
2563          return cgi_error_no_template(csp, rsp, "edit-actions-list-section");
2564       }
2565       return err;
2566    }
2567
2568    err = template_load(csp, &url_template, "edit-actions-list-url");
2569    if (err)
2570    {
2571       free(section_template);
2572       edit_free_file(file);
2573       free_map(exports);
2574       if (err == JB_ERR_FILE)
2575       {
2576          return cgi_error_no_template(csp, rsp, "edit-actions-list-url");
2577       }
2578       return err;
2579    }
2580
2581    err = template_fill(&section_template, exports);
2582    if (err)
2583    {
2584       free(url_template);
2585       edit_free_file(file);
2586       free_map(exports);
2587       free(url_template);
2588       return err;
2589    }
2590
2591    err = template_fill(&url_template, exports);
2592    if (err)
2593    {
2594       free(section_template);
2595       edit_free_file(file);
2596       free_map(exports);
2597       return err;
2598    }
2599
2600    /* Find start of actions in file */
2601    cur_line = file->lines;
2602    line_number = 1;
2603    while ((cur_line != NULL) && (cur_line->type != FILE_LINE_ACTION))
2604    {
2605       cur_line = cur_line->next;
2606       line_number++;
2607    }
2608
2609    if (NULL == (sections = strdup("")))
2610    {
2611       free(section_template);
2612       free(url_template);
2613       edit_free_file(file);
2614       free_map(exports);
2615       return JB_ERR_MEMORY;
2616    }
2617
2618    while ((cur_line != NULL) && (cur_line->type == FILE_LINE_ACTION))
2619    {
2620       if (NULL == (section_exports = new_map()))
2621       {
2622          free(sections);
2623          free(section_template);
2624          free(url_template);
2625          edit_free_file(file);
2626          free_map(exports);
2627          return JB_ERR_MEMORY;
2628       }
2629
2630       snprintf(buf, 50, "%d", line_number);
2631       err = map(section_exports, "s", 1, buf, 1);
2632       if (!err) err = map(section_exports, "actions", 1,
2633                           actions_to_html(cur_line->data.action), 0);
2634
2635       if ( (!err)
2636         && (cur_line->next != NULL)
2637         && (cur_line->next->type == FILE_LINE_URL))
2638       {
2639          /* This section contains at least one URL, don't allow delete */
2640          err = map_block_killer(section_exports, "empty-section");
2641       }
2642       else
2643       {
2644          if (!err) err = map_block_keep(section_exports, "empty-section");
2645       }
2646
2647       if (prev_section_line_number != ((unsigned)(-1)))
2648       {
2649          /* Not last section */
2650          snprintf(buf, 50, "%d", prev_section_line_number);
2651          if (!err) err = map(section_exports, "s-prev", 1, buf, 1);
2652          if (!err) err = map_block_keep(section_exports, "s-prev-exists");
2653       }
2654       else
2655       {
2656          /* Last section */
2657          if (!err) err = map_block_killer(section_exports, "s-prev-exists");
2658       }
2659       prev_section_line_number = line_number;
2660
2661       if (err)
2662       {
2663          free(sections);
2664          free(section_template);
2665          free(url_template);
2666          edit_free_file(file);
2667          free_map(exports);
2668          free_map(section_exports);
2669          return err;
2670       }
2671
2672       /* Should do all section-specific exports above this point */
2673
2674       if (NULL == (urls = strdup("")))
2675       {
2676          free(sections);
2677          free(section_template);
2678          free(url_template);
2679          edit_free_file(file);
2680          free_map(exports);
2681          free_map(section_exports);
2682          return JB_ERR_MEMORY;
2683       }
2684
2685       url_1_2 = 2;
2686
2687       cur_line = cur_line->next;
2688       line_number++;
2689
2690       while ((cur_line != NULL) && (cur_line->type == FILE_LINE_URL))
2691       {
2692          if (NULL == (url_exports = new_map()))
2693          {
2694             free(urls);
2695             free(sections);
2696             free(section_template);
2697             free(url_template);
2698             edit_free_file(file);
2699             free_map(exports);
2700             free_map(section_exports);
2701             return JB_ERR_MEMORY;
2702          }
2703
2704          snprintf(buf, 50, "%d", line_number);
2705          err = map(url_exports, "p", 1, buf, 1);
2706
2707          snprintf(buf, 50, "%d", url_1_2);
2708          if (!err) err = map(url_exports, "url-1-2", 1, buf, 1);
2709
2710          if (!err) err = map(url_exports, "url-html", 1,
2711                              html_encode(cur_line->unprocessed), 0);
2712          if (!err) err = map(url_exports, "url", 1,
2713                              url_encode(cur_line->unprocessed), 0);
2714
2715          if (err)
2716          {
2717             free(urls);
2718             free(sections);
2719             free(section_template);
2720             free(url_template);
2721             edit_free_file(file);
2722             free_map(exports);
2723             free_map(section_exports);
2724             free_map(url_exports);
2725             return err;
2726          }
2727
2728          if (NULL == (s = strdup(url_template)))
2729          {
2730             free(urls);
2731             free(sections);
2732             free(section_template);
2733             free(url_template);
2734             edit_free_file(file);
2735             free_map(exports);
2736             free_map(section_exports);
2737             free_map(url_exports);
2738             return JB_ERR_MEMORY;
2739          }
2740
2741          err = template_fill(&s, section_exports);
2742          if (!err) err = template_fill(&s, url_exports);
2743          if (!err) err = string_append(&urls, s);
2744
2745          free_map(url_exports);
2746          freez(s);
2747
2748          if (err)
2749          {
2750             freez(urls);
2751             free(sections);
2752             free(section_template);
2753             free(url_template);
2754             edit_free_file(file);
2755             free_map(exports);
2756             free_map(section_exports);
2757             return err;
2758          }
2759
2760          url_1_2 = 3 - url_1_2;
2761
2762          cur_line = cur_line->next;
2763          line_number++;
2764       }
2765
2766       err = map(section_exports, "urls", 1, urls, 0);
2767
2768       /* Could also do section-specific exports here, but it wouldn't be as fast */
2769
2770       if ( (cur_line != NULL)
2771         && (cur_line->type == FILE_LINE_ACTION))
2772       {
2773          /* Not last section */
2774          snprintf(buf, 50, "%d", line_number);
2775          if (!err) err = map(section_exports, "s-next", 1, buf, 1);
2776          if (!err) err = map_block_keep(section_exports, "s-next-exists");
2777       }
2778       else
2779       {
2780          /* Last section */
2781          if (!err) err = map_block_killer(section_exports, "s-next-exists");
2782       }
2783
2784       if (err)
2785       {
2786          free(sections);
2787          free(section_template);
2788          free(url_template);
2789          edit_free_file(file);
2790          free_map(exports);
2791          free_map(section_exports);
2792          return err;
2793       }
2794
2795       if (NULL == (s = strdup(section_template)))
2796       {
2797          free(sections);
2798          free(section_template);
2799          free(url_template);
2800          edit_free_file(file);
2801          free_map(exports);
2802          free_map(section_exports);
2803          return JB_ERR_MEMORY;
2804       }
2805
2806       err = template_fill(&s, section_exports);
2807       if (!err) err = string_append(&sections, s);
2808
2809       freez(s);
2810       free_map(section_exports);
2811
2812       if (err)
2813       {
2814          freez(sections);
2815          free(section_template);
2816          free(url_template);
2817          edit_free_file(file);
2818          free_map(exports);
2819          return err;
2820       }
2821    }
2822
2823    edit_free_file(file);
2824    free(section_template);
2825    free(url_template);
2826
2827    err = map(exports, "sections", 1, sections, 0);
2828    if (err)
2829    {
2830       free_map(exports);
2831       return err;
2832    }
2833
2834    /* Could also do global exports here, but it wouldn't be as fast */
2835
2836    return template_fill_for_cgi(csp, "edit-actions-list", exports, rsp);
2837 }
2838
2839
2840 /*********************************************************************
2841  *
2842  * Function    :  cgi_edit_actions
2843  *
2844  * Description :  CGI function that edits the Actions list.
2845  *
2846  * Parameters  :
2847  *          1  :  csp = Current client state (buffers, headers, etc...)
2848  *          2  :  rsp = http_response data structure for output
2849  *          3  :  parameters = map of cgi parameters
2850  *
2851  * CGI Parameters : None
2852  *
2853  * Returns     :  JB_ERR_OK     on success
2854  *                JB_ERR_MEMORY on out-of-memory
2855  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
2856  *                                  specified or not valid.
2857  *
2858  *********************************************************************/
2859 jb_err cgi_edit_actions_for_url(struct client_state *csp,
2860                                 struct http_response *rsp,
2861                                 const struct map *parameters)
2862 {
2863    struct map * exports;
2864    unsigned sectionid;
2865    struct editable_file * file;
2866    struct file_line * cur_line;
2867    unsigned line_number;
2868    jb_err err;
2869    struct file_list *filter_file;
2870    struct re_filterfile_spec *filter_group;
2871
2872    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
2873    {
2874       return cgi_error_disabled(csp, rsp);
2875    }
2876
2877    err = get_number_param(csp, parameters, "s", &sectionid);
2878    if (err)
2879    {
2880       return err;
2881    }
2882
2883    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
2884    if (err)
2885    {
2886       /* No filename specified, can't read file, modified, or out of memory. */
2887       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
2888    }
2889
2890    cur_line = file->lines;
2891
2892    for (line_number = 1; (cur_line != NULL) && (line_number < sectionid); line_number++)
2893    {
2894       cur_line = cur_line->next;
2895    }
2896
2897    if ( (cur_line == NULL)
2898      || (line_number != sectionid)
2899      || (sectionid < 1)
2900      || (cur_line->type != FILE_LINE_ACTION))
2901    {
2902       /* Invalid "sectionid" parameter */
2903       edit_free_file(file);
2904       return JB_ERR_CGI_PARAMS;
2905    }
2906
2907    if (NULL == (exports = default_exports(csp, NULL)))
2908    {
2909       edit_free_file(file);
2910       return JB_ERR_MEMORY;
2911    }
2912
2913    err = map(exports, "f", 1, file->identifier, 1);
2914    if (!err) err = map(exports, "v", 1, file->version_str, 1);
2915    if (!err) err = map(exports, "s", 1, url_encode(lookup(parameters, "s")), 0);
2916
2917    if (!err) err = actions_to_radio(exports, cur_line->data.action);
2918
2919    filter_file = csp->rlist;
2920    filter_group = ((filter_file != NULL) ? filter_file->f : NULL);
2921
2922    if (!err) err = map_conditional(exports, "any-filters-defined", (filter_group != NULL));
2923
2924    if (err)
2925    {
2926       edit_free_file(file);
2927       free_map(exports);
2928       return err;
2929    }
2930
2931    if (filter_group == NULL)
2932    {
2933       err = map(exports, "filter-params", 1, "", 1);
2934    }
2935    else
2936    {
2937       /* We have some entries in the filter list */
2938       char * result;
2939       int index = 0;
2940       char * filter_template;
2941
2942       err = template_load(csp, &filter_template, "edit-actions-for-url-filter");
2943       if (err)
2944       {
2945          edit_free_file(file);
2946          free_map(exports);
2947          if (err == JB_ERR_FILE)
2948          {
2949             return cgi_error_no_template(csp, rsp, "edit-actions-for-url-filter");
2950          }
2951          return err;
2952       }
2953
2954       result = strdup("");
2955
2956       for (;(!err) && (filter_group != NULL); filter_group = filter_group->next)
2957       {
2958          char current_mode = 'x';
2959          struct list_entry *filter_name;
2960          char * this_line;
2961          struct map *line_exports;
2962          char number[20];
2963
2964          filter_name = cur_line->data.action->multi_add[ACTION_MULTI_FILTER]->first;
2965          while ((filter_name != NULL)
2966              && (0 != strcmp(filter_group->name, filter_name->str)))
2967          {
2968               filter_name = filter_name->next;
2969          }
2970
2971          if (filter_name != NULL)
2972          {
2973             current_mode = 'y';
2974          }
2975          else
2976          {
2977             filter_name = cur_line->data.action->multi_remove[ACTION_MULTI_FILTER]->first;
2978             while ((filter_name != NULL)
2979                 && (0 != strcmp(filter_group->name, filter_name->str)))
2980             {
2981                  filter_name = filter_name->next;
2982             }
2983             if (filter_name != NULL)
2984             {
2985                current_mode = 'n';
2986             }
2987          }
2988
2989          /* Generate a unique serial number */
2990          snprintf(number, sizeof(number), "%x", index++);
2991          number[sizeof(number) - 1] = '\0';
2992
2993          line_exports = new_map();
2994          if (line_exports == NULL)
2995          {
2996             err = JB_ERR_MEMORY;
2997             freez(result);
2998          }
2999          else
3000          {
3001             if (!err) err = map(line_exports, "index", 1, number, 1);
3002             if (!err) err = map(line_exports, "name",  1, filter_group->name, 1);
3003             if (!err) err = map(line_exports, "description",  1, filter_group->description, 1);
3004             if (!err) err = map_radio(line_exports, "this-filter", "ynx", current_mode);
3005
3006             this_line = NULL;
3007             if (!err)
3008             {
3009                this_line = strdup(filter_template);
3010                if (this_line == NULL) err = JB_ERR_MEMORY;
3011             }
3012             if (!err) err = template_fill(&this_line, line_exports);
3013             string_join(&result, this_line);
3014
3015             free_map(line_exports);
3016          }
3017       }
3018       if (!err)
3019       {
3020          err = map(exports, "filter-params", 1, result, 0);
3021       }
3022       else
3023       {
3024          freez(result);
3025       }
3026    }
3027
3028    if (!err) err = map_radio(exports, "filter-all", "nx",
3029       (cur_line->data.action->multi_remove_all[ACTION_MULTI_FILTER] ? 'n' : 'x'));
3030
3031    edit_free_file(file);
3032
3033    if (err)
3034    {
3035       free_map(exports);
3036       return err;
3037    }
3038
3039    return template_fill_for_cgi(csp, "edit-actions-for-url", exports, rsp);
3040 }
3041
3042
3043 /*********************************************************************
3044  *
3045  * Function    :  cgi_edit_actions_submit
3046  *
3047  * Description :  CGI function that actually edits the Actions list.
3048  *
3049  * Parameters  :
3050  *          1  :  csp = Current client state (buffers, headers, etc...)
3051  *          2  :  rsp = http_response data structure for output
3052  *          3  :  parameters = map of cgi parameters
3053  *
3054  * CGI Parameters : None
3055  *
3056  * Returns     :  JB_ERR_OK     on success
3057  *                JB_ERR_MEMORY on out-of-memory
3058  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3059  *                                  specified or not valid.
3060  *
3061  *********************************************************************/
3062 jb_err cgi_edit_actions_submit(struct client_state *csp,
3063                                struct http_response *rsp,
3064                                const struct map *parameters)
3065 {
3066    unsigned sectionid;
3067    char * actiontext;
3068    char * newtext;
3069    size_t len;
3070    struct editable_file * file;
3071    struct file_line * cur_line;
3072    unsigned line_number;
3073    char * target;
3074    jb_err err;
3075    int index;
3076    char ch;
3077
3078    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3079    {
3080       return cgi_error_disabled(csp, rsp);
3081    }
3082
3083    err = get_number_param(csp, parameters, "s", &sectionid);
3084    if (err)
3085    {
3086       return err;
3087    }
3088
3089    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3090    if (err)
3091    {
3092       /* No filename specified, can't read file, modified, or out of memory. */
3093       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3094    }
3095
3096    cur_line = file->lines;
3097
3098    for (line_number = 1; (cur_line != NULL) && (line_number < sectionid); line_number++)
3099    {
3100       cur_line = cur_line->next;
3101    }
3102
3103    if ( (cur_line == NULL)
3104      || (line_number != sectionid)
3105      || (sectionid < 1)
3106      || (cur_line->type != FILE_LINE_ACTION))
3107    {
3108       /* Invalid "sectionid" parameter */
3109       edit_free_file(file);
3110       return JB_ERR_CGI_PARAMS;
3111    }
3112
3113    err = actions_from_radio(parameters, cur_line->data.action);
3114    if(err)
3115    {
3116       /* Out of memory */
3117       edit_free_file(file);
3118       return err;
3119    }
3120
3121    ch = get_char_param(parameters, "filter_all");
3122    if (ch == 'N')
3123    {
3124       list_remove_all(cur_line->data.action->multi_add[ACTION_MULTI_FILTER]);
3125       list_remove_all(cur_line->data.action->multi_remove[ACTION_MULTI_FILTER]);
3126       cur_line->data.action->multi_remove_all[ACTION_MULTI_FILTER] = 1;
3127    }
3128    else if (ch == 'X')
3129    {
3130       cur_line->data.action->multi_remove_all[ACTION_MULTI_FILTER] = 0;
3131    }
3132
3133    for (index = 0; !err; index++)
3134    {
3135       char key_value[30];
3136       char key_name[30];
3137       const char *name;
3138       char value;
3139
3140       /* Generate the keys */
3141       snprintf(key_value, sizeof(key_value), "filter_r%x", index);
3142       key_value[sizeof(key_value) - 1] = '\0';
3143       snprintf(key_name, sizeof(key_name), "filter_n%x", index);
3144       key_name[sizeof(key_name) - 1] = '\0';
3145
3146       err = get_string_param(parameters, key_name, &name);
3147       if (err) break;
3148
3149       if (name == NULL)
3150       {
3151          /* End of list */
3152          break;
3153       }
3154
3155
3156       value = get_char_param(parameters, key_value);
3157       if (value == 'Y')
3158       {
3159          list_remove_item(cur_line->data.action->multi_add[ACTION_MULTI_FILTER], name);
3160          if (!err) err = enlist(cur_line->data.action->multi_add[ACTION_MULTI_FILTER], name);
3161          list_remove_item(cur_line->data.action->multi_remove[ACTION_MULTI_FILTER], name);
3162       }
3163       else if (value == 'N')
3164       {
3165          list_remove_item(cur_line->data.action->multi_add[ACTION_MULTI_FILTER], name);
3166          if (!cur_line->data.action->multi_remove_all[ACTION_MULTI_FILTER])
3167          {
3168             list_remove_item(cur_line->data.action->multi_remove[ACTION_MULTI_FILTER], name);
3169             if (!err) err = enlist(cur_line->data.action->multi_remove[ACTION_MULTI_FILTER], name);
3170          }
3171       }
3172       else if (value == 'X')
3173       {
3174          list_remove_item(cur_line->data.action->multi_add[ACTION_MULTI_FILTER], name);
3175          list_remove_item(cur_line->data.action->multi_remove[ACTION_MULTI_FILTER], name);
3176       }
3177    }
3178
3179    if(err)
3180    {
3181       /* Out of memory */
3182       edit_free_file(file);
3183       return err;
3184    }
3185
3186    if (NULL == (actiontext = actions_to_text(cur_line->data.action)))
3187    {
3188       /* Out of memory */
3189       edit_free_file(file);
3190       return JB_ERR_MEMORY;
3191    }
3192
3193    len = strlen(actiontext);
3194    if (len == 0)
3195    {
3196       /*
3197        * Empty action - must special-case this.
3198        * Simply setting len to 1 is sufficient...
3199        */
3200       len = 1;
3201    }
3202
3203    if (NULL == (newtext = malloc(len + 2)))
3204    {
3205       /* Out of memory */
3206       free(actiontext);
3207       edit_free_file(file);
3208       return JB_ERR_MEMORY;
3209    }
3210    strcpy(newtext, actiontext);
3211    free(actiontext);
3212    newtext[0]       = '{';
3213    newtext[len]     = '}';
3214    newtext[len + 1] = '\0';
3215
3216    freez(cur_line->raw);
3217    freez(cur_line->unprocessed);
3218    cur_line->unprocessed = newtext;
3219
3220    err = edit_write_file(file);
3221    if (err)
3222    {
3223       /* Error writing file */
3224       edit_free_file(file);
3225       return err;
3226    }
3227
3228    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3229    string_append(&target, file->identifier);
3230
3231    edit_free_file(file);
3232
3233    if (target == NULL)
3234    {
3235       /* Out of memory */
3236       return JB_ERR_MEMORY;
3237    }
3238
3239    rsp->status = strdup("302 Local Redirect from Privoxy");
3240    if (rsp->status == NULL)
3241    {
3242       free(target);
3243       return JB_ERR_MEMORY;
3244    }
3245    err = enlist_unique_header(rsp->headers, "Location", target);
3246    free(target);
3247
3248    return err;
3249 }
3250
3251
3252 /*********************************************************************
3253  *
3254  * Function    :  cgi_edit_actions_url
3255  *
3256  * Description :  CGI function that actually edits a URL pattern in
3257  *                an actions file.
3258  *
3259  * Parameters  :
3260  *          1  :  csp = Current client state (buffers, headers, etc...)
3261  *          2  :  rsp = http_response data structure for output
3262  *          3  :  parameters = map of cgi parameters
3263  *
3264  * CGI Parameters :
3265  *    filename : Identifies the file to edit
3266  *         ver : File's last-modified time
3267  *     section : Line number of section to edit
3268  *     pattern : Line number of pattern to edit
3269  *      newval : New value for pattern
3270  *
3271  * Returns     :  JB_ERR_OK     on success
3272  *                JB_ERR_MEMORY on out-of-memory
3273  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3274  *                                  specified or not valid.
3275  *
3276  *********************************************************************/
3277 jb_err cgi_edit_actions_url(struct client_state *csp,
3278                             struct http_response *rsp,
3279                             const struct map *parameters)
3280 {
3281    unsigned patternid;
3282    char * new_pattern;
3283    struct editable_file * file;
3284    struct file_line * cur_line;
3285    unsigned line_number;
3286    char * target;
3287    jb_err err;
3288
3289    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3290    {
3291       return cgi_error_disabled(csp, rsp);
3292    }
3293
3294    err = get_number_param(csp, parameters, "p", &patternid);
3295    if (err)
3296    {
3297       return err;
3298    }
3299    if (patternid < 1U)
3300    {
3301       return JB_ERR_CGI_PARAMS;
3302    }
3303
3304    err = get_url_spec_param(csp, parameters, "u", &new_pattern);
3305    if (err)
3306    {
3307       return err;
3308    }
3309
3310    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3311    if (err)
3312    {
3313       /* No filename specified, can't read file, modified, or out of memory. */
3314       free(new_pattern);
3315       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3316    }
3317
3318    line_number = 1;
3319    cur_line = file->lines;
3320
3321    while ((cur_line != NULL) && (line_number < patternid))
3322    {
3323       cur_line = cur_line->next;
3324       line_number++;
3325    }
3326
3327    if ( (cur_line == NULL)
3328      || (cur_line->type != FILE_LINE_URL))
3329    {
3330       /* Invalid "patternid" parameter */
3331       free(new_pattern);
3332       edit_free_file(file);
3333       return JB_ERR_CGI_PARAMS;
3334    }
3335
3336    /* At this point, the line to edit is in cur_line */
3337
3338    freez(cur_line->raw);
3339    freez(cur_line->unprocessed);
3340    cur_line->unprocessed = new_pattern;
3341
3342    err = edit_write_file(file);
3343    if (err)
3344    {
3345       /* Error writing file */
3346       edit_free_file(file);
3347       return err;
3348    }
3349
3350    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3351    string_append(&target, file->identifier);
3352
3353    edit_free_file(file);
3354
3355    if (target == NULL)
3356    {
3357       /* Out of memory */
3358       return JB_ERR_MEMORY;
3359    }
3360
3361    rsp->status = strdup("302 Local Redirect from Privoxy");
3362    if (rsp->status == NULL)
3363    {
3364       free(target);
3365       return JB_ERR_MEMORY;
3366    }
3367    err = enlist_unique_header(rsp->headers, "Location", target);
3368    free(target);
3369
3370    return err;
3371 }
3372
3373
3374 /*********************************************************************
3375  *
3376  * Function    :  cgi_edit_actions_add_url
3377  *
3378  * Description :  CGI function that actually adds a URL pattern to
3379  *                an actions file.
3380  *
3381  * Parameters  :
3382  *          1  :  csp = Current client state (buffers, headers, etc...)
3383  *          2  :  rsp = http_response data structure for output
3384  *          3  :  parameters = map of cgi parameters
3385  *
3386  * CGI Parameters :
3387  *    filename : Identifies the file to edit
3388  *         ver : File's last-modified time
3389  *     section : Line number of section to edit
3390  *      newval : New pattern
3391  *
3392  * Returns     :  JB_ERR_OK     on success
3393  *                JB_ERR_MEMORY on out-of-memory
3394  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3395  *                                  specified or not valid.
3396  *
3397  *********************************************************************/
3398 jb_err cgi_edit_actions_add_url(struct client_state *csp,
3399                                 struct http_response *rsp,
3400                                 const struct map *parameters)
3401 {
3402    unsigned sectionid;
3403    char * new_pattern;
3404    struct file_line * new_line;
3405    struct editable_file * file;
3406    struct file_line * cur_line;
3407    unsigned line_number;
3408    char * target;
3409    jb_err err;
3410
3411    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3412    {
3413       return cgi_error_disabled(csp, rsp);
3414    }
3415
3416    err = get_number_param(csp, parameters, "s", &sectionid);
3417    if (err)
3418    {
3419       return err;
3420    }
3421    if (sectionid < 1U)
3422    {
3423       return JB_ERR_CGI_PARAMS;
3424    }
3425
3426    err = get_url_spec_param(csp, parameters, "u", &new_pattern);
3427    if (err)
3428    {
3429       return err;
3430    }
3431
3432    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3433    if (err)
3434    {
3435       /* No filename specified, can't read file, modified, or out of memory. */
3436       free(new_pattern);
3437       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3438    }
3439
3440    line_number = 1;
3441    cur_line = file->lines;
3442
3443    while ((cur_line != NULL) && (line_number < sectionid))
3444    {
3445       cur_line = cur_line->next;
3446       line_number++;
3447    }
3448
3449    if ( (cur_line == NULL)
3450      || (cur_line->type != FILE_LINE_ACTION))
3451    {
3452       /* Invalid "sectionid" parameter */
3453       free(new_pattern);
3454       edit_free_file(file);
3455       return JB_ERR_CGI_PARAMS;
3456    }
3457
3458    /* At this point, the section header is in cur_line - add after this. */
3459
3460    /* Allocate the new line */
3461    new_line = (struct file_line *)zalloc(sizeof(*new_line));
3462    if (new_line == NULL)
3463    {
3464       free(new_pattern);
3465       edit_free_file(file);
3466       return JB_ERR_MEMORY;
3467    }
3468
3469    /* Fill in the data members of the new line */
3470    new_line->raw = NULL;
3471    new_line->prefix = NULL;
3472    new_line->unprocessed = new_pattern;
3473    new_line->type = FILE_LINE_URL;
3474
3475    /* Link new_line into the list, after cur_line */
3476    new_line->next = cur_line->next;
3477    cur_line->next = new_line;
3478
3479    /* Done making changes, now commit */
3480
3481    err = edit_write_file(file);
3482    if (err)
3483    {
3484       /* Error writing file */
3485       edit_free_file(file);
3486       return err;
3487    }
3488
3489    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3490    string_append(&target, file->identifier);
3491
3492    edit_free_file(file);
3493
3494    if (target == NULL)
3495    {
3496       /* Out of memory */
3497       return JB_ERR_MEMORY;
3498    }
3499
3500    rsp->status = strdup("302 Local Redirect from Privoxy");
3501    if (rsp->status == NULL)
3502    {
3503       free(target);
3504       return JB_ERR_MEMORY;
3505    }
3506    err = enlist_unique_header(rsp->headers, "Location", target);
3507    free(target);
3508
3509    return err;
3510 }
3511
3512
3513 /*********************************************************************
3514  *
3515  * Function    :  cgi_edit_actions_remove_url
3516  *
3517  * Description :  CGI function that actually removes a URL pattern from
3518  *                the actions file.
3519  *
3520  * Parameters  :
3521  *          1  :  csp = Current client state (buffers, headers, etc...)
3522  *          2  :  rsp = http_response data structure for output
3523  *          3  :  parameters = map of cgi parameters
3524  *
3525  * CGI Parameters :
3526  *           f : (filename) Identifies the file to edit
3527  *           v : (version) File's last-modified time
3528  *           p : (pattern) Line number of pattern to remove
3529  *
3530  * Returns     :  JB_ERR_OK     on success
3531  *                JB_ERR_MEMORY on out-of-memory
3532  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3533  *                                  specified or not valid.
3534  *
3535  *********************************************************************/
3536 jb_err cgi_edit_actions_remove_url(struct client_state *csp,
3537                                    struct http_response *rsp,
3538                                    const struct map *parameters)
3539 {
3540    unsigned patternid;
3541    struct editable_file * file;
3542    struct file_line * cur_line;
3543    struct file_line * prev_line;
3544    unsigned line_number;
3545    char * target;
3546    jb_err err;
3547
3548    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3549    {
3550       return cgi_error_disabled(csp, rsp);
3551    }
3552
3553    err = get_number_param(csp, parameters, "p", &patternid);
3554    if (err)
3555    {
3556       return err;
3557    }
3558
3559    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3560    if (err)
3561    {
3562       /* No filename specified, can't read file, modified, or out of memory. */
3563       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3564    }
3565
3566    line_number = 1;
3567    prev_line = NULL;
3568    cur_line = file->lines;
3569
3570    while ((cur_line != NULL) && (line_number < patternid))
3571    {
3572       prev_line = cur_line;
3573       cur_line = cur_line->next;
3574       line_number++;
3575    }
3576
3577    if ( (cur_line == NULL)
3578      || (prev_line == NULL)
3579      || (cur_line->type != FILE_LINE_URL))
3580    {
3581       /* Invalid "patternid" parameter */
3582       edit_free_file(file);
3583       return JB_ERR_CGI_PARAMS;
3584    }
3585
3586    /* At this point, the line to remove is in cur_line, and the previous
3587     * one is in prev_line
3588     */
3589
3590    /* Unlink cur_line */
3591    prev_line->next = cur_line->next;
3592    cur_line->next = NULL;
3593
3594    /* Free cur_line */
3595    edit_free_file_lines(cur_line);
3596
3597    err = edit_write_file(file);
3598    if (err)
3599    {
3600       /* Error writing file */
3601       edit_free_file(file);
3602       return err;
3603    }
3604
3605    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3606    string_append(&target, file->identifier);
3607
3608    edit_free_file(file);
3609
3610    if (target == NULL)
3611    {
3612       /* Out of memory */
3613       return JB_ERR_MEMORY;
3614    }
3615
3616    rsp->status = strdup("302 Local Redirect from Privoxy");
3617    if (rsp->status == NULL)
3618    {
3619       free(target);
3620       return JB_ERR_MEMORY;
3621    }
3622    err = enlist_unique_header(rsp->headers, "Location", target);
3623    free(target);
3624
3625    return err;
3626 }
3627
3628
3629 /*********************************************************************
3630  *
3631  * Function    :  cgi_edit_actions_section_remove
3632  *
3633  * Description :  CGI function that actually removes a whole section from
3634  *                the actions file.  The section must be empty first
3635  *                (else JB_ERR_CGI_PARAMS).
3636  *
3637  * Parameters  :
3638  *          1  :  csp = Current client state (buffers, headers, etc...)
3639  *          2  :  rsp = http_response data structure for output
3640  *          3  :  parameters = map of cgi parameters
3641  *
3642  * CGI Parameters :
3643  *           f : (filename) Identifies the file to edit
3644  *           v : (version) File's last-modified time
3645  *           s : (section) Line number of section to edit
3646  *
3647  * Returns     :  JB_ERR_OK     on success
3648  *                JB_ERR_MEMORY on out-of-memory
3649  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3650  *                                  specified or not valid.
3651  *
3652  *********************************************************************/
3653 jb_err cgi_edit_actions_section_remove(struct client_state *csp,
3654                                        struct http_response *rsp,
3655                                        const struct map *parameters)
3656 {
3657    unsigned sectionid;
3658    struct editable_file * file;
3659    struct file_line * cur_line;
3660    struct file_line * prev_line;
3661    unsigned line_number;
3662    char * target;
3663    jb_err err;
3664
3665    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3666    {
3667       return cgi_error_disabled(csp, rsp);
3668    }
3669
3670    err = get_number_param(csp, parameters, "s", &sectionid);
3671    if (err)
3672    {
3673       return err;
3674    }
3675
3676    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3677    if (err)
3678    {
3679       /* No filename specified, can't read file, modified, or out of memory. */
3680       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3681    }
3682
3683    line_number = 1;
3684    cur_line = file->lines;
3685
3686    prev_line = NULL;
3687    while ((cur_line != NULL) && (line_number < sectionid))
3688    {
3689       prev_line = cur_line;
3690       cur_line = cur_line->next;
3691       line_number++;
3692    }
3693
3694    if ( (cur_line == NULL)
3695      || (cur_line->type != FILE_LINE_ACTION) )
3696    {
3697       /* Invalid "sectionid" parameter */
3698       edit_free_file(file);
3699       return JB_ERR_CGI_PARAMS;
3700    }
3701
3702    if ( (cur_line->next != NULL)
3703      && (cur_line->next->type == FILE_LINE_URL) )
3704    {
3705       /* Section not empty. */
3706       edit_free_file(file);
3707       return JB_ERR_CGI_PARAMS;
3708    }
3709
3710    /* At this point, the line to remove is in cur_line, and the previous
3711     * one is in prev_line
3712     */
3713
3714    /* Unlink cur_line */
3715    if (prev_line == NULL)
3716    {
3717       /* Removing the first line from the file */
3718       file->lines = cur_line->next;
3719    }
3720    else
3721    {
3722       prev_line->next = cur_line->next;
3723    }
3724    cur_line->next = NULL;
3725
3726    /* Free cur_line */
3727    edit_free_file_lines(cur_line);
3728
3729    err = edit_write_file(file);
3730    if (err)
3731    {
3732       /* Error writing file */
3733       edit_free_file(file);
3734       return err;
3735    }
3736
3737    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3738    string_append(&target, file->identifier);
3739
3740    edit_free_file(file);
3741
3742    if (target == NULL)
3743    {
3744       /* Out of memory */
3745       return JB_ERR_MEMORY;
3746    }
3747
3748    rsp->status = strdup("302 Local Redirect from Privoxy");
3749    if (rsp->status == NULL)
3750    {
3751       free(target);
3752       return JB_ERR_MEMORY;
3753    }
3754    err = enlist_unique_header(rsp->headers, "Location", target);
3755    free(target);
3756
3757    return err;
3758 }
3759
3760
3761 /*********************************************************************
3762  *
3763  * Function    :  cgi_edit_actions_section_add
3764  *
3765  * Description :  CGI function that adds a new empty section to
3766  *                an actions file.
3767  *
3768  * Parameters  :
3769  *          1  :  csp = Current client state (buffers, headers, etc...)
3770  *          2  :  rsp = http_response data structure for output
3771  *          3  :  parameters = map of cgi parameters
3772  *
3773  * CGI Parameters :
3774  *           f : (filename) Identifies the file to edit
3775  *           v : (version) File's last-modified time
3776  *           s : (section) Line number of section to add after, 0 for
3777  *               start of file.
3778  *
3779  * Returns     :  JB_ERR_OK     on success
3780  *                JB_ERR_MEMORY on out-of-memory
3781  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3782  *                                  specified or not valid.
3783  *
3784  *********************************************************************/
3785 jb_err cgi_edit_actions_section_add(struct client_state *csp,
3786                                     struct http_response *rsp,
3787                                     const struct map *parameters)
3788 {
3789    unsigned sectionid;
3790    struct file_line * new_line;
3791    char * new_text;
3792    struct editable_file * file;
3793    struct file_line * cur_line;
3794    unsigned line_number;
3795    char * target;
3796    jb_err err;
3797
3798    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3799    {
3800       return cgi_error_disabled(csp, rsp);
3801    }
3802
3803    err = get_number_param(csp, parameters, "s", &sectionid);
3804    if (err)
3805    {
3806       return err;
3807    }
3808
3809    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
3810    if (err)
3811    {
3812       /* No filename specified, can't read file, modified, or out of memory. */
3813       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
3814    }
3815
3816    line_number = 1;
3817    cur_line = file->lines;
3818
3819    if (sectionid < 1U)
3820    {
3821       /* Add to start of file */
3822       if (cur_line != NULL)
3823       {
3824          /* There's something in the file, find the line before the first
3825           * action.
3826           */
3827          while ( (cur_line->next != NULL)
3828               && (cur_line->next->type != FILE_LINE_ACTION) )
3829          {
3830             cur_line = cur_line->next;
3831             line_number++;
3832          }
3833       }
3834    }
3835    else
3836    {
3837       /* Add after stated section. */
3838       while ((cur_line != NULL) && (line_number < sectionid))
3839       {
3840          cur_line = cur_line->next;
3841          line_number++;
3842       }
3843
3844       if ( (cur_line == NULL)
3845         || (cur_line->type != FILE_LINE_ACTION))
3846       {
3847          /* Invalid "sectionid" parameter */
3848          edit_free_file(file);
3849          return JB_ERR_CGI_PARAMS;
3850       }
3851
3852       /* Skip through the section to find the last line in it. */
3853       while ( (cur_line->next != NULL)
3854            && (cur_line->next->type != FILE_LINE_ACTION) )
3855       {
3856          cur_line = cur_line->next;
3857          line_number++;
3858       }
3859    }
3860
3861    /* At this point, the last line in the previous section is in cur_line
3862     * - add after this.  (Or if we need to add as the first line, cur_line
3863     * will be NULL).
3864     */
3865
3866    new_text = strdup("{}");
3867    if (NULL == new_text)
3868    {
3869       edit_free_file(file);
3870       return JB_ERR_MEMORY;
3871    }
3872
3873    /* Allocate the new line */
3874    new_line = (struct file_line *)zalloc(sizeof(*new_line));
3875    if (new_line == NULL)
3876    {
3877       free(new_text);
3878       edit_free_file(file);
3879       return JB_ERR_MEMORY;
3880    }
3881
3882    /* Fill in the data members of the new line */
3883    new_line->raw = NULL;
3884    new_line->prefix = NULL;
3885    new_line->unprocessed = new_text;
3886    new_line->type = FILE_LINE_ACTION;
3887
3888    if (cur_line != NULL)
3889    {
3890       /* Link new_line into the list, after cur_line */
3891       new_line->next = cur_line->next;
3892       cur_line->next = new_line;
3893    }
3894    else
3895    {
3896       /* Link new_line into the list, as first line */
3897       new_line->next = file->lines;
3898       file->lines = new_line;
3899    }
3900
3901    /* Done making changes, now commit */
3902
3903    err = edit_write_file(file);
3904    if (err)
3905    {
3906       /* Error writing file */
3907       edit_free_file(file);
3908       return err;
3909    }
3910
3911    target = strdup(CGI_PREFIX "edit-actions-list?f=");
3912    string_append(&target, file->identifier);
3913
3914    edit_free_file(file);
3915
3916    if (target == NULL)
3917    {
3918       /* Out of memory */
3919       return JB_ERR_MEMORY;
3920    }
3921
3922    rsp->status = strdup("302 Local Redirect from Privoxy");
3923    if (rsp->status == NULL)
3924    {
3925       free(target);
3926       return JB_ERR_MEMORY;
3927    }
3928    err = enlist_unique_header(rsp->headers, "Location", target);
3929    free(target);
3930
3931    return err;
3932 }
3933
3934
3935 /*********************************************************************
3936  *
3937  * Function    :  cgi_edit_actions_section_swap
3938  *
3939  * Description :  CGI function that swaps the order of two sections
3940  *                in the actions file.  Note that this CGI can actually
3941  *                swap any two arbitrary sections, but the GUI interface
3942  *                currently only allows consecutive sections to be
3943  *                specified.
3944  *
3945  * Parameters  :
3946  *          1  :  csp = Current client state (buffers, headers, etc...)
3947  *          2  :  rsp = http_response data structure for output
3948  *          3  :  parameters = map of cgi parameters
3949  *
3950  * CGI Parameters :
3951  *           f : (filename) Identifies the file to edit
3952  *           v : (version) File's last-modified time
3953  *          s1 : (section1) Line number of first section to swap
3954  *          s2 : (section2) Line number of second section to swap
3955  *
3956  * Returns     :  JB_ERR_OK     on success
3957  *                JB_ERR_MEMORY on out-of-memory
3958  *                JB_ERR_CGI_PARAMS if the CGI parameters are not
3959  *                                  specified or not valid.
3960  *
3961  *********************************************************************/
3962 jb_err cgi_edit_actions_section_swap(struct client_state *csp,
3963                                      struct http_response *rsp,
3964                                      const struct map *parameters)
3965 {
3966    unsigned section1;
3967    unsigned section2;
3968    struct editable_file * file;
3969    struct file_line * cur_line;
3970    struct file_line * prev_line;
3971    struct file_line * line_before_section1;
3972    struct file_line * line_start_section1;
3973    struct file_line * line_end_section1;
3974    struct file_line * line_after_section1;
3975    struct file_line * line_before_section2;
3976    struct file_line * line_start_section2;
3977    struct file_line * line_end_section2;
3978    struct file_line * line_after_section2;
3979    unsigned line_number;
3980    char * target;
3981    jb_err err;
3982
3983    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_EDIT_ACTIONS))
3984    {
3985       return cgi_error_disabled(csp, rsp);
3986    }
3987
3988    err = get_number_param(csp, parameters, "s1", &section1);
3989    if (!err) err = get_number_param(csp, parameters, "s2", &section2);
3990    if (err)
3991    {
3992       return err;
3993    }
3994
3995    if (section1 > section2)
3996    {
3997       unsigned temp = section2;
3998       section2 = section1;
3999       section1 = temp;
4000    }
4001
4002    err = edit_read_actions_file(csp, rsp, parameters, 1, &file);
4003    if (err)
4004    {
4005       /* No filename specified, can't read file, modified, or out of memory. */
4006       return (err == JB_ERR_FILE ? JB_ERR_OK : err);
4007    }
4008
4009    /* Start at the beginning... */
4010    line_number = 1;
4011    cur_line = file->lines;
4012    prev_line = NULL;
4013
4014    /* ... find section1 ... */
4015    while ((cur_line != NULL) && (line_number < section1))
4016    {
4017       prev_line = cur_line;
4018       cur_line = cur_line->next;
4019       line_number++;
4020    }
4021
4022    if ( (cur_line == NULL)
4023      || (cur_line->type != FILE_LINE_ACTION) )
4024    {
4025       /* Invalid "section1" parameter */
4026       edit_free_file(file);
4027       return JB_ERR_CGI_PARAMS;
4028    }
4029
4030    /* If no-op, we've validated params and can skip the rest. */
4031    if (section1 != section2)
4032    {
4033       /* ... find the end of section1 ... */
4034       line_before_section1 = prev_line;
4035       line_start_section1 = cur_line;
4036       do
4037       {
4038          prev_line = cur_line;
4039          cur_line = cur_line->next;
4040          line_number++;
4041       }
4042       while ((cur_line != NULL) && (cur_line->type == FILE_LINE_URL));
4043       line_end_section1 = prev_line;
4044       line_after_section1 = cur_line;
4045
4046       /* ... find section2 ... */
4047       while ((cur_line != NULL) && (line_number < section2))
4048       {
4049          prev_line = cur_line;
4050          cur_line = cur_line->next;
4051          line_number++;
4052       }
4053
4054       if ( (cur_line == NULL)
4055         || (cur_line->type != FILE_LINE_ACTION) )
4056       {
4057          /* Invalid "section2" parameter */
4058          edit_free_file(file);
4059          return JB_ERR_CGI_PARAMS;
4060       }
4061
4062       /* ... find the end of section2 ... */
4063       line_before_section2 = prev_line;
4064       line_start_section2 = cur_line;
4065       do
4066       {
4067          prev_line = cur_line;
4068          cur_line = cur_line->next;
4069          line_number++;
4070       }
4071       while ((cur_line != NULL) && (cur_line->type == FILE_LINE_URL));
4072       line_end_section2 = prev_line;
4073       line_after_section2 = cur_line;
4074
4075       /* Now have all the pointers we need. Do the swap. */
4076
4077       /* Change the pointer to section1 to point to section2 instead */
4078       if (line_before_section1 == NULL)
4079       {
4080          file->lines = line_start_section2;
4081       }
4082       else
4083       {
4084          line_before_section1->next = line_start_section2;
4085       }
4086
4087       if (line_before_section2 == line_end_section1)
4088       {
4089          /* Consecutive sections */
4090          line_end_section2->next = line_start_section1;
4091       }
4092       else
4093       {
4094          line_end_section2->next = line_after_section1;
4095          line_before_section2->next = line_start_section1;
4096       }
4097
4098       /* Set the pointer from the end of section1 to the rest of the file */
4099       line_end_section1->next = line_after_section2;
4100
4101       err = edit_write_file(file);
4102       if (err)
4103       {
4104          /* Error writing file */
4105          edit_free_file(file);
4106          return err;
4107       }
4108    } /* END if (section1 != section2) */
4109
4110    target = strdup(CGI_PREFIX "edit-actions-list?f=");
4111    string_append(&target, file->identifier);
4112
4113    edit_free_file(file);
4114
4115    if (target == NULL)
4116    {
4117       /* Out of memory */
4118       return JB_ERR_MEMORY;
4119    }
4120
4121    rsp->status = strdup("302 Local Redirect from Privoxy");
4122    if (rsp->status == NULL)
4123    {
4124       free(target);
4125       return JB_ERR_MEMORY;
4126    }
4127    err = enlist_unique_header(rsp->headers, "Location", target);
4128    free(target);
4129
4130    return err;
4131 }
4132
4133
4134 /*********************************************************************
4135  *
4136  * Function    :  cgi_toggle
4137  *
4138  * Description :  CGI function that adds a new empty section to
4139  *                an actions file.
4140  *
4141  * Parameters  :
4142  *          1  :  csp = Current client state (buffers, headers, etc...)
4143  *          2  :  rsp = http_response data structure for output
4144  *          3  :  parameters = map of cgi parameters
4145  *
4146  * CGI Parameters :
4147  *         set : If present, how to change toggle setting:
4148  *               "enable", "disable", "toggle", or none (default).
4149  *        mini : If present, use mini reply template.
4150  *
4151  * Returns     :  JB_ERR_OK     on success
4152  *                JB_ERR_MEMORY on out-of-memory
4153  *
4154  *********************************************************************/
4155 jb_err cgi_toggle(struct client_state *csp,
4156                   struct http_response *rsp,
4157                   const struct map *parameters)
4158 {
4159    struct map *exports;
4160    char mode;
4161    const char *template_name;
4162
4163    assert(csp);
4164    assert(rsp);
4165    assert(parameters);
4166
4167    if (0 == (csp->config->feature_flags & RUNTIME_FEATURE_CGI_TOGGLE))
4168    {
4169       return cgi_error_disabled(csp, rsp);
4170    }
4171
4172    mode = get_char_param(parameters, "set");
4173
4174    if (mode == 'E')
4175    {
4176       /* Enable */
4177       g_bToggleIJB = 1;
4178    }
4179    else if (mode == 'D')
4180    {
4181       /* Disable */
4182       g_bToggleIJB = 0;
4183    }
4184    else if (mode == 'T')
4185    {
4186       /* Toggle */
4187       g_bToggleIJB = !g_bToggleIJB;
4188    }
4189
4190    if (NULL == (exports = default_exports(csp, "toggle")))
4191    {
4192       return JB_ERR_MEMORY;
4193    }
4194
4195    template_name = (get_char_param(parameters, "mini")
4196                  ? "toggle-mini"
4197                  : "toggle");
4198
4199    return template_fill_for_cgi(csp, template_name, exports, rsp);
4200 }
4201
4202
4203 /*********************************************************************
4204  *
4205  * Function    :  javascriptify
4206  *
4207  * Description :  Converts a string into a form JavaScript will like.
4208  *
4209  *                Netscape 4's JavaScript sucks - it doesn't use 
4210  *                "id" parameters, so you have to set the "name"
4211  *                used to submit a form element to something JavaScript
4212  *                will like.  (Or access the elements by index in an
4213  *                array.  That array contains >60 elements and will
4214  *                be changed whenever we add a new action to the
4215  *                editor, so I'm NOT going to use indexes that have
4216  *                to be figured out by hand.)
4217  *
4218  *                Currently the only thing we have to worry about
4219  *                is "-" ==> "_" conversion.
4220  *
4221  *                This is a length-preserving operation so it is
4222  *                carried out in-place, no memory is allocated
4223  *                or freed.
4224  *
4225  * Parameters  :
4226  *          1  :  identifier = String to make JavaScript-friendly.
4227  *
4228  * Returns     :  N/A
4229  *
4230  *********************************************************************/
4231 static void javascriptify(char * identifier)
4232 {
4233    char * p = identifier;
4234    while (NULL != (p = strchr(p, '-')))
4235    {
4236       *p++ = '_';
4237    }
4238 }
4239
4240
4241 /*********************************************************************
4242  *
4243  * Function    :  actions_to_radio
4244  *
4245  * Description :  Converts a actionsfile entry into settings for
4246  *                radio buttons and edit boxes on a HTML form.
4247  *
4248  * Parameters  :
4249  *          1  :  exports = List of substitutions to add to.
4250  *          2  :  action  = Action to read
4251  *
4252  * Returns     :  JB_ERR_OK     on success
4253  *                JB_ERR_MEMORY on out-of-memory
4254  *
4255  *********************************************************************/
4256 static jb_err actions_to_radio(struct map * exports,
4257                                const struct action_spec *action)
4258 {
4259    unsigned mask = action->mask;
4260    unsigned add  = action->add;
4261    int mapped_param;
4262    int checked;
4263    char current_mode;
4264
4265    assert(exports);
4266    assert(action);
4267
4268    mask = action->mask;
4269    add  = action->add;
4270
4271    /* sanity - prevents "-feature +feature" */
4272    mask |= add;
4273
4274
4275 #define DEFINE_ACTION_BOOL(name, bit)                 \
4276    if (!(mask & bit))                                 \
4277    {                                                  \
4278       current_mode = 'n';                             \
4279    }                                                  \
4280    else if (add & bit)                                \
4281    {                                                  \
4282       current_mode = 'y';                             \
4283    }                                                  \
4284    else                                               \
4285    {                                                  \
4286       current_mode = 'x';                             \
4287    }                                                  \
4288    if (map_radio(exports, name, "ynx", current_mode)) \
4289    {                                                  \
4290       return JB_ERR_MEMORY;                           \
4291    }
4292
4293 #define DEFINE_ACTION_STRING(name, bit, index)        \
4294    DEFINE_ACTION_BOOL(name, bit);                     \
4295    mapped_param = 0;
4296
4297 #define DEFINE_CGI_PARAM_RADIO(name, bit, index, value, is_default)  \
4298    if (add & bit)                                                    \
4299    {                                                                 \
4300       checked = !strcmp(action->string[index], value);               \
4301    }                                                                 \
4302    else                                                              \
4303    {                                                                 \
4304       checked = is_default;                                          \
4305    }                                                                 \
4306    mapped_param |= checked;                                          \
4307    if (map(exports, name "-param-" value, 1, (checked ? "checked" : ""), 1)) \
4308    {                                                                 \
4309       return JB_ERR_MEMORY;                                          \
4310    }
4311
4312 #define DEFINE_CGI_PARAM_CUSTOM(name, bit, index, default_val)       \
4313    if (map(exports, name "-param-custom", 1,                         \
4314            ((!mapped_param) ? "checked" : ""), 1))                   \
4315    {                                                                 \
4316       return JB_ERR_MEMORY;                                          \
4317    }                                                                 \
4318    if (map(exports, name "-param", 1,                                \
4319            (((add & bit) && !mapped_param) ?                         \
4320            action->string[index] : default_val), 1))                 \
4321    {                                                                 \
4322       return JB_ERR_MEMORY;                                          \
4323    }
4324
4325 #define DEFINE_CGI_PARAM_NO_RADIO(name, bit, index, default_val)     \
4326    if (map(exports, name "-param", 1,                                \
4327            ((add & bit) ? action->string[index] : default_val), 1))  \
4328    {                                                                 \
4329       return JB_ERR_MEMORY;                                          \
4330    }
4331
4332 #define DEFINE_ACTION_MULTI(name, index)              \
4333    if (action->multi_add[index]->first)               \
4334    {                                                  \
4335       current_mode = 'y';                             \
4336    }                                                  \
4337    else if (action->multi_remove_all[index])          \
4338    {                                                  \
4339       current_mode = 'n';                             \
4340    }                                                  \
4341    else if (action->multi_remove[index]->first)       \
4342    {                                                  \
4343       current_mode = 'y';                             \
4344    }                                                  \
4345    else                                               \
4346    {                                                  \
4347       current_mode = 'x';                             \
4348    }                                                  \
4349    if (map_radio(exports, name, "ynx", current_mode)) \
4350    {                                                  \
4351       return JB_ERR_MEMORY;                           \
4352    }
4353
4354 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
4355
4356 #include "actionlist.h"
4357
4358 #undef DEFINE_ACTION_MULTI
4359 #undef DEFINE_ACTION_STRING
4360 #undef DEFINE_ACTION_BOOL
4361 #undef DEFINE_ACTION_ALIAS
4362 #undef DEFINE_CGI_PARAM_CUSTOM
4363 #undef DEFINE_CGI_PARAM_RADIO
4364 #undef DEFINE_CGI_PARAM_NO_RADIO
4365
4366    return JB_ERR_OK;
4367 }
4368
4369
4370 /*********************************************************************
4371  *
4372  * Function    :  actions_from_radio
4373  *
4374  * Description :  Converts a map of parameters passed to a CGI function
4375  *                into an actionsfile entry.
4376  *
4377  * Parameters  :
4378  *          1  :  parameters = parameters to the CGI call
4379  *          2  :  action  = Action to change.  Must be valid before
4380  *                          the call, actions not specified will be
4381  *                          left unchanged.
4382  *
4383  * Returns     :  JB_ERR_OK     on success
4384  *                JB_ERR_MEMORY on out-of-memory
4385  *
4386  *********************************************************************/
4387 static jb_err actions_from_radio(const struct map * parameters,
4388                                  struct action_spec *action)
4389 {
4390    static int first_time = 1;
4391    const char * param;
4392    char * param_dup;
4393    char ch;
4394    const char * js_name;
4395    jb_err err = JB_ERR_OK;
4396
4397    assert(parameters);
4398    assert(action);
4399
4400    /* Statics are generally a potential race condition,
4401     * but in this case we're safe and don't need semaphores.
4402     * Be careful if you modify this function.
4403     * - Jon
4404     */
4405
4406 #define JAVASCRIPTIFY(dest_var, string)               \
4407    {                                                  \
4408       static char js_name_arr[] = string;             \
4409       if (first_time)                                 \
4410       {                                               \
4411          javascriptify(js_name_arr);                  \
4412       }                                               \
4413       dest_var = js_name_arr;                         \
4414    }                                                  \
4415
4416 #define DEFINE_ACTION_BOOL(name, bit)                 \
4417    JAVASCRIPTIFY(js_name, name);                      \
4418    ch = get_char_param(parameters, js_name);          \
4419    if (ch == 'Y')                                     \
4420    {                                                  \
4421       action->add  |= bit;                            \
4422       action->mask |= bit;                            \
4423    }                                                  \
4424    else if (ch == 'N')                                \
4425    {                                                  \
4426       action->add  &= ~bit;                           \
4427       action->mask &= ~bit;                           \
4428    }                                                  \
4429    else if (ch == 'X')                                \
4430    {                                                  \
4431       action->add  &= ~bit;                           \
4432       action->mask |= bit;                            \
4433    }                                                  \
4434
4435 #define DEFINE_ACTION_STRING(name, bit, index)                 \
4436    JAVASCRIPTIFY(js_name, name);                               \
4437    ch = get_char_param(parameters, js_name);                   \
4438    if (ch == 'Y')                                              \
4439    {                                                           \
4440       param = NULL;                                            \
4441       JAVASCRIPTIFY(js_name, name "-mode");                    \
4442       if (!err) err = get_string_param(parameters, js_name, &param);    \
4443       if ((param == NULL) || (0 == strcmp(param, "CUSTOM")))            \
4444       {                                                                 \
4445          JAVASCRIPTIFY(js_name, name "-param");                         \
4446          if (!err) err = get_string_param(parameters, js_name, &param); \
4447       }                                                        \
4448       if (param != NULL)                                       \
4449       {                                                        \
4450          if (NULL == (param_dup = strdup(param)))              \
4451          {                                                     \
4452             return JB_ERR_MEMORY;                              \
4453          }                                                     \
4454          freez(action->string[index]);                         \
4455          action->add  |= bit;                                  \
4456          action->mask |= bit;                                  \
4457          action->string[index] = param_dup;                    \
4458       }                                                        \
4459    }                                                           \
4460    else if (ch == 'N')                                         \
4461    {                                                           \
4462       if (action->add & bit)                                   \
4463       {                                                        \
4464          freez(action->string[index]);                         \
4465       }                                                        \
4466       action->add  &= ~bit;                                    \
4467       action->mask &= ~bit;                                    \
4468    }                                                           \
4469    else if (ch == 'X')                                         \
4470    {                                                           \
4471       if (action->add & bit)                                   \
4472       {                                                        \
4473          freez(action->string[index]);                         \
4474       }                                                        \
4475       action->add  &= ~bit;                                    \
4476       action->mask |= bit;                                     \
4477    }                                                           \
4478
4479 #define DEFINE_ACTION_MULTI(name, index)                       \
4480    JAVASCRIPTIFY(js_name, name);                               \
4481    ch = get_char_param(parameters, js_name);                   \
4482    if (ch == 'Y')                                              \
4483    {                                                           \
4484       /* FIXME */                                              \
4485    }                                                           \
4486    else if (ch == 'N')                                         \
4487    {                                                           \
4488       list_remove_all(action->multi_add[index]);               \
4489       list_remove_all(action->multi_remove[index]);            \
4490       action->multi_remove_all[index] = 1;                     \
4491    }                                                           \
4492    else if (ch == 'X')                                         \
4493    {                                                           \
4494       list_remove_all(action->multi_add[index]);               \
4495       list_remove_all(action->multi_remove[index]);            \
4496       action->multi_remove_all[index] = 0;                     \
4497    }                                                           \
4498
4499 #define DEFINE_ACTION_ALIAS 0 /* No aliases for URL parsing */
4500
4501 #include "actionlist.h"
4502
4503 #undef DEFINE_ACTION_MULTI
4504 #undef DEFINE_ACTION_STRING
4505 #undef DEFINE_ACTION_BOOL
4506 #undef DEFINE_ACTION_ALIAS
4507 #undef JAVASCRIPTIFY
4508
4509    first_time = 0;
4510
4511    return err;
4512 }
4513
4514
4515 #endif /* def FEATURE_CGI_EDIT_ACTIONS */
4516
4517
4518 /*
4519   Local Variables:
4520   tab-width: 3
4521   end:
4522 */