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