Add some parentheses. No intended functional change.
[privoxy.git] / actions.c
1 const char actions_rcs[] = "$Id: actions.c,v 1.79 2012/03/09 16:23:50 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/actions.c,v $
5  *
6  * Purpose     :  Declares functions to work with actions files
7  *
8  * Copyright   :  Written by and Copyright (C) 2001-2011 the
9  *                Privoxy team. http://www.privoxy.org/
10  *
11  *                Based on the Internet Junkbuster originally written
12  *                by and Copyright (C) 1997 Anonymous Coders and
13  *                Junkbusters Corporation.  http://www.junkbusters.com
14  *
15  *                This program is free software; you can redistribute it
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <stdio.h>
39 #include <string.h>
40 #include <assert.h>
41 #include <stdlib.h>
42
43 #ifdef FEATURE_PTHREAD
44 #include <pthread.h>
45 #endif
46
47 #include "project.h"
48 #include "jcc.h"
49 #include "list.h"
50 #include "actions.h"
51 #include "miscutil.h"
52 #include "errlog.h"
53 #include "loaders.h"
54 #include "encode.h"
55 #include "urlmatch.h"
56 #include "cgi.h"
57 #include "ssplit.h"
58
59 const char actions_h_rcs[] = ACTIONS_H_VERSION;
60
61
62 /*
63  * We need the main list of options.
64  *
65  * First, we need a way to tell between boolean, string, and multi-string
66  * options.  For string and multistring options, we also need to be
67  * able to tell the difference between a "+" and a "-".  (For bools,
68  * the "+"/"-" information is encoded in "add" and "mask").  So we use
69  * an enumerated type (well, the preprocessor equivalent).  Here are
70  * the values:
71  */
72 enum action_value_type {
73    AV_NONE       = 0, /* +opt -opt */
74    AV_ADD_STRING = 1, /* +stropt{string} */
75    AV_REM_STRING = 2, /* -stropt */
76    AV_ADD_MULTI  = 3, /* +multiopt{string} +multiopt{string2} */
77    AV_REM_MULTI  = 4  /* -multiopt{string} -multiopt          */
78 };
79
80 /*
81  * We need a structure to hold the name, flag changes,
82  * type, and string index.
83  */
84 struct action_name
85 {
86    const char * name;
87    unsigned long mask;                /* a bit set to "0" = remove action */
88    unsigned long add;                 /* a bit set to "1" = add action */
89    enum action_value_type value_type; /* an AV_... constant */
90    int index;                         /* index into strings[] or multi[] */
91 };
92
93 /*
94  * And with those building blocks in place, here's the array.
95  */
96 static const struct action_name action_names[] =
97 {
98    /*
99     * Well actually there's no data here - it's in actionlist.h
100     * This keeps it together to make it easy to change.
101     *
102     * Here's the macros used to format it:
103     */
104 #define DEFINE_ACTION_MULTI(name,index)                   \
105    { "+" name, ACTION_MASK_ALL, 0, AV_ADD_MULTI, index }, \
106    { "-" name, ACTION_MASK_ALL, 0, AV_REM_MULTI, index },
107 #define DEFINE_ACTION_STRING(name,flag,index)                 \
108    { "+" name, ACTION_MASK_ALL, flag, AV_ADD_STRING, index }, \
109    { "-" name, ~flag, 0, AV_REM_STRING, index },
110 #define DEFINE_ACTION_BOOL(name,flag)   \
111    { "+" name, ACTION_MASK_ALL, flag }, \
112    { "-" name, ~flag, 0 },
113 #define DEFINE_ACTION_ALIAS 1 /* Want aliases please */
114
115 #include "actionlist.h"
116
117 #undef DEFINE_ACTION_MULTI
118 #undef DEFINE_ACTION_STRING
119 #undef DEFINE_ACTION_BOOL
120 #undef DEFINE_ACTION_ALIAS
121
122    { NULL, 0, 0 } /* End marker */
123 };
124
125
126 static int load_one_actions_file(struct client_state *csp, int fileid);
127
128
129 /*********************************************************************
130  *
131  * Function    :  merge_actions
132  *
133  * Description :  Merge two actions together.
134  *                Similar to "dest += src".
135  *
136  * Parameters  :
137  *          1  :  dest = Actions to modify.
138  *          2  :  src = Action to add.
139  *
140  * Returns     :  JB_ERR_OK or JB_ERR_MEMORY
141  *
142  *********************************************************************/
143 jb_err merge_actions (struct action_spec *dest,
144                       const struct action_spec *src)
145 {
146    int i;
147    jb_err err;
148
149    dest->mask &= src->mask;
150    dest->add  &= src->mask;
151    dest->add  |= src->add;
152
153    for (i = 0; i < ACTION_STRING_COUNT; i++)
154    {
155       char * str = src->string[i];
156       if (str)
157       {
158          freez(dest->string[i]);
159          dest->string[i] = strdup(str);
160          if (NULL == dest->string[i])
161          {
162             return JB_ERR_MEMORY;
163          }
164       }
165    }
166
167    for (i = 0; i < ACTION_MULTI_COUNT; i++)
168    {
169       if (src->multi_remove_all[i])
170       {
171          /* Remove everything from dest */
172          list_remove_all(dest->multi_remove[i]);
173          dest->multi_remove_all[i] = 1;
174
175          err = list_duplicate(dest->multi_add[i], src->multi_add[i]);
176       }
177       else if (dest->multi_remove_all[i])
178       {
179          /*
180           * dest already removes everything, so we only need to worry
181           * about what we add.
182           */
183          list_remove_list(dest->multi_add[i], src->multi_remove[i]);
184          err = list_append_list_unique(dest->multi_add[i], src->multi_add[i]);
185       }
186       else
187       {
188          /* No "remove all"s to worry about. */
189          list_remove_list(dest->multi_add[i], src->multi_remove[i]);
190          err = list_append_list_unique(dest->multi_remove[i], src->multi_remove[i]);
191          if (!err) err = list_append_list_unique(dest->multi_add[i], src->multi_add[i]);
192       }
193
194       if (err)
195       {
196          return err;
197       }
198    }
199
200    return JB_ERR_OK;
201 }
202
203
204 /*********************************************************************
205  *
206  * Function    :  copy_action
207  *
208  * Description :  Copy an action_specs.
209  *                Similar to "dest = src".
210  *
211  * Parameters  :
212  *          1  :  dest = Destination of copy.
213  *          2  :  src = Source for copy.
214  *
215  * Returns     :  N/A
216  *
217  *********************************************************************/
218 jb_err copy_action (struct action_spec *dest,
219                     const struct action_spec *src)
220 {
221    int i;
222    jb_err err = JB_ERR_OK;
223
224    free_action(dest);
225    memset(dest, '\0', sizeof(*dest));
226
227    dest->mask = src->mask;
228    dest->add  = src->add;
229
230    for (i = 0; i < ACTION_STRING_COUNT; i++)
231    {
232       char * str = src->string[i];
233       if (str)
234       {
235          str = strdup(str);
236          if (!str)
237          {
238             return JB_ERR_MEMORY;
239          }
240          dest->string[i] = str;
241       }
242    }
243
244    for (i = 0; i < ACTION_MULTI_COUNT; i++)
245    {
246       dest->multi_remove_all[i] = src->multi_remove_all[i];
247       err = list_duplicate(dest->multi_remove[i], src->multi_remove[i]);
248       if (err)
249       {
250          return err;
251       }
252       err = list_duplicate(dest->multi_add[i],    src->multi_add[i]);
253       if (err)
254       {
255          return err;
256       }
257    }
258    return err;
259 }
260
261 /*********************************************************************
262  *
263  * Function    :  free_action_spec
264  *
265  * Description :  Frees an action_spec and the memory used by it.
266  *
267  * Parameters  :
268  *          1  :  src = Source to free.
269  *
270  * Returns     :  N/A
271  *
272  *********************************************************************/
273 void free_action_spec(struct action_spec *src)
274 {
275    free_action(src);
276    freez(src);
277 }
278
279
280 /*********************************************************************
281  *
282  * Function    :  free_action
283  *
284  * Description :  Destroy an action_spec.  Frees memory used by it,
285  *                except for the memory used by the struct action_spec
286  *                itself.
287  *
288  * Parameters  :
289  *          1  :  src = Source to free.
290  *
291  * Returns     :  N/A
292  *
293  *********************************************************************/
294 void free_action (struct action_spec *src)
295 {
296    int i;
297
298    if (src == NULL)
299    {
300       return;
301    }
302
303    for (i = 0; i < ACTION_STRING_COUNT; i++)
304    {
305       freez(src->string[i]);
306    }
307
308    for (i = 0; i < ACTION_MULTI_COUNT; i++)
309    {
310       destroy_list(src->multi_remove[i]);
311       destroy_list(src->multi_add[i]);
312    }
313
314    memset(src, '\0', sizeof(*src));
315 }
316
317
318 /*********************************************************************
319  *
320  * Function    :  get_action_token
321  *
322  * Description :  Parses a line for the first action.
323  *                Modifies its input array, doesn't allocate memory.
324  *                e.g. given:
325  *                *line="  +abc{def}  -ghi "
326  *                Returns:
327  *                *line="  -ghi "
328  *                *name="+abc"
329  *                *value="def"
330  *
331  * Parameters  :
332  *          1  :  line = [in] The line containing the action.
333  *                       [out] Start of next action on line, or
334  *                       NULL if we reached the end of line before
335  *                       we found an action.
336  *          2  :  name = [out] Start of action name, null
337  *                       terminated.  NULL on EOL
338  *          3  :  value = [out] Start of action value, null
339  *                        terminated.  NULL if none or EOL.
340  *
341  * Returns     :  JB_ERR_OK => Ok
342  *                JB_ERR_PARSE => Mismatched {} (line was trashed anyway)
343  *
344  *********************************************************************/
345 jb_err get_action_token(char **line, char **name, char **value)
346 {
347    char * str = *line;
348    char ch;
349
350    /* set default returns */
351    *line = NULL;
352    *name = NULL;
353    *value = NULL;
354
355    /* Eat any leading whitespace */
356    while ((*str == ' ') || (*str == '\t'))
357    {
358       str++;
359    }
360
361    if (*str == '\0')
362    {
363       return 0;
364    }
365
366    if (*str == '{')
367    {
368       /* null name, just value is prohibited */
369       return JB_ERR_PARSE;
370    }
371
372    *name = str;
373
374    /* parse option */
375    while (((ch = *str) != '\0') &&
376           (ch != ' ') && (ch != '\t') && (ch != '{'))
377    {
378       if (ch == '}')
379       {
380          /* error, '}' without '{' */
381          return JB_ERR_PARSE;
382       }
383       str++;
384    }
385    *str = '\0';
386
387    if (ch != '{')
388    {
389       /* no value */
390       if (ch == '\0')
391       {
392          /* EOL - be careful not to run off buffer */
393          *line = str;
394       }
395       else
396       {
397          /* More to parse next time. */
398          *line = str + 1;
399       }
400       return JB_ERR_OK;
401    }
402
403    str++;
404    *value = str;
405
406    str = strchr(str, '}');
407    if (str == NULL)
408    {
409       /* error */
410       *value = NULL;
411       return JB_ERR_PARSE;
412    }
413
414    /* got value */
415    *str = '\0';
416    *line = str + 1;
417
418    chomp(*value);
419
420    return JB_ERR_OK;
421 }
422
423 /*********************************************************************
424  *
425  * Function    :  action_used_to_be_valid
426  *
427  * Description :  Checks if unrecognized actions were valid in earlier
428  *                releases.
429  *
430  * Parameters  :
431  *          1  :  action = The string containing the action to check.
432  *
433  * Returns     :  True if yes, otherwise false.
434  *
435  *********************************************************************/
436 static int action_used_to_be_valid(const char *action)
437 {
438    static const char * const formerly_valid_actions[] = {
439       "inspect-jpegs",
440       "kill-popups",
441       "send-vanilla-wafer",
442       "send-wafer",
443       "treat-forbidden-connects-like-blocks",
444       "vanilla-wafer",
445       "wafer"
446    };
447    unsigned int i;
448
449    for (i = 0; i < SZ(formerly_valid_actions); i++)
450    {
451       if (0 == strcmpic(action, formerly_valid_actions[i]))
452       {
453          return TRUE;
454       }
455    }
456
457    return FALSE;
458 }
459
460 /*********************************************************************
461  *
462  * Function    :  get_actions
463  *
464  * Description :  Parses a list of actions.
465  *
466  * Parameters  :
467  *          1  :  line = The string containing the actions.
468  *                       Will be written to by this function.
469  *          2  :  alias_list = Custom alias list, or NULL for none.
470  *          3  :  cur_action = Where to store the action.  Caller
471  *                             allocates memory.
472  *
473  * Returns     :  JB_ERR_OK => Ok
474  *                JB_ERR_PARSE => Parse error (line was trashed anyway)
475  *                nonzero => Out of memory (line was trashed anyway)
476  *
477  *********************************************************************/
478 jb_err get_actions(char *line,
479                    struct action_alias * alias_list,
480                    struct action_spec *cur_action)
481 {
482    jb_err err;
483    init_action(cur_action);
484    cur_action->mask = ACTION_MASK_ALL;
485
486    while (line)
487    {
488       char * option = NULL;
489       char * value = NULL;
490
491       err = get_action_token(&line, &option, &value);
492       if (err)
493       {
494          return err;
495       }
496
497       if (option)
498       {
499          /* handle option in 'option' */
500
501          /* Check for standard action name */
502          const struct action_name * action = action_names;
503
504          while ((action->name != NULL) && (0 != strcmpic(action->name, option)))
505          {
506             action++;
507          }
508          if (action->name != NULL)
509          {
510             /* Found it */
511             cur_action->mask &= action->mask;
512             cur_action->add  &= action->mask;
513             cur_action->add  |= action->add;
514
515             switch (action->value_type)
516             {
517             case AV_NONE:
518                /* ignore any option. */
519                break;
520             case AV_ADD_STRING:
521                {
522                   /* add single string. */
523
524                   if ((value == NULL) || (*value == '\0'))
525                   {
526                      if (0 == strcmpic(action->name, "+block"))
527                      {
528                         /*
529                          * XXX: Temporary backwards compatibility hack.
530                          * XXX: should include line number.
531                          */
532                         value = "No reason specified.";
533                         log_error(LOG_LEVEL_ERROR,
534                            "block action without reason found. This may "
535                            "become a fatal error in future versions.");
536                      }
537                      else
538                      {
539                         return JB_ERR_PARSE;
540                      }
541                   }
542                   /* FIXME: should validate option string here */
543                   freez (cur_action->string[action->index]);
544                   cur_action->string[action->index] = strdup(value);
545                   if (NULL == cur_action->string[action->index])
546                   {
547                      return JB_ERR_MEMORY;
548                   }
549                   break;
550                }
551             case AV_REM_STRING:
552                {
553                   /* remove single string. */
554
555                   freez (cur_action->string[action->index]);
556                   break;
557                }
558             case AV_ADD_MULTI:
559                {
560                   /* append multi string. */
561
562                   struct list * remove_p = cur_action->multi_remove[action->index];
563                   struct list * add_p    = cur_action->multi_add[action->index];
564
565                   if ((value == NULL) || (*value == '\0'))
566                   {
567                      return JB_ERR_PARSE;
568                   }
569
570                   list_remove_item(remove_p, value);
571                   err = enlist_unique(add_p, value, 0);
572                   if (err)
573                   {
574                      return err;
575                   }
576                   break;
577                }
578             case AV_REM_MULTI:
579                {
580                   /* remove multi string. */
581
582                   struct list * remove_p = cur_action->multi_remove[action->index];
583                   struct list * add_p    = cur_action->multi_add[action->index];
584
585                   if ((value == NULL) || (*value == '\0')
586                      || ((*value == '*') && (value[1] == '\0')))
587                   {
588                      /*
589                       * no option, or option == "*".
590                       *
591                       * Remove *ALL*.
592                       */
593                      list_remove_all(remove_p);
594                      list_remove_all(add_p);
595                      cur_action->multi_remove_all[action->index] = 1;
596                   }
597                   else
598                   {
599                      /* Valid option - remove only 1 option */
600
601                      if (!cur_action->multi_remove_all[action->index])
602                      {
603                         /* there isn't a catch-all in the remove list already */
604                         err = enlist_unique(remove_p, value, 0);
605                         if (err)
606                         {
607                            return err;
608                         }
609                      }
610                      list_remove_item(add_p, value);
611                   }
612                   break;
613                }
614             default:
615                /* Shouldn't get here unless there's memory corruption. */
616                assert(0);
617                return JB_ERR_PARSE;
618             }
619          }
620          else
621          {
622             /* try user aliases. */
623             const struct action_alias * alias = alias_list;
624
625             while ((alias != NULL) && (0 != strcmpic(alias->name, option)))
626             {
627                alias = alias->next;
628             }
629             if (alias != NULL)
630             {
631                /* Found it */
632                merge_actions(cur_action, alias->action);
633             }
634             else if (((size_t)2 < strlen(option)) && action_used_to_be_valid(option+1))
635             {
636                log_error(LOG_LEVEL_ERROR, "Action '%s' is no longer valid "
637                   "in this Privoxy release. Ignored.", option+1);
638             }
639             else if (((size_t)2 < strlen(option)) && 0 == strcmpic(option+1, "hide-forwarded-for-headers"))
640             {
641                log_error(LOG_LEVEL_FATAL, "The action 'hide-forwarded-for-headers' "
642                   "is no longer valid in this Privoxy release. "
643                   "Use 'change-x-forwarded-for' instead.");
644             }
645             else
646             {
647                /* Bad action name */
648                /*
649                 * XXX: This is a fatal error and Privoxy will later on exit
650                 * in load_one_actions_file() because of an "invalid line".
651                 *
652                 * It would be preferable to name the offending option in that
653                 * error message, but currently there is no way to do that and
654                 * we have to live with two error messages for basically the
655                 * same reason.
656                 */
657                log_error(LOG_LEVEL_ERROR, "Unknown action or alias: %s", option);
658                return JB_ERR_PARSE;
659             }
660          }
661       }
662    }
663
664    return JB_ERR_OK;
665 }
666
667
668 /*********************************************************************
669  *
670  * Function    :  init_current_action
671  *
672  * Description :  Zero out an action.
673  *
674  * Parameters  :
675  *          1  :  dest = An uninitialized current_action_spec.
676  *
677  * Returns     :  N/A
678  *
679  *********************************************************************/
680 void init_current_action (struct current_action_spec *dest)
681 {
682    memset(dest, '\0', sizeof(*dest));
683
684    dest->flags = ACTION_MOST_COMPATIBLE;
685 }
686
687
688 /*********************************************************************
689  *
690  * Function    :  init_action
691  *
692  * Description :  Zero out an action.
693  *
694  * Parameters  :
695  *          1  :  dest = An uninitialized action_spec.
696  *
697  * Returns     :  N/A
698  *
699  *********************************************************************/
700 void init_action (struct action_spec *dest)
701 {
702    memset(dest, '\0', sizeof(*dest));
703 }
704
705
706 /*********************************************************************
707  *
708  * Function    :  merge_current_action
709  *
710  * Description :  Merge two actions together.
711  *                Similar to "dest += src".
712  *                Differences between this and merge_actions()
713  *                is that this one doesn't allocate memory for
714  *                strings (so "src" better be in memory for at least
715  *                as long as "dest" is, and you'd better free
716  *                "dest" using "free_current_action").
717  *                Also, there is no  mask or remove lists in dest.
718  *                (If we're applying it to a URL, we don't need them)
719  *
720  * Parameters  :
721  *          1  :  dest = Current actions, to modify.
722  *          2  :  src = Action to add.
723  *
724  * Returns  0  :  no error
725  *        !=0  :  error, probably JB_ERR_MEMORY.
726  *
727  *********************************************************************/
728 jb_err merge_current_action (struct current_action_spec *dest,
729                              const struct action_spec *src)
730 {
731    int i;
732    jb_err err = JB_ERR_OK;
733
734    dest->flags  &= src->mask;
735    dest->flags  |= src->add;
736
737    for (i = 0; i < ACTION_STRING_COUNT; i++)
738    {
739       char * str = src->string[i];
740       if (str)
741       {
742          str = strdup(str);
743          if (!str)
744          {
745             return JB_ERR_MEMORY;
746          }
747          freez(dest->string[i]);
748          dest->string[i] = str;
749       }
750    }
751
752    for (i = 0; i < ACTION_MULTI_COUNT; i++)
753    {
754       if (src->multi_remove_all[i])
755       {
756          /* Remove everything from dest, then add src->multi_add */
757          err = list_duplicate(dest->multi[i], src->multi_add[i]);
758          if (err)
759          {
760             return err;
761          }
762       }
763       else
764       {
765          list_remove_list(dest->multi[i], src->multi_remove[i]);
766          err = list_append_list_unique(dest->multi[i], src->multi_add[i]);
767          if (err)
768          {
769             return err;
770          }
771       }
772    }
773    return err;
774 }
775
776
777 /*********************************************************************
778  *
779  * Function    :  update_action_bits_for_tag
780  *
781  * Description :  Updates the action bits based on the action sections
782  *                whose tag patterns match a provided tag.
783  *
784  * Parameters  :
785  *          1  :  csp = Current client state (buffers, headers, etc...)
786  *          2  :  tag = The tag on which the update should be based on
787  *
788  * Returns     :  0 if no tag matched, or
789  *                1 otherwise
790  *
791  *********************************************************************/
792 int update_action_bits_for_tag(struct client_state *csp, const char *tag)
793 {
794    struct file_list *fl;
795    struct url_actions *b;
796
797    int updated = 0;
798    int i;
799
800    assert(tag);
801    assert(list_contains_item(csp->tags, tag));
802
803    /* Run through all action files, */
804    for (i = 0; i < MAX_AF_FILES; i++)
805    {
806       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
807       {
808          /* Skip empty files */
809          continue;
810       }
811
812       /* and through all the action patterns, */
813       for (b = b->next; NULL != b; b = b->next)
814       {
815          /* skip the URL patterns, */
816          if (NULL == b->url->tag_regex)
817          {
818             continue;
819          }
820
821          /* and check if one of the tag patterns matches the tag, */
822          if (0 == regexec(b->url->tag_regex, tag, 0, NULL, 0))
823          {
824             /* if it does, update the action bit map, */
825             if (merge_current_action(csp->action, b->action))
826             {
827                log_error(LOG_LEVEL_ERROR,
828                   "Out of memory while changing action bits");
829             }
830             /* and signal the change. */
831             updated = 1;
832          }
833       }
834    }
835
836    return updated;
837 }
838
839
840 /*********************************************************************
841  *
842  * Function    :  free_current_action
843  *
844  * Description :  Free memory used by a current_action_spec.
845  *                Does not free the current_action_spec itself.
846  *
847  * Parameters  :
848  *          1  :  src = Source to free.
849  *
850  * Returns     :  N/A
851  *
852  *********************************************************************/
853 void free_current_action(struct current_action_spec *src)
854 {
855    int i;
856
857    for (i = 0; i < ACTION_STRING_COUNT; i++)
858    {
859       freez(src->string[i]);
860    }
861
862    for (i = 0; i < ACTION_MULTI_COUNT; i++)
863    {
864       destroy_list(src->multi[i]);
865    }
866
867    memset(src, '\0', sizeof(*src));
868 }
869
870
871 static struct file_list *current_actions_file[MAX_AF_FILES]  = {
872    NULL, NULL, NULL, NULL, NULL,
873    NULL, NULL, NULL, NULL, NULL
874 };
875
876
877 #ifdef FEATURE_GRACEFUL_TERMINATION
878 /*********************************************************************
879  *
880  * Function    :  unload_current_actions_file
881  *
882  * Description :  Unloads current actions file - reset to state at
883  *                beginning of program.
884  *
885  * Parameters  :  None
886  *
887  * Returns     :  N/A
888  *
889  *********************************************************************/
890 void unload_current_actions_file(void)
891 {
892    int i;
893
894    for (i = 0; i < MAX_AF_FILES; i++)
895    {
896       if (current_actions_file[i])
897       {
898          current_actions_file[i]->unloader = unload_actions_file;
899          current_actions_file[i] = NULL;
900       }
901    }
902 }
903 #endif /* FEATURE_GRACEFUL_TERMINATION */
904
905
906 /*********************************************************************
907  *
908  * Function    :  unload_actions_file
909  *
910  * Description :  Unloads an actions module.
911  *
912  * Parameters  :
913  *          1  :  file_data = the data structure associated with the
914  *                            actions file.
915  *
916  * Returns     :  N/A
917  *
918  *********************************************************************/
919 void unload_actions_file(void *file_data)
920 {
921    struct url_actions * next;
922    struct url_actions * cur = (struct url_actions *)file_data;
923    while (cur != NULL)
924    {
925       next = cur->next;
926       free_url_spec(cur->url);
927       if ((next == NULL) || (next->action != cur->action))
928       {
929          /*
930           * As the action settings might be shared,
931           * we can only free them if the current
932           * url pattern is the last one, or if the
933           * next one is using different settings.
934           */
935          free_action_spec(cur->action);
936       }
937       freez(cur);
938       cur = next;
939    }
940 }
941
942
943 /*********************************************************************
944  *
945  * Function    :  free_alias_list
946  *
947  * Description :  Free memory used by a list of aliases.
948  *
949  * Parameters  :
950  *          1  :  alias_list = Linked list to free.
951  *
952  * Returns     :  N/A
953  *
954  *********************************************************************/
955 void free_alias_list(struct action_alias *alias_list)
956 {
957    while (alias_list != NULL)
958    {
959       struct action_alias * next = alias_list->next;
960       alias_list->next = NULL;
961       freez(alias_list->name);
962       free_action(alias_list->action);
963       free(alias_list);
964       alias_list = next;
965    }
966 }
967
968
969 /*********************************************************************
970  *
971  * Function    :  load_action_files
972  *
973  * Description :  Read and parse all the action files and add to files
974  *                list.
975  *
976  * Parameters  :
977  *          1  :  csp = Current client state (buffers, headers, etc...)
978  *
979  * Returns     :  0 => Ok, everything else is an error.
980  *
981  *********************************************************************/
982 int load_action_files(struct client_state *csp)
983 {
984    int i;
985    int result;
986
987    for (i = 0; i < MAX_AF_FILES; i++)
988    {
989       if (csp->config->actions_file[i])
990       {
991          result = load_one_actions_file(csp, i);
992          if (result)
993          {
994             return result;
995          }
996       }
997       else if (current_actions_file[i])
998       {
999          current_actions_file[i]->unloader = unload_actions_file;
1000          current_actions_file[i] = NULL;
1001       }
1002    }
1003
1004    return 0;
1005 }
1006
1007
1008 /*********************************************************************
1009  *
1010  * Function    :  referenced_filters_are_missing
1011  *
1012  * Description :  Checks if any filters of a certain type referenced
1013  *                in an action spec are missing.
1014  *
1015  * Parameters  :
1016  *          1  :  csp = Current client state (buffers, headers, etc...)
1017  *          2  :  cur_action = The action spec to check.
1018  *          3  :  multi_index = The index where to look for the filter.
1019  *          4  :  filter_type = The filter type the caller is interested in.
1020  *
1021  * Returns     :  0 => All referenced filters exists, everything else is an error.
1022  *
1023  *********************************************************************/
1024 static int referenced_filters_are_missing(const struct client_state *csp,
1025    const struct action_spec *cur_action, int multi_index, enum filter_type filter_type)
1026 {
1027    int i;
1028    struct file_list *fl;
1029    struct re_filterfile_spec *b;
1030    struct list_entry *filtername;
1031
1032    for (filtername = cur_action->multi_add[multi_index]->first;
1033         filtername; filtername = filtername->next)
1034    {
1035       int filter_found = 0;
1036       for (i = 0; i < MAX_AF_FILES; i++)
1037       {
1038          fl = csp->rlist[i];
1039          if ((NULL == fl) || (NULL == fl->f))
1040          {
1041             continue;
1042          }
1043
1044          for (b = fl->f; b; b = b->next)
1045          {
1046             if (b->type != filter_type)
1047             {
1048                continue;
1049             }
1050             if (strcmp(b->name, filtername->str) == 0)
1051             {
1052                filter_found = 1;
1053             }
1054          }
1055       }
1056       if (!filter_found)
1057       {
1058          log_error(LOG_LEVEL_ERROR, "Missing filter '%s'", filtername->str);
1059          return 1;
1060       }
1061    }
1062
1063    return 0;
1064
1065 }
1066
1067
1068 /*********************************************************************
1069  *
1070  * Function    :  action_spec_is_valid
1071  *
1072  * Description :  Should eventually figure out if an action spec
1073  *                is valid, but currently only checks that the
1074  *                referenced filters are accounted for.
1075  *
1076  * Parameters  :
1077  *          1  :  csp = Current client state (buffers, headers, etc...)
1078  *          2  :  cur_action = The action spec to check.
1079  *
1080  * Returns     :  0 => No problems detected, everything else is an error.
1081  *
1082  *********************************************************************/
1083 static int action_spec_is_valid(struct client_state *csp, const struct action_spec *cur_action)
1084 {
1085    struct {
1086       int multi_index;
1087       enum filter_type filter_type;
1088    } filter_map[] = {
1089       {ACTION_MULTI_FILTER, FT_CONTENT_FILTER},
1090       {ACTION_MULTI_CLIENT_HEADER_FILTER, FT_CLIENT_HEADER_FILTER},
1091       {ACTION_MULTI_SERVER_HEADER_FILTER, FT_SERVER_HEADER_FILTER},
1092       {ACTION_MULTI_CLIENT_HEADER_TAGGER, FT_CLIENT_HEADER_TAGGER},
1093       {ACTION_MULTI_SERVER_HEADER_TAGGER, FT_SERVER_HEADER_TAGGER}
1094    };
1095    int errors = 0;
1096    int i;
1097
1098    for (i = 0; i < SZ(filter_map); i++)
1099    {
1100       errors += referenced_filters_are_missing(csp, cur_action,
1101          filter_map[i].multi_index, filter_map[i].filter_type);
1102    }
1103
1104    return errors;
1105
1106 }
1107
1108
1109 /*********************************************************************
1110  *
1111  * Function    :  load_one_actions_file
1112  *
1113  * Description :  Read and parse a action file and add to files
1114  *                list.
1115  *
1116  * Parameters  :
1117  *          1  :  csp = Current client state (buffers, headers, etc...)
1118  *          2  :  fileid = File index to load.
1119  *
1120  * Returns     :  0 => Ok, everything else is an error.
1121  *
1122  *********************************************************************/
1123 static int load_one_actions_file(struct client_state *csp, int fileid)
1124 {
1125
1126    /*
1127     * Parser mode.
1128     * Note: Keep these in the order they occur in the file, they are
1129     * sometimes tested with <=
1130     */
1131    enum {
1132       MODE_START_OF_FILE = 1,
1133       MODE_SETTINGS      = 2,
1134       MODE_DESCRIPTION   = 3,
1135       MODE_ALIAS         = 4,
1136       MODE_ACTIONS       = 5
1137    } mode;
1138
1139    FILE *fp;
1140    struct url_actions *last_perm;
1141    struct url_actions *perm;
1142    char  *buf;
1143    struct file_list *fs;
1144    struct action_spec * cur_action = NULL;
1145    int cur_action_used = 0;
1146    struct action_alias * alias_list = NULL;
1147    unsigned long linenum = 0;
1148    mode = MODE_START_OF_FILE;
1149
1150    if (!check_file_changed(current_actions_file[fileid], csp->config->actions_file[fileid], &fs))
1151    {
1152       /* No need to load */
1153       csp->actions_list[fileid] = current_actions_file[fileid];
1154       return 0;
1155    }
1156    if (!fs)
1157    {
1158       log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': %E. "
1159          "Note that beginning with Privoxy 3.0.7, actions files have to be specified "
1160          "with their complete file names.", csp->config->actions_file[fileid]);
1161       return 1; /* never get here */
1162    }
1163
1164    fs->f = last_perm = (struct url_actions *)zalloc(sizeof(*last_perm));
1165    if (last_perm == NULL)
1166    {
1167       log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': out of memory!",
1168                 csp->config->actions_file[fileid]);
1169       return 1; /* never get here */
1170    }
1171
1172    if ((fp = fopen(csp->config->actions_file[fileid], "r")) == NULL)
1173    {
1174       log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': error opening file: %E",
1175                 csp->config->actions_file[fileid]);
1176       return 1; /* never get here */
1177    }
1178
1179    log_error(LOG_LEVEL_INFO, "Loading actions file: %s", csp->config->actions_file[fileid]);
1180
1181    while (read_config_line(fp, &linenum, &buf) != NULL)
1182    {
1183       if (*buf == '{')
1184       {
1185          /* It's a header block */
1186          if (buf[1] == '{')
1187          {
1188             /* It's {{settings}} or {{alias}} */
1189             size_t len = strlen(buf);
1190             char * start = buf + 2;
1191             char * end = buf + len - 1;
1192             if ((len < (size_t)5) || (*end-- != '}') || (*end-- != '}'))
1193             {
1194                /* too short */
1195                fclose(fp);
1196                log_error(LOG_LEVEL_FATAL,
1197                   "can't load actions file '%s': invalid line (%lu): %s",
1198                   csp->config->actions_file[fileid], linenum, buf);
1199                return 1; /* never get here */
1200             }
1201
1202             /* Trim leading and trailing whitespace. */
1203             end[1] = '\0';
1204             chomp(start);
1205
1206             if (*start == '\0')
1207             {
1208                /* too short */
1209                fclose(fp);
1210                log_error(LOG_LEVEL_FATAL,
1211                   "can't load actions file '%s': invalid line (%lu): {{ }}",
1212                   csp->config->actions_file[fileid], linenum);
1213                return 1; /* never get here */
1214             }
1215
1216             /*
1217              * An actionsfile can optionally contain the following blocks.
1218              * They *MUST* be in this order, to simplify processing:
1219              *
1220              * {{settings}}
1221              * name=value...
1222              *
1223              * {{description}}
1224              * ...free text, format TBD, but no line may start with a '{'...
1225              *
1226              * {{alias}}
1227              * name=actions...
1228              *
1229              * The actual actions must be *after* these special blocks.
1230              * None of these special blocks may be repeated.
1231              *
1232              */
1233             if (0 == strcmpic(start, "settings"))
1234             {
1235                /* it's a {{settings}} block */
1236                if (mode >= MODE_SETTINGS)
1237                {
1238                   /* {{settings}} must be first thing in file and must only
1239                    * appear once.
1240                    */
1241                   fclose(fp);
1242                   log_error(LOG_LEVEL_FATAL,
1243                      "can't load actions file '%s': line %lu: {{settings}} must only appear once, and it must be before anything else.",
1244                      csp->config->actions_file[fileid], linenum);
1245                }
1246                mode = MODE_SETTINGS;
1247             }
1248             else if (0 == strcmpic(start, "description"))
1249             {
1250                /* it's a {{description}} block */
1251                if (mode >= MODE_DESCRIPTION)
1252                {
1253                   /* {{description}} is a singleton and only {{settings}} may proceed it
1254                    */
1255                   fclose(fp);
1256                   log_error(LOG_LEVEL_FATAL,
1257                      "can't load actions file '%s': line %lu: {{description}} must only appear once, and only a {{settings}} block may be above it.",
1258                      csp->config->actions_file[fileid], linenum);
1259                }
1260                mode = MODE_DESCRIPTION;
1261             }
1262             else if (0 == strcmpic(start, "alias"))
1263             {
1264                /* it's an {{alias}} block */
1265                if (mode >= MODE_ALIAS)
1266                {
1267                   /* {{alias}} must be first thing in file, possibly after
1268                    * {{settings}} and {{description}}
1269                    *
1270                    * {{alias}} must only appear once.
1271                    *
1272                    * Note that these are new restrictions introduced in
1273                    * v2.9.10 in order to make actionsfile editing simpler.
1274                    * (Otherwise, reordering actionsfile entries without
1275                    * completely rewriting the file becomes non-trivial)
1276                    */
1277                   fclose(fp);
1278                   log_error(LOG_LEVEL_FATAL,
1279                      "can't load actions file '%s': line %lu: {{alias}} must only appear once, and it must be before all actions.",
1280                      csp->config->actions_file[fileid], linenum);
1281                }
1282                mode = MODE_ALIAS;
1283             }
1284             else
1285             {
1286                /* invalid {{something}} block */
1287                fclose(fp);
1288                log_error(LOG_LEVEL_FATAL,
1289                   "can't load actions file '%s': invalid line (%lu): {{%s}}",
1290                   csp->config->actions_file[fileid], linenum, start);
1291                return 1; /* never get here */
1292             }
1293          }
1294          else
1295          {
1296             /* It's an actions block */
1297
1298             char *actions_buf;
1299             char * end;
1300
1301             /* set mode */
1302             mode = MODE_ACTIONS;
1303
1304             /* free old action */
1305             if (cur_action)
1306             {
1307                if (!cur_action_used)
1308                {
1309                   free_action_spec(cur_action);
1310                }
1311                cur_action = NULL;
1312             }
1313             cur_action_used = 0;
1314             cur_action = (struct action_spec *)zalloc(sizeof(*cur_action));
1315             if (cur_action == NULL)
1316             {
1317                fclose(fp);
1318                log_error(LOG_LEVEL_FATAL,
1319                   "can't load actions file '%s': out of memory",
1320                   csp->config->actions_file[fileid]);
1321                return 1; /* never get here */
1322             }
1323             init_action(cur_action);
1324
1325             /*
1326              * Copy the buffer before messing with it as we may need the
1327              * unmodified version in for the fatal error messages. Given
1328              * that this is not a common event, we could instead simply
1329              * read the line again.
1330              *
1331              * buf + 1 to skip the leading '{'
1332              */
1333             actions_buf = strdup(buf + 1);
1334             if (actions_buf == NULL)
1335             {
1336                fclose(fp);
1337                log_error(LOG_LEVEL_FATAL,
1338                   "can't load actions file '%s': out of memory",
1339                   csp->config->actions_file[fileid]);
1340                return 1; /* never get here */
1341             }
1342
1343             /* check we have a trailing } and then trim it */
1344             end = actions_buf + strlen(actions_buf) - 1;
1345             if (*end != '}')
1346             {
1347                /* No closing } */
1348                fclose(fp);
1349                freez(actions_buf);
1350                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1351                   "Missing trailing '}' in action section starting at line (%lu): %s",
1352                   csp->config->actions_file[fileid], linenum, buf);
1353                return 1; /* never get here */
1354             }
1355             *end = '\0';
1356
1357             /* trim any whitespace immediately inside {} */
1358             chomp(actions_buf);
1359
1360             if (get_actions(actions_buf, alias_list, cur_action))
1361             {
1362                /* error */
1363                fclose(fp);
1364                freez(actions_buf);
1365                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1366                   "can't completely parse the action section starting at line (%lu): %s",
1367                   csp->config->actions_file[fileid], linenum, buf);
1368                return 1; /* never get here */
1369             }
1370
1371             if (action_spec_is_valid(csp, cur_action))
1372             {
1373                log_error(LOG_LEVEL_ERROR, "Invalid action section in file '%s', "
1374                   "starting at line %lu: %s",
1375                   csp->config->actions_file[fileid], linenum, buf);
1376             }
1377
1378             freez(actions_buf);
1379          }
1380       }
1381       else if (mode == MODE_SETTINGS)
1382       {
1383          /*
1384           * Part of the {{settings}} block.
1385           * For now only serves to check if the file's minimum Privoxy
1386           * version requirement is met, but we may want to read & check
1387           * permissions when we go multi-user.
1388           */
1389          if (!strncmp(buf, "for-privoxy-version=", 20))
1390          {
1391             char *version_string, *fields[3];
1392             int num_fields;
1393
1394             if ((version_string = strdup(buf + 20)) == NULL)
1395             {
1396                fclose(fp);
1397                log_error(LOG_LEVEL_FATAL,
1398                          "can't load actions file '%s': out of memory!",
1399                          csp->config->actions_file[fileid]);
1400                return 1; /* never get here */
1401             }
1402
1403             num_fields = ssplit(version_string, ".", fields, SZ(fields), TRUE, FALSE);
1404
1405             if (num_fields < 1 || atoi(fields[0]) == 0)
1406             {
1407                log_error(LOG_LEVEL_ERROR,
1408                  "While loading actions file '%s': invalid line (%lu): %s",
1409                   csp->config->actions_file[fileid], linenum, buf);
1410             }
1411             else if (                  (atoi(fields[0]) > VERSION_MAJOR)
1412                || ((num_fields) > 1 && (atoi(fields[1]) > VERSION_MINOR))
1413                || ((num_fields) > 2 && (atoi(fields[2]) > VERSION_POINT)))
1414             {
1415                fclose(fp);
1416                log_error(LOG_LEVEL_FATAL,
1417                          "Actions file '%s', line %lu requires newer Privoxy version: %s",
1418                          csp->config->actions_file[fileid], linenum, buf);
1419                return 1; /* never get here */
1420             }
1421             free(version_string);
1422          }
1423       }
1424       else if (mode == MODE_DESCRIPTION)
1425       {
1426          /*
1427           * Part of the {{description}} block.
1428           * Ignore for now.
1429           */
1430       }
1431       else if (mode == MODE_ALIAS)
1432       {
1433          /*
1434           * define an alias
1435           */
1436          char  actions_buf[BUFFER_SIZE];
1437          struct action_alias * new_alias;
1438
1439          char * start = strchr(buf, '=');
1440          char * end = start;
1441
1442          if ((start == NULL) || (start == buf))
1443          {
1444             log_error(LOG_LEVEL_FATAL,
1445                "can't load actions file '%s': invalid alias line (%lu): %s",
1446                csp->config->actions_file[fileid], linenum, buf);
1447             return 1; /* never get here */
1448          }
1449
1450          if ((new_alias = zalloc(sizeof(*new_alias))) == NULL)
1451          {
1452             fclose(fp);
1453             log_error(LOG_LEVEL_FATAL,
1454                "can't load actions file '%s': out of memory!",
1455                csp->config->actions_file[fileid]);
1456             return 1; /* never get here */
1457          }
1458
1459          /* Eat any the whitespace before the '=' */
1460          end--;
1461          while ((*end == ' ') || (*end == '\t'))
1462          {
1463             /*
1464              * we already know we must have at least 1 non-ws char
1465              * at start of buf - no need to check
1466              */
1467             end--;
1468          }
1469          end[1] = '\0';
1470
1471          /* Eat any the whitespace after the '=' */
1472          start++;
1473          while ((*start == ' ') || (*start == '\t'))
1474          {
1475             start++;
1476          }
1477          if (*start == '\0')
1478          {
1479             log_error(LOG_LEVEL_FATAL,
1480                "can't load actions file '%s': invalid alias line (%lu): %s",
1481                csp->config->actions_file[fileid], linenum, buf);
1482             return 1; /* never get here */
1483          }
1484
1485          if ((new_alias->name = strdup(buf)) == NULL)
1486          {
1487             fclose(fp);
1488             log_error(LOG_LEVEL_FATAL,
1489                "can't load actions file '%s': out of memory!",
1490                csp->config->actions_file[fileid]);
1491             return 1; /* never get here */
1492          }
1493
1494          strlcpy(actions_buf, start, sizeof(actions_buf));
1495
1496          if (get_actions(actions_buf, alias_list, new_alias->action))
1497          {
1498             /* error */
1499             fclose(fp);
1500             log_error(LOG_LEVEL_FATAL,
1501                "can't load actions file '%s': invalid alias line (%lu): %s = %s",
1502                csp->config->actions_file[fileid], linenum, buf, start);
1503             return 1; /* never get here */
1504          }
1505
1506          /* add to list */
1507          new_alias->next = alias_list;
1508          alias_list = new_alias;
1509       }
1510       else if (mode == MODE_ACTIONS)
1511       {
1512          /* it's an URL pattern */
1513
1514          /* allocate a new node */
1515          if ((perm = zalloc(sizeof(*perm))) == NULL)
1516          {
1517             fclose(fp);
1518             log_error(LOG_LEVEL_FATAL,
1519                "can't load actions file '%s': out of memory!",
1520                csp->config->actions_file[fileid]);
1521             return 1; /* never get here */
1522          }
1523
1524          perm->action = cur_action;
1525          cur_action_used = 1;
1526
1527          /* Save the URL pattern */
1528          if (create_url_spec(perm->url, buf))
1529          {
1530             fclose(fp);
1531             log_error(LOG_LEVEL_FATAL,
1532                "can't load actions file '%s': line %lu: cannot create URL or TAG pattern from: %s",
1533                csp->config->actions_file[fileid], linenum, buf);
1534             return 1; /* never get here */
1535          }
1536
1537          /* add it to the list */
1538          last_perm->next = perm;
1539          last_perm = perm;
1540       }
1541       else if (mode == MODE_START_OF_FILE)
1542       {
1543          /* oops - please have a {} line as 1st line in file. */
1544          fclose(fp);
1545          log_error(LOG_LEVEL_FATAL,
1546             "can't load actions file '%s': line %lu should begin with a '{': %s",
1547             csp->config->actions_file[fileid], linenum, buf);
1548          return 1; /* never get here */
1549       }
1550       else
1551       {
1552          /* How did we get here? This is impossible! */
1553          fclose(fp);
1554          log_error(LOG_LEVEL_FATAL,
1555             "can't load actions file '%s': INTERNAL ERROR - mode = %d",
1556             csp->config->actions_file[fileid], mode);
1557          return 1; /* never get here */
1558       }
1559       freez(buf);
1560    }
1561
1562    fclose(fp);
1563
1564    if (!cur_action_used)
1565    {
1566       free_action_spec(cur_action);
1567    }
1568    free_alias_list(alias_list);
1569
1570    /* the old one is now obsolete */
1571    if (current_actions_file[fileid])
1572    {
1573       current_actions_file[fileid]->unloader = unload_actions_file;
1574    }
1575
1576    fs->next    = files->next;
1577    files->next = fs;
1578    current_actions_file[fileid] = fs;
1579
1580    csp->actions_list[fileid] = fs;
1581
1582    return(0);
1583
1584 }
1585
1586
1587 /*********************************************************************
1588  *
1589  * Function    :  actions_to_text
1590  *
1591  * Description :  Converts a actionsfile entry from the internal
1592  *                structure into a text line.  The output is split
1593  *                into one line for each action with line continuation.
1594  *
1595  * Parameters  :
1596  *          1  :  action = The action to format.
1597  *
1598  * Returns     :  A string.  Caller must free it.
1599  *                NULL on out-of-memory error.
1600  *
1601  *********************************************************************/
1602 char * actions_to_text(const struct action_spec *action)
1603 {
1604    unsigned long mask = action->mask;
1605    unsigned long add  = action->add;
1606    char *result = strdup("");
1607    struct list_entry * lst;
1608
1609    /* sanity - prevents "-feature +feature" */
1610    mask |= add;
1611
1612
1613 #define DEFINE_ACTION_BOOL(__name, __bit)          \
1614    if (!(mask & __bit))                            \
1615    {                                               \
1616       string_append(&result, " -" __name " \\\n"); \
1617    }                                               \
1618    else if (add & __bit)                           \
1619    {                                               \
1620       string_append(&result, " +" __name " \\\n"); \
1621    }
1622
1623 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1624    if (!(mask & __bit))                                \
1625    {                                                   \
1626       string_append(&result, " -" __name " \\\n");     \
1627    }                                                   \
1628    else if (add & __bit)                               \
1629    {                                                   \
1630       string_append(&result, " +" __name "{");         \
1631       string_append(&result, action->string[__index]); \
1632       string_append(&result, "} \\\n");                \
1633    }
1634
1635 #define DEFINE_ACTION_MULTI(__name, __index)         \
1636    if (action->multi_remove_all[__index])            \
1637    {                                                 \
1638       string_append(&result, " -" __name " \\\n");   \
1639    }                                                 \
1640    else                                              \
1641    {                                                 \
1642       lst = action->multi_remove[__index]->first;    \
1643       while (lst)                                    \
1644       {                                              \
1645          string_append(&result, " -" __name "{");    \
1646          string_append(&result, lst->str);           \
1647          string_append(&result, "} \\\n");           \
1648          lst = lst->next;                            \
1649       }                                              \
1650    }                                                 \
1651    lst = action->multi_add[__index]->first;          \
1652    while (lst)                                       \
1653    {                                                 \
1654       string_append(&result, " +" __name "{");       \
1655       string_append(&result, lst->str);              \
1656       string_append(&result, "} \\\n");              \
1657       lst = lst->next;                               \
1658    }
1659
1660 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1661
1662 #include "actionlist.h"
1663
1664 #undef DEFINE_ACTION_MULTI
1665 #undef DEFINE_ACTION_STRING
1666 #undef DEFINE_ACTION_BOOL
1667 #undef DEFINE_ACTION_ALIAS
1668
1669    return result;
1670 }
1671
1672
1673 /*********************************************************************
1674  *
1675  * Function    :  actions_to_html
1676  *
1677  * Description :  Converts a actionsfile entry from numeric form
1678  *                ("mask" and "add") to a <br>-separated HTML string
1679  *                in which each action is linked to its chapter in
1680  *                the user manual.
1681  *
1682  * Parameters  :
1683  *          1  :  csp    = Client state (for config)
1684  *          2  :  action = Action spec to be converted
1685  *
1686  * Returns     :  A string.  Caller must free it.
1687  *                NULL on out-of-memory error.
1688  *
1689  *********************************************************************/
1690 char * actions_to_html(const struct client_state *csp,
1691                        const struct action_spec *action)
1692 {
1693    unsigned long mask = action->mask;
1694    unsigned long add  = action->add;
1695    char *result = strdup("");
1696    struct list_entry * lst;
1697
1698    /* sanity - prevents "-feature +feature" */
1699    mask |= add;
1700
1701
1702 #define DEFINE_ACTION_BOOL(__name, __bit)       \
1703    if (!(mask & __bit))                         \
1704    {                                            \
1705       string_append(&result, "\n<br>-");        \
1706       string_join(&result, add_help_link(__name, csp->config)); \
1707    }                                            \
1708    else if (add & __bit)                        \
1709    {                                            \
1710       string_append(&result, "\n<br>+");        \
1711       string_join(&result, add_help_link(__name, csp->config)); \
1712    }
1713
1714 #define DEFINE_ACTION_STRING(__name, __bit, __index) \
1715    if (!(mask & __bit))                              \
1716    {                                                 \
1717       string_append(&result, "\n<br>-");             \
1718       string_join(&result, add_help_link(__name, csp->config)); \
1719    }                                                 \
1720    else if (add & __bit)                             \
1721    {                                                 \
1722       string_append(&result, "\n<br>+");             \
1723       string_join(&result, add_help_link(__name, csp->config)); \
1724       string_append(&result, "{");                   \
1725       string_join(&result, html_encode(action->string[__index])); \
1726       string_append(&result, "}");                   \
1727    }
1728
1729 #define DEFINE_ACTION_MULTI(__name, __index)          \
1730    if (action->multi_remove_all[__index])             \
1731    {                                                  \
1732       string_append(&result, "\n<br>-");              \
1733       string_join(&result, add_help_link(__name, csp->config)); \
1734    }                                                  \
1735    else                                               \
1736    {                                                  \
1737       lst = action->multi_remove[__index]->first;     \
1738       while (lst)                                     \
1739       {                                               \
1740          string_append(&result, "\n<br>-");           \
1741          string_join(&result, add_help_link(__name, csp->config)); \
1742          string_append(&result, "{");                 \
1743          string_join(&result, html_encode(lst->str)); \
1744          string_append(&result, "}");                 \
1745          lst = lst->next;                             \
1746       }                                               \
1747    }                                                  \
1748    lst = action->multi_add[__index]->first;           \
1749    while (lst)                                        \
1750    {                                                  \
1751       string_append(&result, "\n<br>+");              \
1752       string_join(&result, add_help_link(__name, csp->config)); \
1753       string_append(&result, "{");                    \
1754       string_join(&result, html_encode(lst->str));    \
1755       string_append(&result, "}");                    \
1756       lst = lst->next;                                \
1757    }
1758
1759 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1760
1761 #include "actionlist.h"
1762
1763 #undef DEFINE_ACTION_MULTI
1764 #undef DEFINE_ACTION_STRING
1765 #undef DEFINE_ACTION_BOOL
1766 #undef DEFINE_ACTION_ALIAS
1767
1768    /* trim leading <br> */
1769    if (result && *result)
1770    {
1771       char * s = result;
1772       result = strdup(result + 5);
1773       free(s);
1774    }
1775
1776    return result;
1777 }
1778
1779
1780 /*********************************************************************
1781  *
1782  * Function    :  current_actions_to_html
1783  *
1784  * Description :  Converts a curren action spec to a <br> separated HTML
1785  *                text in which each action is linked to its chapter in
1786  *                the user manual.
1787  *
1788  * Parameters  :
1789  *          1  :  csp    = Client state (for config)
1790  *          2  :  action = Current action spec to be converted
1791  *
1792  * Returns     :  A string.  Caller must free it.
1793  *                NULL on out-of-memory error.
1794  *
1795  *********************************************************************/
1796 char *current_action_to_html(const struct client_state *csp,
1797                              const struct current_action_spec *action)
1798 {
1799    unsigned long flags  = action->flags;
1800    struct list_entry * lst;
1801    char *result   = strdup("");
1802    char *active   = strdup("");
1803    char *inactive = strdup("");
1804
1805 #define DEFINE_ACTION_BOOL(__name, __bit)  \
1806    if (flags & __bit)                      \
1807    {                                       \
1808       string_append(&active, "\n<br>+");   \
1809       string_join(&active, add_help_link(__name, csp->config)); \
1810    }                                       \
1811    else                                    \
1812    {                                       \
1813       string_append(&inactive, "\n<br>-"); \
1814       string_join(&inactive, add_help_link(__name, csp->config)); \
1815    }
1816
1817 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1818    if (flags & __bit)                                  \
1819    {                                                   \
1820       string_append(&active, "\n<br>+");               \
1821       string_join(&active, add_help_link(__name, csp->config)); \
1822       string_append(&active, "{");                     \
1823       string_join(&active, html_encode(action->string[__index])); \
1824       string_append(&active, "}");                     \
1825    }                                                   \
1826    else                                                \
1827    {                                                   \
1828       string_append(&inactive, "\n<br>-");             \
1829       string_join(&inactive, add_help_link(__name, csp->config)); \
1830    }
1831
1832 #define DEFINE_ACTION_MULTI(__name, __index)           \
1833    lst = action->multi[__index]->first;                \
1834    if (lst == NULL)                                    \
1835    {                                                   \
1836       string_append(&inactive, "\n<br>-");             \
1837       string_join(&inactive, add_help_link(__name, csp->config)); \
1838    }                                                   \
1839    else                                                \
1840    {                                                   \
1841       while (lst)                                      \
1842       {                                                \
1843          string_append(&active, "\n<br>+");            \
1844          string_join(&active, add_help_link(__name, csp->config)); \
1845          string_append(&active, "{");                  \
1846          string_join(&active, html_encode(lst->str));  \
1847          string_append(&active, "}");                  \
1848          lst = lst->next;                              \
1849       }                                                \
1850    }
1851
1852 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1853
1854 #include "actionlist.h"
1855
1856 #undef DEFINE_ACTION_MULTI
1857 #undef DEFINE_ACTION_STRING
1858 #undef DEFINE_ACTION_BOOL
1859 #undef DEFINE_ACTION_ALIAS
1860
1861    if (active != NULL)
1862    {
1863       string_append(&result, active);
1864       freez(active);
1865    }
1866    string_append(&result, "\n<br>");
1867    if (inactive != NULL)
1868    {
1869       string_append(&result, inactive);
1870       freez(inactive);
1871    }
1872    return result;
1873 }