driver: Fix memory leak in output_submit().
[pspp] / src / output / driver.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2012, 2014, 2019 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "output/driver.h"
20 #include "output/driver-provider.h"
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <libxml/parser.h>
25 #include <libxml/tree.h>
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <time.h>
30
31 #include "data/file-handle-def.h"
32 #include "data/settings.h"
33 #include "libpspp/array.h"
34 #include "libpspp/assertion.h"
35 #include "libpspp/message.h"
36 #include "libpspp/llx.h"
37 #include "libpspp/string-map.h"
38 #include "libpspp/string-set.h"
39 #include "libpspp/str.h"
40 #include "output/group-item.h"
41 #include "output/message-item.h"
42 #include "output/output-item.h"
43 #include "output/text-item.h"
44
45 #include "gl/error.h"
46 #include "gl/xalloc.h"
47 #include "gl/xmemdup0.h"
48
49 #include "gettext.h"
50 #define _(msgid) gettext (msgid)
51
52 struct output_engine
53   {
54     struct ll ll;                  /* Node for this engine. */
55     struct llx_list drivers;       /* Contains "struct output_driver"s. */
56     struct string deferred_text;   /* Output text being accumulated. */
57     enum text_item_type deferred_type; /* Type of text being accumulated. */
58     char *command_name;            /* Name of command being processed. */
59     char *title, *subtitle;        /* Components of page title. */
60
61     /* Output grouping stack.
62
63        TEXT_ITEM_GROUP_OPEN pushes a group on the stack and
64        TEXT_ITEM_GROUP_CLOSE pops one off. */
65     char **groups;               /* Command names of nested sections. */
66     size_t n_groups;
67     size_t allocated_groups;
68
69     struct string_map heading_vars;
70   };
71
72 static struct ll_list engine_stack = LL_INITIALIZER (engine_stack);
73
74 static const struct output_driver_factory *factories[];
75
76 static struct output_engine *
77 engine_stack_top (void)
78 {
79   struct ll *head = ll_head (&engine_stack);
80   if (ll_is_empty (&engine_stack))
81     return NULL;
82   return ll_data (head, struct output_engine, ll);
83 }
84
85 static void
86 put_strftime (const char *key, const char *format,
87               const struct tm *tm, struct string_map *vars)
88 {
89   if (!string_map_find (vars, key))
90     {
91       char value[128];
92       strftime (value, sizeof value, format, tm);
93       string_map_insert (vars, key, value);
94     }
95 }
96
97 void
98 output_engine_push (void)
99 {
100   struct output_engine *e = xzalloc (sizeof (*e));
101
102   llx_init (&e->drivers);
103   ds_init_empty (&e->deferred_text);
104
105   string_map_init (&e->heading_vars);
106
107   time_t t = time (NULL);
108   const struct tm *tm = localtime (&t);
109   put_strftime ("Date", "%x", tm, &e->heading_vars);
110   put_strftime ("Time", "%X", tm, &e->heading_vars);
111
112   ll_push_head (&engine_stack, &e->ll);
113 }
114
115 void
116 output_engine_pop (void)
117 {
118   struct ll *head = ll_pop_head (&engine_stack);
119   struct output_engine *e =ll_data (head, struct output_engine, ll);
120
121   while (!llx_is_empty (&e->drivers))
122     {
123       struct output_driver *d = llx_pop_head (&e->drivers, &llx_malloc_mgr);
124       output_driver_destroy (d);
125     }
126   ds_destroy (&e->deferred_text);
127   free (e->command_name);
128   free (e->title);
129   free (e->subtitle);
130   for (size_t i = 0; i < e->n_groups; i++)
131     free (e->groups[i]);
132   free (e->groups);
133   string_map_destroy (&e->heading_vars);
134   free (e);
135 }
136
137 void
138 output_get_supported_formats (struct string_set *formats)
139 {
140   const struct output_driver_factory **fp;
141
142   for (fp = factories; *fp != NULL; fp++)
143     string_set_insert (formats, (*fp)->extension);
144 }
145
146 static void
147 output_submit__ (struct output_engine *e, struct output_item *item)
148 {
149   struct llx *llx, *next;
150
151   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers); llx = next)
152     {
153       struct output_driver *d = llx_data (llx);
154       enum settings_output_type type;
155
156       next = llx_next (llx);
157
158       if (is_message_item (item))
159         {
160           const struct msg *m = message_item_get_msg (to_message_item (item));
161           if (m->severity == MSG_S_NOTE)
162             type = SETTINGS_OUTPUT_NOTE;
163           else
164             type = SETTINGS_OUTPUT_ERROR;
165         }
166       else if (is_text_item (item)
167                && text_item_get_type (to_text_item (item)) == TEXT_ITEM_SYNTAX)
168         type = SETTINGS_OUTPUT_SYNTAX;
169       else
170         type = SETTINGS_OUTPUT_RESULT;
171
172       if (settings_get_output_routing (type) & d->device_type)
173         d->class->submit (d, item);
174     }
175
176   output_item_unref (item);
177 }
178
179 static void
180 flush_deferred_text (struct output_engine *e)
181 {
182   if (!ds_is_empty (&e->deferred_text))
183     {
184       char *text = ds_steal_cstr (&e->deferred_text);
185       output_submit__ (e, text_item_super (text_item_create_nocopy (
186                                              e->deferred_type, text)));
187     }
188 }
189
190 static bool
191 defer_text (struct output_engine *e, struct output_item *item)
192 {
193   if (!is_text_item (item))
194     return false;
195
196   enum text_item_type type = text_item_get_type (to_text_item (item));
197   if (type != TEXT_ITEM_SYNTAX && type != TEXT_ITEM_LOG)
198     return false;
199
200   if (!ds_is_empty (&e->deferred_text) && e->deferred_type != type)
201     flush_deferred_text (e);
202
203   e->deferred_type = type;
204
205   if (!ds_is_empty (&e->deferred_text))
206     ds_put_byte (&e->deferred_text, '\n');
207
208   const char *text = text_item_get_text (to_text_item (item));
209   ds_put_cstr (&e->deferred_text, text);
210   output_item_unref (item);
211
212   return true;
213 }
214
215 /* Submits ITEM to the configured output drivers, and transfers ownership to
216    the output subsystem. */
217 void
218 output_submit (struct output_item *item)
219 {
220   struct output_engine *e = engine_stack_top ();
221
222   if (e == NULL)
223     return;
224
225   if (item == NULL)
226     return;
227
228   if (defer_text (e, item))
229     return;
230   flush_deferred_text (e);
231
232   if (is_group_open_item (item))
233     {
234       const struct group_open_item *group_open_item
235         = to_group_open_item (item);
236       if (e->n_groups >= e->allocated_groups)
237         e->groups = x2nrealloc (e->groups, &e->allocated_groups,
238                                 sizeof *e->groups);
239       e->groups[e->n_groups] = (group_open_item->command_name
240                                 ? xstrdup (group_open_item->command_name)
241                                 : NULL);
242       e->n_groups++;
243     }
244   else if (is_group_close_item (item))
245     {
246       assert (e->n_groups > 0);
247
248       size_t idx = --e->n_groups;
249       free (e->groups[idx]);
250       if (idx >= 1 && idx <= 4)
251         {
252           char *key = xasprintf ("Head%zu", idx);
253           free (string_map_find_and_delete (&e->heading_vars, key));
254           free (key);
255         }
256     }
257   else if (is_text_item (item))
258     {
259       const struct text_item *text_item = to_text_item (item);
260       enum text_item_type type = text_item_get_type (text_item);
261       const char *text = text_item_get_text (text_item);
262       if (type == TEXT_ITEM_TITLE
263           && e->n_groups >= 1 && e->n_groups <= 4)
264         {
265           char *key = xasprintf ("Head%zu", e->n_groups);
266           string_map_replace (&e->heading_vars, key, text);
267           free (key);
268         }
269       else if (type == TEXT_ITEM_PAGE_TITLE)
270         string_map_replace (&e->heading_vars, "PageTitle", text);
271     }
272
273   output_submit__ (e, item);
274 }
275
276 const char *
277 output_get_command_name (void)
278 {
279   struct output_engine *e = engine_stack_top ();
280   if (e == NULL)
281     return NULL;
282
283   for (size_t i = e->n_groups; i-- > 0; )
284     if (e->groups[i])
285       return e->groups[i];
286
287   return NULL;
288 }
289
290 /* Flushes output to screen devices, so that the user can see
291    output that doesn't fill up an entire page. */
292 void
293 output_flush (void)
294 {
295   struct output_engine *e = engine_stack_top ();
296   struct llx *llx;
297
298   flush_deferred_text (e);
299   for (llx = llx_head (&e->drivers); llx != llx_null (&e->drivers);
300        llx = llx_next (llx))
301     {
302       struct output_driver *d = llx_data (llx);
303       if (d->device_type & SETTINGS_DEVICE_TERMINAL && d->class->flush != NULL)
304         d->class->flush (d);
305     }
306 }
307
308 static void
309 output_set_title__ (struct output_engine *e, char **dst, const char *src)
310 {
311   free (*dst);
312   *dst = src ? xstrdup (src) : NULL;
313
314   char *page_title
315     = (e->title && e->subtitle ? xasprintf ("%s\n%s", e->title, e->subtitle)
316        : e->title ? xstrdup (e->title)
317        : e->subtitle ? xstrdup (e->subtitle)
318        : xzalloc (1));
319   text_item_submit (text_item_create_nocopy (TEXT_ITEM_PAGE_TITLE,
320                                              page_title));
321 }
322
323 void
324 output_set_title (const char *title)
325 {
326   struct output_engine *e = engine_stack_top ();
327
328   output_set_title__ (e, &e->title, title);
329 }
330
331 void
332 output_set_subtitle (const char *subtitle)
333 {
334   struct output_engine *e = engine_stack_top ();
335
336   output_set_title__ (e, &e->subtitle, subtitle);
337 }
338
339 void
340 output_set_filename (const char *filename)
341 {
342   struct output_engine *e = engine_stack_top ();
343
344   string_map_replace (&e->heading_vars, "Filename", filename);
345 }
346
347 size_t
348 output_get_group_level (void)
349 {
350   struct output_engine *e = engine_stack_top ();
351
352   return e->n_groups;
353 }
354 \f
355 void
356 output_driver_init (struct output_driver *driver,
357                     const struct output_driver_class *class,
358                     const char *name, enum settings_output_devices type)
359 {
360   driver->class = class;
361   driver->name = xstrdup (name);
362   driver->device_type = type;
363 }
364
365 void
366 output_driver_destroy (struct output_driver *driver)
367 {
368   if (driver != NULL)
369     {
370       char *name = driver->name;
371       if (output_driver_is_registered (driver))
372         output_driver_unregister (driver);
373       if (driver->class->destroy)
374         driver->class->destroy (driver);
375       free (name);
376     }
377 }
378
379 const char *
380 output_driver_get_name (const struct output_driver *driver)
381 {
382   return driver->name;
383 }
384 \f
385 static struct output_engine *
386 output_driver_get_engine (const struct output_driver *driver)
387 {
388   struct output_engine *e;
389
390   ll_for_each (e, struct output_engine, ll, &engine_stack)
391     {
392       if (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver))
393         return e;
394     }
395
396   return NULL;
397 }
398
399 void
400 output_driver_register (struct output_driver *driver)
401 {
402   struct output_engine *e = engine_stack_top ();
403
404   assert (!output_driver_is_registered (driver));
405   llx_push_tail (&e->drivers, driver, &llx_malloc_mgr);
406 }
407
408 void
409 output_driver_unregister (struct output_driver *driver)
410 {
411   struct output_engine *e = output_driver_get_engine (driver);
412
413   assert (e != NULL);
414   llx_remove (llx_find (llx_head (&e->drivers), llx_null (&e->drivers), driver),
415               &llx_malloc_mgr);
416 }
417
418 bool
419 output_driver_is_registered (const struct output_driver *driver)
420 {
421   return output_driver_get_engine (driver) != NULL;
422 }
423 \f
424 extern const struct output_driver_factory txt_driver_factory;
425 extern const struct output_driver_factory list_driver_factory;
426 extern const struct output_driver_factory html_driver_factory;
427 extern const struct output_driver_factory csv_driver_factory;
428 extern const struct output_driver_factory odt_driver_factory;
429 #ifdef HAVE_CAIRO
430 extern const struct output_driver_factory pdf_driver_factory;
431 extern const struct output_driver_factory ps_driver_factory;
432 extern const struct output_driver_factory svg_driver_factory;
433 #endif
434
435 static const struct output_driver_factory *factories[] =
436   {
437     &txt_driver_factory,
438     &list_driver_factory,
439     &html_driver_factory,
440     &csv_driver_factory,
441     &odt_driver_factory,
442 #ifdef HAVE_CAIRO
443     &pdf_driver_factory,
444     &ps_driver_factory,
445     &svg_driver_factory,
446 #endif
447     NULL
448   };
449
450 static const struct output_driver_factory *
451 find_factory (const char *format)
452 {
453   const struct output_driver_factory **fp;
454
455   for (fp = factories; *fp != NULL; fp++)
456     {
457       const struct output_driver_factory *f = *fp;
458
459       if (!strcmp (f->extension, format))
460         return f;
461     }
462   return &txt_driver_factory;
463 }
464
465 static enum settings_output_devices
466 default_device_type (const char *file_name)
467 {
468   return (!strcmp (file_name, "-")
469           ? SETTINGS_DEVICE_TERMINAL
470           : SETTINGS_DEVICE_LISTING);
471 }
472
473 struct output_driver *
474 output_driver_create (struct string_map *options)
475 {
476   enum settings_output_devices device_type;
477   const struct output_driver_factory *f;
478   struct output_driver *driver;
479   char *device_string;
480   char *file_name;
481   char *format;
482
483   format = string_map_find_and_delete (options, "format");
484   file_name = string_map_find_and_delete (options, "output-file");
485
486   if (format == NULL)
487     {
488       if (file_name != NULL)
489         {
490           const char *extension = strrchr (file_name, '.');
491           format = xstrdup (extension != NULL ? extension + 1 : "");
492         }
493       else
494         format = xstrdup ("txt");
495     }
496   f = find_factory (format);
497
498   if (file_name == NULL)
499     file_name = xstrdup (f->default_file_name);
500
501   /* XXX should use parse_enum(). */
502   device_string = string_map_find_and_delete (options, "device");
503   if (device_string == NULL || device_string[0] == '\0')
504     device_type = default_device_type (file_name);
505   else if (!strcmp (device_string, "terminal"))
506     device_type = SETTINGS_DEVICE_TERMINAL;
507   else if (!strcmp (device_string, "listing"))
508     device_type = SETTINGS_DEVICE_LISTING;
509   else
510     {
511       msg (MW, _("%s is not a valid device type (the choices are `%s' and `%s')"),
512                      device_string, "terminal", "listing");
513       device_type = default_device_type (file_name);
514     }
515
516   struct file_handle *fh = fh_create_file (NULL, file_name, NULL, fh_default_properties ());
517
518   driver = f->create (fh, device_type, options);
519   if (driver != NULL)
520     {
521       const struct string_map_node *node;
522       const char *key;
523
524       STRING_MAP_FOR_EACH_KEY (key, node, options)
525         msg (MW, _("%s: unknown option `%s'"), file_name, key);
526     }
527   string_map_clear (options);
528
529   free (file_name);
530   free (format);
531   free (device_string);
532
533   return driver;
534 }
535
536 void
537 output_driver_parse_option (const char *option, struct string_map *options)
538 {
539   const char *equals = strchr (option, '=');
540   if (equals == NULL)
541     {
542       error (0, 0, _("%s: output option missing `='"), option);
543       return;
544     }
545
546   char *key = xmemdup0 (option, equals - option);
547   if (string_map_contains (options, key))
548     {
549       error (0, 0, _("%s: output option specified more than once"), key);
550       free (key);
551       return;
552     }
553
554   char *value = xmemdup0 (equals + 1, strlen (equals + 1));
555   string_map_insert_nocopy (options, key, value);
556 }
557 \f
558 /* Extracts the actual text content from the given Pango MARKUP and returns it
559    as as a malloc()'d string. */
560 char *
561 output_get_text_from_markup (const char *markup)
562 {
563   xmlParserCtxt *parser = xmlCreatePushParserCtxt (NULL, NULL, NULL, 0, NULL);
564   if (!parser)
565     return xstrdup (markup);
566
567   xmlParseChunk (parser, "<xml>", strlen ("<xml>"), false);
568   xmlParseChunk (parser, markup, strlen (markup), false);
569   xmlParseChunk (parser, "</xml>", strlen ("</xml>"), true);
570
571   char *content
572     = (parser->wellFormed
573        ? CHAR_CAST (char *,
574                     xmlNodeGetContent (xmlDocGetRootElement (parser->myDoc)))
575        : xstrdup (markup));
576   xmlFreeDoc (parser->myDoc);
577   xmlFreeParserCtxt (parser);
578
579   return content;
580 }
581
582 char *
583 output_driver_substitute_heading_vars (const char *src, int page_number)
584 {
585   struct output_engine *e = engine_stack_top ();
586   struct string dst = DS_EMPTY_INITIALIZER;
587   ds_extend (&dst, strlen (src));
588   for (const char *p = src; *p; )
589     {
590       if (!strncmp (p, "&amp;[", 6))
591         {
592           if (page_number != INT_MIN)
593             {
594               const char *start = p + 6;
595               const char *end = strchr (start, ']');
596               if (end)
597                 {
598                   const char *value = string_map_find__ (&e->heading_vars,
599                                                          start, end - start);
600                   if (value)
601                     ds_put_cstr (&dst, value);
602                   else if (ss_equals (ss_buffer (start, end - start),
603                                       ss_cstr ("Page")))
604                     ds_put_format (&dst, "%d", page_number);
605                   p = end + 1;
606                   continue;
607                 }
608             }
609           ds_put_cstr (&dst, "&amp;");
610           p += 5;
611         }
612       else
613         ds_put_byte (&dst, *p++);
614     }
615   return ds_steal_cstr (&dst);
616 }