Move LIMIT_MUTEX_NUMBER definition to project.h
[privoxy.git] / actions.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/actions.c,v $
4  *
5  * Purpose     :  Declares functions to work with actions files
6  *
7  * Copyright   :  Written by and Copyright (C) 2001-2016 the
8  *                Privoxy team. http://www.privoxy.org/
9  *
10  *                Based on the Internet Junkbuster originally written
11  *                by and Copyright (C) 1997 Anonymous Coders and
12  *                Junkbusters Corporation.  http://www.junkbusters.com
13  *
14  *                This program is free software; you can redistribute it
15  *                and/or modify it under the terms of the GNU General
16  *                Public License as published by the Free Software
17  *                Foundation; either version 2 of the License, or (at
18  *                your option) any later version.
19  *
20  *                This program is distributed in the hope that it will
21  *                be useful, but WITHOUT ANY WARRANTY; without even the
22  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
23  *                PARTICULAR PURPOSE.  See the GNU General Public
24  *                License for more details.
25  *
26  *                The GNU General Public License should be included with
27  *                this file.  If not, you can view it at
28  *                http://www.gnu.org/copyleft/gpl.html
29  *                or write to the Free Software Foundation, Inc., 59
30  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
31  *
32  *********************************************************************/
33
34
35 #include "config.h"
36
37 #include <stdio.h>
38 #include <string.h>
39 #include <assert.h>
40 #include <stdlib.h>
41
42 #ifdef FEATURE_PTHREAD
43 #include <pthread.h>
44 #endif
45
46 #include "project.h"
47 #include "jcc.h"
48 #include "list.h"
49 #include "actions.h"
50 #include "miscutil.h"
51 #include "errlog.h"
52 #include "loaders.h"
53 #include "encode.h"
54 #include "urlmatch.h"
55 #include "cgi.h"
56 #include "ssplit.h"
57 #include "filters.h"
58
59 /*
60  * We need the main list of options.
61  *
62  * First, we need a way to tell between boolean, string, and multi-string
63  * options.  For string and multistring options, we also need to be
64  * able to tell the difference between a "+" and a "-".  (For bools,
65  * the "+"/"-" information is encoded in "add" and "mask").  So we use
66  * an enumerated type (well, the preprocessor equivalent).  Here are
67  * the values:
68  */
69 enum action_value_type {
70    AV_NONE       = 0, /* +opt -opt */
71    AV_ADD_STRING = 1, /* +stropt{string} */
72    AV_REM_STRING = 2, /* -stropt */
73    AV_ADD_MULTI  = 3, /* +multiopt{string} +multiopt{string2} */
74    AV_REM_MULTI  = 4  /* -multiopt{string} -multiopt          */
75 };
76
77 /*
78  * We need a structure to hold the name, flag changes,
79  * type, and string index.
80  */
81 struct action_name
82 {
83    const char * name;
84    unsigned long mask;                /* a bit set to "0" = remove action */
85    unsigned long add;                 /* a bit set to "1" = add action */
86    enum action_value_type value_type; /* an AV_... constant */
87    int index;                         /* index into strings[] or multi[] */
88 };
89
90 /*
91  * And with those building blocks in place, here's the array.
92  */
93 static const struct action_name action_names[] =
94 {
95    /*
96     * Well actually there's no data here - it's in actionlist.h
97     * This keeps it together to make it easy to change.
98     *
99     * Here's the macros used to format it:
100     */
101 #define DEFINE_ACTION_MULTI(name,index)                   \
102    { "+" name, ACTION_MASK_ALL, 0, AV_ADD_MULTI, index }, \
103    { "-" name, ACTION_MASK_ALL, 0, AV_REM_MULTI, index },
104 #define DEFINE_ACTION_STRING(name,flag,index)                 \
105    { "+" name, ACTION_MASK_ALL, flag, AV_ADD_STRING, index }, \
106    { "-" name, ~flag, 0, AV_REM_STRING, index },
107 #define DEFINE_ACTION_BOOL(name,flag)   \
108    { "+" name, ACTION_MASK_ALL, flag }, \
109    { "-" name, ~flag, 0 },
110 #define DEFINE_ACTION_ALIAS 1 /* Want aliases please */
111
112 #include "actionlist.h"
113
114 #undef DEFINE_ACTION_MULTI
115 #undef DEFINE_ACTION_STRING
116 #undef DEFINE_ACTION_BOOL
117 #undef DEFINE_ACTION_ALIAS
118
119    { NULL, 0, 0 } /* End marker */
120 };
121
122
123 #ifndef FUZZ
124 static
125 #endif
126 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                if (value != NULL)
521                {
522                   log_error(LOG_LEVEL_ERROR,
523                      "Action %s does not take parameters but %s was given.",
524                      action->name, value);
525                   return JB_ERR_PARSE;
526                }
527                break;
528             case AV_ADD_STRING:
529                {
530                   /* add single string. */
531
532                   if ((value == NULL) || (*value == '\0'))
533                   {
534                      if (0 == strcmpic(action->name, "+block"))
535                      {
536                         /*
537                          * XXX: Temporary backwards compatibility hack.
538                          * XXX: should include line number.
539                          */
540                         value = "No reason specified.";
541                         log_error(LOG_LEVEL_ERROR,
542                            "block action without reason found. This may "
543                            "become a fatal error in future versions.");
544                      }
545                      else
546                      {
547                         return JB_ERR_PARSE;
548                      }
549                   }
550                   /* FIXME: should validate option string here */
551                   freez (cur_action->string[action->index]);
552                   cur_action->string[action->index] = strdup(value);
553                   if (NULL == cur_action->string[action->index])
554                   {
555                      return JB_ERR_MEMORY;
556                   }
557                   break;
558                }
559             case AV_REM_STRING:
560                {
561                   /* remove single string. */
562
563                   freez (cur_action->string[action->index]);
564                   break;
565                }
566             case AV_ADD_MULTI:
567                {
568                   /* append multi string. */
569
570                   struct list * remove_p = cur_action->multi_remove[action->index];
571                   struct list * add_p    = cur_action->multi_add[action->index];
572
573                   if ((value == NULL) || (*value == '\0'))
574                   {
575                      return JB_ERR_PARSE;
576                   }
577
578                   list_remove_item(remove_p, value);
579                   err = enlist_unique(add_p, value, 0);
580                   if (err)
581                   {
582                      return err;
583                   }
584                   break;
585                }
586             case AV_REM_MULTI:
587                {
588                   /* remove multi string. */
589
590                   struct list * remove_p = cur_action->multi_remove[action->index];
591                   struct list * add_p    = cur_action->multi_add[action->index];
592
593                   if ((value == NULL) || (*value == '\0')
594                      || ((*value == '*') && (value[1] == '\0')))
595                   {
596                      /*
597                       * no option, or option == "*".
598                       *
599                       * Remove *ALL*.
600                       */
601                      list_remove_all(remove_p);
602                      list_remove_all(add_p);
603                      cur_action->multi_remove_all[action->index] = 1;
604                   }
605                   else
606                   {
607                      /* Valid option - remove only 1 option */
608
609                      if (!cur_action->multi_remove_all[action->index])
610                      {
611                         /* there isn't a catch-all in the remove list already */
612                         err = enlist_unique(remove_p, value, 0);
613                         if (err)
614                         {
615                            return err;
616                         }
617                      }
618                      list_remove_item(add_p, value);
619                   }
620                   break;
621                }
622             default:
623                /* Shouldn't get here unless there's memory corruption. */
624                assert(0);
625                return JB_ERR_PARSE;
626             }
627          }
628          else
629          {
630             /* try user aliases. */
631             const struct action_alias * alias = alias_list;
632
633             while ((alias != NULL) && (0 != strcmpic(alias->name, option)))
634             {
635                alias = alias->next;
636             }
637             if (alias != NULL)
638             {
639                /* Found it */
640                merge_actions(cur_action, alias->action);
641             }
642             else if (((size_t)2 < strlen(option)) && action_used_to_be_valid(option+1))
643             {
644                log_error(LOG_LEVEL_ERROR, "Action '%s' is no longer valid "
645                   "in this Privoxy release. Ignored.", option+1);
646             }
647             else if (((size_t)2 < strlen(option)) && 0 == strcmpic(option+1, "hide-forwarded-for-headers"))
648             {
649                log_error(LOG_LEVEL_FATAL, "The action 'hide-forwarded-for-headers' "
650                   "is no longer valid in this Privoxy release. "
651                   "Use 'change-x-forwarded-for' instead.");
652             }
653             else
654             {
655                /* Bad action name */
656                /*
657                 * XXX: This is a fatal error and Privoxy will later on exit
658                 * in load_one_actions_file() because of an "invalid line".
659                 *
660                 * It would be preferable to name the offending option in that
661                 * error message, but currently there is no way to do that and
662                 * we have to live with two error messages for basically the
663                 * same reason.
664                 */
665                log_error(LOG_LEVEL_ERROR, "Unknown action or alias: %s", option);
666                return JB_ERR_PARSE;
667             }
668          }
669       }
670    }
671
672    return JB_ERR_OK;
673 }
674
675
676 /*********************************************************************
677  *
678  * Function    :  init_current_action
679  *
680  * Description :  Zero out an action.
681  *
682  * Parameters  :
683  *          1  :  dest = An uninitialized current_action_spec.
684  *
685  * Returns     :  N/A
686  *
687  *********************************************************************/
688 void init_current_action (struct current_action_spec *dest)
689 {
690    memset(dest, '\0', sizeof(*dest));
691
692    dest->flags = ACTION_MOST_COMPATIBLE;
693 }
694
695
696 /*********************************************************************
697  *
698  * Function    :  init_action
699  *
700  * Description :  Zero out an action.
701  *
702  * Parameters  :
703  *          1  :  dest = An uninitialized action_spec.
704  *
705  * Returns     :  N/A
706  *
707  *********************************************************************/
708 void init_action (struct action_spec *dest)
709 {
710    memset(dest, '\0', sizeof(*dest));
711 }
712
713
714 /*********************************************************************
715  *
716  * Function    :  merge_current_action
717  *
718  * Description :  Merge two actions together.
719  *                Similar to "dest += src".
720  *                Differences between this and merge_actions()
721  *                is that this one doesn't allocate memory for
722  *                strings (so "src" better be in memory for at least
723  *                as long as "dest" is, and you'd better free
724  *                "dest" using "free_current_action").
725  *                Also, there is no  mask or remove lists in dest.
726  *                (If we're applying it to a URL, we don't need them)
727  *
728  * Parameters  :
729  *          1  :  dest = Current actions, to modify.
730  *          2  :  src = Action to add.
731  *
732  * Returns  0  :  no error
733  *        !=0  :  error, probably JB_ERR_MEMORY.
734  *
735  *********************************************************************/
736 jb_err merge_current_action (struct current_action_spec *dest,
737                              const struct action_spec *src)
738 {
739    int i;
740    jb_err err = JB_ERR_OK;
741
742    dest->flags  &= src->mask;
743    dest->flags  |= src->add;
744
745    for (i = 0; i < ACTION_STRING_COUNT; i++)
746    {
747       char * str = src->string[i];
748       if (str)
749       {
750          str = strdup_or_die(str);
751          freez(dest->string[i]);
752          dest->string[i] = str;
753       }
754    }
755
756    for (i = 0; i < ACTION_MULTI_COUNT; i++)
757    {
758       if (src->multi_remove_all[i])
759       {
760          /* Remove everything from dest, then add src->multi_add */
761          err = list_duplicate(dest->multi[i], src->multi_add[i]);
762          if (err)
763          {
764             return err;
765          }
766       }
767       else
768       {
769          list_remove_list(dest->multi[i], src->multi_remove[i]);
770          err = list_append_list_unique(dest->multi[i], src->multi_add[i]);
771          if (err)
772          {
773             return err;
774          }
775       }
776    }
777    return err;
778 }
779
780
781 /*********************************************************************
782  *
783  * Function    :  update_action_bits_for_tag
784  *
785  * Description :  Updates the action bits based on the action sections
786  *                whose tag patterns match a provided tag.
787  *
788  * Parameters  :
789  *          1  :  csp = Current client state (buffers, headers, etc...)
790  *          2  :  tag = The tag on which the update should be based on
791  *
792  * Returns     :  0 if no tag matched, or
793  *                1 otherwise
794  *
795  *********************************************************************/
796 int update_action_bits_for_tag(struct client_state *csp, const char *tag)
797 {
798    struct file_list *fl;
799    struct url_actions *b;
800
801    int updated = 0;
802    int i;
803
804    assert(tag);
805    assert(list_contains_item(csp->tags, tag));
806
807    /* Run through all action files, */
808    for (i = 0; i < MAX_AF_FILES; i++)
809    {
810       if (((fl = csp->actions_list[i]) == NULL) || ((b = fl->f) == NULL))
811       {
812          /* Skip empty files */
813          continue;
814       }
815
816       /* and through all the action patterns, */
817       for (b = b->next; NULL != b; b = b->next)
818       {
819          /* skip everything but TAG patterns, */
820          if (!(b->url->flags & PATTERN_SPEC_TAG_PATTERN))
821          {
822             continue;
823          }
824
825          /* and check if one of the tag patterns matches the tag, */
826          if (0 == regexec(b->url->pattern.tag_regex, tag, 0, NULL, 0))
827          {
828             /* if it does, update the action bit map, */
829             if (merge_current_action(csp->action, b->action))
830             {
831                log_error(LOG_LEVEL_ERROR,
832                   "Out of memory while changing action bits");
833             }
834             /* and signal the change. */
835             updated = 1;
836          }
837       }
838    }
839
840    return updated;
841 }
842
843
844 /*********************************************************************
845  *
846  * Function    :  check_negative_tag_patterns
847  *
848  * Description :  Updates the action bits based on NO-*-TAG patterns.
849  *
850  * Parameters  :
851  *          1  :  csp = Current client state (buffers, headers, etc...)
852  *          2  :  flag = The tag pattern type
853  *
854  * Returns     :  JB_ERR_OK in case off success, or
855  *                JB_ERR_MEMORY on out-of-memory error.
856  *
857  *********************************************************************/
858 jb_err check_negative_tag_patterns(struct client_state *csp, unsigned int flag)
859 {
860    struct list_entry *tag;
861    struct file_list *fl;
862    struct url_actions *b = NULL;
863    int i;
864
865    for (i = 0; i < MAX_AF_FILES; i++)
866    {
867       fl = csp->actions_list[i];
868       if ((fl == NULL) || ((b = fl->f) == NULL))
869       {
870          continue;
871       }
872       for (b = b->next; NULL != b; b = b->next)
873       {
874          int tag_found = 0;
875          if (0 == (b->url->flags & flag))
876          {
877             continue;
878          }
879          for (tag = csp->tags->first; NULL != tag; tag = tag->next)
880          {
881             if (0 == regexec(b->url->pattern.tag_regex, tag->str, 0, NULL, 0))
882             {
883                /*
884                 * The pattern matches at least one tag, thus the action
885                 * section doesn't apply and we don't need to look at the
886                 * other tags.
887                 */
888                tag_found = 1;
889                break;
890             }
891          }
892          if (!tag_found)
893          {
894             /*
895              * The pattern doesn't match any tags,
896              * thus the action section applies.
897              */
898             if (merge_current_action(csp->action, b->action))
899             {
900                log_error(LOG_LEVEL_ERROR,
901                   "Out of memory while changing action bits");
902                return JB_ERR_MEMORY;
903             }
904             log_error(LOG_LEVEL_HEADER, "Updated action bits based on: %s",
905                b->url->spec);
906          }
907       }
908    }
909
910    return JB_ERR_OK;
911 }
912
913
914 /*********************************************************************
915  *
916  * Function    :  free_current_action
917  *
918  * Description :  Free memory used by a current_action_spec.
919  *                Does not free the current_action_spec itself.
920  *
921  * Parameters  :
922  *          1  :  src = Source to free.
923  *
924  * Returns     :  N/A
925  *
926  *********************************************************************/
927 void free_current_action(struct current_action_spec *src)
928 {
929    int i;
930
931    for (i = 0; i < ACTION_STRING_COUNT; i++)
932    {
933       freez(src->string[i]);
934    }
935
936    for (i = 0; i < ACTION_MULTI_COUNT; i++)
937    {
938       destroy_list(src->multi[i]);
939    }
940
941    memset(src, '\0', sizeof(*src));
942 }
943
944
945 static struct file_list *current_actions_file[MAX_AF_FILES]  = {
946    NULL, NULL, NULL, NULL, NULL,
947    NULL, NULL, NULL, NULL, NULL
948 };
949
950
951 #ifdef FEATURE_GRACEFUL_TERMINATION
952 /*********************************************************************
953  *
954  * Function    :  unload_current_actions_file
955  *
956  * Description :  Unloads current actions file - reset to state at
957  *                beginning of program.
958  *
959  * Parameters  :  None
960  *
961  * Returns     :  N/A
962  *
963  *********************************************************************/
964 void unload_current_actions_file(void)
965 {
966    int i;
967
968    for (i = 0; i < MAX_AF_FILES; i++)
969    {
970       if (current_actions_file[i])
971       {
972          current_actions_file[i]->unloader = unload_actions_file;
973          current_actions_file[i] = NULL;
974       }
975    }
976 }
977 #endif /* FEATURE_GRACEFUL_TERMINATION */
978
979
980 /*********************************************************************
981  *
982  * Function    :  unload_actions_file
983  *
984  * Description :  Unloads an actions module.
985  *
986  * Parameters  :
987  *          1  :  file_data = the data structure associated with the
988  *                            actions file.
989  *
990  * Returns     :  N/A
991  *
992  *********************************************************************/
993 void unload_actions_file(void *file_data)
994 {
995    struct url_actions * next;
996    struct url_actions * cur = (struct url_actions *)file_data;
997    while (cur != NULL)
998    {
999       next = cur->next;
1000       free_pattern_spec(cur->url);
1001       if ((next == NULL) || (next->action != cur->action))
1002       {
1003          /*
1004           * As the action settings might be shared,
1005           * we can only free them if the current
1006           * url pattern is the last one, or if the
1007           * next one is using different settings.
1008           */
1009          free_action_spec(cur->action);
1010       }
1011       freez(cur);
1012       cur = next;
1013    }
1014 }
1015
1016
1017 /*********************************************************************
1018  *
1019  * Function    :  free_alias_list
1020  *
1021  * Description :  Free memory used by a list of aliases.
1022  *
1023  * Parameters  :
1024  *          1  :  alias_list = Linked list to free.
1025  *
1026  * Returns     :  N/A
1027  *
1028  *********************************************************************/
1029 void free_alias_list(struct action_alias *alias_list)
1030 {
1031    while (alias_list != NULL)
1032    {
1033       struct action_alias * next = alias_list->next;
1034       alias_list->next = NULL;
1035       freez(alias_list->name);
1036       free_action(alias_list->action);
1037       free(alias_list);
1038       alias_list = next;
1039    }
1040 }
1041
1042
1043 /*********************************************************************
1044  *
1045  * Function    :  load_action_files
1046  *
1047  * Description :  Read and parse all the action files and add to files
1048  *                list.
1049  *
1050  * Parameters  :
1051  *          1  :  csp = Current client state (buffers, headers, etc...)
1052  *
1053  * Returns     :  0 => Ok, everything else is an error.
1054  *
1055  *********************************************************************/
1056 int load_action_files(struct client_state *csp)
1057 {
1058    int i;
1059    int result;
1060
1061    for (i = 0; i < MAX_AF_FILES; i++)
1062    {
1063       if (csp->config->actions_file[i])
1064       {
1065          result = load_one_actions_file(csp, i);
1066          if (result)
1067          {
1068             return result;
1069          }
1070       }
1071       else if (current_actions_file[i])
1072       {
1073          current_actions_file[i]->unloader = unload_actions_file;
1074          current_actions_file[i] = NULL;
1075       }
1076    }
1077
1078    return 0;
1079 }
1080
1081
1082 /*********************************************************************
1083  *
1084  * Function    :  filter_type_to_string
1085  *
1086  * Description :  Converts a filter type enum into a string.
1087  *
1088  * Parameters  :
1089  *          1  :  filter_type = filter_type as enum
1090  *
1091  * Returns     :  Pointer to static string.
1092  *
1093  *********************************************************************/
1094 static const char *filter_type_to_string(enum filter_type filter_type)
1095 {
1096    switch (filter_type)
1097    {
1098    case FT_CONTENT_FILTER:
1099       return "content filter";
1100    case FT_CLIENT_HEADER_FILTER:
1101       return "client-header filter";
1102    case FT_SERVER_HEADER_FILTER:
1103       return "server-header filter";
1104    case FT_CLIENT_HEADER_TAGGER:
1105       return "client-header tagger";
1106    case FT_SERVER_HEADER_TAGGER:
1107       return "server-header tagger";
1108 #ifdef FEATURE_EXTERNAL_FILTERS
1109    case FT_EXTERNAL_CONTENT_FILTER:
1110       return "external content filter";
1111 #endif
1112    case FT_INVALID_FILTER:
1113       return "invalid filter type";
1114    }
1115
1116    return "unknown filter type";
1117
1118 }
1119
1120 /*********************************************************************
1121  *
1122  * Function    :  referenced_filters_are_missing
1123  *
1124  * Description :  Checks if any filters of a certain type referenced
1125  *                in an action spec are missing.
1126  *
1127  * Parameters  :
1128  *          1  :  csp = Current client state (buffers, headers, etc...)
1129  *          2  :  cur_action = The action spec to check.
1130  *          3  :  multi_index = The index where to look for the filter.
1131  *          4  :  filter_type = The filter type the caller is interested in.
1132  *
1133  * Returns     :  0 => All referenced filters exist, everything else is an error.
1134  *
1135  *********************************************************************/
1136 static int referenced_filters_are_missing(const struct client_state *csp,
1137    const struct action_spec *cur_action, int multi_index, enum filter_type filter_type)
1138 {
1139    struct list_entry *filtername;
1140
1141    for (filtername = cur_action->multi_add[multi_index]->first;
1142         filtername; filtername = filtername->next)
1143    {
1144       if (NULL == get_filter(csp, filtername->str, filter_type))
1145       {
1146          log_error(LOG_LEVEL_ERROR, "Missing %s '%s'",
1147             filter_type_to_string(filter_type), filtername->str);
1148          return 1;
1149       }
1150    }
1151
1152    return 0;
1153
1154 }
1155
1156
1157 /*********************************************************************
1158  *
1159  * Function    :  action_spec_is_valid
1160  *
1161  * Description :  Should eventually figure out if an action spec
1162  *                is valid, but currently only checks that the
1163  *                referenced filters are accounted for.
1164  *
1165  * Parameters  :
1166  *          1  :  csp = Current client state (buffers, headers, etc...)
1167  *          2  :  cur_action = The action spec to check.
1168  *
1169  * Returns     :  0 => No problems detected, everything else is an error.
1170  *
1171  *********************************************************************/
1172 static int action_spec_is_valid(struct client_state *csp, const struct action_spec *cur_action)
1173 {
1174    struct {
1175       int multi_index;
1176       enum filter_type filter_type;
1177    } filter_map[] = {
1178       {ACTION_MULTI_FILTER, FT_CONTENT_FILTER},
1179       {ACTION_MULTI_CLIENT_HEADER_FILTER, FT_CLIENT_HEADER_FILTER},
1180       {ACTION_MULTI_SERVER_HEADER_FILTER, FT_SERVER_HEADER_FILTER},
1181       {ACTION_MULTI_CLIENT_HEADER_TAGGER, FT_CLIENT_HEADER_TAGGER},
1182       {ACTION_MULTI_SERVER_HEADER_TAGGER, FT_SERVER_HEADER_TAGGER}
1183    };
1184    int errors = 0;
1185    int i;
1186
1187    for (i = 0; i < SZ(filter_map); i++)
1188    {
1189       errors += referenced_filters_are_missing(csp, cur_action,
1190          filter_map[i].multi_index, filter_map[i].filter_type);
1191    }
1192
1193    return errors;
1194
1195 }
1196
1197
1198 /*********************************************************************
1199  *
1200  * Function    :  load_one_actions_file
1201  *
1202  * Description :  Read and parse a action file and add to files
1203  *                list.
1204  *
1205  * Parameters  :
1206  *          1  :  csp = Current client state (buffers, headers, etc...)
1207  *          2  :  fileid = File index to load.
1208  *
1209  * Returns     :  0 => Ok, everything else is an error.
1210  *
1211  *********************************************************************/
1212 #ifndef FUZZ
1213 static
1214 #endif
1215 int load_one_actions_file(struct client_state *csp, int fileid)
1216 {
1217
1218    /*
1219     * Parser mode.
1220     * Note: Keep these in the order they occur in the file, they are
1221     * sometimes tested with <=
1222     */
1223    enum {
1224       MODE_START_OF_FILE = 1,
1225       MODE_SETTINGS      = 2,
1226       MODE_DESCRIPTION   = 3,
1227       MODE_ALIAS         = 4,
1228       MODE_ACTIONS       = 5
1229    } mode;
1230
1231    FILE *fp;
1232    struct url_actions *last_perm;
1233    struct url_actions *perm;
1234    char  *buf;
1235    struct file_list *fs;
1236    struct action_spec * cur_action = NULL;
1237    int cur_action_used = 0;
1238    struct action_alias * alias_list = NULL;
1239    unsigned long linenum = 0;
1240    mode = MODE_START_OF_FILE;
1241
1242    if (!check_file_changed(current_actions_file[fileid], csp->config->actions_file[fileid], &fs))
1243    {
1244       /* No need to load */
1245       csp->actions_list[fileid] = current_actions_file[fileid];
1246       return 0;
1247    }
1248    if (!fs)
1249    {
1250       log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': %E. "
1251          "Note that beginning with Privoxy 3.0.7, actions files have to be specified "
1252          "with their complete file names.", csp->config->actions_file[fileid]);
1253       return 1; /* never get here */
1254    }
1255
1256    fs->f = last_perm = zalloc_or_die(sizeof(*last_perm));
1257
1258    if ((fp = fopen(csp->config->actions_file[fileid], "r")) == NULL)
1259    {
1260       log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': error opening file: %E",
1261                 csp->config->actions_file[fileid]);
1262       return 1; /* never get here */
1263    }
1264
1265    log_error(LOG_LEVEL_INFO, "Loading actions file: %s", csp->config->actions_file[fileid]);
1266
1267    while (read_config_line(fp, &linenum, &buf) != NULL)
1268    {
1269       if (*buf == '{')
1270       {
1271          /* It's a header block */
1272          if (buf[1] == '{')
1273          {
1274             /* It's {{settings}} or {{alias}} */
1275             size_t len = strlen(buf);
1276             char * start = buf + 2;
1277             char * end = buf + len - 1;
1278             if ((len < (size_t)5) || (*end-- != '}') || (*end-- != '}'))
1279             {
1280                /* too short */
1281                fclose(fp);
1282                log_error(LOG_LEVEL_FATAL,
1283                   "can't load actions file '%s': invalid line (%lu): %s",
1284                   csp->config->actions_file[fileid], linenum, buf);
1285                return 1; /* never get here */
1286             }
1287
1288             /* Trim leading and trailing whitespace. */
1289             end[1] = '\0';
1290             chomp(start);
1291
1292             if (*start == '\0')
1293             {
1294                /* too short */
1295                fclose(fp);
1296                log_error(LOG_LEVEL_FATAL,
1297                   "can't load actions file '%s': invalid line (%lu): {{ }}",
1298                   csp->config->actions_file[fileid], linenum);
1299                return 1; /* never get here */
1300             }
1301
1302             /*
1303              * An actionsfile can optionally contain the following blocks.
1304              * They *MUST* be in this order, to simplify processing:
1305              *
1306              * {{settings}}
1307              * name=value...
1308              *
1309              * {{description}}
1310              * ...free text, format TBD, but no line may start with a '{'...
1311              *
1312              * {{alias}}
1313              * name=actions...
1314              *
1315              * The actual actions must be *after* these special blocks.
1316              * None of these special blocks may be repeated.
1317              *
1318              */
1319             if (0 == strcmpic(start, "settings"))
1320             {
1321                /* it's a {{settings}} block */
1322                if (mode >= MODE_SETTINGS)
1323                {
1324                   /* {{settings}} must be first thing in file and must only
1325                    * appear once.
1326                    */
1327                   fclose(fp);
1328                   log_error(LOG_LEVEL_FATAL,
1329                      "can't load actions file '%s': line %lu: {{settings}} must only appear once, and it must be before anything else.",
1330                      csp->config->actions_file[fileid], linenum);
1331                }
1332                mode = MODE_SETTINGS;
1333             }
1334             else if (0 == strcmpic(start, "description"))
1335             {
1336                /* it's a {{description}} block */
1337                if (mode >= MODE_DESCRIPTION)
1338                {
1339                   /* {{description}} is a singleton and only {{settings}} may proceed it
1340                    */
1341                   fclose(fp);
1342                   log_error(LOG_LEVEL_FATAL,
1343                      "can't load actions file '%s': line %lu: {{description}} must only appear once, and only a {{settings}} block may be above it.",
1344                      csp->config->actions_file[fileid], linenum);
1345                }
1346                mode = MODE_DESCRIPTION;
1347             }
1348             else if (0 == strcmpic(start, "alias"))
1349             {
1350                /* it's an {{alias}} block */
1351                if (mode >= MODE_ALIAS)
1352                {
1353                   /* {{alias}} must be first thing in file, possibly after
1354                    * {{settings}} and {{description}}
1355                    *
1356                    * {{alias}} must only appear once.
1357                    *
1358                    * Note that these are new restrictions introduced in
1359                    * v2.9.10 in order to make actionsfile editing simpler.
1360                    * (Otherwise, reordering actionsfile entries without
1361                    * completely rewriting the file becomes non-trivial)
1362                    */
1363                   fclose(fp);
1364                   log_error(LOG_LEVEL_FATAL,
1365                      "can't load actions file '%s': line %lu: {{alias}} must only appear once, and it must be before all actions.",
1366                      csp->config->actions_file[fileid], linenum);
1367                }
1368                mode = MODE_ALIAS;
1369             }
1370             else
1371             {
1372                /* invalid {{something}} block */
1373                fclose(fp);
1374                log_error(LOG_LEVEL_FATAL,
1375                   "can't load actions file '%s': invalid line (%lu): {{%s}}",
1376                   csp->config->actions_file[fileid], linenum, start);
1377                return 1; /* never get here */
1378             }
1379          }
1380          else
1381          {
1382             /* It's an actions block */
1383
1384             char *actions_buf;
1385             char * end;
1386
1387             /* set mode */
1388             mode = MODE_ACTIONS;
1389
1390             /* free old action */
1391             if (cur_action)
1392             {
1393                if (!cur_action_used)
1394                {
1395                   free_action_spec(cur_action);
1396                }
1397                cur_action = NULL;
1398             }
1399             cur_action_used = 0;
1400             cur_action = zalloc_or_die(sizeof(*cur_action));
1401             init_action(cur_action);
1402
1403             /*
1404              * Copy the buffer before messing with it as we may need the
1405              * unmodified version in for the fatal error messages. Given
1406              * that this is not a common event, we could instead simply
1407              * read the line again.
1408              *
1409              * buf + 1 to skip the leading '{'
1410              */
1411             actions_buf = end = strdup_or_die(buf + 1);
1412
1413             /* check we have a trailing } and then trim it */
1414             if (strlen(actions_buf))
1415             {
1416                end += strlen(actions_buf) - 1;
1417             }
1418             if (*end != '}')
1419             {
1420                /* No closing } */
1421                fclose(fp);
1422                freez(actions_buf);
1423                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1424                   "Missing trailing '}' in action section starting at line (%lu): %s",
1425                   csp->config->actions_file[fileid], linenum, buf);
1426                return 1; /* never get here */
1427             }
1428             *end = '\0';
1429
1430             /* trim any whitespace immediately inside {} */
1431             chomp(actions_buf);
1432
1433             if (get_actions(actions_buf, alias_list, cur_action))
1434             {
1435                /* error */
1436                fclose(fp);
1437                freez(actions_buf);
1438                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1439                   "can't completely parse the action section starting at line (%lu): %s",
1440                   csp->config->actions_file[fileid], linenum, buf);
1441                return 1; /* never get here */
1442             }
1443
1444             if (action_spec_is_valid(csp, cur_action))
1445             {
1446                log_error(LOG_LEVEL_ERROR, "Invalid action section in file '%s', "
1447                   "starting at line %lu: %s",
1448                   csp->config->actions_file[fileid], linenum, buf);
1449             }
1450
1451             freez(actions_buf);
1452          }
1453       }
1454       else if (mode == MODE_SETTINGS)
1455       {
1456          /*
1457           * Part of the {{settings}} block.
1458           * For now only serves to check if the file's minimum Privoxy
1459           * version requirement is met, but we may want to read & check
1460           * permissions when we go multi-user.
1461           */
1462          if (!strncmp(buf, "for-privoxy-version=", 20))
1463          {
1464             char *version_string, *fields[3];
1465             int num_fields;
1466
1467             version_string = strdup_or_die(buf + 20);
1468
1469             num_fields = ssplit(version_string, ".", fields, SZ(fields));
1470
1471             if (num_fields < 1 || atoi(fields[0]) == 0)
1472             {
1473                log_error(LOG_LEVEL_ERROR,
1474                  "While loading actions file '%s': invalid line (%lu): %s",
1475                   csp->config->actions_file[fileid], linenum, buf);
1476             }
1477             else if (                  (atoi(fields[0]) > VERSION_MAJOR)
1478                || ((num_fields > 1) && (atoi(fields[1]) > VERSION_MINOR))
1479                || ((num_fields > 2) && (atoi(fields[2]) > VERSION_POINT)))
1480             {
1481                fclose(fp);
1482                log_error(LOG_LEVEL_FATAL,
1483                          "Actions file '%s', line %lu requires newer Privoxy version: %s",
1484                          csp->config->actions_file[fileid], linenum, buf);
1485                return 1; /* never get here */
1486             }
1487             free(version_string);
1488          }
1489       }
1490       else if (mode == MODE_DESCRIPTION)
1491       {
1492          /*
1493           * Part of the {{description}} block.
1494           * Ignore for now.
1495           */
1496       }
1497       else if (mode == MODE_ALIAS)
1498       {
1499          /*
1500           * define an alias
1501           */
1502          char  actions_buf[BUFFER_SIZE];
1503          struct action_alias * new_alias;
1504
1505          char * start = strchr(buf, '=');
1506          char * end = start;
1507
1508          if ((start == NULL) || (start == buf))
1509          {
1510             log_error(LOG_LEVEL_FATAL,
1511                "can't load actions file '%s': invalid alias line (%lu): %s",
1512                csp->config->actions_file[fileid], linenum, buf);
1513             return 1; /* never get here */
1514          }
1515
1516          new_alias = zalloc_or_die(sizeof(*new_alias));
1517
1518          /* Eat any the whitespace before the '=' */
1519          end--;
1520          while ((*end == ' ') || (*end == '\t'))
1521          {
1522             /*
1523              * we already know we must have at least 1 non-ws char
1524              * at start of buf - no need to check
1525              */
1526             end--;
1527          }
1528          end[1] = '\0';
1529
1530          /* Eat any the whitespace after the '=' */
1531          start++;
1532          while ((*start == ' ') || (*start == '\t'))
1533          {
1534             start++;
1535          }
1536          if (*start == '\0')
1537          {
1538             log_error(LOG_LEVEL_FATAL,
1539                "can't load actions file '%s': invalid alias line (%lu): %s",
1540                csp->config->actions_file[fileid], linenum, buf);
1541             return 1; /* never get here */
1542          }
1543
1544          new_alias->name = strdup_or_die(buf);
1545
1546          strlcpy(actions_buf, start, sizeof(actions_buf));
1547
1548          if (get_actions(actions_buf, alias_list, new_alias->action))
1549          {
1550             /* error */
1551             fclose(fp);
1552             log_error(LOG_LEVEL_FATAL,
1553                "can't load actions file '%s': invalid alias line (%lu): %s = %s",
1554                csp->config->actions_file[fileid], linenum, buf, start);
1555             return 1; /* never get here */
1556          }
1557
1558          /* add to list */
1559          new_alias->next = alias_list;
1560          alias_list = new_alias;
1561       }
1562       else if (mode == MODE_ACTIONS)
1563       {
1564          /* it's an URL pattern */
1565
1566          /* allocate a new node */
1567          perm = zalloc_or_die(sizeof(*perm));
1568
1569          perm->action = cur_action;
1570          cur_action_used = 1;
1571
1572          /* Save the URL pattern */
1573          if (create_pattern_spec(perm->url, buf))
1574          {
1575             fclose(fp);
1576             log_error(LOG_LEVEL_FATAL,
1577                "can't load actions file '%s': line %lu: cannot create URL or TAG pattern from: %s",
1578                csp->config->actions_file[fileid], linenum, buf);
1579             return 1; /* never get here */
1580          }
1581
1582          /* add it to the list */
1583          last_perm->next = perm;
1584          last_perm = perm;
1585       }
1586       else if (mode == MODE_START_OF_FILE)
1587       {
1588          /* oops - please have a {} line as 1st line in file. */
1589          fclose(fp);
1590          log_error(LOG_LEVEL_FATAL,
1591             "can't load actions file '%s': line %lu should begin with a '{': %s",
1592             csp->config->actions_file[fileid], linenum, buf);
1593          return 1; /* never get here */
1594       }
1595       else
1596       {
1597          /* How did we get here? This is impossible! */
1598          fclose(fp);
1599          log_error(LOG_LEVEL_FATAL,
1600             "can't load actions file '%s': INTERNAL ERROR - mode = %d",
1601             csp->config->actions_file[fileid], mode);
1602          return 1; /* never get here */
1603       }
1604       freez(buf);
1605    }
1606
1607    fclose(fp);
1608
1609    if (!cur_action_used)
1610    {
1611       free_action_spec(cur_action);
1612    }
1613    free_alias_list(alias_list);
1614
1615    /* the old one is now obsolete */
1616    if (current_actions_file[fileid])
1617    {
1618       current_actions_file[fileid]->unloader = unload_actions_file;
1619    }
1620
1621    fs->next    = files->next;
1622    files->next = fs;
1623    current_actions_file[fileid] = fs;
1624
1625    csp->actions_list[fileid] = fs;
1626
1627    return(0);
1628
1629 }
1630
1631
1632 /*********************************************************************
1633  *
1634  * Function    :  actions_to_text
1635  *
1636  * Description :  Converts a actionsfile entry from the internal
1637  *                structure into a text line.  The output is split
1638  *                into one line for each action with line continuation.
1639  *
1640  * Parameters  :
1641  *          1  :  action = The action to format.
1642  *
1643  * Returns     :  A string.  Caller must free it.
1644  *                NULL on out-of-memory error.
1645  *
1646  *********************************************************************/
1647 char * actions_to_text(const struct action_spec *action)
1648 {
1649    unsigned long mask = action->mask;
1650    unsigned long add  = action->add;
1651    char *result = strdup_or_die("");
1652    struct list_entry * lst;
1653
1654    /* sanity - prevents "-feature +feature" */
1655    mask |= add;
1656
1657
1658 #define DEFINE_ACTION_BOOL(__name, __bit)          \
1659    if (!(mask & __bit))                            \
1660    {                                               \
1661       string_append(&result, " -" __name " \\\n"); \
1662    }                                               \
1663    else if (add & __bit)                           \
1664    {                                               \
1665       string_append(&result, " +" __name " \\\n"); \
1666    }
1667
1668 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1669    if (!(mask & __bit))                                \
1670    {                                                   \
1671       string_append(&result, " -" __name " \\\n");     \
1672    }                                                   \
1673    else if (add & __bit)                               \
1674    {                                                   \
1675       string_append(&result, " +" __name "{");         \
1676       string_append(&result, action->string[__index]); \
1677       string_append(&result, "} \\\n");                \
1678    }
1679
1680 #define DEFINE_ACTION_MULTI(__name, __index)         \
1681    if (action->multi_remove_all[__index])            \
1682    {                                                 \
1683       string_append(&result, " -" __name " \\\n");   \
1684    }                                                 \
1685    else                                              \
1686    {                                                 \
1687       lst = action->multi_remove[__index]->first;    \
1688       while (lst)                                    \
1689       {                                              \
1690          string_append(&result, " -" __name "{");    \
1691          string_append(&result, lst->str);           \
1692          string_append(&result, "} \\\n");           \
1693          lst = lst->next;                            \
1694       }                                              \
1695    }                                                 \
1696    lst = action->multi_add[__index]->first;          \
1697    while (lst)                                       \
1698    {                                                 \
1699       string_append(&result, " +" __name "{");       \
1700       string_append(&result, lst->str);              \
1701       string_append(&result, "} \\\n");              \
1702       lst = lst->next;                               \
1703    }
1704
1705 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1706
1707 #include "actionlist.h"
1708
1709 #undef DEFINE_ACTION_MULTI
1710 #undef DEFINE_ACTION_STRING
1711 #undef DEFINE_ACTION_BOOL
1712 #undef DEFINE_ACTION_ALIAS
1713
1714    return result;
1715 }
1716
1717
1718 /*********************************************************************
1719  *
1720  * Function    :  actions_to_html
1721  *
1722  * Description :  Converts a actionsfile entry from numeric form
1723  *                ("mask" and "add") to a <br>-separated HTML string
1724  *                in which each action is linked to its chapter in
1725  *                the user manual.
1726  *
1727  * Parameters  :
1728  *          1  :  csp    = Client state (for config)
1729  *          2  :  action = Action spec to be converted
1730  *
1731  * Returns     :  A string.  Caller must free it.
1732  *                NULL on out-of-memory error.
1733  *
1734  *********************************************************************/
1735 char * actions_to_html(const struct client_state *csp,
1736                        const struct action_spec *action)
1737 {
1738    unsigned long mask = action->mask;
1739    unsigned long add  = action->add;
1740    char *result = strdup_or_die("");
1741    struct list_entry * lst;
1742
1743    /* sanity - prevents "-feature +feature" */
1744    mask |= add;
1745
1746
1747 #define DEFINE_ACTION_BOOL(__name, __bit)       \
1748    if (!(mask & __bit))                         \
1749    {                                            \
1750       string_append(&result, "\n<br>-");        \
1751       string_join(&result, add_help_link(__name, csp->config)); \
1752    }                                            \
1753    else if (add & __bit)                        \
1754    {                                            \
1755       string_append(&result, "\n<br>+");        \
1756       string_join(&result, add_help_link(__name, csp->config)); \
1757    }
1758
1759 #define DEFINE_ACTION_STRING(__name, __bit, __index) \
1760    if (!(mask & __bit))                              \
1761    {                                                 \
1762       string_append(&result, "\n<br>-");             \
1763       string_join(&result, add_help_link(__name, csp->config)); \
1764    }                                                 \
1765    else if (add & __bit)                             \
1766    {                                                 \
1767       string_append(&result, "\n<br>+");             \
1768       string_join(&result, add_help_link(__name, csp->config)); \
1769       string_append(&result, "{");                   \
1770       string_join(&result, html_encode(action->string[__index])); \
1771       string_append(&result, "}");                   \
1772    }
1773
1774 #define DEFINE_ACTION_MULTI(__name, __index)          \
1775    if (action->multi_remove_all[__index])             \
1776    {                                                  \
1777       string_append(&result, "\n<br>-");              \
1778       string_join(&result, add_help_link(__name, csp->config)); \
1779    }                                                  \
1780    else                                               \
1781    {                                                  \
1782       lst = action->multi_remove[__index]->first;     \
1783       while (lst)                                     \
1784       {                                               \
1785          string_append(&result, "\n<br>-");           \
1786          string_join(&result, add_help_link(__name, csp->config)); \
1787          string_append(&result, "{");                 \
1788          string_join(&result, html_encode(lst->str)); \
1789          string_append(&result, "}");                 \
1790          lst = lst->next;                             \
1791       }                                               \
1792    }                                                  \
1793    lst = action->multi_add[__index]->first;           \
1794    while (lst)                                        \
1795    {                                                  \
1796       string_append(&result, "\n<br>+");              \
1797       string_join(&result, add_help_link(__name, csp->config)); \
1798       string_append(&result, "{");                    \
1799       string_join(&result, html_encode(lst->str));    \
1800       string_append(&result, "}");                    \
1801       lst = lst->next;                                \
1802    }
1803
1804 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1805
1806 #include "actionlist.h"
1807
1808 #undef DEFINE_ACTION_MULTI
1809 #undef DEFINE_ACTION_STRING
1810 #undef DEFINE_ACTION_BOOL
1811 #undef DEFINE_ACTION_ALIAS
1812
1813    /* trim leading <br> */
1814    if (result && *result)
1815    {
1816       char * s = result;
1817       result = strdup(result + 5);
1818       free(s);
1819    }
1820
1821    return result;
1822 }
1823
1824
1825 /*********************************************************************
1826  *
1827  * Function    :  current_actions_to_html
1828  *
1829  * Description :  Converts a curren action spec to a <br> separated HTML
1830  *                text in which each action is linked to its chapter in
1831  *                the user manual.
1832  *
1833  * Parameters  :
1834  *          1  :  csp    = Client state (for config)
1835  *          2  :  action = Current action spec to be converted
1836  *
1837  * Returns     :  A string.  Caller must free it.
1838  *                NULL on out-of-memory error.
1839  *
1840  *********************************************************************/
1841 char *current_action_to_html(const struct client_state *csp,
1842                              const struct current_action_spec *action)
1843 {
1844    unsigned long flags  = action->flags;
1845    struct list_entry * lst;
1846    char *result   = strdup_or_die("");
1847    char *active   = strdup_or_die("");
1848    char *inactive = strdup_or_die("");
1849
1850 #define DEFINE_ACTION_BOOL(__name, __bit)  \
1851    if (flags & __bit)                      \
1852    {                                       \
1853       string_append(&active, "\n<br>+");   \
1854       string_join(&active, add_help_link(__name, csp->config)); \
1855    }                                       \
1856    else                                    \
1857    {                                       \
1858       string_append(&inactive, "\n<br>-"); \
1859       string_join(&inactive, add_help_link(__name, csp->config)); \
1860    }
1861
1862 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1863    if (flags & __bit)                                  \
1864    {                                                   \
1865       string_append(&active, "\n<br>+");               \
1866       string_join(&active, add_help_link(__name, csp->config)); \
1867       string_append(&active, "{");                     \
1868       string_join(&active, html_encode(action->string[__index])); \
1869       string_append(&active, "}");                     \
1870    }                                                   \
1871    else                                                \
1872    {                                                   \
1873       string_append(&inactive, "\n<br>-");             \
1874       string_join(&inactive, add_help_link(__name, csp->config)); \
1875    }
1876
1877 #define DEFINE_ACTION_MULTI(__name, __index)           \
1878    lst = action->multi[__index]->first;                \
1879    if (lst == NULL)                                    \
1880    {                                                   \
1881       string_append(&inactive, "\n<br>-");             \
1882       string_join(&inactive, add_help_link(__name, csp->config)); \
1883    }                                                   \
1884    else                                                \
1885    {                                                   \
1886       while (lst)                                      \
1887       {                                                \
1888          string_append(&active, "\n<br>+");            \
1889          string_join(&active, add_help_link(__name, csp->config)); \
1890          string_append(&active, "{");                  \
1891          string_join(&active, html_encode(lst->str));  \
1892          string_append(&active, "}");                  \
1893          lst = lst->next;                              \
1894       }                                                \
1895    }
1896
1897 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1898
1899 #include "actionlist.h"
1900
1901 #undef DEFINE_ACTION_MULTI
1902 #undef DEFINE_ACTION_STRING
1903 #undef DEFINE_ACTION_BOOL
1904 #undef DEFINE_ACTION_ALIAS
1905
1906    if (active != NULL)
1907    {
1908       string_append(&result, active);
1909       freez(active);
1910    }
1911    string_append(&result, "\n<br>");
1912    if (inactive != NULL)
1913    {
1914       string_append(&result, inactive);
1915       freez(inactive);
1916    }
1917    return result;
1918 }
1919
1920
1921 /*********************************************************************
1922  *
1923  * Function    :  action_to_line_of_text
1924  *
1925  * Description :  Converts a action spec to a single text line
1926  *                listing the enabled actions.
1927  *
1928  * Parameters  :
1929  *          1  :  action = Current action spec to be converted
1930  *
1931  * Returns     :  A string. Caller must free it.
1932  *                Out-of-memory errors are fatal.
1933  *
1934  *********************************************************************/
1935 char *actions_to_line_of_text(const struct current_action_spec *action)
1936 {
1937    char buffer[200];
1938    struct list_entry *lst;
1939    char *active;
1940    const unsigned long flags = action->flags;
1941
1942    active = strdup_or_die("");
1943
1944 #define DEFINE_ACTION_BOOL(__name, __bit)               \
1945    if (flags & __bit)                                   \
1946    {                                                    \
1947       snprintf(buffer, sizeof(buffer), "+%s ", __name); \
1948       string_append(&active, buffer);                   \
1949    }                                                    \
1950
1951 #define DEFINE_ACTION_STRING(__name, __bit, __index)    \
1952    if (flags & __bit)                                   \
1953    {                                                    \
1954       snprintf(buffer, sizeof(buffer), "+%s{%s} ",      \
1955          __name, action->string[__index]);              \
1956       string_append(&active, buffer);                   \
1957    }                                                    \
1958
1959 #define DEFINE_ACTION_MULTI(__name, __index)            \
1960    lst = action->multi[__index]->first;                 \
1961    while (lst != NULL)                                  \
1962    {                                                    \
1963       snprintf(buffer, sizeof(buffer), "+%s{%s} ",      \
1964          __name, lst->str);                             \
1965       string_append(&active, buffer);                   \
1966       lst = lst->next;                                  \
1967    }                                                    \
1968
1969 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1970
1971 #include "actionlist.h"
1972
1973 #undef DEFINE_ACTION_MULTI
1974 #undef DEFINE_ACTION_STRING
1975 #undef DEFINE_ACTION_BOOL
1976 #undef DEFINE_ACTION_ALIAS
1977
1978    if (active == NULL)
1979    {
1980       log_error(LOG_LEVEL_FATAL, "Out of memory in action_to_line_of_text()");
1981    }
1982
1983    return active;
1984 }