Gnumeric reader: Avoid potential crash reading invalid gnumeric files
[pspp] / src / data / gnumeric-reader.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007, 2009, 2010, 2011, 2012 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 "libpspp/message.h"
20 #include "libpspp/misc.h"
21
22 #include "gl/minmax.h"
23 #include "gl/c-strtod.h"
24
25 #include "gettext.h"
26 #define _(msgid) gettext (msgid)
27 #define N_(msgid) (msgid)
28
29 #include "spreadsheet-reader.h"
30
31 #if !GNM_SUPPORT
32
33 struct casereader *
34 gnumeric_open_reader (struct spreadsheet_read_info *gri, struct dictionary **dict)
35 {
36   msg (ME, _("Support for %s files was not compiled into this installation of PSPP"), "Gnumeric");
37
38   return NULL;
39 }
40
41 #else
42
43 #include "data/gnumeric-reader.h"
44
45 #include <assert.h>
46 #include <stdbool.h>
47 #include <errno.h>
48 #include <libxml/xmlreader.h>
49 #include <zlib.h>
50
51 #include "data/case.h"
52 #include "data/casereader-provider.h"
53 #include "data/dictionary.h"
54 #include "data/identifier.h"
55 #include "data/value.h"
56 #include "data/variable.h"
57 #include "libpspp/i18n.h"
58 #include "libpspp/str.h"
59
60 #include "gl/xalloc.h"
61
62 static void gnm_file_casereader_destroy (struct casereader *, void *);
63
64 static struct ccase *gnm_file_casereader_read (struct casereader *, void *);
65
66 static const struct casereader_class gnm_file_casereader_class =
67   {
68     gnm_file_casereader_read,
69     gnm_file_casereader_destroy,
70     NULL,
71     NULL,
72   };
73
74 enum reader_state
75   {
76     STATE_INIT = 0,        /* Initial state */
77     STATE_SHEET_START,     /* Found the start of a sheet */
78     STATE_SHEET_NAME,      /* Found the sheet name */
79     STATE_MAXROW,
80     STATE_SHEET_FOUND,     /* Found the sheet that we actually want */
81     STATE_CELLS_START,     /* Found the start of the cell array */
82     STATE_CELL             /* Found a cell */
83   };
84
85
86 struct gnumeric_reader
87 {
88   xmlTextReaderPtr xtr;
89
90   enum reader_state state;
91   int row;
92   int col;
93   int node_type;
94   int sheet_index;
95
96
97   const xmlChar *target_sheet;
98   int target_sheet_index;
99
100   int start_row;
101   int start_col;
102   int stop_row;
103   int stop_col;
104
105   struct caseproto *proto;
106   struct dictionary *dict;
107   struct ccase *first_case;
108   bool used_first_case;
109 };
110
111 static void process_node (struct gnumeric_reader *r);
112
113
114 static void
115 gnm_file_casereader_destroy (struct casereader *reader UNUSED, void *r_)
116 {
117   struct gnumeric_reader *r = r_;
118   if ( r == NULL)
119         return ;
120
121   if ( r->xtr)
122     xmlFreeTextReader (r->xtr);
123
124   if ( ! r->used_first_case )
125     case_unref (r->first_case);
126
127   caseproto_unref (r->proto);
128
129   free (r);
130 }
131
132 static void
133 process_node (struct gnumeric_reader *r)
134 {
135   xmlChar *name = xmlTextReaderName (r->xtr);
136   if (name == NULL)
137     name = xmlStrdup (_xml ("--"));
138
139
140   r->node_type = xmlTextReaderNodeType (r->xtr);
141
142   switch ( r->state)
143     {
144     case STATE_INIT:
145       if (0 == xmlStrcasecmp (name, _xml("gnm:Sheet")) &&
146           XML_READER_TYPE_ELEMENT  == r->node_type)
147         {
148           r->state = STATE_SHEET_START;
149         }
150       break;
151     case STATE_SHEET_START:
152       if (0 == xmlStrcasecmp (name, _xml("gnm:Name"))  &&
153           XML_READER_TYPE_ELEMENT  == r->node_type)
154         {
155           r->state = STATE_SHEET_NAME;
156         }
157       else if (0 == xmlStrcasecmp (name, _xml("gnm:Name"))  &&
158                XML_READER_TYPE_END_ELEMENT  == r->node_type)
159         {
160           r->state = STATE_INIT;
161         }
162       break;
163     case STATE_SHEET_NAME:
164       if (0 == xmlStrcasecmp (name, _xml("gnm:Name"))  &&
165           XML_READER_TYPE_END_ELEMENT  == r->node_type)
166         {
167           r->state = STATE_SHEET_START;
168         }
169       else if (XML_READER_TYPE_TEXT == r->node_type)
170         {
171           ++r->sheet_index;
172           if ( r->target_sheet != NULL)
173             {
174               xmlChar *value = xmlTextReaderValue (r->xtr);
175               if ( 0 == xmlStrcmp (value, r->target_sheet))
176                 r->state = STATE_SHEET_FOUND;
177               free (value);
178             }
179           else if (r->target_sheet_index == r->sheet_index)
180             {
181               r->state = STATE_SHEET_FOUND;
182             }
183         }
184       break;
185     case STATE_SHEET_FOUND:
186       if (0 == xmlStrcasecmp (name, _xml("gnm:Cells"))  &&
187           XML_READER_TYPE_ELEMENT  == r->node_type)
188         {
189           if (! xmlTextReaderIsEmptyElement (r->xtr))
190             r->state = STATE_CELLS_START;
191         }
192       else if (0 == xmlStrcasecmp (name, _xml("gnm:MaxRow"))  &&
193           XML_READER_TYPE_ELEMENT  == r->node_type)
194         {
195           r->state = STATE_MAXROW;
196         }
197       else if (0 == xmlStrcasecmp (name, _xml("gnm:Sheet"))  &&
198           XML_READER_TYPE_END_ELEMENT  == r->node_type)
199         {
200           r->state = STATE_INIT;
201         }
202       break;
203     case STATE_MAXROW:
204       if (0 == xmlStrcasecmp (name, _xml("gnm:MaxRow"))  &&
205           XML_READER_TYPE_END_ELEMENT  == r->node_type)
206         {
207           r->state = STATE_SHEET_FOUND;
208         }
209     case STATE_CELLS_START:
210       if (0 == xmlStrcasecmp (name, _xml ("gnm:Cell"))  &&
211           XML_READER_TYPE_ELEMENT  == r->node_type)
212         {
213           xmlChar *attr = NULL;
214           r->state = STATE_CELL;
215
216           attr = xmlTextReaderGetAttribute (r->xtr, _xml ("Col"));
217           r->col =  _xmlchar_to_int (attr);
218           free (attr);
219
220           attr = xmlTextReaderGetAttribute (r->xtr, _xml ("Row"));
221           r->row = _xmlchar_to_int (attr);
222           free (attr);
223         }
224       else if (0 == xmlStrcasecmp (name, _xml("gnm:Cells"))  &&
225                XML_READER_TYPE_END_ELEMENT  == r->node_type)
226         r->state = STATE_SHEET_NAME;
227
228       break;
229     case STATE_CELL:
230       if (0 == xmlStrcasecmp (name, _xml("gnm:Cell"))  &&
231                               XML_READER_TYPE_END_ELEMENT  == r->node_type)
232         r->state = STATE_CELLS_START;
233       break;
234     default:
235       break;
236     };
237
238   xmlFree (name);
239 }
240
241
242 /*
243    Sets the VAR of case C, to the value corresponding to the xml string XV
244  */
245 static void
246 convert_xml_string_to_value (struct ccase *c, const struct variable *var,
247                              const xmlChar *xv)
248 {
249   union value *v = case_data_rw (c, var);
250
251   if (xv == NULL)
252     value_set_missing (v, var_get_width (var));
253   else if ( var_is_alpha (var))
254     value_copy_str_rpad (v, var_get_width (var), xv, ' ');
255   else
256     {
257       const char *text = CHAR_CAST (const char *, xv);
258       char *endptr;
259
260       errno = 0;
261       v->f = c_strtod (text, &endptr);
262       if ( errno != 0 || endptr == text)
263         v->f = SYSMIS;
264     }
265 }
266
267 struct var_spec
268 {
269   char *name;
270   int width;
271   xmlChar *first_value;
272 };
273
274 struct casereader *
275 gnumeric_open_reader (struct spreadsheet_read_info *gri, struct dictionary **dict)
276 {
277   unsigned long int vstart = 0;
278   int ret;
279   casenumber n_cases = CASENUMBER_MAX;
280   int i;
281   struct var_spec *var_spec = NULL;
282   int n_var_specs = 0;
283
284   struct gnumeric_reader *r = NULL;
285
286   gzFile gz = gzopen (gri->file_name, "r");
287
288   if ( NULL == gz)
289     {
290       msg (ME, _("Error opening `%s' for reading as a Gnumeric file: %s."),
291            gri->file_name, strerror (errno));
292
293       goto error;
294     }
295
296   r = xzalloc (sizeof *r);
297
298   r->xtr = xmlReaderForIO ((xmlInputReadCallback) gzread,
299                            (xmlInputCloseCallback) gzclose, gz,
300                            NULL, NULL, 0);
301
302   if ( r->xtr == NULL )
303     goto error;
304
305   if ( gri->cell_range )
306     {
307       if ( ! convert_cell_ref (gri->cell_range,
308                                &r->start_col, &r->start_row,
309                                &r->stop_col, &r->stop_row))
310         {
311           msg (SE, _("Invalid cell range `%s'"),
312                gri->cell_range);
313           goto error;
314         }
315     }
316   else
317     {
318       r->start_col = 0;
319       r->start_row = 0;
320       r->stop_col = -1;
321       r->stop_row = -1;
322     }
323
324   r->state = STATE_INIT;
325   r->target_sheet = BAD_CAST gri->sheet_name;
326   r->target_sheet_index = gri->sheet_index;
327   r->row = r->col = -1;
328   r->sheet_index = 0;
329
330   /* Advance to the start of the cells for the target sheet */
331   while ( (r->state != STATE_CELL || r->row < r->start_row )
332           && 1 == (ret = xmlTextReaderRead (r->xtr)))
333     {
334       xmlChar *value ;
335       process_node (r);
336       value = xmlTextReaderValue (r->xtr);
337
338       if ( r->state == STATE_MAXROW  && r->node_type == XML_READER_TYPE_TEXT)
339         {
340           n_cases = 1 + _xmlchar_to_int (value) ;
341         }
342       free (value);
343     }
344
345
346   /* If a range has been given, then  use that to calculate the number
347      of cases */
348   if ( gri->cell_range)
349     {
350       n_cases = MIN (n_cases, r->stop_row - r->start_row + 1);
351     }
352
353   if ( gri->read_names )
354     {
355       r->start_row++;
356       n_cases --;
357     }
358
359   /* Read in the first row of cells,
360      including the headers if read_names was set */
361   while (
362          (( r->state == STATE_CELLS_START && r->row <= r->start_row) || r->state == STATE_CELL )
363          && (ret = xmlTextReaderRead (r->xtr))
364          )
365     {
366       int idx;
367       process_node (r);
368
369       if ( r->row > r->start_row ) break;
370
371       if ( r->col < r->start_col ||
372            (r->stop_col != -1 && r->col > r->stop_col))
373         continue;
374
375       idx = r->col - r->start_col;
376
377       if ( idx  >= n_var_specs )
378         {
379           n_var_specs =  idx + 1 ;
380           var_spec = xrealloc (var_spec, sizeof (*var_spec) * n_var_specs);
381           var_spec [idx].name = NULL;
382           var_spec [idx].width = -1;
383           var_spec [idx].first_value = NULL;
384         }
385
386       if ( r->node_type == XML_READER_TYPE_TEXT )
387         {
388           xmlChar *value = xmlTextReaderValue (r->xtr);
389           const char *text  = CHAR_CAST (const char *, value);
390
391           if ( r->row < r->start_row)
392             {
393               if ( gri->read_names )
394                 {
395                   var_spec [idx].name = xstrdup (text);
396                 }
397             }
398           else
399             {
400               var_spec [idx].first_value = xmlStrdup (value);
401
402               if (-1 ==  var_spec [idx].width )
403                 var_spec [idx].width = (gri->asw == -1) ?
404                   ROUND_UP (strlen(text), SPREADSHEET_DEFAULT_WIDTH) : gri->asw;
405             }
406
407           free (value);
408         }
409       else if ( r->node_type == XML_READER_TYPE_ELEMENT
410                 && r->state == STATE_CELL)
411         {
412           if ( r->row == r->start_row )
413             {
414               xmlChar *attr =
415                 xmlTextReaderGetAttribute (r->xtr, _xml ("ValueType"));
416
417               if ( NULL == attr || 60 !=  _xmlchar_to_int (attr))
418                 var_spec [idx].width = 0;
419
420               free (attr);
421             }
422         }
423     }
424
425   {
426     const xmlChar *enc = xmlTextReaderConstEncoding (r->xtr);
427     if ( enc == NULL)
428       goto error;
429     /* Create the dictionary and populate it */
430     *dict = r->dict = dict_create (CHAR_CAST (const char *, enc));
431   }
432
433   for (i = 0 ; i < n_var_specs ; ++i )
434     {
435       char *name;
436
437       /* Probably no data exists for this variable, so allocate a
438          default width */
439       if ( var_spec[i].width == -1 )
440         var_spec[i].width = SPREADSHEET_DEFAULT_WIDTH;
441
442       name = dict_make_unique_var_name (r->dict, var_spec[i].name, &vstart);
443       dict_create_var (r->dict, name, var_spec[i].width);
444       free (name);
445     }
446
447   /* Create the first case, and cache it */
448   r->used_first_case = false;
449
450   if ( n_var_specs ==  0 )
451     {
452       msg (MW, _("Selected sheet or range of spreadsheet `%s' is empty."),
453            gri->file_name);
454       goto error;
455     }
456
457   r->proto = caseproto_ref (dict_get_proto (r->dict));
458   r->first_case = case_create (r->proto);
459   case_set_missing (r->first_case);
460
461   for ( i = 0 ; i < n_var_specs ; ++i )
462     {
463       const struct variable *var = dict_get_var (r->dict, i);
464
465       convert_xml_string_to_value (r->first_case, var,
466                                    var_spec[i].first_value);
467     }
468
469   for ( i = 0 ; i < n_var_specs ; ++i )
470     {
471       free (var_spec[i].first_value);
472       free (var_spec[i].name);
473     }
474
475   free (var_spec);
476
477   return casereader_create_sequential
478     (NULL,
479      r->proto,
480      n_cases,
481      &gnm_file_casereader_class, r);
482
483
484  error:
485   for ( i = 0 ; i < n_var_specs ; ++i )
486     {
487       free (var_spec[i].first_value);
488       free (var_spec[i].name);
489     }
490
491   free (var_spec);
492   dict_destroy (*dict);
493
494   gnm_file_casereader_destroy (NULL, r);
495
496   return NULL;
497 };
498
499
500 /* Reads and returns one case from READER's file.  Returns a null
501    pointer on failure. */
502 static struct ccase *
503 gnm_file_casereader_read (struct casereader *reader UNUSED, void *r_)
504 {
505   struct ccase *c;
506   int ret = 0;
507
508   struct gnumeric_reader *r = r_;
509   int current_row = r->row;
510
511   if ( !r->used_first_case )
512     {
513       r->used_first_case = true;
514       return r->first_case;
515     }
516
517   c = case_create (r->proto);
518   case_set_missing (c);
519
520   while ((r->state == STATE_CELL || r->state == STATE_CELLS_START )
521          && r->row == current_row && (ret = xmlTextReaderRead (r->xtr)))
522     {
523       process_node (r);
524
525       if ( r->col < r->start_col || (r->stop_col != -1 &&
526                                      r->col > r->stop_col))
527         continue;
528
529       if ( r->col - r->start_col >= caseproto_get_n_widths (r->proto))
530         continue;
531
532       if ( r->stop_row != -1 && r->row > r->stop_row)
533         break;
534
535       if ( r->node_type == XML_READER_TYPE_TEXT )
536         {
537           xmlChar *value = xmlTextReaderValue (r->xtr);
538
539           const int idx = r->col - r->start_col;
540
541           const struct variable *var = dict_get_var (r->dict, idx);
542
543           convert_xml_string_to_value (c, var, value);
544
545           free (value);
546         }
547
548     }
549
550   if (ret == 1)
551     return c;
552   else
553     {
554       case_unref (c);
555       return NULL;
556     }
557 }
558
559
560 #endif /* GNM_SUPPORT */