Ditch the already-dead update_action_bits_for_all_tags()
[privoxy.git] / actions.c
1 const char actions_rcs[] = "$Id: actions.c,v 1.75 2011/12/31 14:49:58 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 #define AV_NONE       0 /* +opt -opt */
73 #define AV_ADD_STRING 1 /* +stropt{string} */
74 #define AV_REM_STRING 2 /* -stropt */
75 #define AV_ADD_MULTI  3 /* +multiopt{string} +multiopt{string2} */
76 #define AV_REM_MULTI  4 /* -multiopt{string} -multiopt          */
77
78 /*
79  * We need a structure to hold the name, flag changes,
80  * type, and string index.
81  */
82 struct action_name
83 {
84    const char * name;
85    unsigned long mask;   /* a bit set to "0" = remove action */
86    unsigned long add;    /* a bit set to "1" = add action */
87    int takes_value;      /* an AV_... constant */
88    int index;            /* index into strings[] or multi[] */
89 };
90
91 /*
92  * And with those building blocks in place, here's the array.
93  */
94 static const struct action_name action_names[] =
95 {
96    /*
97     * Well actually there's no data here - it's in actionlist.h
98     * This keeps it together to make it easy to change.
99     *
100     * Here's the macros used to format it:
101     */
102 #define DEFINE_ACTION_MULTI(name,index)                   \
103    { "+" name, ACTION_MASK_ALL, 0, AV_ADD_MULTI, index }, \
104    { "-" name, ACTION_MASK_ALL, 0, AV_REM_MULTI, index },
105 #define DEFINE_ACTION_STRING(name,flag,index)                 \
106    { "+" name, ACTION_MASK_ALL, flag, AV_ADD_STRING, index }, \
107    { "-" name, ~flag, 0, AV_REM_STRING, index },
108 #define DEFINE_ACTION_BOOL(name,flag)   \
109    { "+" name, ACTION_MASK_ALL, flag }, \
110    { "-" name, ~flag, 0 },
111 #define DEFINE_ACTION_ALIAS 1 /* Want aliases please */
112
113 #include "actionlist.h"
114
115 #undef DEFINE_ACTION_MULTI
116 #undef DEFINE_ACTION_STRING
117 #undef DEFINE_ACTION_BOOL
118 #undef DEFINE_ACTION_ALIAS
119
120    { NULL, 0, 0 } /* End marker */
121 };
122
123
124 static int load_one_actions_file(struct client_state *csp, int fileid);
125
126
127 /*********************************************************************
128  *
129  * Function    :  merge_actions
130  *
131  * Description :  Merge two actions together.
132  *                Similar to "dest += src".
133  *
134  * Parameters  :
135  *          1  :  dest = Actions to modify.
136  *          2  :  src = Action to add.
137  *
138  * Returns     :  JB_ERR_OK or JB_ERR_MEMORY
139  *
140  *********************************************************************/
141 jb_err merge_actions (struct action_spec *dest,
142                       const struct action_spec *src)
143 {
144    int i;
145    jb_err err;
146
147    dest->mask &= src->mask;
148    dest->add  &= src->mask;
149    dest->add  |= src->add;
150
151    for (i = 0; i < ACTION_STRING_COUNT; i++)
152    {
153       char * str = src->string[i];
154       if (str)
155       {
156          freez(dest->string[i]);
157          dest->string[i] = strdup(str);
158          if (NULL == dest->string[i])
159          {
160             return JB_ERR_MEMORY;
161          }
162       }
163    }
164
165    for (i = 0; i < ACTION_MULTI_COUNT; i++)
166    {
167       if (src->multi_remove_all[i])
168       {
169          /* Remove everything from dest */
170          list_remove_all(dest->multi_remove[i]);
171          dest->multi_remove_all[i] = 1;
172
173          err = list_duplicate(dest->multi_add[i], src->multi_add[i]);
174       }
175       else if (dest->multi_remove_all[i])
176       {
177          /*
178           * dest already removes everything, so we only need to worry
179           * about what we add.
180           */
181          list_remove_list(dest->multi_add[i], src->multi_remove[i]);
182          err = list_append_list_unique(dest->multi_add[i], src->multi_add[i]);
183       }
184       else
185       {
186          /* No "remove all"s to worry about. */
187          list_remove_list(dest->multi_add[i], src->multi_remove[i]);
188          err = list_append_list_unique(dest->multi_remove[i], src->multi_remove[i]);
189          if (!err) err = list_append_list_unique(dest->multi_add[i], src->multi_add[i]);
190       }
191
192       if (err)
193       {
194          return err;
195       }
196    }
197
198    return JB_ERR_OK;
199 }
200
201
202 /*********************************************************************
203  *
204  * Function    :  copy_action
205  *
206  * Description :  Copy an action_specs.
207  *                Similar to "dest = src".
208  *
209  * Parameters  :
210  *          1  :  dest = Destination of copy.
211  *          2  :  src = Source for copy.
212  *
213  * Returns     :  N/A
214  *
215  *********************************************************************/
216 jb_err copy_action (struct action_spec *dest,
217                     const struct action_spec *src)
218 {
219    int i;
220    jb_err err = JB_ERR_OK;
221
222    free_action(dest);
223    memset(dest, '\0', sizeof(*dest));
224
225    dest->mask = src->mask;
226    dest->add  = src->add;
227
228    for (i = 0; i < ACTION_STRING_COUNT; i++)
229    {
230       char * str = src->string[i];
231       if (str)
232       {
233          str = strdup(str);
234          if (!str)
235          {
236             return JB_ERR_MEMORY;
237          }
238          dest->string[i] = str;
239       }
240    }
241
242    for (i = 0; i < ACTION_MULTI_COUNT; i++)
243    {
244       dest->multi_remove_all[i] = src->multi_remove_all[i];
245       err = list_duplicate(dest->multi_remove[i], src->multi_remove[i]);
246       if (err)
247       {
248          return err;
249       }
250       err = list_duplicate(dest->multi_add[i],    src->multi_add[i]);
251       if (err)
252       {
253          return err;
254       }
255    }
256    return err;
257 }
258
259 /*********************************************************************
260  *
261  * Function    :  free_action_spec
262  *
263  * Description :  Frees an action_spec and the memory used by it.
264  *
265  * Parameters  :
266  *          1  :  src = Source to free.
267  *
268  * Returns     :  N/A
269  *
270  *********************************************************************/
271 void free_action_spec(struct action_spec *src)
272 {
273    free_action(src);
274    freez(src);
275 }
276
277
278 /*********************************************************************
279  *
280  * Function    :  free_action
281  *
282  * Description :  Destroy an action_spec.  Frees memory used by it,
283  *                except for the memory used by the struct action_spec
284  *                itself.
285  *
286  * Parameters  :
287  *          1  :  src = Source to free.
288  *
289  * Returns     :  N/A
290  *
291  *********************************************************************/
292 void free_action (struct action_spec *src)
293 {
294    int i;
295
296    if (src == NULL)
297    {
298       return;
299    }
300
301    for (i = 0; i < ACTION_STRING_COUNT; i++)
302    {
303       freez(src->string[i]);
304    }
305
306    for (i = 0; i < ACTION_MULTI_COUNT; i++)
307    {
308       destroy_list(src->multi_remove[i]);
309       destroy_list(src->multi_add[i]);
310    }
311
312    memset(src, '\0', sizeof(*src));
313 }
314
315
316 /*********************************************************************
317  *
318  * Function    :  get_action_token
319  *
320  * Description :  Parses a line for the first action.
321  *                Modifies its input array, doesn't allocate memory.
322  *                e.g. given:
323  *                *line="  +abc{def}  -ghi "
324  *                Returns:
325  *                *line="  -ghi "
326  *                *name="+abc"
327  *                *value="def"
328  *
329  * Parameters  :
330  *          1  :  line = [in] The line containing the action.
331  *                       [out] Start of next action on line, or
332  *                       NULL if we reached the end of line before
333  *                       we found an action.
334  *          2  :  name = [out] Start of action name, null
335  *                       terminated.  NULL on EOL
336  *          3  :  value = [out] Start of action value, null
337  *                        terminated.  NULL if none or EOL.
338  *
339  * Returns     :  JB_ERR_OK => Ok
340  *                JB_ERR_PARSE => Mismatched {} (line was trashed anyway)
341  *
342  *********************************************************************/
343 jb_err get_action_token(char **line, char **name, char **value)
344 {
345    char * str = *line;
346    char ch;
347
348    /* set default returns */
349    *line = NULL;
350    *name = NULL;
351    *value = NULL;
352
353    /* Eat any leading whitespace */
354    while ((*str == ' ') || (*str == '\t'))
355    {
356       str++;
357    }
358
359    if (*str == '\0')
360    {
361       return 0;
362    }
363
364    if (*str == '{')
365    {
366       /* null name, just value is prohibited */
367       return JB_ERR_PARSE;
368    }
369
370    *name = str;
371
372    /* parse option */
373    while (((ch = *str) != '\0') &&
374           (ch != ' ') && (ch != '\t') && (ch != '{'))
375    {
376       if (ch == '}')
377       {
378          /* error, '}' without '{' */
379          return JB_ERR_PARSE;
380       }
381       str++;
382    }
383    *str = '\0';
384
385    if (ch != '{')
386    {
387       /* no value */
388       if (ch == '\0')
389       {
390          /* EOL - be careful not to run off buffer */
391          *line = str;
392       }
393       else
394       {
395          /* More to parse next time. */
396          *line = str + 1;
397       }
398       return JB_ERR_OK;
399    }
400
401    str++;
402    *value = str;
403
404    str = strchr(str, '}');
405    if (str == NULL)
406    {
407       /* error */
408       *value = NULL;
409       return JB_ERR_PARSE;
410    }
411
412    /* got value */
413    *str = '\0';
414    *line = str + 1;
415
416    chomp(*value);
417
418    return JB_ERR_OK;
419 }
420
421 /*********************************************************************
422  *
423  * Function    :  action_used_to_be_valid
424  *
425  * Description :  Checks if unrecognized actions were valid in earlier
426  *                releases.
427  *
428  * Parameters  :
429  *          1  :  action = The string containing the action to check.
430  *
431  * Returns     :  True if yes, otherwise false.
432  *
433  *********************************************************************/
434 static int action_used_to_be_valid(const char *action)
435 {
436    static const char * const formerly_valid_actions[] = {
437       "inspect-jpegs",
438       "kill-popups",
439       "send-vanilla-wafer",
440       "send-wafer",
441       "treat-forbidden-connects-like-blocks",
442       "vanilla-wafer",
443       "wafer"
444    };
445    unsigned int i;
446
447    for (i = 0; i < SZ(formerly_valid_actions); i++)
448    {
449       if (0 == strcmpic(action, formerly_valid_actions[i]))
450       {
451          return TRUE;
452       }
453    }
454
455    return FALSE;
456 }
457
458 /*********************************************************************
459  *
460  * Function    :  get_actions
461  *
462  * Description :  Parses a list of actions.
463  *
464  * Parameters  :
465  *          1  :  line = The string containing the actions.
466  *                       Will be written to by this function.
467  *          2  :  alias_list = Custom alias list, or NULL for none.
468  *          3  :  cur_action = Where to store the action.  Caller
469  *                             allocates memory.
470  *
471  * Returns     :  JB_ERR_OK => Ok
472  *                JB_ERR_PARSE => Parse error (line was trashed anyway)
473  *                nonzero => Out of memory (line was trashed anyway)
474  *
475  *********************************************************************/
476 jb_err get_actions(char *line,
477                    struct action_alias * alias_list,
478                    struct action_spec *cur_action)
479 {
480    jb_err err;
481    init_action(cur_action);
482    cur_action->mask = ACTION_MASK_ALL;
483
484    while (line)
485    {
486       char * option = NULL;
487       char * value = NULL;
488
489       err = get_action_token(&line, &option, &value);
490       if (err)
491       {
492          return err;
493       }
494
495       if (option)
496       {
497          /* handle option in 'option' */
498
499          /* Check for standard action name */
500          const struct action_name * action = action_names;
501
502          while ( (action->name != NULL) && (0 != strcmpic(action->name, option)) )
503          {
504             action++;
505          }
506          if (action->name != NULL)
507          {
508             /* Found it */
509             cur_action->mask &= action->mask;
510             cur_action->add  &= action->mask;
511             cur_action->add  |= action->add;
512
513             switch (action->takes_value)
514             {
515             case AV_NONE:
516                /* ignore any option. */
517                break;
518             case AV_ADD_STRING:
519                {
520                   /* add single string. */
521
522                   if ((value == NULL) || (*value == '\0'))
523                   {
524                      if (0 == strcmpic(action->name, "+block"))
525                      {
526                         /*
527                          * XXX: Temporary backwards compatibility hack.
528                          * XXX: should include line number.
529                          */
530                         value = "No reason specified.";
531                         log_error(LOG_LEVEL_ERROR,
532                            "block action without reason found. This may "
533                            "become a fatal error in future versions.");
534                      }
535                      else
536                      {
537                         return JB_ERR_PARSE;
538                      }
539                   }
540                   /* FIXME: should validate option string here */
541                   freez (cur_action->string[action->index]);
542                   cur_action->string[action->index] = strdup(value);
543                   if (NULL == cur_action->string[action->index])
544                   {
545                      return JB_ERR_MEMORY;
546                   }
547                   break;
548                }
549             case AV_REM_STRING:
550                {
551                   /* remove single string. */
552
553                   freez (cur_action->string[action->index]);
554                   break;
555                }
556             case AV_ADD_MULTI:
557                {
558                   /* append multi string. */
559
560                   struct list * remove_p = cur_action->multi_remove[action->index];
561                   struct list * add_p    = cur_action->multi_add[action->index];
562
563                   if ((value == NULL) || (*value == '\0'))
564                   {
565                      return JB_ERR_PARSE;
566                   }
567
568                   list_remove_item(remove_p, value);
569                   err = enlist_unique(add_p, value, 0);
570                   if (err)
571                   {
572                      return err;
573                   }
574                   break;
575                }
576             case AV_REM_MULTI:
577                {
578                   /* remove multi string. */
579
580                   struct list * remove_p = cur_action->multi_remove[action->index];
581                   struct list * add_p    = cur_action->multi_add[action->index];
582
583                   if ( (value == NULL) || (*value == '\0')
584                      || ((*value == '*') && (value[1] == '\0')) )
585                   {
586                      /*
587                       * no option, or option == "*".
588                       *
589                       * Remove *ALL*.
590                       */
591                      list_remove_all(remove_p);
592                      list_remove_all(add_p);
593                      cur_action->multi_remove_all[action->index] = 1;
594                   }
595                   else
596                   {
597                      /* Valid option - remove only 1 option */
598
599                      if ( !cur_action->multi_remove_all[action->index] )
600                      {
601                         /* there isn't a catch-all in the remove list already */
602                         err = enlist_unique(remove_p, value, 0);
603                         if (err)
604                         {
605                            return err;
606                         }
607                      }
608                      list_remove_item(add_p, value);
609                   }
610                   break;
611                }
612             default:
613                /* Shouldn't get here unless there's memory corruption. */
614                assert(0);
615                return JB_ERR_PARSE;
616             }
617          }
618          else
619          {
620             /* try user aliases. */
621             const struct action_alias * alias = alias_list;
622
623             while ( (alias != NULL) && (0 != strcmpic(alias->name, option)) )
624             {
625                alias = alias->next;
626             }
627             if (alias != NULL)
628             {
629                /* Found it */
630                merge_actions(cur_action, alias->action);
631             }
632             else if (((size_t)2 < strlen(option)) && action_used_to_be_valid(option+1))
633             {
634                log_error(LOG_LEVEL_ERROR, "Action '%s' is no longer valid "
635                   "in this Privoxy release. Ignored.", option+1);
636             }
637             else if (((size_t)2 < strlen(option)) && 0 == strcmpic(option+1, "hide-forwarded-for-headers"))
638             {
639                log_error(LOG_LEVEL_FATAL, "The action 'hide-forwarded-for-headers' "
640                   "is no longer valid in this Privoxy release. "
641                   "Use 'change-x-forwarded-for' instead.");
642             }
643             else
644             {
645                /* Bad action name */
646                /*
647                 * XXX: This is a fatal error and Privoxy will later on exit
648                 * in load_one_actions_file() because of an "invalid line".
649                 *
650                 * It would be preferable to name the offending option in that
651                 * error message, but currently there is no way to do that and
652                 * we have to live with two error messages for basically the
653                 * same reason.
654                 */
655                log_error(LOG_LEVEL_ERROR, "Unknown action or alias: %s", option);
656                return JB_ERR_PARSE;
657             }
658          }
659       }
660    }
661
662    return JB_ERR_OK;
663 }
664
665
666 /*********************************************************************
667  *
668  * Function    :  init_current_action
669  *
670  * Description :  Zero out an action.
671  *
672  * Parameters  :
673  *          1  :  dest = An uninitialized current_action_spec.
674  *
675  * Returns     :  N/A
676  *
677  *********************************************************************/
678 void init_current_action (struct current_action_spec *dest)
679 {
680    memset(dest, '\0', sizeof(*dest));
681
682    dest->flags = ACTION_MOST_COMPATIBLE;
683 }
684
685
686 /*********************************************************************
687  *
688  * Function    :  init_action
689  *
690  * Description :  Zero out an action.
691  *
692  * Parameters  :
693  *          1  :  dest = An uninitialized action_spec.
694  *
695  * Returns     :  N/A
696  *
697  *********************************************************************/
698 void init_action (struct action_spec *dest)
699 {
700    memset(dest, '\0', sizeof(*dest));
701 }
702
703
704 /*********************************************************************
705  *
706  * Function    :  merge_current_action
707  *
708  * Description :  Merge two actions together.
709  *                Similar to "dest += src".
710  *                Differences between this and merge_actions()
711  *                is that this one doesn't allocate memory for
712  *                strings (so "src" better be in memory for at least
713  *                as long as "dest" is, and you'd better free
714  *                "dest" using "free_current_action").
715  *                Also, there is no  mask or remove lists in dest.
716  *                (If we're applying it to a URL, we don't need them)
717  *
718  * Parameters  :
719  *          1  :  dest = Current actions, to modify.
720  *          2  :  src = Action to add.
721  *
722  * Returns  0  :  no error
723  *        !=0  :  error, probably JB_ERR_MEMORY.
724  *
725  *********************************************************************/
726 jb_err merge_current_action (struct current_action_spec *dest,
727                              const struct action_spec *src)
728 {
729    int i;
730    jb_err err = JB_ERR_OK;
731
732    dest->flags  &= src->mask;
733    dest->flags  |= src->add;
734
735    for (i = 0; i < ACTION_STRING_COUNT; i++)
736    {
737       char * str = src->string[i];
738       if (str)
739       {
740          str = strdup(str);
741          if (!str)
742          {
743             return JB_ERR_MEMORY;
744          }
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(buf + 1);
1332             if (actions_buf == NULL)
1333             {
1334                fclose(fp);
1335                log_error(LOG_LEVEL_FATAL,
1336                   "can't load actions file '%s': out of memory",
1337                   csp->config->actions_file[fileid]);
1338                return 1; /* never get here */
1339             }
1340
1341             /* check we have a trailing } and then trim it */
1342             end = actions_buf + strlen(actions_buf) - 1;
1343             if (*end != '}')
1344             {
1345                /* No closing } */
1346                fclose(fp);
1347                freez(actions_buf);
1348                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1349                   "Missing trailing '}' in action section starting at line (%lu): %s",
1350                   csp->config->actions_file[fileid], linenum, buf);
1351                return 1; /* never get here */
1352             }
1353             *end = '\0';
1354
1355             /* trim any whitespace immediately inside {} */
1356             chomp(actions_buf);
1357
1358             if (get_actions(actions_buf, alias_list, cur_action))
1359             {
1360                /* error */
1361                fclose(fp);
1362                freez(actions_buf);
1363                log_error(LOG_LEVEL_FATAL, "can't load actions file '%s': "
1364                   "can't completely parse the action section starting at line (%lu): %s",
1365                   csp->config->actions_file[fileid], linenum, buf);
1366                return 1; /* never get here */
1367             }
1368
1369             if (action_spec_is_valid(csp, cur_action))
1370             {
1371                log_error(LOG_LEVEL_ERROR, "Invalid action section in file '%s', "
1372                   "starting at line %lu: %s",
1373                   csp->config->actions_file[fileid], linenum, buf);
1374             }
1375
1376             freez(actions_buf);
1377          }
1378       }
1379       else if (mode == MODE_SETTINGS)
1380       {
1381          /*
1382           * Part of the {{settings}} block.
1383           * For now only serves to check if the file's minimum Privoxy
1384           * version requirement is met, but we may want to read & check
1385           * permissions when we go multi-user.
1386           */
1387          if (!strncmp(buf, "for-privoxy-version=", 20))
1388          {
1389             char *version_string, *fields[3];
1390             int num_fields;
1391
1392             if ((version_string = strdup(buf + 20)) == NULL)
1393             {
1394                fclose(fp);
1395                log_error(LOG_LEVEL_FATAL,
1396                          "can't load actions file '%s': out of memory!",
1397                          csp->config->actions_file[fileid]);
1398                return 1; /* never get here */
1399             }
1400
1401             num_fields = ssplit(version_string, ".", fields, SZ(fields), TRUE, FALSE);
1402
1403             if (num_fields < 1 || atoi(fields[0]) == 0)
1404             {
1405                log_error(LOG_LEVEL_ERROR,
1406                  "While loading actions file '%s': invalid line (%lu): %s",
1407                   csp->config->actions_file[fileid], linenum, buf);
1408             }
1409             else if (                      atoi(fields[0]) > VERSION_MAJOR
1410                      || (num_fields > 1 && atoi(fields[1]) > VERSION_MINOR)
1411                      || (num_fields > 2 && atoi(fields[2]) > VERSION_POINT))
1412             {
1413                fclose(fp);
1414                log_error(LOG_LEVEL_FATAL,
1415                          "Actions file '%s', line %lu requires newer Privoxy version: %s",
1416                          csp->config->actions_file[fileid], linenum, buf );
1417                return 1; /* never get here */
1418             }
1419             free(version_string);
1420          }
1421       }
1422       else if (mode == MODE_DESCRIPTION)
1423       {
1424          /*
1425           * Part of the {{description}} block.
1426           * Ignore for now.
1427           */
1428       }
1429       else if (mode == MODE_ALIAS)
1430       {
1431          /*
1432           * define an alias
1433           */
1434          char  actions_buf[BUFFER_SIZE];
1435          struct action_alias * new_alias;
1436
1437          char * start = strchr(buf, '=');
1438          char * end = start;
1439
1440          if ((start == NULL) || (start == buf))
1441          {
1442             log_error(LOG_LEVEL_FATAL,
1443                "can't load actions file '%s': invalid alias line (%lu): %s",
1444                csp->config->actions_file[fileid], linenum, buf);
1445             return 1; /* never get here */
1446          }
1447
1448          if ((new_alias = zalloc(sizeof(*new_alias))) == NULL)
1449          {
1450             fclose(fp);
1451             log_error(LOG_LEVEL_FATAL,
1452                "can't load actions file '%s': out of memory!",
1453                csp->config->actions_file[fileid]);
1454             return 1; /* never get here */
1455          }
1456
1457          /* Eat any the whitespace before the '=' */
1458          end--;
1459          while ((*end == ' ') || (*end == '\t'))
1460          {
1461             /*
1462              * we already know we must have at least 1 non-ws char
1463              * at start of buf - no need to check
1464              */
1465             end--;
1466          }
1467          end[1] = '\0';
1468
1469          /* Eat any the whitespace after the '=' */
1470          start++;
1471          while ((*start == ' ') || (*start == '\t'))
1472          {
1473             start++;
1474          }
1475          if (*start == '\0')
1476          {
1477             log_error(LOG_LEVEL_FATAL,
1478                "can't load actions file '%s': invalid alias line (%lu): %s",
1479                csp->config->actions_file[fileid], linenum, buf);
1480             return 1; /* never get here */
1481          }
1482
1483          if ((new_alias->name = strdup(buf)) == NULL)
1484          {
1485             fclose(fp);
1486             log_error(LOG_LEVEL_FATAL,
1487                "can't load actions file '%s': out of memory!",
1488                csp->config->actions_file[fileid]);
1489             return 1; /* never get here */
1490          }
1491
1492          strlcpy(actions_buf, start, sizeof(actions_buf));
1493
1494          if (get_actions(actions_buf, alias_list, new_alias->action))
1495          {
1496             /* error */
1497             fclose(fp);
1498             log_error(LOG_LEVEL_FATAL,
1499                "can't load actions file '%s': invalid alias line (%lu): %s = %s",
1500                csp->config->actions_file[fileid], linenum, buf, start);
1501             return 1; /* never get here */
1502          }
1503
1504          /* add to list */
1505          new_alias->next = alias_list;
1506          alias_list = new_alias;
1507       }
1508       else if (mode == MODE_ACTIONS)
1509       {
1510          /* it's an URL pattern */
1511
1512          /* allocate a new node */
1513          if ((perm = zalloc(sizeof(*perm))) == NULL)
1514          {
1515             fclose(fp);
1516             log_error(LOG_LEVEL_FATAL,
1517                "can't load actions file '%s': out of memory!",
1518                csp->config->actions_file[fileid]);
1519             return 1; /* never get here */
1520          }
1521
1522          perm->action = cur_action;
1523          cur_action_used = 1;
1524
1525          /* Save the URL pattern */
1526          if (create_url_spec(perm->url, buf))
1527          {
1528             fclose(fp);
1529             log_error(LOG_LEVEL_FATAL,
1530                "can't load actions file '%s': line %lu: cannot create URL or TAG pattern from: %s",
1531                csp->config->actions_file[fileid], linenum, buf);
1532             return 1; /* never get here */
1533          }
1534
1535          /* add it to the list */
1536          last_perm->next = perm;
1537          last_perm = perm;
1538       }
1539       else if (mode == MODE_START_OF_FILE)
1540       {
1541          /* oops - please have a {} line as 1st line in file. */
1542          fclose(fp);
1543          log_error(LOG_LEVEL_FATAL,
1544             "can't load actions file '%s': line %lu should begin with a '{': %s",
1545             csp->config->actions_file[fileid], linenum, buf);
1546          return 1; /* never get here */
1547       }
1548       else
1549       {
1550          /* How did we get here? This is impossible! */
1551          fclose(fp);
1552          log_error(LOG_LEVEL_FATAL,
1553             "can't load actions file '%s': INTERNAL ERROR - mode = %d",
1554             csp->config->actions_file[fileid], mode);
1555          return 1; /* never get here */
1556       }
1557       freez(buf);
1558    }
1559
1560    fclose(fp);
1561
1562    if (!cur_action_used)
1563    {
1564       free_action_spec(cur_action);
1565    }
1566    free_alias_list(alias_list);
1567
1568    /* the old one is now obsolete */
1569    if (current_actions_file[fileid])
1570    {
1571       current_actions_file[fileid]->unloader = unload_actions_file;
1572    }
1573
1574    fs->next    = files->next;
1575    files->next = fs;
1576    current_actions_file[fileid] = fs;
1577
1578    csp->actions_list[fileid] = fs;
1579
1580    return(0);
1581
1582 }
1583
1584
1585 /*********************************************************************
1586  *
1587  * Function    :  actions_to_text
1588  *
1589  * Description :  Converts a actionsfile entry from the internal
1590  *                structure into a text line.  The output is split
1591  *                into one line for each action with line continuation.
1592  *
1593  * Parameters  :
1594  *          1  :  action = The action to format.
1595  *
1596  * Returns     :  A string.  Caller must free it.
1597  *                NULL on out-of-memory error.
1598  *
1599  *********************************************************************/
1600 char * actions_to_text(const struct action_spec *action)
1601 {
1602    unsigned long mask = action->mask;
1603    unsigned long add  = action->add;
1604    char *result = strdup("");
1605    struct list_entry * lst;
1606
1607    /* sanity - prevents "-feature +feature" */
1608    mask |= add;
1609
1610
1611 #define DEFINE_ACTION_BOOL(__name, __bit)          \
1612    if (!(mask & __bit))                            \
1613    {                                               \
1614       string_append(&result, " -" __name " \\\n"); \
1615    }                                               \
1616    else if (add & __bit)                           \
1617    {                                               \
1618       string_append(&result, " +" __name " \\\n"); \
1619    }
1620
1621 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1622    if (!(mask & __bit))                                \
1623    {                                                   \
1624       string_append(&result, " -" __name " \\\n");     \
1625    }                                                   \
1626    else if (add & __bit)                               \
1627    {                                                   \
1628       string_append(&result, " +" __name "{");         \
1629       string_append(&result, action->string[__index]); \
1630       string_append(&result, "} \\\n");                \
1631    }
1632
1633 #define DEFINE_ACTION_MULTI(__name, __index)         \
1634    if (action->multi_remove_all[__index])            \
1635    {                                                 \
1636       string_append(&result, " -" __name " \\\n");   \
1637    }                                                 \
1638    else                                              \
1639    {                                                 \
1640       lst = action->multi_remove[__index]->first;    \
1641       while (lst)                                    \
1642       {                                              \
1643          string_append(&result, " -" __name "{");    \
1644          string_append(&result, lst->str);           \
1645          string_append(&result, "} \\\n");           \
1646          lst = lst->next;                            \
1647       }                                              \
1648    }                                                 \
1649    lst = action->multi_add[__index]->first;          \
1650    while (lst)                                       \
1651    {                                                 \
1652       string_append(&result, " +" __name "{");       \
1653       string_append(&result, lst->str);              \
1654       string_append(&result, "} \\\n");              \
1655       lst = lst->next;                               \
1656    }
1657
1658 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1659
1660 #include "actionlist.h"
1661
1662 #undef DEFINE_ACTION_MULTI
1663 #undef DEFINE_ACTION_STRING
1664 #undef DEFINE_ACTION_BOOL
1665 #undef DEFINE_ACTION_ALIAS
1666
1667    return result;
1668 }
1669
1670
1671 /*********************************************************************
1672  *
1673  * Function    :  actions_to_html
1674  *
1675  * Description :  Converts a actionsfile entry from numeric form
1676  *                ("mask" and "add") to a <br>-separated HTML string
1677  *                in which each action is linked to its chapter in
1678  *                the user manual.
1679  *
1680  * Parameters  :
1681  *          1  :  csp    = Client state (for config)
1682  *          2  :  action = Action spec to be converted
1683  *
1684  * Returns     :  A string.  Caller must free it.
1685  *                NULL on out-of-memory error.
1686  *
1687  *********************************************************************/
1688 char * actions_to_html(const struct client_state *csp,
1689                        const struct action_spec *action)
1690 {
1691    unsigned long mask = action->mask;
1692    unsigned long add  = action->add;
1693    char *result = strdup("");
1694    struct list_entry * lst;
1695
1696    /* sanity - prevents "-feature +feature" */
1697    mask |= add;
1698
1699
1700 #define DEFINE_ACTION_BOOL(__name, __bit)       \
1701    if (!(mask & __bit))                         \
1702    {                                            \
1703       string_append(&result, "\n<br>-");        \
1704       string_join(&result, add_help_link(__name, csp->config)); \
1705    }                                            \
1706    else if (add & __bit)                        \
1707    {                                            \
1708       string_append(&result, "\n<br>+");        \
1709       string_join(&result, add_help_link(__name, csp->config)); \
1710    }
1711
1712 #define DEFINE_ACTION_STRING(__name, __bit, __index) \
1713    if (!(mask & __bit))                              \
1714    {                                                 \
1715       string_append(&result, "\n<br>-");             \
1716       string_join(&result, add_help_link(__name, csp->config)); \
1717    }                                                 \
1718    else if (add & __bit)                             \
1719    {                                                 \
1720       string_append(&result, "\n<br>+");             \
1721       string_join(&result, add_help_link(__name, csp->config)); \
1722       string_append(&result, "{");                   \
1723       string_join(&result, html_encode(action->string[__index])); \
1724       string_append(&result, "}");                   \
1725    }
1726
1727 #define DEFINE_ACTION_MULTI(__name, __index)          \
1728    if (action->multi_remove_all[__index])             \
1729    {                                                  \
1730       string_append(&result, "\n<br>-");              \
1731       string_join(&result, add_help_link(__name, csp->config)); \
1732    }                                                  \
1733    else                                               \
1734    {                                                  \
1735       lst = action->multi_remove[__index]->first;     \
1736       while (lst)                                     \
1737       {                                               \
1738          string_append(&result, "\n<br>-");           \
1739          string_join(&result, add_help_link(__name, csp->config)); \
1740          string_append(&result, "{");                 \
1741          string_join(&result, html_encode(lst->str)); \
1742          string_append(&result, "}");                 \
1743          lst = lst->next;                             \
1744       }                                               \
1745    }                                                  \
1746    lst = action->multi_add[__index]->first;           \
1747    while (lst)                                        \
1748    {                                                  \
1749       string_append(&result, "\n<br>+");              \
1750       string_join(&result, add_help_link(__name, csp->config)); \
1751       string_append(&result, "{");                    \
1752       string_join(&result, html_encode(lst->str));    \
1753       string_append(&result, "}");                    \
1754       lst = lst->next;                                \
1755    }
1756
1757 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1758
1759 #include "actionlist.h"
1760
1761 #undef DEFINE_ACTION_MULTI
1762 #undef DEFINE_ACTION_STRING
1763 #undef DEFINE_ACTION_BOOL
1764 #undef DEFINE_ACTION_ALIAS
1765
1766    /* trim leading <br> */
1767    if (result && *result)
1768    {
1769       char * s = result;
1770       result = strdup(result + 5);
1771       free(s);
1772    }
1773
1774    return result;
1775 }
1776
1777
1778 /*********************************************************************
1779  *
1780  * Function    :  current_actions_to_html
1781  *
1782  * Description :  Converts a curren action spec to a <br> separated HTML
1783  *                text in which each action is linked to its chapter in
1784  *                the user manual.
1785  *
1786  * Parameters  :
1787  *          1  :  csp    = Client state (for config)
1788  *          2  :  action = Current action spec to be converted
1789  *
1790  * Returns     :  A string.  Caller must free it.
1791  *                NULL on out-of-memory error.
1792  *
1793  *********************************************************************/
1794 char *current_action_to_html(const struct client_state *csp,
1795                              const struct current_action_spec *action)
1796 {
1797    unsigned long flags  = action->flags;
1798    struct list_entry * lst;
1799    char *result   = strdup("");
1800    char *active   = strdup("");
1801    char *inactive = strdup("");
1802
1803 #define DEFINE_ACTION_BOOL(__name, __bit)  \
1804    if (flags & __bit)                      \
1805    {                                       \
1806       string_append(&active, "\n<br>+");   \
1807       string_join(&active, add_help_link(__name, csp->config)); \
1808    }                                       \
1809    else                                    \
1810    {                                       \
1811       string_append(&inactive, "\n<br>-"); \
1812       string_join(&inactive, add_help_link(__name, csp->config)); \
1813    }
1814
1815 #define DEFINE_ACTION_STRING(__name, __bit, __index)   \
1816    if (flags & __bit)                                  \
1817    {                                                   \
1818       string_append(&active, "\n<br>+");               \
1819       string_join(&active, add_help_link(__name, csp->config)); \
1820       string_append(&active, "{");                     \
1821       string_join(&active, html_encode(action->string[__index])); \
1822       string_append(&active, "}");                     \
1823    }                                                   \
1824    else                                                \
1825    {                                                   \
1826       string_append(&inactive, "\n<br>-");             \
1827       string_join(&inactive, add_help_link(__name, csp->config)); \
1828    }
1829
1830 #define DEFINE_ACTION_MULTI(__name, __index)           \
1831    lst = action->multi[__index]->first;                \
1832    if (lst == NULL)                                    \
1833    {                                                   \
1834       string_append(&inactive, "\n<br>-");             \
1835       string_join(&inactive, add_help_link(__name, csp->config)); \
1836    }                                                   \
1837    else                                                \
1838    {                                                   \
1839       while (lst)                                      \
1840       {                                                \
1841          string_append(&active, "\n<br>+");            \
1842          string_join(&active, add_help_link(__name, csp->config)); \
1843          string_append(&active, "{");                  \
1844          string_join(&active, html_encode(lst->str));  \
1845          string_append(&active, "}");                  \
1846          lst = lst->next;                              \
1847       }                                                \
1848    }
1849
1850 #define DEFINE_ACTION_ALIAS 0 /* No aliases for output */
1851
1852 #include "actionlist.h"
1853
1854 #undef DEFINE_ACTION_MULTI
1855 #undef DEFINE_ACTION_STRING
1856 #undef DEFINE_ACTION_BOOL
1857 #undef DEFINE_ACTION_ALIAS
1858
1859    if (active != NULL)
1860    {
1861       string_append(&result, active);
1862       freez(active);
1863    }
1864    string_append(&result, "\n<br>");
1865    if (inactive != NULL)
1866    {
1867       string_append(&result, inactive);
1868       freez(inactive);
1869    }
1870    return result;
1871 }