source: branches/prototype-v0/zoo-project/zoo-kernel/request_parser.c @ 863

Last change on this file since 863 was 863, checked in by djay, 6 years ago

Change the default ZOO-Kernel behavior, if an input has been passed by reference, the ZOO-Service will receive a cache_file map rather than the value field which was usually returned, same for array value apply. To use the previous behavior, one can add "memory=load" to the main section of the main.cfg file. Update ZOO-Services for using this new field if available.

  • Property svn:keywords set to Id
File size: 53.2 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2015 GeoLabs SARL
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25#include "request_parser.h"
26#include "service_internal.h"
27#include "server_internal.h"
28#include "response_print.h"
29#include "caching.h"
30
31/**
32 * Apply XPath Expression on XML document.
33 *
34 * @param doc the XML Document
35 * @param search the XPath expression
36 * @return xmlXPathObjectPtr containing the resulting nodes set
37 */
38xmlXPathObjectPtr
39extractFromDoc (xmlDocPtr doc, const char *search)
40{
41  xmlXPathContextPtr xpathCtx;
42  xmlXPathObjectPtr xpathObj;
43  xpathCtx = xmlXPathNewContext (doc);
44  xpathObj = xmlXPathEvalExpression (BAD_CAST search, xpathCtx);
45  xmlXPathFreeContext (xpathCtx);
46  return xpathObj;
47}
48
49/**
50 * Create (or append to) an array valued maps value = "["",""]"
51 *
52 * @param m the conf maps containing the main.cfg settings
53 * @param mo the map to update
54 * @param mi the map to append
55 * @param elem the elements containing default definitions
56 * @return 0 on success, -1 on failure
57 */
58int appendMapsToMaps (maps * m, maps * mo, maps * mi, elements * elem){
59  maps *tmpMaps = getMaps (mo, mi->name);
60  map *tmap = getMapType (tmpMaps->content);
61  elements *el = getElements (elem, mi->name);
62  elements *cursor = elem;
63  while(cursor!=NULL && el==NULL){
64    if(cursor->child!=NULL)
65      el = getElements (cursor->child, mi->name);
66    cursor=cursor->next;
67  }
68  int hasEl = 1;
69  if (el == NULL)
70    hasEl = -1;
71
72  if (tmap == NULL)
73    {
74      if (hasEl > 0)
75        tmap = getMapType (el->defaults->content);
76    }
77 
78  map *testMap = NULL;
79  if (hasEl > 0)
80    {
81      testMap = getMap (el->content, "maxOccurs");
82    }
83  else
84    {
85      testMap = createMap ("maxOccurs", "unbounded");
86    }
87   
88  if (testMap != NULL)
89    {
90      if (strncasecmp (testMap->value, "unbounded", 9) != 0
91          && atoi (testMap->value) > 1)
92        {
93          addMapsArrayToMaps (&mo, mi, tmap->name);
94          map* nb=getMapFromMaps(mo,mi->name,"length");
95          if (nb!=NULL && atoi(nb->value)>atoi(testMap->value))
96            {
97              char emsg[1024];
98              sprintf (emsg,
99                       _("The maximum allowed occurrences for <%s> (%i) was exceeded."),
100                       mi->name, atoi (testMap->value));
101              errorException (m, emsg, "InternalError", NULL);
102              return -1;
103            }
104        }
105      else
106        {
107          if (strncasecmp (testMap->value, "unbounded", 9) == 0)
108            {
109              if (hasEl < 0)
110                {
111                  freeMap (&testMap);
112                  free (testMap);
113                }
114              if (addMapsArrayToMaps (&mo, mi, tmap->name) < 0)
115                {
116                  char emsg[1024];
117                  map *tmpMap = getMap (mi->content, "length");
118                  sprintf (emsg,
119                           _
120                           ("ZOO-Kernel was unable to load your data for %s position %s."),
121                           mi->name, tmpMap->value);
122                  errorException (m, emsg, "InternalError", NULL);
123                  return -1;
124                }
125            }
126          else
127            {
128              char emsg[1024];
129              sprintf (emsg,
130                       _
131                       ("The maximum allowed occurrences for <%s> is one."),
132                       mi->name);
133              errorException (m, emsg, "InternalError", NULL);
134              return -1;
135            }
136        }
137    }
138  return 0;
139}
140
141/**
142 * Make sure that each value encoded in base64 in a maps is decoded.
143 *
144 * @param in the maps containing the values
145 * @see readBase64
146 */
147void ensureDecodedBase64(maps **in){
148  maps* cursor=*in;
149  while(cursor!=NULL){
150    map *tmp=getMap(cursor->content,"encoding");
151    if(tmp!=NULL && strncasecmp(tmp->value,"base64",6)==0){
152      tmp=getMap(cursor->content,"value");
153      readBase64(&tmp);
154      addToMap(cursor->content,"base64_value",tmp->value);
155      int size=0;
156      char *s=strdup(tmp->value);
157      free(tmp->value);
158      tmp->value=base64d(s,strlen(s),&size);
159      free(s);
160      char sizes[1024];
161      sprintf(sizes,"%d",size);
162      addToMap(cursor->content,"size",sizes);
163    }
164    map* length=getMap(cursor->content,"length");
165    if(length!=NULL){
166      int len=atoi(length->value);
167      for(int i=1;i<len;i++){
168        tmp=getMapArray(cursor->content,"encoding",i);
169        if(tmp!=NULL && strncasecmp(tmp->value,"base64",6)==0){
170          char key[17];
171          sprintf(key,"base64_value_%d",i);
172          tmp=getMapArray(cursor->content,"value",i);
173          readBase64(&tmp);
174          addToMap(cursor->content,key,tmp->value);
175          int size=0;
176          char *s=strdup(tmp->value);
177          free(tmp->value);
178          tmp->value=base64d(s,strlen(s),&size);
179          free(s);
180          char sizes[1024];
181          sprintf(sizes,"%d",size);
182          sprintf(key,"size_%d",i);
183          addToMap(cursor->content,key,sizes);
184        }
185      }
186    }
187    if(cursor->child!=NULL)
188      ensureDecodedBase64(&cursor->child);
189    cursor=cursor->next;
190  }
191}
192
193/**
194 * Parse inputs provided as KVP and store them in a maps.
195 *
196 * @param main_conf the conf maps containing the main.cfg settings
197 * @param s the service
198 * @param request_inputs the map storing KVP raw value
199 * @param request_output the maps to store the KVP pairs
200 * @param hInternet the HINTERNET queue to add potential requests
201 * @return 0 on success, -1 on failure
202 */
203int kvpParseInputs(maps** main_conf,service* s,map *request_inputs,maps** request_output,HINTERNET* hInternet){
204  // Parsing inputs provided as KVP
205  maps *tmpmaps = *request_output;
206  map* r_inputs = getMap (request_inputs, "DataInputs");
207  char* cursor_input;
208  if (r_inputs != NULL){
209    //snprintf (cursor_input, 40960, "%s", r_inputs->value);
210    if(strstr(r_inputs->value,"=")==NULL)
211      cursor_input = url_decode (r_inputs->value);
212    else
213      cursor_input = zStrdup (r_inputs->value);
214    int j = 0;
215
216    // Put each DataInputs into the inputs_as_text array
217    char *pToken;
218    pToken = strtok (cursor_input, ";");
219    char **inputs_as_text = (char **) malloc (100 * sizeof (char *));
220    if (inputs_as_text == NULL)
221      {
222        free(cursor_input);
223        return errorException (*main_conf, _("Unable to allocate memory"),
224                               "InternalError", NULL);
225      }
226    int i = 0;
227    while (pToken != NULL)
228      {
229        inputs_as_text[i] =
230          (char *) malloc ((strlen (pToken) + 1) * sizeof (char));
231        if (inputs_as_text[i] == NULL)
232          {
233            free(cursor_input);
234            return errorException (*main_conf, _("Unable to allocate memory"),
235                                   "InternalError", NULL);
236          }
237        snprintf (inputs_as_text[i], strlen (pToken) + 1, "%s", pToken);
238        pToken = strtok (NULL, ";");
239        i++;
240      }
241       
242    for (j = 0; j < i; j++)
243      {
244        char *tmp = zStrdup (inputs_as_text[j]);
245        free (inputs_as_text[j]);
246        char *tmpc;
247        tmpc = strtok (tmp, "@");
248        while (tmpc != NULL)
249          {
250            char *tmpv = strstr (tmpc, "=");
251            char tmpn[256];
252            memset (tmpn, 0, 256);
253            if (tmpv != NULL)
254              {
255                strncpy (tmpn, tmpc,
256                         (strlen (tmpc) - strlen (tmpv)) * sizeof (char));
257                tmpn[strlen (tmpc) - strlen (tmpv)] = 0;
258              }
259            else
260              {
261                strncpy (tmpn, tmpc, strlen (tmpc) * sizeof (char));
262                tmpn[strlen (tmpc)] = 0;
263              }
264            if (tmpmaps == NULL)
265              {
266                tmpmaps = createMaps(tmpn);
267                if (tmpmaps == NULL)
268                  {
269                    free(cursor_input);
270                    return errorException (*main_conf,
271                                           _("Unable to allocate memory"),
272                                           "InternalError", NULL);
273                  }
274                if (tmpv != NULL)
275                  {
276                    char *tmpvf = url_decode (tmpv + 1);
277                    tmpmaps->content = createMap ("value", tmpvf);
278                    free (tmpvf);
279                  }
280                else
281                  tmpmaps->content = createMap ("value", "Reference");
282                tmpmaps->next = NULL;
283              }
284            tmpc = strtok (NULL, "@");
285            while (tmpc != NULL)
286              {
287                char *tmpv1 = strstr (tmpc, "=");
288                char tmpn1[1024];
289                memset (tmpn1, 0, 1024);
290                if (tmpv1 != NULL)
291                  {
292                    strncpy (tmpn1, tmpc, strlen (tmpc) - strlen (tmpv1));
293                    tmpn1[strlen (tmpc) - strlen (tmpv1)] = 0;
294                    addToMap (tmpmaps->content, tmpn1, tmpv1 + 1);
295                  }
296                else
297                  {
298                    strncpy (tmpn1, tmpc, strlen (tmpc));
299                    tmpn1[strlen (tmpc)] = 0;
300                    map *lmap = getLastMap (tmpmaps->content);
301                    char *tmpValue =
302                      (char *) malloc ((strlen (tmpv) + strlen (tmpc) + 1) *
303                                       sizeof (char));
304                    sprintf (tmpValue, "%s@%s", tmpv + 1, tmpc);
305                    free (lmap->value);
306                    lmap->value = zStrdup (tmpValue);
307                    free (tmpValue);
308                    tmpc = strtok (NULL, "@");
309                    continue;
310                  }
311                if (strcmp (tmpn1, "xlink:href") != 0)
312                  addToMap (tmpmaps->content, tmpn1, tmpv1 + 1);
313                else if (tmpv1 != NULL)
314                  {
315                    char *tmpx2 = url_decode (tmpv1 + 1);
316                    if (strncasecmp (tmpx2, "http://", 7) != 0 &&
317                        strncasecmp (tmpx2, "ftp://", 6) != 0 &&
318                        strncasecmp (tmpx2, "https://", 8) != 0)
319                      {
320                        char emsg[1024];
321                        sprintf (emsg,
322                                 _
323                                 ("Unable to find a valid protocol to download the remote file %s"),
324                                 tmpv1 + 1);
325                        free(cursor_input);
326                        return errorException (*main_conf, emsg, "InternalError", NULL);
327                      }
328                    addToMap (tmpmaps->content, tmpn1, tmpx2);
329                    {
330                      if (loadRemoteFile
331                          (&*main_conf, &tmpmaps->content, hInternet, tmpx2) < 0)
332                        {
333                          free(cursor_input);
334                          return errorException (*main_conf, "Unable to fetch any resource", "InternalError", NULL);
335                        }
336                      }
337                    free (tmpx2);
338                    addIntToMap (tmpmaps->content, "Order", hInternet->nb);
339                    addToMap (tmpmaps->content, "Reference", tmpv1 + 1);
340                  }
341                tmpc = strtok (NULL, "@");
342              }
343            if (*request_output == NULL)
344              *request_output = dupMaps (&tmpmaps);
345            else
346              {
347                maps *testPresence =
348                  getMaps (*request_output, tmpmaps->name);
349                if (testPresence != NULL)
350                  {
351                    elements *elem =
352                      getElements (s->inputs, tmpmaps->name);
353                    if (elem != NULL)
354                      {
355                        if (appendMapsToMaps
356                            (*main_conf, *request_output, tmpmaps,
357                             elem) < 0)
358                          {
359                            free(cursor_input);
360                            return errorException (*main_conf, "Unable to append maps", "InternalError", NULL);
361                          }
362                      }
363                  }
364                else
365                  addMapsToMaps (request_output, tmpmaps);
366              }
367            freeMaps (&tmpmaps);
368            free (tmpmaps);
369            tmpmaps = NULL;
370            free (tmp);
371          }
372      }
373    free (inputs_as_text);
374    free(cursor_input);
375  }
376  return 1;
377}
378
379/**
380 * Parse outputs provided as KVP and store them in a maps.
381 *
382 * @param main_conf the conf maps containing the main.cfg settings
383 * @param request_inputs the map storing KVP raw value
384 * @param request_output the maps to store the KVP pairs
385 * @return 0 on success, -1 on failure
386 */
387int kvpParseOutputs(maps** main_conf,map *request_inputs,maps** request_output){
388  /**
389   * Parsing outputs provided as KVP
390   */
391  map *r_inputs = NULL;
392  r_inputs = getMap (request_inputs, "ResponseDocument");
393  if (r_inputs == NULL)
394    r_inputs = getMap (request_inputs, "RawDataOutput");
395
396  if (r_inputs != NULL)
397    {
398      char *cursor_output = zStrdup (r_inputs->value);
399      int j = 0;
400
401      /**
402       * Put each Output into the outputs_as_text array
403       */
404      char *pToken;
405      maps *tmp_output = NULL;
406      pToken = strtok (cursor_output, ";");
407      char **outputs_as_text = (char **) malloc (128 * sizeof (char *));
408      if (outputs_as_text == NULL)
409        {
410          free(cursor_output);
411          return errorException (*main_conf, _("Unable to allocate memory"),
412                                 "InternalError", NULL);
413        }
414      int i = 0;
415      while (pToken != NULL)
416        {
417          outputs_as_text[i] =
418            (char *) malloc ((strlen (pToken) + 1) * sizeof (char));
419          if (outputs_as_text[i] == NULL)
420            {
421              free(cursor_output);
422              return errorException (*main_conf, _("Unable to allocate memory"),
423                                     "InternalError", NULL);
424            }
425          snprintf (outputs_as_text[i], strlen (pToken) + 1, "%s",
426                    pToken);
427          pToken = strtok (NULL, ";");
428          i++;
429        }
430      for (j = 0; j < i; j++)
431        {
432          char *tmp = zStrdup (outputs_as_text[j]);
433          free (outputs_as_text[j]);
434          char *tmpc;
435          tmpc = strtok (tmp, "@");
436          int k = 0;
437          while (tmpc != NULL)
438            {
439              if (k == 0)
440                {
441                  if (tmp_output == NULL)
442                    {
443                      tmp_output = createMaps(tmpc);
444                      if (tmp_output == NULL)
445                        {
446                          free(cursor_output);
447                          return errorException (*main_conf,
448                                                 _
449                                                 ("Unable to allocate memory"),
450                                                 "InternalError", NULL);
451                        }
452                    }
453                }
454              else
455                {
456                  char *tmpv = strstr (tmpc, "=");
457                  char tmpn[256];
458                  memset (tmpn, 0, 256);
459                  strncpy (tmpn, tmpc,
460                           (strlen (tmpc) -
461                            strlen (tmpv)) * sizeof (char));
462                  tmpn[strlen (tmpc) - strlen (tmpv)] = 0;
463                  if (tmp_output->content == NULL)
464                    {
465                      tmp_output->content = createMap (tmpn, tmpv + 1);
466                      tmp_output->content->next = NULL;
467                    }
468                  else
469                    addToMap (tmp_output->content, tmpn, tmpv + 1);
470                }
471              k++;
472              tmpc = strtok (NULL, "@");
473            }
474          if (*request_output == NULL)
475            *request_output = dupMaps (&tmp_output);
476          else
477            addMapsToMaps (request_output, tmp_output);
478          freeMaps (&tmp_output);
479          free (tmp_output);
480          tmp_output = NULL;
481          free (tmp);
482        }
483      free (outputs_as_text);
484      free(cursor_output);
485    }
486  return 1;
487}
488
489/**
490 * Create a "missingIdentifier" maps in case it is NULL.
491 *
492 * @param main_conf the conf maps containing the main.cfg settings
493 * @param mymaps the maps to update
494 * @return 0 on success, 4 on failure
495 */
496int defineMissingIdentifier(maps** main_conf,maps** mymaps){
497  if (*mymaps == NULL){
498    *mymaps = createMaps("missingIndetifier");
499    if (*mymaps == NULL){
500      return errorException (*main_conf,
501                             _("Unable to allocate memory"),
502                             "InternalError", NULL);
503    }
504  }
505  return 0;
506}
507
508/**
509 * Parse inputs from XML nodes and store them in a maps.
510 *
511 * @param main_conf the conf maps containing the main.cfg settings
512 * @param s the service
513 * @param request_output the maps to store the KVP pairs
514 * @param doc the xmlDocPtr containing the original request
515 * @param nodes the input nodes array
516 * @param hInternet the HINTERNET queue to add potential requests
517 * @return 0 on success, -1 on failure
518 */
519int xmlParseInputs(maps** main_conf,service* s,maps** request_output,xmlDocPtr doc,xmlNodeSet* nodes,HINTERNET* hInternet){
520  int k = 0;
521  int l = 0;
522  map* version=getMapFromMaps(*main_conf,"main","rversion");
523  int vid=getVersionId(version->value);
524  for (k=0; k < nodes->nodeNr; k++)
525    {
526      maps *tmpmaps = NULL;
527      xmlNodePtr cur = nodes->nodeTab[k];
528
529      if (nodes->nodeTab[k]->type == XML_ELEMENT_NODE)
530        {
531          // A specific Input node.
532          if(vid==1){
533            xmlChar *val = xmlGetProp (cur, BAD_CAST "id");
534            tmpmaps = createMaps((char *) val);
535            xmlFree(val);
536          }
537
538          xmlNodePtr cur2 = cur->children;
539          while (cur2 != NULL)
540            {
541              while (cur2 != NULL && cur2->type != XML_ELEMENT_NODE)
542                cur2 = cur2->next;
543              if (cur2 == NULL)
544                break;
545              // Indentifier
546              if (xmlStrncasecmp
547                  (cur2->name, BAD_CAST "Identifier",
548                   xmlStrlen (cur2->name)) == 0)
549                {
550                  xmlChar *val =
551                    xmlNodeListGetString (doc, cur2->xmlChildrenNode, 1);
552                  if (tmpmaps == NULL && val!=NULL)
553                    {
554                      tmpmaps = createMaps((char*)val);
555                      if (tmpmaps == NULL)
556                        {
557                          return errorException (*main_conf,
558                                                 _
559                                                 ("Unable to allocate memory"),
560                                                 "InternalError", NULL);
561                        }
562                      xmlFree (val);
563                    }
564                }
565              // Title, Asbtract
566              if (xmlStrncasecmp
567                  (cur2->name, BAD_CAST "Title",
568                   xmlStrlen (cur2->name)) == 0
569                  || xmlStrncasecmp (cur2->name, BAD_CAST "Abstract",
570                                     xmlStrlen (cur2->name)) == 0)
571                {
572                  xmlChar *val =
573                    xmlNodeListGetString (doc, cur2->xmlChildrenNode, 1);
574                  defineMissingIdentifier(main_conf,&tmpmaps);
575                  if(val!=NULL){
576                    if (tmpmaps->content != NULL)
577                      addToMap (tmpmaps->content,
578                                (char *) cur2->name, (char *) val);
579                    else
580                      tmpmaps->content =
581                        createMap ((char *) cur2->name, (char *) val);
582                    xmlFree (val);
583                  }
584                }
585              // InputDataFormChoice (Reference or Data ?) / 2.0.0 DataInputType / Input
586              if (xmlStrcasecmp (cur2->name, BAD_CAST "Input") == 0)
587                {
588                  char *xpathExpr=(char*)malloc(61+strlen(tmpmaps->name));
589                  sprintf(xpathExpr,"/*/*[local-name()='Input' and @id='%s']/*[local-name()='Input']",tmpmaps->name);
590                  xmlXPathObjectPtr tmpsptr = extractFromDoc (doc, xpathExpr);
591                  xmlNodeSet *tmps = tmpsptr->nodesetval;
592                  if(tmps!=NULL){
593                    maps* request_output1=NULL;
594                    if(xmlParseInputs(main_conf,s,&request_output1,doc,tmps,hInternet)<0)
595                      return -1;
596                    if(tmpmaps->child==NULL)
597                      tmpmaps->child=dupMaps(&request_output1);
598                    else
599                      addMapsToMaps(&tmpmaps->child,request_output1);
600                    freeMaps(&request_output1);
601                    free(request_output1);
602                  }
603                  while(cur2->next!=NULL)
604                    cur2=cur2->next;
605                }
606              else if (xmlStrcasecmp (cur2->name, BAD_CAST "Reference") == 0)
607                {
608                  defineMissingIdentifier(main_conf,&tmpmaps);
609                  // Get every attribute from a Reference node
610                  // mimeType, encoding, schema, href, method
611                  // Header and Body gesture should be added here
612                  const char *refs[5] =
613                    { "mimeType", "encoding", "schema", "method",
614                      "href"
615                    };
616                  for (l = 0; l < 5; l++)
617                    {
618                      xmlChar *val = xmlGetProp (cur2, BAD_CAST refs[l]);
619                      if (val != NULL && xmlStrlen (val) > 0)
620                        {
621                          if (tmpmaps->content != NULL)
622                            addToMap (tmpmaps->content, refs[l],
623                                      (char *) val);
624                          else
625                            tmpmaps->content =
626                              createMap (refs[l], (char *) val);
627                          map *ltmp = getMap (tmpmaps->content, "method");
628                          if (l == 4 )
629                            {
630                              if ((ltmp==NULL || strncmp (ltmp->value, "POST",4) != 0))
631                                {
632                                  if (loadRemoteFile
633                                      (main_conf, &tmpmaps->content, hInternet,
634                                       (char *) val) != 0)
635                                    {
636                                      return errorException (*main_conf,
637                                                             _("Unable to add a request in the queue."),
638                                                             "InternalError",
639                                                             NULL);
640                                    }
641                                  addIntToMap (tmpmaps->content, "Order", hInternet->nb);
642                                }
643                              addToMap (tmpmaps->content, "Reference", (char*) val);
644                            }
645                        }
646                      xmlFree (val);
647                    }
648                  // Parse Header and Body from Reference
649                  xmlNodePtr cur3 = cur2->children;
650                  while (cur3 != NULL)
651                    {
652                      while (cur3 != NULL
653                             && cur3->type != XML_ELEMENT_NODE)
654                        cur3 = cur3->next;
655                      if (cur3 == NULL)
656                        break;
657                      if (xmlStrcasecmp (cur3->name, BAD_CAST "Header") ==
658                          0)
659                        {
660                          const char *ha[2];
661                          ha[0] = "key";
662                          ha[1] = "value";
663                          int hai;
664                          char *has=NULL;
665                          char *key;
666                          for (hai = 0; hai < 2; hai++)
667                            {
668                              xmlChar *val =
669                                xmlGetProp (cur3, BAD_CAST ha[hai]);
670#ifdef POST_DEBUG
671                              fprintf (stderr, "%s = %s\n", ha[hai],
672                                       (char *) val);
673#endif
674                              if (hai == 0)
675                                {
676                                  key = zStrdup ((char *) val);
677                                }
678                              else
679                                {
680                                  has =
681                                    (char *)
682                                    malloc ((4 + xmlStrlen (val) +
683                                             strlen (key)) *
684                                            sizeof (char));
685                                  if (has == NULL)
686                                    {
687                                      return errorException (*main_conf,
688                                                             _
689                                                             ("Unable to allocate memory"),
690                                                             "InternalError",
691                                                             NULL);
692                                    }
693                                  snprintf (has,
694                                            (3 + xmlStrlen (val) +
695                                             strlen (key)), "%s: %s", key,
696                                            (char *) val);
697                                  free (key);
698                                }
699                              xmlFree (val);
700                            }
701                          if (has != NULL){
702                            hInternet->ihandle[hInternet->nb].header = NULL;
703                            hInternet->ihandle[hInternet->nb].header =
704                              curl_slist_append (hInternet->ihandle
705                                                 [hInternet->nb].header,
706                                                 has);
707                            free (has);
708                          }
709                        }
710                      else
711                        {
712#ifdef POST_DEBUG
713                          fprintf (stderr,
714                                   "Try to fetch the body part of the request ...\n");
715#endif
716                          if (xmlStrcasecmp (cur3->name, BAD_CAST "Body")
717                              == 0)
718                            {
719#ifdef POST_DEBUG
720                              fprintf (stderr, "Body part found (%s) !!!\n",
721                                       (char *) cur3->content);
722#endif
723                              char *tmp = NULL;
724                              xmlNodePtr cur4 = cur3->children;
725                              while (cur4 != NULL)
726                                {
727                                  while (cur4 && cur4 != NULL && cur4->type && cur4->type != XML_ELEMENT_NODE){
728                                    if(cur4->next)
729                                      cur4 = cur4->next;
730                                    else
731                                      cur4 = NULL;
732                                  }
733                                  if(cur4 != NULL) {
734                                    xmlDocPtr bdoc =
735                                      xmlNewDoc (BAD_CAST "1.0");
736                                    bdoc->encoding =
737                                      xmlCharStrdup ("UTF-8");
738                                    xmlDocSetRootElement (bdoc, cur4);
739                                    xmlChar *btmps;
740                                    int bsize;
741                                    // TODO : check for encoding defined in the input
742                                    xmlDocDumpFormatMemoryEnc(bdoc, &btmps, &bsize, "UTF-8", 0);
743                                    if (btmps != NULL){
744                                      tmp = (char *) malloc ((bsize + 1) * sizeof (char));
745
746                                      sprintf (tmp, "%s", (char*) btmps);
747
748                                      //xmlFreeDoc (bdoc);
749                                         
750                                      map *btmp =
751                                        getMap (tmpmaps->content, "Reference");
752                                      addToMap (tmpmaps->content, "Body", tmp);
753                                      if (btmp != NULL)
754                                        {
755                                          addRequestToQueue(main_conf,hInternet,(char *) btmp->value,false);
756                                          InternetOpenUrl (hInternet,
757                                                           btmp->value,
758                                                           tmp,
759                                                           xmlStrlen(btmps),
760                                                           INTERNET_FLAG_NO_CACHE_WRITE,
761                                                           0,
762                                                           *main_conf);
763                                          addIntToMap (tmpmaps->content, "Order", hInternet->nb);
764                                        }
765                                      xmlFree (btmps);
766                                      free (tmp);
767                                      break;
768                                    }
769                                  }
770                                  cur4 = cur4->next;
771                                }
772                            }
773                          else
774                            if (xmlStrcasecmp
775                                (cur3->name,
776                                 BAD_CAST "BodyReference") == 0)
777                              {
778                                xmlChar *val =
779                                  xmlGetProp (cur3, BAD_CAST "href");
780                                HINTERNET bInternet, res1, res;
781                                bInternet = InternetOpen (
782#ifndef WIN32
783                                                          (LPCTSTR)
784#endif
785                                                          "ZooWPSClient\0",
786                                                          INTERNET_OPEN_TYPE_PRECONFIG,
787                                                          NULL, NULL, 0);
788                                if (!CHECK_INET_HANDLE (bInternet))
789                                  fprintf (stderr,
790                                           "WARNING : bInternet handle failed to initialize");
791                                bInternet.waitingRequests[0] =
792                                  strdup ((char *) val);
793                                res1 =
794                                  InternetOpenUrl (&bInternet,
795                                                   bInternet.waitingRequests
796                                                   [0], NULL, 0,
797                                                   INTERNET_FLAG_NO_CACHE_WRITE,
798                                                   0,
799                                                   *main_conf);
800                                processDownloads (&bInternet);
801                                char *tmp =
802                                  (char *)
803                                  malloc ((bInternet.ihandle[0].nDataLen +
804                                           1) * sizeof (char));
805                                if (tmp == NULL)
806                                  {
807                                    return errorException (*main_conf,
808                                                           _
809                                                           ("Unable to allocate memory"),
810                                                           "InternalError",
811                                                           NULL);
812                                  }
813                                size_t bRead;
814                                InternetReadFile (bInternet.ihandle[0],
815                                                  (LPVOID) tmp,
816                                                  bInternet.
817                                                  ihandle[0].nDataLen,
818                                                  &bRead);
819                                tmp[bInternet.ihandle[0].nDataLen] = 0;
820                                InternetCloseHandle(&bInternet);
821                                addToMap (tmpmaps->content, "Body", tmp);
822                                map *btmp =
823                                  getMap (tmpmaps->content, "href");
824                                if (btmp != NULL)
825                                  {
826                                    addRequestToQueue(main_conf,hInternet,(char *) btmp->value,false);
827
828                                    res =
829                                      InternetOpenUrl (hInternet,
830                                                       btmp->value,
831                                                       tmp,
832                                                       strlen(tmp),
833                                                       INTERNET_FLAG_NO_CACHE_WRITE,
834                                                       0,
835                                                       *main_conf);
836                                    addIntToMap (tmpmaps->content, "Order", hInternet->nb);
837                                  }
838                                free (tmp);
839                                xmlFree (val);
840                              }
841                        }
842                      cur3 = cur3->next;
843                    }
844                }
845              else if (xmlStrcasecmp (cur2->name, BAD_CAST "Data") == 0)
846                {
847                  defineMissingIdentifier(main_conf,&tmpmaps);
848                  xmlNodePtr cur4 = cur2->children;
849                  if(vid==1){
850                    // Get every dataEncodingAttributes from a Data node:
851                    // mimeType, encoding, schema
852                    const char *coms[3] =
853                      { "mimeType", "encoding", "schema" };
854                    for (l = 0; l < 3; l++){
855                      xmlChar *val =
856                          xmlGetProp (cur4, BAD_CAST coms[l]);
857                        if (val != NULL && strlen ((char *) val) > 0){
858                          if (tmpmaps->content != NULL)
859                            addToMap (tmpmaps->content,coms[l],(char *) val);
860                          else
861                            tmpmaps->content =
862                              createMap (coms[l],(char *) val);
863                        }
864                        xmlFree (val);
865                    }
866                    while (cur4 != NULL){
867                      while(cur4 != NULL && 
868                            cur4->type != XML_CDATA_SECTION_NODE &&
869                            cur4->type != XML_TEXT_NODE &&
870                            cur4->type != XML_ELEMENT_NODE)
871                        cur4=cur4->next;
872                      if(cur4!=NULL){
873                        if (cur4->type == XML_ELEMENT_NODE)
874                          {
875                            xmlChar *mv;
876                            int buffersize;
877                            xmlDocPtr doc1 = xmlNewDoc (BAD_CAST "1.0");
878                            xmlDocSetRootElement (doc1, cur4);
879                            xmlDocDumpFormatMemoryEnc (doc1, &mv,
880                                                       &buffersize,
881                                                       "utf-8", 0);
882                            if (tmpmaps->content != NULL)
883                              addToMap (tmpmaps->content, "value",
884                                        (char *) mv);
885                            else
886                              tmpmaps->content =
887                                createMap ("value", (char *) mv);
888                            free(mv);
889                          }
890                        else{
891                          if (tmpmaps->content != NULL)
892                            addToMap (tmpmaps->content, "value",
893                                      (char *) cur4->content);
894                          else
895                            tmpmaps->content =
896                              createMap ("value", (char *) cur4->content);
897                        }
898                        cur4=cur4->next;
899                      }
900                    }
901                  }
902
903
904                  while (cur4 != NULL)
905                    {
906                      while (cur4 != NULL
907                             && cur4->type != XML_ELEMENT_NODE)
908                        cur4 = cur4->next;
909                      if (cur4 == NULL)
910                        break;
911                      if (xmlStrcasecmp
912                          (cur4->name, BAD_CAST "LiteralData") == 0)
913                        {
914                          // Get every attribute from a LiteralData node
915                          // dataType , uom
916                          char *list[2];
917                          list[0] = zStrdup ("dataType");
918                          list[1] = zStrdup ("uom");
919                          for (l = 0; l < 2; l++)
920                            {
921                              xmlChar *val =
922                                xmlGetProp (cur4, BAD_CAST list[l]);
923                              if (val != NULL
924                                  && strlen ((char *) val) > 0)
925                                {
926                                  if (tmpmaps->content != NULL)
927                                    addToMap (tmpmaps->content, list[l],
928                                              (char *) val);
929                                  else
930                                    tmpmaps->content =
931                                      createMap (list[l], (char *) val);
932                                }
933                              xmlFree (val);
934                              free (list[l]);
935                            }
936                        }
937                      else
938                        if (xmlStrcasecmp
939                            (cur4->name, BAD_CAST "ComplexData") == 0)
940                          {
941                            // Get every attribute from a Reference node
942                            // mimeType, encoding, schema
943                            const char *coms[3] =
944                              { "mimeType", "encoding", "schema" };
945                            for (l = 0; l < 3; l++)
946                              {
947                                xmlChar *val =
948                                  xmlGetProp (cur4, BAD_CAST coms[l]);
949                                if (val != NULL
950                                    && strlen ((char *) val) > 0)
951                                  {
952                                    if (tmpmaps->content != NULL)
953                                      addToMap (tmpmaps->content, coms[l],
954                                                (char *) val);
955                                    else
956                                      tmpmaps->content =
957                                        createMap (coms[l], (char *) val);
958                                  }
959                                xmlFree (val);
960                              }
961                          }
962
963                      map *test = getMap (tmpmaps->content, "encoding");
964
965                      if (test == NULL)
966                        { 
967                          if (tmpmaps->content != NULL)
968                            addToMap (tmpmaps->content, "encoding",
969                                      "utf-8");
970                          else
971                            tmpmaps->content =
972                              createMap ("encoding", "utf-8");
973                          test = getMap (tmpmaps->content, "encoding");
974                        }
975
976                      if (strcasecmp (test->value, "base64") != 0)
977                        { 
978                          xmlChar *mv = xmlNodeListGetString (doc,
979                                                              cur4->xmlChildrenNode,
980                                                              1);
981                          map *ltmp =
982                            getMap (tmpmaps->content, "mimeType");
983                          if (mv == NULL
984                              ||
985                              (xmlStrcasecmp
986                               (cur4->name, BAD_CAST "ComplexData") == 0
987                               && (ltmp == NULL
988                                   || strncasecmp (ltmp->value,
989                                                   "text/xml", 8) == 0)))
990                            {
991                              xmlDocPtr doc1 = xmlNewDoc (BAD_CAST "1.0");
992                              int buffersize;
993                              xmlNodePtr cur5 = cur4->children;
994                              while (cur5 != NULL
995                                     && cur5->type != XML_ELEMENT_NODE
996                                     && cur5->type != XML_CDATA_SECTION_NODE)
997                                cur5 = cur5->next;
998                              if (cur5 != NULL
999                                  && cur5->type != XML_CDATA_SECTION_NODE)
1000                                {
1001                                  xmlDocSetRootElement (doc1, cur5);
1002                                  xmlDocDumpFormatMemoryEnc (doc1, &mv,
1003                                                             &buffersize,
1004                                                             "utf-8", 0);
1005                                }
1006                              else
1007                                {
1008                                  if (cur5 != NULL
1009                                      && cur5->type == XML_CDATA_SECTION_NODE){
1010                                    xmlDocPtr doc2 = xmlReadMemory((const char*)cur5->content,xmlStrlen(cur5->content),
1011                                                                   "input_content.xml", NULL, XML_PARSE_RECOVER);
1012                                    xmlDocDumpFormatMemoryEnc (doc2, &mv,
1013                                                               &buffersize,
1014                                                               "utf-8", 0);
1015                                    xmlFreeDoc (doc2);
1016                                  }
1017                                }
1018                              addIntToMap (tmpmaps->content, "size",
1019                                           buffersize);
1020                              xmlFreeDoc (doc1);
1021                            }else{
1022                            xmlNodePtr cur5 = cur4->children;
1023                            while (cur5 != NULL
1024                                   && cur5->type != XML_CDATA_SECTION_NODE)
1025                              cur5 = cur5->next;
1026                            if (cur5 != NULL
1027                                && cur5->type == XML_CDATA_SECTION_NODE){
1028                              xmlFree(mv);
1029                              mv=xmlStrdup(cur5->content);
1030                            }
1031                          }
1032                          if (mv != NULL)
1033                            {
1034                              addToMap (tmpmaps->content, "value",
1035                                        (char*) mv);
1036                              xmlFree (mv);
1037                            }
1038                        }
1039                      else
1040                        {
1041                          xmlChar *tmp = xmlNodeListGetRawString (doc,
1042                                                                  cur4->xmlChildrenNode,
1043                                                                  0);
1044                          addToMap (tmpmaps->content, "value",
1045                                    (char *) tmp);
1046                          xmlFree (tmp);
1047                        }
1048
1049                      cur4 = cur4->next;
1050                    }
1051                }
1052              cur2 = cur2->next;
1053              while (cur2 != NULL && cur2->type != XML_ELEMENT_NODE){
1054                cur2 = cur2->next;
1055              }
1056            }
1057          {
1058            map* test=getMap(tmpmaps->content,"value");
1059            if(test==NULL && tmpmaps->child==NULL)
1060              addToMap(tmpmaps->content,"value","");
1061            maps *testPresence = getMaps (*request_output, tmpmaps->name);
1062            maps *cursor=*request_output;
1063            while(testPresence == NULL && cursor!=NULL){
1064              if(cursor->child!=NULL){
1065                testPresence = getMaps (cursor->child, tmpmaps->name);
1066              }
1067              cursor=cursor->next;
1068            }
1069            if (testPresence != NULL)
1070              {
1071                elements *elem = getElements (s->inputs, tmpmaps->name);
1072                elements *cursor=s->inputs;
1073                while(elem == NULL && cursor!=NULL){
1074                  if(cursor->child!=NULL){
1075                    elem = getElements (cursor->child, tmpmaps->name);
1076                  }
1077                  cursor=cursor->next;
1078                }
1079                if (elem != NULL)
1080                  {
1081                    if (appendMapsToMaps
1082                        (*main_conf, testPresence, tmpmaps, elem) < 0)
1083                      {
1084                        return errorException (*main_conf,
1085                                               _("Unable to append maps to maps."),
1086                                               "InternalError",
1087                                               NULL);
1088                      }
1089                  }
1090              }
1091            else
1092              addMapsToMaps (request_output, tmpmaps);
1093          }
1094          freeMaps (&tmpmaps);
1095          free (tmpmaps);
1096          tmpmaps = NULL;
1097        }
1098    }
1099  return 1;
1100}
1101
1102/**
1103 * Parse outputs from XML nodes and store them in a maps (WPS version 2.0.0).
1104 *
1105 * @param main_conf the conf maps containing the main.cfg settings
1106 * @param request_inputs the map storing KVP raw value
1107 * @param request_output the maps to store the KVP pairs
1108 * @param doc the xmlDocPtr containing the original request
1109 * @param cur the xmlNodePtr corresponding to the ResponseDocument or RawDataOutput XML node
1110 * @param raw true if the node is RawDataOutput, false in case of ResponseDocument
1111 * @return 0 on success, -1 on failure
1112 */
1113int xmlParseOutputs2(maps** main_conf,map** request_inputs,maps** request_output,xmlDocPtr doc,xmlNodeSet* nodes){
1114  int k = 0;
1115  int l = 0;
1116  for (k=0; k < nodes->nodeNr; k++){
1117    maps *tmpmaps = NULL;
1118    xmlNodePtr cur = nodes->nodeTab[k];
1119    if (cur->type == XML_ELEMENT_NODE){
1120      maps *tmpmaps = NULL;
1121      xmlChar *val = xmlGetProp (cur, BAD_CAST "id");
1122      if(val!=NULL)
1123        tmpmaps = createMaps((char *)val);
1124      else
1125        tmpmaps = createMaps("unknownIdentifier");
1126      const char ress[4][13] =
1127        { "mimeType", "encoding", "schema", "transmission" };
1128      xmlFree (val);
1129      for (l = 0; l < 4; l++){
1130        val = xmlGetProp (cur, BAD_CAST ress[l]);
1131        if (val != NULL && strlen ((char *) val) > 0)
1132          {
1133            if (tmpmaps->content != NULL)
1134              addToMap (tmpmaps->content, ress[l],
1135                        (char *) val);
1136            else
1137              tmpmaps->content =
1138                createMap (ress[l], (char *) val);
1139            if(l==3 && strncasecmp((char*)val,"reference",xmlStrlen(val))==0)
1140              addToMap (tmpmaps->content,"asReference","true");
1141          }
1142        xmlFree (val);
1143      }
1144      if(cur->children!=NULL){
1145        xmlNodePtr ccur = cur->children;
1146        while (ccur != NULL){
1147          if(ccur->type == XML_ELEMENT_NODE){
1148            char *xpathExpr=(char*)malloc(66+strlen(tmpmaps->name));
1149            sprintf(xpathExpr,"/*/*[local-name()='Output' and @id='%s']/*[local-name()='Output']",tmpmaps->name);           
1150            xmlXPathObjectPtr tmpsptr = extractFromDoc (doc, xpathExpr);
1151            xmlNodeSet* cnodes = tmpsptr->nodesetval;
1152            xmlParseOutputs2(main_conf,request_inputs,&tmpmaps->child,doc,cnodes);
1153            xmlXPathFreeObject (tmpsptr);
1154            free(xpathExpr);
1155            break;
1156          }
1157          ccur = ccur->next;
1158        }
1159      }
1160      if (*request_output == NULL){
1161        *request_output = dupMaps(&tmpmaps);
1162      }
1163      else{
1164        addMapsToMaps(request_output,tmpmaps);
1165      }
1166      freeMaps(&tmpmaps);
1167      free(tmpmaps);
1168    }
1169  }
1170  return 0;
1171}
1172
1173/**
1174 * Parse outputs from XML nodes and store them in a maps.
1175 *
1176 * @param main_conf the conf maps containing the main.cfg settings
1177 * @param request_inputs the map storing KVP raw value
1178 * @param request_output the maps to store the KVP pairs
1179 * @param doc the xmlDocPtr containing the original request
1180 * @param cur the xmlNodePtr corresponding to the ResponseDocument or RawDataOutput XML node
1181 * @param raw true if the node is RawDataOutput, false in case of ResponseDocument
1182 * @return 0 on success, -1 on failure
1183 */
1184int xmlParseOutputs(maps** main_conf,map** request_inputs,maps** request_output,xmlDocPtr doc,xmlNodePtr cur,bool raw){
1185  int l=0;
1186  if( raw == true)
1187    {
1188      addToMap (*request_inputs, "RawDataOutput", "");
1189      if (cur->type == XML_ELEMENT_NODE)
1190        {
1191
1192          maps *tmpmaps = createMaps("unknownIdentifier");
1193          if (tmpmaps == NULL)
1194            {
1195              return errorException (*main_conf, _("Unable to allocate memory"),
1196                                     "InternalError", NULL);
1197            }
1198
1199          // Get every attribute from a RawDataOutput node
1200          // mimeType, encoding, schema, uom
1201          const char *outs[4] =
1202            { "mimeType", "encoding", "schema", "uom" };
1203          for (l = 0; l < 4; l++)
1204            {
1205              xmlChar *val = xmlGetProp (cur, BAD_CAST outs[l]);
1206              if (val != NULL)
1207                {
1208                  if (strlen ((char *) val) > 0)
1209                    {
1210                      if (tmpmaps->content != NULL)
1211                        addToMap (tmpmaps->content, outs[l],
1212                                  (char *) val);
1213                      else
1214                        tmpmaps->content =
1215                          createMap (outs[l], (char *) val);
1216                    }
1217                  xmlFree (val);
1218                }
1219            }
1220          xmlNodePtr cur2 = cur->children;
1221          while (cur2 != NULL && cur2->type != XML_ELEMENT_NODE)
1222            cur2 = cur2->next;
1223          while (cur2 != NULL)
1224            {
1225              if (xmlStrncasecmp
1226                  (cur2->name, BAD_CAST "Identifier",
1227                   xmlStrlen (cur2->name)) == 0)
1228                {
1229                  xmlChar *val =
1230                    xmlNodeListGetString (NULL, cur2->xmlChildrenNode, 1);
1231                  free (tmpmaps->name);
1232                  tmpmaps->name = zStrdup ((char *) val);
1233                  xmlFree (val);
1234                }
1235              cur2 = cur2->next;
1236              while (cur2 != NULL && cur2->type != XML_ELEMENT_NODE)
1237                cur2 = cur2->next;
1238            }
1239          if (*request_output == NULL)
1240            *request_output = dupMaps (&tmpmaps);
1241          else
1242            addMapsToMaps (request_output, tmpmaps);
1243          if (tmpmaps != NULL)
1244            {
1245              freeMaps (&tmpmaps);
1246              free (tmpmaps);
1247              tmpmaps = NULL;
1248            }
1249        }
1250    }
1251  else
1252    {
1253      addToMap (*request_inputs, "ResponseDocument", "");
1254
1255      if (cur->type == XML_ELEMENT_NODE) {
1256        // Get every attribute: storeExecuteResponse, lineage, status
1257        const char *ress[3] =
1258          { "storeExecuteResponse", "lineage", "status" };
1259        xmlChar *val;
1260        for (l = 0; l < 3; l++)
1261          {
1262            val = xmlGetProp (cur, BAD_CAST ress[l]);
1263            if (val != NULL && strlen ((char *) val) > 0)
1264              {
1265                addToMap (*request_inputs, ress[l], (char *) val);
1266              }
1267            xmlFree (val);
1268          }
1269                       
1270        xmlNodePtr cur1 = cur->children;               
1271        while (cur1 != NULL) // iterate over Output nodes
1272          {
1273            if (cur1->type != XML_ELEMENT_NODE || 
1274                xmlStrncasecmp(cur1->name, BAD_CAST "Output", 
1275                               xmlStrlen (cur1->name)) != 0) {
1276              cur1 = cur1->next;
1277              continue;
1278            }
1279                               
1280            maps *tmpmaps = createMaps("unknownIdentifier"); // one per Output node
1281            if (tmpmaps == NULL) {
1282              return errorException (*main_conf,
1283                                     _
1284                                     ("Unable to allocate memory"),
1285                                     "InternalError", NULL);
1286            }
1287                               
1288            xmlNodePtr elems = cur1->children;
1289                               
1290            while (elems != NULL) {
1291
1292              // Identifier
1293              if (xmlStrncasecmp
1294                  (elems->name, BAD_CAST "Identifier",
1295                   xmlStrlen (elems->name)) == 0)
1296                {
1297                  xmlChar *val =
1298                    xmlNodeListGetString (doc, elems->xmlChildrenNode, 1);
1299               
1300                  free(tmpmaps->name);
1301                  tmpmaps->name = zStrdup ((char *) val);
1302                  if (tmpmaps->content == NULL) {
1303                    tmpmaps->content = createMap("Identifier", zStrdup ((char *) val));
1304                  }
1305                  else {
1306                    addToMap(tmpmaps->content, "Identifier", zStrdup ((char *) val));
1307                  }
1308
1309                  map* tt = getMap (*request_inputs, "ResponseDocument");
1310                  if (strlen(tt->value) == 0) {
1311                    addToMap (*request_inputs, "ResponseDocument",
1312                              (char *) val);
1313                  }
1314                  else {
1315                    char* tmp = (char*) malloc((strlen(tt->value) + 1 
1316                                                + strlen((char*) val) + 1) * sizeof(char));
1317                    sprintf (tmp, "%s;%s", tt->value, (char *) val);
1318                    free(tt->value);
1319                    tt->value = tmp;
1320                  }
1321                  xmlFree (val);
1322                }
1323             
1324              // Title, Abstract
1325              else if (xmlStrncasecmp(elems->name, BAD_CAST "Title",
1326                                      xmlStrlen (elems->name)) == 0
1327                       || xmlStrncasecmp(elems->name, BAD_CAST "Abstract",
1328                                         xmlStrlen (elems->name)) == 0)
1329                {
1330                  xmlChar *val =
1331                    xmlNodeListGetString (doc, elems->xmlChildrenNode, 1);
1332                                                       
1333                  if (tmpmaps->content == NULL) {
1334                    tmpmaps->content = createMap((char*) elems->name, zStrdup ((char *) val));
1335                  }
1336                  else {
1337                    addToMap(tmpmaps->content, (char*) elems->name, zStrdup ((char *) val));
1338                  }
1339                  xmlFree (val);
1340                }
1341              elems = elems->next;
1342            }
1343                               
1344            // Get every attribute from an Output node:
1345            // mimeType, encoding, schema, uom, asReference
1346            const char *outs[5] =
1347              { "mimeType", "encoding", "schema", "uom", "asReference" };
1348                                         
1349            for (l = 0; l < 5; l++) {
1350              xmlChar *val = xmlGetProp (cur1, BAD_CAST outs[l]);                               
1351              if (val != NULL && xmlStrlen(val) > 0) {
1352                if (tmpmaps->content != NULL) {
1353                  addToMap (tmpmaps->content, outs[l], (char *) val);
1354                }                         
1355                else {
1356                  tmpmaps->content = createMap (outs[l], (char *) val);
1357                }       
1358              }
1359              xmlFree (val);
1360            }
1361                               
1362            if (*request_output == NULL) {
1363              *request_output = tmpmaps;
1364            }   
1365            else if (getMaps(*request_output, tmpmaps->name) != NULL) {
1366              return errorException (*main_conf,
1367                                     _
1368                                     ("Duplicate <Output> elements in WPS Execute request"),
1369                                     "InternalError", NULL);
1370            }
1371            else {
1372              maps* mptr = *request_output;
1373              while (mptr->next != NULL) {
1374                mptr = mptr->next;
1375              }
1376              mptr->next = tmpmaps;     
1377            }                                   
1378            cur1 = cur1->next;
1379          }                     
1380      }
1381    }
1382  return 1;
1383}
1384
1385/**
1386 * Parse XML request and store information in maps.
1387 *
1388 * @param main_conf the conf maps containing the main.cfg settings
1389 * @param post the string containing the XML request
1390 * @param request_inputs the map storing KVP raw value
1391 * @param s the service
1392 * @param inputs the maps to store the KVP pairs
1393 * @param outputs the maps to store the KVP pairs
1394 * @param hInternet the HINTERNET queue to add potential requests
1395 * @return 0 on success, -1 on failure
1396 */
1397int xmlParseRequest(maps** main_conf,const char* post,map** request_inputs,service* s,maps** inputs,maps** outputs,HINTERNET* hInternet){
1398
1399  map* version=getMapFromMaps(*main_conf,"main","rversion");
1400  int vid=getVersionId(version->value);
1401
1402  xmlInitParser ();
1403  xmlDocPtr doc = xmlReadMemory (post, cgiContentLength, "input_request.xml", NULL, XML_PARSE_RECOVER);
1404
1405  /**
1406   * Extract Input nodes from the XML Request.
1407   */
1408  xmlXPathObjectPtr tmpsptr =
1409    extractFromDoc (doc, (vid==0?"/*/*/*[local-name()='Input']":"/*/*[local-name()='Input']"));
1410  xmlNodeSet *tmps = tmpsptr->nodesetval;
1411  if(tmps==NULL || xmlParseInputs(main_conf,s,inputs,doc,tmps,hInternet)<0){
1412    xmlXPathFreeObject (tmpsptr);
1413    xmlFreeDoc (doc);
1414    xmlCleanupParser ();
1415    return -1;
1416  }
1417  xmlXPathFreeObject (tmpsptr);
1418
1419  if(vid==1){
1420    tmpsptr =
1421      extractFromDoc (doc, "/*[local-name()='Execute']");
1422    bool asRaw = false;
1423    tmps = tmpsptr->nodesetval;
1424    if(tmps->nodeNr > 0){
1425      int k = 0;
1426      for (k=0; k < tmps->nodeNr; k++){
1427        maps *tmpmaps = NULL;
1428        xmlNodePtr cur = tmps->nodeTab[k];
1429        if (cur->type == XML_ELEMENT_NODE){
1430          xmlChar *val = xmlGetProp (cur, BAD_CAST "mode");
1431          if(val!=NULL)
1432            addToMap(*request_inputs,"mode",(char*)val);
1433          else
1434            addToMap(*request_inputs,"mode","auto");
1435          xmlFree(val);
1436          val = xmlGetProp (cur, BAD_CAST "response");
1437          if(val!=NULL){
1438            addToMap(*request_inputs,"response",(char*)val);
1439            if(strncasecmp((char*)val,"raw",xmlStrlen(val))==0)
1440              addToMap(*request_inputs,"RawDataOutput","");
1441            else
1442              addToMap(*request_inputs,"ResponseDocument","");
1443          }
1444          else{
1445            addToMap(*request_inputs,"response","document");
1446            addToMap(*request_inputs,"ResponseDocument","");
1447          }
1448          xmlFree(val);
1449        }
1450      }
1451    }
1452    xmlXPathFreeObject (tmpsptr);
1453    tmpsptr =
1454      extractFromDoc (doc, "/*/*[local-name()='Output']");
1455    tmps = tmpsptr->nodesetval;
1456    if(tmps->nodeNr > 0){
1457      if(xmlParseOutputs2(main_conf,request_inputs,outputs,doc,tmps)<0){
1458        xmlXPathFreeObject (tmpsptr);
1459        xmlFreeDoc (doc);
1460        xmlCleanupParser ();
1461        return -1;
1462      }
1463    }
1464  }
1465  else{
1466    // Extract ResponseDocument / RawDataOutput from the XML Request
1467    tmpsptr =
1468      extractFromDoc (doc, "/*/*/*[local-name()='ResponseDocument']");
1469    bool asRaw = false;
1470    tmps = tmpsptr->nodesetval;
1471    if (tmps->nodeNr == 0)
1472      {
1473        xmlXPathFreeObject (tmpsptr);
1474        tmpsptr =
1475          extractFromDoc (doc, "/*/*/*[local-name()='RawDataOutput']");
1476        tmps = tmpsptr->nodesetval;
1477        asRaw = true;
1478      }
1479    if(tmps->nodeNr != 0){
1480      if(xmlParseOutputs(main_conf,request_inputs,outputs,doc,tmps->nodeTab[0],asRaw)<0){
1481        xmlXPathFreeObject (tmpsptr);
1482        xmlFreeDoc (doc);
1483        xmlCleanupParser ();
1484        return -1;
1485      }
1486    }
1487  }
1488  xmlXPathFreeObject (tmpsptr);
1489  xmlFreeDoc (doc);
1490  xmlCleanupParser ();
1491  return 1;
1492}
1493
1494/**
1495 * Parse request and store information in maps.
1496 *
1497 * @param main_conf the conf maps containing the main.cfg settings
1498 * @param post the string containing the XML request
1499 * @param request_inputs the map storing KVP raw value
1500 * @param s the service
1501 * @param inputs the maps to store the KVP pairs
1502 * @param outputs the maps to store the KVP pairs
1503 * @param hInternet the HINTERNET queue to add potential requests
1504 * @return 0 on success, -1 on failure
1505 * @see kvpParseOutputs,kvpParseInputs,xmlParseRequest
1506 */
1507int parseRequest(maps** main_conf,map** request_inputs,service* s,maps** inputs,maps** outputs,HINTERNET* hInternet){
1508  map *postRequest = NULL;
1509  postRequest = getMap (*request_inputs, "xrequest");
1510  if (postRequest == NULLMAP)
1511    {
1512      if(kvpParseOutputs(main_conf,*request_inputs,outputs)<0){
1513        return -1;
1514      }
1515      if(kvpParseInputs(main_conf,s,*request_inputs,inputs,hInternet)<0){
1516        return -1;
1517      }
1518    }
1519  else
1520    {
1521      //Parse XML request
1522      if(xmlParseRequest(main_conf,postRequest->value,request_inputs,s,inputs,outputs,hInternet)<0){
1523        return -1;
1524      }
1525    }
1526  return 1;
1527}
1528
1529/**
1530 * Ensure that each requested arguments are present in the request
1531 * DataInputs and ResponseDocument / RawDataOutput. Potentially run
1532 * http requests from the queue in parallel.
1533 * For optional inputs add default values defined in the ZCFG file.
1534 *
1535 * @param main_conf
1536 * @param s
1537 * @param original_request
1538 * @param request_inputs
1539 * @param request_outputs
1540 * @param hInternet
1541 *
1542 * @see runHttpRequests
1543 */
1544int validateRequest(maps** main_conf,service* s,map* original_request, maps** request_inputs,maps** request_outputs,HINTERNET* hInternet){
1545
1546  map* errI0=NULL;
1547  runHttpRequests (main_conf, request_inputs, hInternet,&errI0);
1548  if(errI0!=NULL){
1549    printExceptionReportResponse (*main_conf, errI0);
1550    InternetCloseHandle (hInternet);
1551    return -1;
1552  }
1553  InternetCloseHandle (hInternet);
1554
1555
1556  map* errI=NULL;
1557  char *dfv = addDefaultValues (request_inputs, s->inputs, *main_conf, 0,&errI);
1558
1559  maps *ptr = *request_inputs;
1560  while (ptr != NULL)
1561    {
1562      map *tmp0 = getMap (ptr->content, "size");
1563      map *tmp1 = getMap (ptr->content, "maximumMegabytes");
1564      if (tmp1 != NULL && tmp0 != NULL)
1565        {
1566          float i = atof (tmp0->value) / 1048576.0;
1567          if (i >= atoi (tmp1->value))
1568            {
1569              char tmps[1024];
1570              map *tmpe = createMap ("code", "FileSizeExceeded");
1571              snprintf (tmps, 1024,
1572                        _
1573                        ("The <%s> parameter has a size limit (%s MB) defined in the ZOO ServicesProvider configuration file, but the reference you provided exceeds this limit (%f MB)."),
1574                        ptr->name, tmp1->value, i);
1575              addToMap (tmpe, "locator", ptr->name);
1576              addToMap (tmpe, "text", tmps);
1577              printExceptionReportResponse (*main_conf, tmpe);
1578              freeMap (&tmpe);
1579              free (tmpe);
1580              return -1;
1581            }
1582        }
1583      ptr = ptr->next;
1584    }
1585
1586  map* errO=NULL;
1587  char *dfv1 =
1588    addDefaultValues (request_outputs, s->outputs, *main_conf, 1,&errO);
1589
1590  if (strcmp (dfv1, "") != 0 || strcmp (dfv, "") != 0)
1591    {
1592      char tmps[1024];
1593      map *tmpe = NULL;
1594      if (strcmp (dfv, "") != 0)
1595        {
1596          tmpe = createMap ("code", "MissingParameterValue");
1597          int nb=0;
1598          int length=1;
1599          map* len=getMap(errI,"length");
1600          if(len!=NULL)
1601            length=atoi(len->value);
1602          for(nb=0;nb<length;nb++){
1603            map* errp=getMapArray(errI,"value",nb);
1604            snprintf (tmps, 1024,
1605                      _
1606                      ("The <%s> argument was not specified in DataInputs but is required according to the ZOO ServicesProvider configuration file."),
1607                      errp->value);
1608            setMapArray (tmpe, "locator", nb , errp->value);
1609            setMapArray (tmpe, "text", nb , tmps);
1610            setMapArray (tmpe, "code", nb , "MissingParameterValue");
1611          }
1612        }
1613      if (strcmp (dfv1, "") != 0)
1614        {
1615          int ilength=0;
1616          if(tmpe==NULL)
1617            tmpe = createMap ("code", "InvalidParameterValue");
1618          else{
1619            map* len=getMap(tmpe,"length");
1620            if(len!=NULL)
1621              ilength=atoi(len->value);
1622          }
1623          int nb=0;
1624          int length=1;
1625          map* len=getMap(errO,"length");
1626          if(len!=NULL)
1627            length=atoi(len->value);
1628          for(nb=0;nb<length;nb++){
1629            map* errp=getMapArray(errO,"value",nb);
1630            snprintf (tmps, 1024,
1631                      _
1632                      ("The <%s> argument specified as %s identifier was not recognized (not defined in the ZOO Configuration File)."),
1633                      errp->value,
1634                      ((getMap(original_request,"RawDataOutput")!=NULL)?"RawDataOutput":"ResponseDocument"));
1635            setMapArray (tmpe, "locator", nb+ilength , errp->value);
1636            setMapArray (tmpe, "text", nb+ilength , tmps);
1637            setMapArray (tmpe, "code", nb+ilength , "InvalidParameterValue");
1638          }
1639        }
1640      printExceptionReportResponse (*main_conf, tmpe);
1641      if(errI!=NULL){
1642        freeMap(&errI);
1643        free(errI);
1644      }
1645      if(errO!=NULL){
1646        freeMap(&errO);
1647        free(errO);
1648      }
1649      freeMap (&tmpe);
1650      free (tmpe);
1651      return -1;
1652    }
1653  maps *tmpReqI = *request_inputs;
1654  while (tmpReqI != NULL)
1655    {
1656      char name[1024];
1657      if (getMap (tmpReqI->content, "isFile") != NULL)
1658        {
1659          if (cgiFormFileName (tmpReqI->name, name, sizeof (name)) ==
1660              cgiFormSuccess)
1661            {
1662              int BufferLen = 1024;
1663              cgiFilePtr file;
1664              int targetFile;
1665              char *storageNameOnServer;
1666              char *fileNameOnServer;
1667              char contentType[1024];
1668              char buffer[1024];
1669              char *tmpStr = NULL;
1670              int size;
1671              int got, t;
1672              map *path = getMapFromMaps (*main_conf, "main", "tmpPath");
1673              cgiFormFileSize (tmpReqI->name, &size);
1674              cgiFormFileContentType (tmpReqI->name, contentType,
1675                                      sizeof (contentType));
1676              if (cgiFormFileOpen (tmpReqI->name, &file) == cgiFormSuccess)
1677                {
1678                  t = -1;
1679                  while (1)
1680                    {
1681                      tmpStr = strstr (name + t + 1, "\\");
1682                      if (NULL == tmpStr)
1683                        tmpStr = strstr (name + t + 1, "/");
1684                      if (NULL != tmpStr)
1685                        t = (int) (tmpStr - name);
1686                      else
1687                        break;
1688                    }
1689                  fileNameOnServer=(char*)malloc((strlen(name) - t - 1 )*sizeof(char));
1690                  strcpy (fileNameOnServer, name + t + 1);
1691
1692                  storageNameOnServer=(char*)malloc((strlen(path->value) + strlen(fileNameOnServer) + 2)*sizeof(char));
1693                  sprintf (storageNameOnServer, "%s/%s", path->value,
1694                           fileNameOnServer);
1695#ifdef DEBUG
1696                  fprintf (stderr, "Name on server %s\n",
1697                           storageNameOnServer);
1698                  fprintf (stderr, "fileNameOnServer: %s\n",
1699                           fileNameOnServer);
1700#endif
1701                  targetFile =
1702                    open (storageNameOnServer, O_RDWR | O_CREAT | O_TRUNC,
1703                          S_IRWXU | S_IRGRP | S_IROTH);
1704                  if (targetFile < 0)
1705                    {
1706#ifdef DEBUG
1707                      fprintf (stderr, "could not create the new file,%s\n",
1708                               fileNameOnServer);
1709#endif
1710                    }
1711                  else
1712                    {
1713                      while (cgiFormFileRead (file, buffer, BufferLen, &got)
1714                             == cgiFormSuccess)
1715                        {
1716                          if (got > 0)
1717                            write (targetFile, buffer, got);
1718                        }
1719                    }
1720                  addToMap (tmpReqI->content, "lref", storageNameOnServer);
1721                  cgiFormFileClose (file);
1722                  close (targetFile);
1723                  free(fileNameOnServer);
1724                  free(storageNameOnServer);
1725#ifdef DEBUG
1726                  fprintf (stderr, "File \"%s\" has been uploaded",
1727                           fileNameOnServer);
1728#endif
1729                }
1730            }
1731        }
1732      tmpReqI = tmpReqI->next;
1733    }
1734
1735  ensureDecodedBase64 (request_inputs);
1736  return 1;
1737}
1738
1739
1740/**
1741 * Verify if a parameter value is valid.
1742 *
1743 * @param request the request map
1744 * @param res the error map potentially generated
1745 * @param toCheck the parameter to use
1746 * @param avalues the acceptable values (or null if testing only for presence)
1747 * @param mandatory verify the presence of the parameter if mandatory > 0
1748 */
1749void checkValidValue(map* request,map** res,const char* toCheck,const char** avalues,int mandatory){
1750  map* lres=*res;
1751  map* r_inputs = getMap (request,toCheck);
1752  if (r_inputs == NULL){
1753    if(mandatory>0){
1754      char *replace=_("Mandatory parameter <%s> was not specified");
1755      char *message=(char*)malloc((strlen(replace)+strlen(toCheck)+1)*sizeof(char));
1756      sprintf(message,replace,toCheck);
1757      if(lres==NULL){
1758        lres=createMap("code","MissingParameterValue");
1759        addToMap(lres,"text",message);
1760        addToMap(lres,"locator",toCheck);       
1761      }else{
1762        int length=1;
1763        map* len=getMap(lres,"length");
1764        if(len!=NULL){
1765          length=atoi(len->value);
1766        }
1767        setMapArray(lres,"text",length,message);
1768        setMapArray(lres,"locator",length,toCheck);
1769        setMapArray(lres,"code",length,"MissingParameterValue");
1770      }
1771      free(message);
1772    }
1773  }else{
1774    if(avalues==NULL)
1775      return;
1776    int nb=0;
1777    int hasValidValue=-1;
1778    if(strncasecmp(toCheck,"Accept",6)==0){
1779      char *tmp=zStrdup(r_inputs->value);
1780      char *pToken,*saveptr;
1781      pToken=strtok_r(tmp,",",&saveptr);
1782      while(pToken!=NULL){
1783        while(avalues[nb]!=NULL){
1784          if(strcasecmp(avalues[nb],pToken)==0){
1785            hasValidValue=1;
1786            break;
1787          }
1788          nb++;
1789        }
1790        pToken=strtok_r(NULL,",",&saveptr);
1791      }
1792      free(tmp);
1793    }else{
1794      while(avalues[nb]!=NULL){
1795        if(strcasecmp(avalues[nb],r_inputs->value)==0){
1796          hasValidValue=1;
1797          break;
1798        }
1799        nb++;
1800      }
1801    }
1802    if(hasValidValue<0){
1803      char *replace=_("The value <%s> was not recognized, %s %s the only acceptable value.");
1804      nb=0;
1805      char *vvalues=NULL;
1806      char* num=_("is");
1807      while(avalues[nb]!=NULL){
1808        char *tvalues;
1809        if(vvalues==NULL){
1810          vvalues=(char*)malloc((strlen(avalues[nb])+3)*sizeof(char));
1811          sprintf(vvalues,"%s",avalues[nb]);
1812        }
1813        else{
1814          tvalues=zStrdup(vvalues);
1815          vvalues=(char*)realloc(vvalues,(strlen(tvalues)+strlen(avalues[nb])+3)*sizeof(char));
1816          sprintf(vvalues,"%s, %s",tvalues,avalues[nb]);
1817          free(tvalues);
1818          num=_("are");
1819        }
1820        nb++;
1821      }
1822      char *message=(char*)malloc((strlen(replace)+strlen(num)+strlen(vvalues)+strlen(toCheck)+1)*sizeof(char));
1823      sprintf(message,replace,toCheck,vvalues,num);
1824      const char *code="VersionNegotiationFailed";
1825      code="InvalidParameterValue";
1826      const char *locator=toCheck;
1827      if( strncasecmp(toCheck,"version",7)==0 ||
1828          strncasecmp(toCheck,"AcceptVersions",14)==0 )
1829        code="VersionNegotiationFailed";
1830      if( strncasecmp(toCheck,"request",7)==0){
1831        code="OperationNotSupported";
1832        locator=r_inputs->value;
1833      }
1834      if(lres==NULL){
1835        lres=createMap("code",code);
1836        addToMap(lres,"text",message);
1837        addToMap(lres,"locator",locator);       
1838      }else{
1839        int length=1;
1840        map* len=getMap(lres,"length");
1841        if(len!=NULL){
1842          length=atoi(len->value);
1843        }
1844        setMapArray(lres,"text",length,message);
1845        setMapArray(lres,"locator",length,locator);
1846        setMapArray(lres,"code",length,code);
1847      }
1848    }
1849  }
1850  if(lres!=NULL){
1851    *res=lres;
1852  }
1853}
1854
1855/**
1856 * Parse cookie contained in request headers.
1857 *
1858 * @param conf the conf maps containinfg the main.cfg
1859 * @param cookie the
1860 */
1861void parseCookie(maps** conf,const char* cookie){
1862  char* tcook=zStrdup(cookie);
1863  char *token, *saveptr;
1864  token = strtok_r (tcook, "; ", &saveptr);
1865  maps* res=createMaps("cookies");
1866  while (token != NULL){
1867    char *token1, *saveptr1, *name;
1868    int i=0;
1869    token1 = strtok_r (token, "=", &saveptr1);
1870    while (token1 != NULL){
1871      if(i==0){
1872        name=zStrdup(token1);
1873        i++;
1874      }
1875      else{
1876        if(res->content==NULL)
1877          res->content=createMap(name,token1);
1878        else
1879          addToMap(res->content,name,token1);
1880        free(name);
1881        i=0;
1882      }
1883      token1 = strtok_r (NULL, "=", &saveptr1);
1884    }
1885    token = strtok_r (NULL, "; ", &saveptr);
1886  }
1887  addMapsToMaps(conf,res);
1888  freeMaps(&res);
1889  free(res);
1890  free(tcook);
1891}
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png