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