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