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