source: trunk/zoo-project/zoo-kernel/request_parser.c @ 682

Last change on this file since 682 was 680, checked in by djay, 9 years ago

Various fixes for Windows support: generate uuid using UuidCreate?, pass usid to the created process, call TerminateProcess? on dismiss request.

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