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