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