source: trunk/zoo-kernel/zoo_service_loader.c @ 105

Last change on this file since 105 was 105, checked in by djay, 13 years ago

Simplification of RawDataOutput? and ResponseDocument? parsing code for XML requests.

File size: 50.1 KB
Line 
1/**
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2011 GeoLabs SARL. All rights reserved.
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#define length(x) (sizeof(x) / sizeof(x[0]))
26
27extern "C" int yylex();
28extern "C" int crlex();
29
30extern "C" {
31#include <libxml/tree.h>
32#include <libxml/xmlmemory.h>
33#include <libxml/parser.h>
34#include <libxml/xpath.h>
35#include <libxml/xpathInternals.h>
36}
37
38#include "cgic.h"
39#include "ulinet.h"
40
41#include <libintl.h>
42#include <locale.h>
43#include <string.h>
44
45#include "service.h"
46
47#include "service_internal.h"
48
49#ifdef USE_PYTHON
50#include "service_internal_python.h"
51#endif
52
53#ifdef USE_JAVA
54#include "service_internal_java.h"
55#endif
56
57#ifdef USE_PHP
58#include "service_internal_php.h"
59#endif
60
61#ifdef USE_JS
62#include "service_internal_js.h"
63#endif
64
65#ifdef USE_PERL
66#include "service_internal_perl.h"
67#endif
68
69
70
71#include <dirent.h>
72#include <signal.h>
73#include <unistd.h>
74#ifndef WIN32
75#include <dlfcn.h>
76#include <libgen.h>
77#else
78#include <windows.h>
79#include <direct.h>
80#endif
81#include <fcntl.h>
82#include <time.h>
83#include <stdarg.h>
84
85#define _(String) dgettext ("zoo-kernel",String)
86
87
88void *translateChar(char* str,char toReplace,char toReplaceBy){
89  int i=0,len=strlen(str);
90  for(i=0;i<len;i++){
91    if(str[i]==toReplace)
92      str[i]=toReplaceBy;
93  }
94}
95
96xmlXPathObjectPtr extractFromDoc(xmlDocPtr doc,char* search){
97  xmlXPathContextPtr xpathCtx;
98  xmlXPathObjectPtr xpathObj;
99  xpathCtx = xmlXPathNewContext(doc);
100  xpathObj = xmlXPathEvalExpression(BAD_CAST search,xpathCtx);
101  xmlXPathFreeContext(xpathCtx);
102  return xpathObj;
103}
104
105void donothing(int sig){
106  fprintf(stderr,"Signal %d after the ZOO-Kernel returned result !\n",sig);
107  exit(0);
108}
109
110void sig_handler(int sig){
111  char tmp[100];
112  char *ssig;
113  switch(sig){
114  case SIGSEGV:
115    ssig="SIGSEGV";
116    break;
117  case SIGTERM:
118    ssig="SIGTERM";
119    break;
120  case SIGINT:
121    ssig="SIGINT";
122    break;
123  case SIGILL:
124    ssig="SIGILL";
125    break;
126  case SIGFPE:
127    ssig="SIGFPE";
128    break;
129  case SIGABRT:
130    ssig="SIGABRT";
131    break;
132  default:
133    ssig="UNKNOWN";
134    break;
135  }
136  sprintf(tmp,_("ZOO Kernel failed to process your request receiving signal %d = %s"),sig,ssig);
137  errorException(NULL, tmp, "InternalError");
138#ifdef DEBUG
139  fprintf(stderr,"Not this time!\n");
140#endif
141  exit(0);
142}
143
144void *loadServiceAndRun(maps **myMap,service* s1,map* request_inputs,maps **inputs,maps** ioutputs,int* eres){
145  char tmps1[1024];
146  char ntmp[1024];
147  maps *m=*myMap;
148  maps *request_output_real_format=*ioutputs;
149  maps *request_input_real_format=*inputs;
150  /**
151   * Extract serviceType to know what kind of service should be loaded
152   */
153  map* r_inputs=NULL;
154#ifndef WIN32
155  getcwd(ntmp,1024);
156#else
157  _getcwd(ntmp,1024);
158#endif
159  r_inputs=getMap(s1->content,"serviceType");
160#ifdef DEBUG
161  fprintf(stderr,"LOAD A %s SERVICE PROVIDER \n",r_inputs->value);
162  fflush(stderr);
163#endif
164  if(strncasecmp(r_inputs->value,"C",1)==0){
165    r_inputs=getMap(request_inputs,"metapath");
166    if(r_inputs!=NULL)
167      sprintf(tmps1,"%s/%s",ntmp,r_inputs->value);
168    else
169      sprintf(tmps1,"%s/",ntmp);
170    char *altPath=strdup(tmps1);
171    r_inputs=getMap(s1->content,"ServiceProvider");
172    sprintf(tmps1,"%s/%s",altPath,r_inputs->value);
173    free(altPath);
174#ifdef DEBUG
175    fprintf(stderr,"Trying to load %s\n",tmps1);
176#endif
177#ifdef WIN32
178    HINSTANCE so = LoadLibraryEx(tmps1,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
179#else
180    void* so = dlopen(tmps1, RTLD_LAZY);
181#endif
182#ifdef DEBUG
183#ifdef WIN32
184    DWORD errstr;
185    errstr = GetLastError();
186    fprintf(stderr,"%s loaded (%d) \n",tmps1,errstr);
187#else
188    char *errstr;
189    errstr = dlerror();
190#endif
191#endif
192
193    if( so != NULL ) {
194#ifdef DEBUG
195      fprintf(stderr,"Library loaded %s \n",errstr);
196      fprintf(stderr,"Service Shared Object = %s\n",r_inputs->value);
197#endif
198      r_inputs=getMap(s1->content,"serviceType");
199#ifdef DEBUG
200      dumpMap(r_inputs);
201      fprintf(stderr,"%s\n",r_inputs->value);
202      fflush(stderr);
203#endif
204      if(strncasecmp(r_inputs->value,"C-FORTRAN",9)==0){
205#ifdef WIN32
206        //Strange return value needed here !
207        return 1;
208#endif
209        r_inputs=getMap(request_inputs,"Identifier");
210        char fname[1024];
211        sprintf(fname,"%s_",r_inputs->value);
212#ifdef DEBUG
213        fprintf(stderr,"Try to load function %s\n",fname);
214#endif
215#ifdef WIN32
216        typedef int (CALLBACK* execute_t)(char***,char***,char***);
217        execute_t execute=(execute_t)GetProcAddress(so,fname);
218#else
219        typedef int (*execute_t)(char***,char***,char***);
220        execute_t execute=(execute_t)dlsym(so,fname);
221#endif
222#ifdef DEBUG
223#ifdef WIN32
224        errstr = GetLastError();
225#else
226        errstr = dlerror();
227#endif
228        fprintf(stderr,"Function loaded %s\n",errstr);
229#endif 
230
231        char main_conf[10][30][1024];
232        char inputs[10][30][1024];
233        char outputs[10][30][1024];
234        for(int i=0;i<10;i++){
235          for(int j=0;j<30;j++){
236            memset(main_conf[i][j],0,1024);
237            memset(inputs[i][j],0,1024);
238            memset(outputs[i][j],0,1024);
239          }
240        }
241        mapsToCharXXX(m,(char***)main_conf);
242        mapsToCharXXX(request_input_real_format,(char***)inputs);
243        mapsToCharXXX(request_output_real_format,(char***)outputs);
244        *eres=execute((char***)&main_conf[0],(char***)&inputs[0],(char***)&outputs[0]);
245#ifdef DEBUG
246        fprintf(stderr,"Function run successfully \n");
247#endif
248        charxxxToMaps((char***)&outputs[0],&request_output_real_format);
249      }else{
250#ifdef DEBUG
251#ifdef WIN32
252        errstr = GetLastError();
253        fprintf(stderr,"Function %s failed to load because of %d\n",r_inputs->value,errstr);
254#endif
255#endif
256        r_inputs=getMap(request_inputs,"Identifier");
257#ifdef DEBUG
258        fprintf(stderr,"Try to load function %s\n",r_inputs->value);
259#endif
260        typedef int (*execute_t)(maps**,maps**,maps**);
261#ifdef WIN32
262        execute_t execute=(execute_t)GetProcAddress(so,r_inputs->value); 
263#else
264        execute_t execute=(execute_t)dlsym(so,r_inputs->value);
265#endif
266
267#ifdef DEBUG
268#ifdef WIN32
269        errstr = GetLastError();
270#else
271        errstr = dlerror();
272#endif
273        fprintf(stderr,"Function loaded %s\n",errstr);
274#endif 
275
276#ifdef DEBUG
277        fprintf(stderr,"Now run the function \n");
278        fflush(stderr);
279#endif
280        *eres=execute(&m,&request_input_real_format,&request_output_real_format);
281#ifdef DEBUG
282        fprintf(stderr,"Function loaded and returned %d\n",eres);
283        fflush(stderr);
284#endif
285      }
286      dlclose(so);
287    } else {
288      /**
289       * Unable to load the specified shared library
290       */
291      char tmps[1024];
292#ifdef WIN32
293      DWORD errstr = GetLastError();
294#else
295      char* errstr = dlerror();
296#endif
297      sprintf(tmps,_("C Library can't be loaded %s \n"),errstr);
298      map* tmps1=createMap("text",tmps);
299      printExceptionReportResponse(m,tmps1);
300      *eres=-1;
301    }
302  }
303  else
304#ifdef USE_PYTHON
305    if(strncasecmp(r_inputs->value,"PYTHON",6)==0){
306      *eres=zoo_python_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
307    }
308    else
309#endif
310       
311#ifdef USE_JAVA
312      if(strncasecmp(r_inputs->value,"JAVA",4)==0){
313        *eres=zoo_java_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
314      }
315      else
316#endif
317
318#ifdef USE_PHP
319        if(strncasecmp(r_inputs->value,"PHP",3)==0){
320          *eres=zoo_php_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
321        }
322        else
323#endif
324           
325           
326#ifdef USE_PERL
327          if(strncasecmp(r_inputs->value,"PERL",4)==0){
328            *eres=zoo_perl_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
329          }
330          else
331#endif
332
333#ifdef USE_JS
334            if(strncasecmp(r_inputs->value,"JS",2)==0){
335              *eres=zoo_js_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
336            }
337            else
338#endif
339              {
340                char tmpv[1024];
341                sprintf(tmpv,_("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),r_inputs->value);
342                map* tmps=createMap("text",tmpv);
343                printExceptionReportResponse(m,tmps);
344                *eres=-1;
345              }
346  *myMap=m;
347  *ioutputs=request_output_real_format;
348}
349
350int runRequest(map* request_inputs)
351{
352
353#ifndef USE_GDB
354  (void) signal(SIGSEGV,sig_handler);
355  (void) signal(SIGTERM,sig_handler);
356  (void) signal(SIGINT,sig_handler);
357  (void) signal(SIGILL,sig_handler);
358  (void) signal(SIGFPE,sig_handler);
359  (void) signal(SIGABRT,sig_handler);
360#endif
361
362  map* r_inputs=NULL,*tmps=NULL;
363  maps* m=NULL;
364  int argc=count(request_inputs);
365
366  char* REQUEST=NULL;
367  /**
368   * Parsing service specfic configuration file
369   */
370  m=(maps*)calloc(1,MAPS_SIZE);
371  if(m == NULL){
372    return errorException(m, _("Unable to allocate memory."), "InternalError");
373  }
374  char ntmp[1024];
375#ifndef WIN32
376  getcwd(ntmp,1024);
377#else
378  _getcwd(ntmp,1024);
379#endif
380  r_inputs=getMap(request_inputs,"metapath");
381  if(r_inputs==NULL){
382    if(request_inputs==NULL)
383      request_inputs=createMap("metapath","");
384    else
385      addToMap(request_inputs,"metapath","");
386#ifdef DEBUG
387    fprintf(stderr,"ADD METAPATH\n");
388    dumpMap(request_inputs);
389#endif
390    r_inputs=getMap(request_inputs,"metapath");
391  }
392  char conf_file[10240];
393  snprintf(conf_file,10240,"%s/%s/main.cfg",ntmp,r_inputs->value);
394  conf_read(conf_file,m);
395#ifdef DEBUG
396  fprintf(stderr, "***** BEGIN MAPS\n"); 
397  dumpMaps(m);
398  fprintf(stderr, "***** END MAPS\n");
399#endif
400
401  bindtextdomain ("zoo-kernel","/usr/share/locale/");
402  bindtextdomain ("zoo-services","/usr/share/locale/");
403 
404  if((r_inputs=getMap(request_inputs,"language"))!=NULL){
405    char *tmp=strdup(r_inputs->value);
406    translateChar(tmp,'-','_');
407    setlocale (LC_ALL, tmp);
408    free(tmp);
409    setMapInMaps(m,"main","language",r_inputs->value);
410  }
411  else{
412    setlocale (LC_ALL, "en_US");
413    setMapInMaps(m,"main","language","en-US");
414  }
415  setlocale (LC_NUMERIC, "en_US");
416  bind_textdomain_codeset("zoo-kernel","UTF-8");
417  textdomain("zoo-kernel");
418  bind_textdomain_codeset("zoo-services","UTF-8");
419  textdomain("zoo-services");
420
421
422  /**
423   * Check for minimum inputs
424   */
425  r_inputs=getMap(request_inputs,"Request");
426  if(request_inputs==NULL || r_inputs==NULL){ 
427    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue");
428    freeMaps(&m);
429    free(m);
430    freeMap(&request_inputs);
431    free(request_inputs);
432    free(REQUEST);
433    return 1;
434  }
435  else{
436    REQUEST=strdup(r_inputs->value);
437    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
438       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
439       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
440      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
441      freeMaps(&m);
442      free(m);
443      free(REQUEST);
444      return 1;
445    }
446  }
447  r_inputs=NULL;
448  r_inputs=getMap(request_inputs,"Service");
449  if(r_inputs==NULLMAP){
450    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue");
451    freeMaps(&m);
452    free(m);
453    free(REQUEST);
454    return 1;
455  }
456  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
457    r_inputs=getMap(request_inputs,"Version");
458    if(r_inputs==NULL){ 
459      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue");
460      freeMaps(&m);
461      free(m);
462      free(REQUEST);
463      return 1;
464    }
465  }
466
467  r_inputs=getMap(request_inputs,"serviceprovider");
468  if(r_inputs==NULL){
469    addToMap(request_inputs,"serviceprovider","");
470  }
471
472  map* outputs=NULL;
473  maps* request_output_real_format=NULL;
474  map* tmpm=getMapFromMaps(m,"main","serverAddress");
475  if(tmpm!=NULL)
476    SERVICE_URL=strdup(tmpm->value);
477  else
478    SERVICE_URL=strdup(DEFAULT_SERVICE_URL);
479
480  service* s[100];
481  service* s1;
482  int scount=0;
483
484#ifdef DEBUG
485  dumpMap(r_inputs);
486#endif
487  char conf_dir[1024];
488  int t;
489  char tmps1[1024];
490
491  r_inputs=NULL;
492  r_inputs=getMap(request_inputs,"metapath");
493  if(r_inputs!=NULL)
494    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
495  else
496    snprintf(conf_dir,1024,"%s",ntmp);
497
498  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
499    int i=0;
500    struct dirent *dp;
501#ifdef DEBUG
502    dumpMap(r_inputs);
503#endif
504    DIR *dirp = opendir(conf_dir);
505    if(dirp==NULL){
506      return errorException(m, _("The specified path doesn't exist."),"InvalidParameterValue");
507    }
508    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
509    r_inputs=NULL;
510    r_inputs=getMap(request_inputs,"ServiceProvider");
511    xmlNodePtr n;
512    //dumpMap(request_inputs);
513    if(r_inputs!=NULL)
514      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
515    else
516      n = printGetCapabilitiesHeader(doc,"",m);
517    /**
518     * Strange, here we need to close stdout to ensure that no uneeded
519     * char will be printed (parser issue ?)
520     */
521    int saved_stdout = dup(fileno(stdout));
522    dup2(fileno(stderr),fileno(stdout));
523    while ((dp = readdir(dirp)) != NULL)
524      if(strstr(dp->d_name,".zcfg")!=0){
525        memset(tmps1,0,1024);
526        snprintf(tmps1,1024,"%s/%s",conf_dir,dp->d_name);
527        s1=(service*)calloc(1,SERVICE_SIZE);
528        if(s1 == NULL){ 
529          return errorException(m, _("Unable to allocate memory."),"InternalError");
530        }
531#ifdef DEBUG
532        fprintf(stderr,"#################\n%s\n#################\n",tmps1);
533#endif
534        t=getServiceFromFile(tmps1,&s1);
535#ifdef DEBUG
536        dumpService(s1);
537        fflush(stdout);
538        fflush(stderr);
539#endif
540        printGetCapabilitiesForProcess(m,n,s1);
541        freeService(&s1);
542        free(s1);
543        scount++;
544      }
545    (void)closedir(dirp);
546    fflush(stdout);
547    dup2(saved_stdout,fileno(stdout));
548    printDocument(m,doc,getpid());
549    freeMaps(&m);
550    free(m);
551    free(REQUEST);
552    free(SERVICE_URL);
553    fflush(stdout);
554    return 0;
555  }
556  else{
557    r_inputs=getMap(request_inputs,"Identifier");
558    if(r_inputs==NULL 
559       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
560      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue");
561      freeMaps(&m);
562      free(m);
563      free(REQUEST);
564      free(SERVICE_URL);
565      return 0;
566    }
567
568    struct dirent *dp;
569    DIR *dirp = opendir(conf_dir);
570    if(dirp==NULL){
571      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue");
572      freeMaps(&m);
573      free(m);
574      free(REQUEST);
575      free(SERVICE_URL);
576      return 0;
577    }
578    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
579      /**
580       * Loop over Identifier list
581       */
582      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
583      r_inputs=NULL;
584      r_inputs=getMap(request_inputs,"ServiceProvider");
585
586      xmlNodePtr n;
587      if(r_inputs!=NULL)
588        n = printDescribeProcessHeader(doc,r_inputs->value,m);
589      else
590        n = printDescribeProcessHeader(doc,"",m);
591
592      r_inputs=getMap(request_inputs,"Identifier");
593      char *tmps=strtok(r_inputs->value,",");
594     
595      char buff[256];
596      char buff1[1024];
597      int i=0;
598      int j=0;
599      int end=-1;
600      int saved_stdout = dup(fileno(stdout));
601      dup2(fileno(stderr),fileno(stdout));
602      while(tmps){
603        memset(buff,0,256);
604        snprintf(buff,256,"%s.zcfg",tmps);
605        memset(buff1,0,1024);
606#ifdef DEBUG
607        fprintf(stderr,"\n#######%s\n########\n",buff1);
608#endif
609        while ((dp = readdir(dirp)) != NULL)
610          if(strcmp(dp->d_name,buff)==0){
611            memset(buff1,0,1024);
612            snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
613            //s1=(service*)malloc(sizeof(service*));
614            s1=(service*)calloc(1,SERVICE_SIZE);
615            if(s1 == NULL){
616              return errorException(m, _("Unable to allocate memory."),"InternalError");
617            }
618#ifdef DEBUG
619            fprintf(stderr,"#################\n%s\n#################\n",buff1);
620#endif
621            t=getServiceFromFile(buff1,&s1);
622#ifdef DEBUG
623            dumpService(s1);
624#endif
625            printDescribeProcessForProcess(m,n,s1,1);
626            freeService(&s1);
627            free(s1);
628            scount++;
629          }
630        rewinddir(dirp);
631        tmps=strtok(NULL,",");
632      }
633      closedir(dirp);
634      fflush(stdout);
635      dup2(saved_stdout,fileno(stdout));
636      printDocument(m,doc,getpid());
637      freeMaps(&m);
638      free(m);
639      free(REQUEST);
640      free(SERVICE_URL);
641      fflush(stdout);
642      //xmlFree(n);
643#ifndef LINUX_FREE_ISSUE
644      if(s1)
645        free(s1);
646#endif
647      return 0;
648    }
649    else
650      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
651        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
652#ifdef DEBUG
653        fprintf(stderr,"No request found %s",REQUEST);
654#endif 
655        closedir(dirp);
656        free(s);
657        return 0;
658      }
659    closedir(dirp);
660  }
661 
662  s1=NULL;
663  s1=(service*)calloc(1,SERVICE_SIZE);
664  if(s1 == NULL){
665    freeMaps(&m);
666    free(m);
667    free(REQUEST);
668    free(SERVICE_URL);
669    return errorException(m, _("Unable to allocate memory."),"InternalError");
670  }
671  r_inputs=getMap(request_inputs,"MetaPath");
672  if(r_inputs!=NULL)
673    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
674  else
675    snprintf(tmps1,1024,"%s/",ntmp);
676  r_inputs=getMap(request_inputs,"Identifier");
677  char *ttmp=strdup(tmps1);
678  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
679  free(ttmp);
680#ifdef DEBUG
681  fprintf(stderr,"Trying to load %s\n", tmps1);
682#endif
683  int saved_stdout = dup(fileno(stdout));
684  dup2(fileno(stderr),fileno(stdout));
685  t=getServiceFromFile(tmps1,&s1);
686  fflush(stdout);
687  dup2(saved_stdout,fileno(stdout));
688  if(t<0){
689    char tmpMsg[2048+strlen(r_inputs->value)];
690    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
691    errorException(m, tmpMsg, "InvalidParameterValue");
692    freeService(&s1);
693    free(s1);
694    freeMaps(&m);
695    free(m);
696    free(REQUEST);
697    free(SERVICE_URL);
698    return 0;
699  }
700  close(saved_stdout);
701
702#ifdef DEBUG
703  dumpService(s1);
704#endif
705  map* inputs=NULL;
706  elements* c_inputs=s1->inputs;
707  int j;
708 
709  /**
710   * Create the input maps data structure
711   */
712  int i=0;
713  HINTERNET hInternet;
714  HINTERNET res;
715  hInternet=InternetOpen(
716#ifndef WIN32
717                         (LPCTSTR)
718#endif
719                         "ZooWPSClient\0",
720                         INTERNET_OPEN_TYPE_PRECONFIG,
721                         NULL,NULL, 0);
722
723#ifndef WIN32
724  if(!CHECK_INET_HANDLE(hInternet))
725    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
726#endif
727  maps* request_input_real_format=NULL;
728  maps* tmpmaps = request_input_real_format;
729  map* postRequest=NULL;
730  postRequest=getMap(request_inputs,"xrequest");
731  if(postRequest==NULLMAP){
732    /**
733     * Parsing outputs provided as KVP
734     */
735    r_inputs=NULL;
736#ifdef DEBUG
737    fprintf(stderr,"OUTPUT Parsing ... \n");
738#endif
739    r_inputs=getMap(request_inputs,"ResponseDocument"); 
740    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
741   
742#ifdef DEBUG
743    fprintf(stderr,"OUTPUT Parsing ... \n");
744#endif
745    if(r_inputs!=NULL){
746#ifdef DEBUG
747      fprintf(stderr,"OUTPUT Parsing start now ... \n");
748#endif
749      char current_output_as_string[10240];
750      char cursor_output[10240];
751      char *cotmp=strdup(r_inputs->value);
752      snprintf(cursor_output,10240,"%s",cotmp);
753      free(cotmp);
754      j=0;
755      map* request_kvp_outputs=NULL;
756       
757      /**
758       * Put each Output into the outputs_as_text array
759       */
760      char * pToken;
761      maps* tmp_output=NULL;
762#ifdef DEBUG
763      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
764#endif
765      pToken=strtok(cursor_output,";");
766      char** outputs_as_text=(char**)calloc(128,sizeof(char*));
767      if(outputs_as_text == NULL) {
768        return errorException(m, _("Unable to allocate memory"), "InternalError");
769      }
770      i=0;
771      while(pToken!=NULL){
772#ifdef DEBUG
773        fprintf(stderr,"***%s***\n",pToken);
774        fflush(stderr);
775        fprintf(stderr,"***%s***\n",pToken);
776#endif
777        outputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
778        if(outputs_as_text[i] == NULL) {
779          return errorException(m, _("Unable to allocate memory"), "InternalError");
780        }
781        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
782        pToken = strtok(NULL,";");
783        i++;
784      }
785      for(j=0;j<i;j++){
786        char *tmp=strdup(outputs_as_text[j]);
787        free(outputs_as_text[j]);
788        char *tmpc;
789        tmpc=strtok(tmp,"@");
790        int k=0;
791        while(tmpc!=NULL){
792          if(k==0){
793            if(tmp_output==NULL){
794              tmp_output=(maps*)calloc(1,MAPS_SIZE);
795              if(tmp_output == NULL){
796                return errorException(m, _("Unable to allocate memory."), "InternalError");
797              }
798              tmp_output->name=strdup(tmpc);
799              tmp_output->content=NULL;
800              tmp_output->next=NULL;
801            }
802          }
803          else{
804            char *tmpv=strstr(tmpc,"=");
805            char tmpn[256];
806            memset(tmpn,0,256);
807            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
808            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
809#ifdef DEBUG
810            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
811#endif
812            if(tmp_output->content==NULL){
813              tmp_output->content=createMap(tmpn,tmpv+1);
814              tmp_output->content->next=NULL;
815            }
816            else
817              addToMap(tmp_output->content,tmpn,tmpv+1);
818          }
819          k++;
820#ifdef DEBUG
821          fprintf(stderr,"***%s***\n",tmpc);
822#endif
823          tmpc=strtok(NULL,"@");
824        }
825        if(request_output_real_format==NULL)
826          request_output_real_format=dupMaps(&tmp_output);
827        else
828          addMapsToMaps(&request_output_real_format,tmp_output);
829        freeMaps(&tmp_output);
830        free(tmp_output);
831        tmp_output=NULL;
832#ifdef DEBUG
833        dumpMaps(tmp_output);
834        fflush(stderr);
835#endif
836        //tmp_output=tmp_output->next;
837        free(tmp);
838      }
839      free(outputs_as_text);
840    }
841
842
843    /**
844     * Parsing inputs provided as KVP
845     */
846    r_inputs=getMap(request_inputs,"DataInputs");
847#ifdef DEBUG
848    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
849#endif
850    char current_input_as_string[40960];
851    char cursor_input[40960];
852    if(r_inputs!=NULL)
853      snprintf(cursor_input,40960,"%s",r_inputs->value);
854    else{
855      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue");
856      freeMaps(&m);
857      free(m);
858      free(REQUEST);
859      free(SERVICE_URL);
860      InternetCloseHandle(hInternet);
861      freeService(&s1);
862      free(s1);
863      return 0;
864    }
865    j=0;
866    map* request_kvp_inputs=NULL;
867 
868    /**
869     * Put each DataInputs into the inputs_as_text array
870     */
871    char * pToken;
872    pToken=strtok(cursor_input,";");
873    char** inputs_as_text=(char**)calloc(100,sizeof(char*));
874    if(inputs_as_text == NULL){
875      return errorException(m, _("Unable to allocate memory."), "InternalError");
876    }
877    i=0;
878    while(pToken!=NULL){
879#ifdef DEBUG
880      fprintf(stderr,"***%s***\n",pToken);
881#endif
882      fflush(stderr);
883#ifdef DEBUG
884      fprintf(stderr,"***%s***\n",pToken);
885#endif
886      inputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
887      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
888      if(inputs_as_text[i] == NULL){
889        return errorException(m, _("Unable to allocate memory."), "InternalError");
890      }
891      pToken = strtok(NULL,";");
892      i++;
893    }
894
895    for(j=0;j<i;j++){
896      char *tmp=strdup(inputs_as_text[j]);
897      free(inputs_as_text[j]);
898      char *tmpc;
899      tmpc=strtok(tmp,"@");
900      while(tmpc!=NULL){
901#ifdef DEBUG
902        fprintf(stderr,"***\n***%s***\n",tmpc);
903#endif
904        char *tmpv=strstr(tmpc,"=");
905        char tmpn[256];
906        memset(tmpn,0,256);
907        strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
908        tmpn[strlen(tmpc)-strlen(tmpv)]=0;
909        int cnt=0;
910#ifdef DEBUG
911        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
912#endif
913        if(tmpmaps==NULL){
914          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
915          if(tmpmaps == NULL){
916            return errorException(m, _("Unable to allocate memory."), "InternalError");
917          }
918          tmpmaps->name=strdup(tmpn);
919          tmpmaps->content=createMap("value",tmpv+1);
920          tmpmaps->next=NULL;
921        }
922        tmpc=strtok(NULL,"@");
923        while(tmpc!=NULL){
924#ifdef DEBUG
925          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
926#endif
927          char *tmpv1=strstr(tmpc,"=");
928#ifdef DEBUG
929          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
930#endif
931          char tmpn1[1024];
932          memset(tmpn1,0,1024);
933          strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
934          tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
935#ifdef DEBUG
936          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
937          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
938#endif
939          if(strcmp(tmpn1,"xlink:href")!=0)
940            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
941          else{
942#ifdef DEBUG
943            fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
944#endif
945#ifndef WIN32
946            if(CHECK_INET_HANDLE(hInternet))
947#endif
948              {
949                res=InternetOpenUrl(hInternet,tmpv1+1,NULL,0,
950                                    INTERNET_FLAG_NO_CACHE_WRITE,0);
951#ifdef DEBUG
952                fprintf(stderr,"(%s) content-length : %d,,res.nDataAlloc %d \n",
953                        tmpv1+1,res.nDataAlloc,res.nDataLen);
954#endif
955                char* tmpContent=(char*)calloc((res.nDataLen+1),sizeof(char));
956                if(tmpContent == NULL){
957                  return errorException(m, _("Unable to allocate memory."), "InternalError");
958                }
959                size_t dwRead;
960                InternetReadFile(res, (LPVOID)tmpContent,res.nDataLen, &dwRead);
961                map* tmpMap=getMap(tmpmaps->content,"value");
962                if(tmpMap!=NULL){
963                  free(tmpMap->value);
964                  tmpMap->value=(char*)malloc((res.nDataLen+1)*sizeof(char));
965                  memmove(tmpMap->value,tmpContent,(res.nDataLen)*sizeof(char));
966                  tmpMap->value[res.nDataLen]=0;
967                  if(strlen(tmpContent)!=res.nDataLen){
968                    char tmp[256];
969                    sprintf(tmp,"%d",res.nDataLen*sizeof(char));
970                    addToMap(tmpmaps->content,"size",tmp);
971                  }
972                }
973                free(tmpContent);
974              }
975            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
976            addToMap(tmpmaps->content,"Reference",tmpv1+1);
977          }
978          tmpc=strtok(NULL,"@");
979        }
980#ifdef DEBUG
981        dumpMaps(tmpmaps);
982        fflush(stderr);
983#endif
984        if(request_input_real_format==NULL)
985          request_input_real_format=dupMaps(&tmpmaps);
986        else
987          addMapsToMaps(&request_input_real_format,tmpmaps);
988        freeMaps(&tmpmaps);
989        free(tmpmaps);
990        tmpmaps=NULL;
991        free(tmp);
992      }
993    }
994    free(inputs_as_text);
995  }
996  else {
997    /**
998     * Parse XML request
999     */ 
1000    xmlInitParser();
1001#ifdef DEBUG
1002    fflush(stderr);
1003    fprintf(stderr,"BEFORE %s\n",postRequest->value);
1004    fflush(stderr);
1005#endif
1006    xmlDocPtr doc =
1007      xmlParseMemory(postRequest->value,cgiContentLength);
1008#ifdef DEBUG
1009    fprintf(stderr,"AFTER\n");
1010    fflush(stderr);
1011#endif
1012    xmlNodePtr cur = xmlDocGetRootElement(doc);
1013    /**
1014     * Parse every Input in DataInputs node.
1015     */
1016    maps* tempMaps=NULL;
1017    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1018    xmlNodeSet* tmps=tmpsptr->nodesetval;
1019#ifdef DEBUG
1020    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1021#endif
1022    for(int k=0;k<tmps->nodeNr;k++){
1023      maps *tmpmaps=NULL;
1024      xmlNodePtr cur=tmps->nodeTab[k];
1025      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1026        /**
1027         * A specific Input node.
1028         */
1029#ifdef DEBUG
1030        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1031#endif
1032        xmlNodePtr cur2=cur->children;
1033        while(cur2!=NULL){
1034          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1035            cur2=cur2->next;
1036          if(cur2==NULL)
1037            break;
1038          /**
1039           * Indentifier
1040           */
1041          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1042            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1043            if(tmpmaps==NULL){
1044              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1045              if(tmpmaps == NULL){
1046                return errorException(m, _("Unable to allocate memory."), "InternalError");
1047              }
1048              tmpmaps->name=strdup((char*)val);
1049              tmpmaps->content=NULL;
1050              tmpmaps->next=NULL;
1051            }
1052            xmlFree(val);
1053          }
1054          /**
1055           * Title, Asbtract
1056           */
1057          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1058             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1059            xmlChar *val=
1060              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1061            if(tmpmaps==NULL){
1062              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1063              if(tmpmaps == NULL){
1064                return errorException(m, _("Unable to allocate memory."), "InternalError");
1065              }
1066              tmpmaps->name="missingIndetifier";
1067              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1068              tmpmaps->next=NULL;
1069            }
1070            else{
1071              if(tmpmaps->content!=NULL)
1072                addToMap(tmpmaps->content,
1073                         (char*)cur2->name,(char*)val);
1074              else
1075                tmpmaps->content=
1076                  createMap((char*)cur2->name,(char*)val);
1077            }
1078#ifdef DEBUG
1079            dumpMaps(tmpmaps);
1080#endif
1081            xmlFree(val);
1082          }
1083          /**
1084           * InputDataFormChoice (Reference or Data ?)
1085           */
1086          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1087            /**
1088             * Get every attribute from a Reference node
1089             * mimeType, encoding, schema, href, method
1090             * Header and Body gesture should be added here
1091             */
1092#ifdef DEBUG
1093            fprintf(stderr,"REFERENCE\n");
1094#endif
1095            map* referenceMap=NULL;
1096            char *refs[5];
1097            refs[0]="mimeType";
1098            refs[1]="encoding";
1099            refs[2]="schema";
1100            refs[3]="method";
1101            refs[4]="href";
1102            char*url;
1103            for(int l=0;l<5;l++){
1104#ifdef DEBUG
1105              fprintf(stderr,"*** %s ***",refs[l]);
1106#endif
1107              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1108              if(val!=NULL && xmlStrlen(val)>0){
1109                if(tmpmaps->content!=NULL)
1110                  addToMap(tmpmaps->content,refs[l],(char*)val);
1111                else
1112                  tmpmaps->content=createMap(refs[l],(char*)val);
1113                map* ltmp=getMap(tmpmaps->content,"method");
1114                if(l==4){
1115                  if(!(ltmp!=NULL && strcmp(ltmp->value,"POST")==0)
1116                     && CHECK_INET_HANDLE(hInternet)){
1117                    res=InternetOpenUrl(hInternet,(char*)val,NULL,0,
1118                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1119                    char* tmpContent=
1120                      (char*)calloc((res.nDataLen+1),sizeof(char));
1121                    if(tmpContent == NULL){
1122                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1123                    }
1124                    size_t dwRead;
1125                    InternetReadFile(res, (LPVOID)tmpContent,
1126                                     res.nDataLen, &dwRead);
1127                    tmpContent[res.nDataLen]=0;
1128                    addToMap(tmpmaps->content,"value",tmpContent);
1129                  }
1130                }
1131              }
1132#ifdef DEBUG
1133              fprintf(stderr,"%s\n",val);
1134#endif
1135              xmlFree(val);
1136            }
1137#ifdef POST_DEBUG
1138            fprintf(stderr,"Parse Header and Body from Reference \n");
1139#endif
1140            xmlNodePtr cur3=cur2->children;
1141            hInternet.header=NULL;
1142            while(cur3){
1143              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1144                xmlNodePtr cur4=cur3;
1145                char *tmp=new char[cgiContentLength];
1146                char *ha[2];
1147                ha[0]="key";
1148                ha[1]="value";
1149                int hai;
1150                char *has;
1151                char *key;
1152                for(hai=0;hai<2;hai++){
1153                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1154#ifdef POST_DEBUG
1155                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1156#endif
1157                  if(hai==0){
1158                    key=(char*)calloc((1+strlen((char*)val)),sizeof(char));
1159                    snprintf(key,1+strlen((char*)val),"%s",(char*)val);
1160                  }else{
1161                    has=(char*)calloc((3+strlen((char*)val)+strlen(key)),sizeof(char));
1162                    if(has == NULL){
1163                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1164                    }
1165                    snprintf(has,(3+strlen((char*)val)+strlen(key)),"%s: %s",key,(char*)val);
1166#ifdef POST_DEBUG
1167                    fprintf(stderr,"%s\n",has);
1168#endif
1169                  }
1170                }
1171                hInternet.header=curl_slist_append(hInternet.header, has);
1172                //free(has);
1173              }
1174              else{
1175#ifdef POST_DEBUG
1176                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1177#endif
1178                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1179#ifdef POST_DEBUG
1180                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1181#endif
1182                  char *tmp=new char[cgiContentLength];
1183                  memset(tmp,0,cgiContentLength);
1184                  xmlNodePtr cur4=cur3->children;
1185                  while(cur4!=NULL){
1186                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1187                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1188                    xmlDocSetRootElement(bdoc,cur4);
1189                    xmlChar* btmps;
1190                    int bsize;
1191                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1192#ifdef POST_DEBUG
1193                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1194#endif
1195                    if(btmps!=NULL)
1196                      sprintf(tmp,"%s",(char*)btmps);
1197                    xmlFreeDoc(bdoc);
1198                    cur4=cur4->next;
1199                  }
1200                  map *btmp=getMap(tmpmaps->content,"href");
1201                  if(btmp!=NULL){
1202#ifdef POST_DEBUG
1203                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1204                    curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1205#endif
1206                    res=InternetOpenUrl(hInternet,btmp->value,tmp,strlen(tmp),
1207                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1208                    char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1209                    if(tmpContent == NULL){
1210                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1211                    }
1212                    size_t dwRead;
1213                    InternetReadFile(res, (LPVOID)tmpContent,
1214                                     res.nDataLen, &dwRead);
1215                    tmpContent[res.nDataLen]=0;
1216                    if(hInternet.header!=NULL)
1217                      curl_slist_free_all(hInternet.header);
1218                    addToMap(tmpmaps->content,"value",tmpContent);
1219#ifdef POST_DEBUG
1220                    fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1221#endif
1222                  }
1223                }
1224                else
1225                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1226                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1227                    HINTERNET bInternet,res1;
1228                    bInternet=InternetOpen(
1229#ifndef WIN32
1230                                           (LPCTSTR)
1231#endif
1232                                           "ZooWPSClient\0",
1233                                           INTERNET_OPEN_TYPE_PRECONFIG,
1234                                           NULL,NULL, 0);
1235                    if(!CHECK_INET_HANDLE(bInternet))
1236                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1237#ifdef POST_DEBUG
1238                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1239#endif
1240                    res1=InternetOpenUrl(bInternet,(char*)val,NULL,0,
1241                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1242                    char* tmp=
1243                      (char*)calloc((res1.nDataLen+1),sizeof(char));
1244                    if(tmp == NULL){
1245                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1246                    }
1247                    size_t bRead;
1248                    InternetReadFile(res1, (LPVOID)tmp,
1249                                     res1.nDataLen, &bRead);
1250                    tmp[res1.nDataLen]=0;
1251                    InternetCloseHandle(bInternet);
1252                    map *btmp=getMap(tmpmaps->content,"href");
1253                    if(btmp!=NULL){
1254#ifdef POST_DEBUG
1255                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1256                      curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1257#endif
1258                      res=InternetOpenUrl(hInternet,btmp->value,tmp,
1259                                          strlen(tmp),
1260                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1261                      char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1262                      if(tmpContent == NULL){
1263                        return errorException(m, _("Unable to allocate memory."), "InternalError");
1264                      }
1265                      size_t dwRead;
1266                      InternetReadFile(res, (LPVOID)tmpContent,
1267                                       res.nDataLen, &dwRead);
1268                      tmpContent[res.nDataLen]=0;
1269                      if(hInternet.header!=NULL)
1270                        curl_slist_free_all(hInternet.header);
1271                      addToMap(tmpmaps->content,"value",tmpContent);
1272#ifdef POST_DEBUG
1273                      fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1274#endif
1275                    }
1276                  }
1277              }
1278              cur3=cur3->next;
1279            }
1280#ifdef POST_DEBUG
1281            fprintf(stderr,"Header and Body was parsed from Reference \n");
1282#endif
1283#ifdef DEBUG
1284            dumpMap(tmpmaps->content);
1285            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1286                    cur2->name,cur2->content);
1287#endif
1288          }
1289          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1290#ifdef DEBUG
1291            fprintf(stderr,"DATA\n");
1292#endif
1293            xmlNodePtr cur4=cur2->children;
1294            while(cur4!=NULL){
1295              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1296                cur4=cur4->next;
1297              if(cur4==NULL)
1298                break;
1299              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1300                /**
1301                 * Get every attribute from a LiteralData node
1302                 * dataType , uom
1303                 */
1304                char *lits[2];
1305                lits[0]="dataType";
1306                lits[1]="uom";
1307                for(int l=0;l<2;l++){
1308#ifdef DEBUG
1309                  fprintf(stderr,"*** LiteralData %s ***",lits[l]);
1310#endif
1311                  xmlChar *val=xmlGetProp(cur4,BAD_CAST lits[l]);
1312                  if(val!=NULL && strlen((char*)val)>0){
1313                    if(tmpmaps->content!=NULL)
1314                      addToMap(tmpmaps->content,lits[l],(char*)val);
1315                    else
1316                      tmpmaps->content=createMap(lits[l],(char*)val);
1317                  }
1318#ifdef DEBUG
1319                  fprintf(stderr,"%s\n",val);
1320#endif
1321                  xmlFree(val);
1322                }
1323              }
1324              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1325                /**
1326                 * Get every attribute from a Reference node
1327                 * mimeType, encoding, schema
1328                 */
1329                char *coms[3];
1330                coms[0]="mimeType";
1331                coms[1]="encoding";
1332                coms[2]="schema";
1333                for(int l=0;l<3;l++){
1334#ifdef DEBUG
1335                  fprintf(stderr,"*** ComplexData %s ***",coms[l]);
1336#endif
1337                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1338                  if(val!=NULL && strlen((char*)val)>0){
1339                    if(tmpmaps->content!=NULL)
1340                      addToMap(tmpmaps->content,coms[l],(char*)val);
1341                    else
1342                      tmpmaps->content=createMap(coms[l],(char*)val);
1343                  }
1344#ifdef DEBUG
1345                  fprintf(stderr,"%s\n",val);
1346#endif
1347                  xmlFree(val);
1348                }
1349              }
1350              map* test=getMap(tmpmaps->content,"encoding");
1351              if(test==NULL || strcasecmp(test->value,"base64")!=0){
1352                xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1353                if(mv==NULL){
1354                  xmlDocPtr doc1=xmlNewDoc(BAD_CAST "1.0");
1355                  int buffersize;
1356                  xmlDocSetRootElement(doc1,cur4->xmlChildrenNode);
1357                  xmlDocDumpFormatMemoryEnc(doc1, &mv, &buffersize, "utf-8", 1);
1358                  char size[1024];
1359                  sprintf(size,"%d",buffersize);
1360                  addToMap(tmpmaps->content,"size",size);
1361                }
1362                addToMap(tmpmaps->content,"value",(char*)mv);
1363                xmlFree(mv);
1364              }else{
1365                xmlChar* tmp=xmlNodeListGetRawString(doc,cur4->xmlChildrenNode,0);
1366                addToMap(tmpmaps->content,"value",(char*)tmp);
1367                map* tmpv=getMap(tmpmaps->content,"value");
1368                char *res=NULL;
1369                char *curs=tmpv->value;
1370                int i=0;
1371                for(int i=0;i<=strlen(tmpv->value)/64;i++) {
1372                  if(res==NULL)
1373                    res=(char*)malloc(67*sizeof(char));
1374                  else
1375                    res=(char*)realloc(res,(((i+1)*65)+i)*sizeof(char));
1376                  int csize=i*65;
1377                  strncpy(res + csize,curs,64);
1378                  if(i==xmlStrlen(tmp)/64)
1379                    strcat(res,"\n\0");
1380                  else{
1381                    strncpy(res + (((i+1)*64)+i),"\n\0",2);
1382                    curs+=64;
1383                  }
1384                }
1385                free(tmpv->value);
1386                tmpv->value=strdup(res);
1387                free(res);
1388                xmlFree(tmp);
1389              }
1390              cur4=cur4->next;
1391            }
1392          }
1393#ifdef DEBUG
1394          fprintf(stderr,"cur2 next \n");
1395          fflush(stderr);
1396#endif
1397          cur2=cur2->next;
1398        }
1399#ifdef DEBUG
1400        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1401        fflush(stderr);
1402#endif
1403        addMapsToMaps(&request_input_real_format,tmpmaps);
1404       
1405#ifdef DEBUG
1406        fprintf(stderr,"******TMPMAPS*****\n");
1407        dumpMaps(tmpmaps);
1408        fprintf(stderr,"******REQUESTMAPS*****\n");
1409        dumpMaps(request_input_real_format);
1410#endif
1411        freeMaps(&tmpmaps);
1412        free(tmpmaps);
1413        tmpmaps=NULL;         
1414      }
1415#ifdef DEBUG
1416      dumpMaps(tmpmaps); 
1417#endif
1418    }
1419#ifdef DEBUG
1420    fprintf(stderr,"Search for response document node\n");
1421#endif
1422    xmlXPathFreeObject(tmpsptr);
1423    //xmlFree(tmps);
1424   
1425    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1426    bool asRaw=false;
1427    tmps=tmpsptr->nodesetval;
1428    if(tmps->nodeNr==0){
1429      tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1430      tmps=tmpsptr->nodesetval;
1431      asRaw=true;
1432    }
1433#ifdef DEBUG
1434    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1435#endif
1436    for(int k=0;k<tmps->nodeNr;k++){
1437      if(asRaw==true)
1438        addToMap(request_inputs,"RawDataOutput","");
1439      else
1440        addToMap(request_inputs,"ResponseDocument","");
1441      request_output_real_format;
1442      maps *tmpmaps=NULL;
1443      xmlNodePtr cur=tmps->nodeTab[k];
1444      if(cur->type == XML_ELEMENT_NODE) {
1445        /**
1446         * A specific responseDocument node.
1447         */
1448        if(tmpmaps==NULL){
1449          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1450          if(tmpmaps == NULL){
1451            return errorException(m, _("Unable to allocate memory."), "InternalError");
1452          }
1453          tmpmaps->name="unknownIdentifier";
1454          tmpmaps->next=NULL;
1455        }
1456        /**
1457         * Get every attribute from a LiteralData node
1458         * storeExecuteResponse, lineage, status
1459         */
1460        char *ress[3];
1461        ress[0]="storeExecuteResponse";
1462        ress[1]="lineage";
1463        ress[2]="status";
1464        xmlChar *val;
1465        for(int l=0;l<3;l++){
1466#ifdef DEBUG
1467          fprintf(stderr,"*** %s ***\t",ress[l]);
1468#endif
1469          val=xmlGetProp(cur,BAD_CAST ress[l]);
1470          if(val!=NULL && strlen((char*)val)>0){
1471            if(tmpmaps->content!=NULL)
1472              addToMap(tmpmaps->content,ress[l],(char*)val);
1473            else
1474              tmpmaps->content=createMap(ress[l],(char*)val);
1475            addToMap(request_inputs,ress[l],(char*)val);
1476          }
1477#ifdef DEBUG
1478          fprintf(stderr,"%s\n",val);
1479#endif
1480          xmlFree(val);
1481        }
1482        xmlNodePtr cur1=cur->children;
1483        while(cur1){
1484          if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
1485            /**
1486             * Get every attribute from a Output node
1487             * mimeType, encoding, schema, uom, asReference
1488             */
1489            char *outs[5];
1490            outs[0]="mimeType";
1491            outs[1]="encoding";
1492            outs[2]="schema";
1493            outs[3]="uom";
1494            outs[4]="asReference";
1495            for(int l=0;l<5;l++){
1496#ifdef DEBUG
1497              fprintf(stderr,"*** %s ***\t",outs[l]);
1498#endif
1499              val=xmlGetProp(cur1,BAD_CAST outs[l]);
1500              if(val!=NULL && strlen((char*)val)>0){
1501                if(tmpmaps->content!=NULL)
1502                  addToMap(tmpmaps->content,outs[l],(char*)val);
1503                else
1504                  tmpmaps->content=createMap(outs[l],(char*)val);
1505              }
1506#ifdef DEBUG
1507              fprintf(stderr,"%s\n",val);
1508#endif
1509              xmlFree(val);
1510            }
1511           
1512            xmlNodePtr cur2=cur1->children;
1513            while(cur2){
1514              /**
1515               * Indentifier
1516               */
1517              if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1518                xmlChar *val=
1519                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1520                if(tmpmaps==NULL){
1521                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1522                  if(tmpmaps == NULL){
1523                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1524                  }
1525                  tmpmaps->name=strdup((char*)val);
1526                  tmpmaps->content=NULL;
1527                  tmpmaps->next=NULL;
1528                }
1529                else
1530                  tmpmaps->name=strdup((char*)val);;
1531                xmlFree(val);
1532              }
1533              /**
1534               * Title, Asbtract
1535               */
1536              if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1537                 xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1538                xmlChar *val=
1539                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1540                if(tmpmaps==NULL){
1541                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1542                  if(tmpmaps == NULL){
1543                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1544                  }
1545                  tmpmaps->name="missingIndetifier";
1546                  tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1547                  tmpmaps->next=NULL;
1548                }
1549                else{
1550                  if(tmpmaps->content!=NULL)
1551                    addToMap(tmpmaps->content,
1552                             (char*)cur2->name,(char*)val);
1553                  else
1554                    tmpmaps->content=
1555                      createMap((char*)cur2->name,(char*)val);
1556                }
1557                xmlFree(val);
1558              }
1559              cur2=cur2->next;
1560            }
1561          }
1562          cur1=cur1->next;
1563        }
1564      }
1565      //xmlFree(cur);
1566      if(request_output_real_format==NULL)
1567        request_output_real_format=dupMaps(&tmpmaps);
1568      else
1569        addMapsToMaps(&request_output_real_format,tmpmaps);
1570#ifdef DEBUG
1571      dumpMaps(tmpmaps);
1572#endif
1573      freeMaps(&tmpmaps);
1574      free(tmpmaps);
1575    }
1576
1577    xmlXPathFreeObject(tmpsptr);
1578    //xmlFree(tmps);
1579    xmlCleanupParser();
1580  }
1581 
1582  //if(CHECK_INET_HANDLE(hInternet))
1583  InternetCloseHandle(hInternet);
1584
1585#ifdef DEBUG
1586  fprintf(stderr,"\n%i\n",i);
1587  dumpMaps(request_input_real_format);
1588  dumpMaps(request_output_real_format);
1589  dumpMap(request_inputs);
1590#endif
1591
1592  /**
1593   * Ensure that each requested arguments are present in the request
1594   * DataInputs and ResponseDocument / RawDataOutput
1595   */
1596  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,0);
1597  if(strcmp(dfv,"")!=0){
1598    char tmps[1024];
1599    snprintf(tmps,1024,_("The <%s> argument was not specified in DataInputs but defined as requested in ZOO ServicesProvider configuration file, please correct your query or the ZOO Configuration file."),dfv);
1600    map* tmpe=createMap("text",tmps);
1601    addToMap(tmpe,"code","MissingParameterValue");
1602    printExceptionReportResponse(m,tmpe);
1603    freeService(&s1);
1604    free(s1);
1605    freeMap(&tmpe);
1606    free(tmpe);
1607    freeMaps(&m);
1608    free(m);
1609    free(REQUEST);
1610    free(SERVICE_URL);
1611    freeMaps(&request_input_real_format);
1612    free(request_input_real_format);
1613    freeMaps(&request_output_real_format);
1614    free(request_output_real_format);
1615    freeMaps(&tmpmaps);
1616    free(tmpmaps);
1617    return 1;
1618  }
1619  addDefaultValues(&request_output_real_format,s1->outputs,m,1);
1620
1621  ensureDecodedBase64(&request_input_real_format);
1622
1623#ifdef DEBUG
1624  fprintf(stderr,"REQUEST_INPUTS\n");
1625  dumpMaps(request_input_real_format);
1626  fprintf(stderr,"REQUEST_OUTPUTS\n");
1627  dumpMaps(request_output_real_format);
1628#endif
1629
1630  maps* curs=getMaps(m,"env");
1631  if(curs!=NULL){
1632    map* mapcs=curs->content;
1633    while(mapcs!=NULLMAP){
1634#ifndef WIN32
1635      setenv(mapcs->name,mapcs->value,1);
1636#else
1637#ifdef DEBUG
1638      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1639#endif
1640      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
1641#ifdef DEBUG
1642        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
1643#endif
1644        mapcs->value[strlen(mapcs->value)-1]=0;
1645      }
1646#ifdef DEBUG
1647      fflush(stderr);
1648      fprintf(stderr,"setting variable... %s\n",
1649#endif
1650              SetEnvironmentVariable(mapcs->name,mapcs->value)
1651#ifdef DEBUG
1652              ? "OK" : "FAILED");
1653#else
1654      ;
1655#endif
1656#ifdef DEBUG
1657      fflush(stderr);
1658#endif
1659#endif
1660#ifdef DEBUG
1661      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1662      fflush(stderr);
1663#endif
1664      mapcs=mapcs->next;
1665    }
1666  }
1667 
1668#ifdef DEBUG
1669  dumpMap(request_inputs);
1670#endif
1671
1672  /**
1673   * Need to check if we need to fork to load a status enabled
1674   */
1675  r_inputs=NULL;
1676  map* store=getMap(request_inputs,"storeExecuteResponse");
1677  map* status=getMap(request_inputs,"status");
1678  /**
1679   * 05-007r7 WPS 1.0.0 page 57 :
1680   * 'If status="true" and storeExecuteResponse is "false" then the service
1681   * shall raise an exception.'
1682   */
1683  if(status!=NULL && strcmp(status->value,"true")==0 && 
1684     store!=NULL && strcmp(store->value,"false")==0){
1685    errorException(m, _("Status cannot be set to true with storeExecuteResponse to false. Please, modify your request parameters."), "InvalidParameterValue");
1686    freeService(&s1);
1687    free(s1);
1688    freeMaps(&m);
1689    free(m);
1690   
1691    freeMaps(&request_input_real_format);
1692    free(request_input_real_format);
1693   
1694    freeMaps(&request_output_real_format);
1695    free(request_output_real_format);
1696   
1697    free(REQUEST);
1698    free(SERVICE_URL);
1699    return 1;
1700  }
1701  r_inputs=getMap(request_inputs,"storeExecuteResponse");
1702  int eres=SERVICE_STARTED;
1703  int cpid=getpid();
1704
1705  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
1706  _tmpMaps->name=strdup("lenv");
1707  char tmpBuff[100];
1708  sprintf(tmpBuff,"%i",cpid);
1709  _tmpMaps->content=createMap("sid",tmpBuff);
1710  _tmpMaps->next=NULL;
1711  addToMap(_tmpMaps->content,"status","0");
1712  if(cgiCookie!=NULL && strlen(cgiCookie)>0){
1713    addToMap(_tmpMaps->content,"sessid",strstr(cgiCookie,"=")+1);
1714    char session_file_path[1024];
1715    map *tmpPath=getMapFromMaps(m,"main","sessPath");
1716    if(tmpPath==NULL)
1717      tmpPath=getMapFromMaps(m,"main","tmpPath");
1718    sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(cgiCookie,"=")+1);
1719    maps *tmpSess=(maps*)calloc(1,MAPS_SIZE);
1720    struct stat file_status;
1721    int istat = stat(session_file_path, &file_status);
1722    if(istat==0){
1723      conf_read(session_file_path,tmpSess);
1724      dumpMaps(tmpSess);
1725      addMapsToMaps(&m,tmpSess);
1726      freeMaps(&tmpSess);
1727    }
1728    free(tmpSess);
1729  }
1730  addMapsToMaps(&m,_tmpMaps);
1731  freeMaps(&_tmpMaps);
1732  free(_tmpMaps);
1733
1734#ifdef DEBUG
1735  dumpMap(request_inputs);
1736#endif
1737
1738  if(status!=NULL)
1739    if(strcasecmp(status->value,"false")==0)
1740      status=NULL;
1741  if(status==NULLMAP){
1742    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
1743  }
1744  else{
1745    pid_t   pid;
1746#ifdef DEBUG
1747    fprintf(stderr,"\nPID : %d\n",cpid);
1748#endif
1749
1750#ifndef WIN32
1751    pid = fork ();
1752#else
1753    pid = 0;
1754#endif
1755    if (pid > 0) {
1756      /**
1757       * dady :
1758       * set status to SERVICE_ACCEPTED
1759       */
1760#ifdef DEBUG
1761      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
1762#endif
1763      eres=SERVICE_ACCEPTED;
1764    }else if (pid == 0) {
1765      /**
1766       * son : have to close the stdout, stdin and stderr to let the parent
1767       * process answer to http client.
1768       */
1769      r_inputs=getMapFromMaps(m,"main","tmpPath");
1770      map* r_inputs1=getMap(s1->content,"ServiceProvider");
1771      char* fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1772      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
1773      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1774      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
1775#ifdef DEBUG
1776      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
1777      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
1778      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
1779#endif
1780      freopen(fbkp , "w+", stdout);
1781      fclose(stdin);
1782      freopen(flog,"w+",stderr);
1783      free(fbkp);
1784      free(flog);
1785      /**
1786       * set status to SERVICE_STARTED and flush stdout to ensure full
1787       * content was outputed (the file used to store the ResponseDocument).
1788       * The rewind stdout to restart writing from the bgining of the file,
1789       * this way the data will be updated at the end of the process run.
1790       */
1791      updateStatus(m);
1792      printProcessResponse(m,request_inputs,cpid,
1793                            s1,r_inputs1->value,SERVICE_STARTED,
1794                            request_input_real_format,
1795                            request_output_real_format);
1796      fflush(stdout);
1797      rewind(stdout);
1798
1799      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
1800
1801    } else {
1802      /**
1803       * error server don't accept the process need to output a valid
1804       * error response here !!!
1805       */
1806      eres=-1;
1807      errorException(m, _("Unable to run the child process properly"), "InternalError");
1808    }
1809  }
1810
1811#ifdef DEBUG
1812  dumpMaps(request_output_real_format);
1813  fprintf(stderr,"Function loaded and returned %d\n",eres);
1814  fflush(stderr);
1815#endif
1816  if(eres!=-1)
1817    outputResponse(s1,request_input_real_format,
1818                   request_output_real_format,request_inputs,
1819                   cpid,m,eres);
1820  /**
1821   * Ensure that if error occurs when freeing memory, no signal will return
1822   * an ExceptionReport document as the result was already returned to the
1823   * client.
1824   */
1825#ifndef USE_GDB
1826  (void) signal(SIGSEGV,donothing);
1827  (void) signal(SIGTERM,donothing);
1828  (void) signal(SIGINT,donothing);
1829  (void) signal(SIGILL,donothing);
1830  (void) signal(SIGFPE,donothing);
1831  (void) signal(SIGABRT,donothing);
1832#endif
1833
1834  if(((int)getpid())!=cpid){
1835    fclose(stdout);
1836    fclose(stderr);
1837    unhandleStatus(m);
1838  }
1839
1840  freeService(&s1);
1841  free(s1);
1842  freeMaps(&m);
1843  free(m);
1844 
1845  freeMaps(&request_input_real_format);
1846  free(request_input_real_format);
1847 
1848  freeMaps(&request_output_real_format);
1849  free(request_output_real_format);
1850 
1851  free(REQUEST);
1852  free(SERVICE_URL);
1853#ifdef DEBUG
1854  fprintf(stderr,"Processed response \n");
1855  fflush(stdout);
1856  fflush(stderr);
1857#endif
1858
1859  return 0;
1860}
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