source: trunk/zoo-project/zoo-kernel/zoo_service_loader.c @ 502

Last change on this file since 502 was 502, checked in by djay, 10 years ago

RawDataOutput? gesture fixes (see ref.).

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 75.7 KB
Line 
1/**
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2013 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
30#include "cgic.h"
31
32extern "C" {
33#include <libxml/tree.h>
34#include <libxml/xmlmemory.h>
35#include <libxml/parser.h>
36#include <libxml/xpath.h>
37#include <libxml/xpathInternals.h>
38}
39
40#include "ulinet.h"
41
42#include <libintl.h>
43#include <locale.h>
44#include <string.h>
45
46#include "service.h"
47
48#include "service_internal.h"
49
50#ifdef USE_PYTHON
51#include "service_internal_python.h"
52#endif
53
54#ifdef USE_JAVA
55#include "service_internal_java.h"
56#endif
57
58#ifdef USE_PHP
59#include "service_internal_php.h"
60#endif
61
62#ifdef USE_JS
63#include "service_internal_js.h"
64#endif
65
66#ifdef USE_RUBY
67#include "service_internal_ruby.h"
68#endif
69
70#ifdef USE_PERL
71#include "service_internal_perl.h"
72#endif
73
74#include <dirent.h>
75#include <signal.h>
76#include <unistd.h>
77#ifndef WIN32
78#include <dlfcn.h>
79#include <libgen.h>
80#else
81#include <windows.h>
82#include <direct.h>
83#include <sys/types.h>
84#include <sys/stat.h>
85#include <unistd.h>
86#define pid_t int;
87#endif
88#include <fcntl.h>
89#include <time.h>
90#include <stdarg.h>
91
92#ifdef WIN32
93extern "C" {
94  __declspec(dllexport) char *strcasestr(char const *a, char const *b)
95#ifndef USE_MS
96 { 
97  char *x=zStrdup(a); 
98  char *y=zStrdup(b); 
99 
100  x=_strlwr(x); 
101  y=_strlwr(y); 
102  char *pos = strstr(x, y); 
103  char *ret = pos == NULL ? NULL : (char *)(a + (pos-x)); 
104  free(x); 
105  free(y); 
106  return ret; 
107 };
108#else
109  ;
110#endif
111}
112#endif
113
114#define _(String) dgettext ("zoo-kernel",String)
115#define __(String) dgettext ("zoo-service",String)
116
117extern   int getServiceFromFile(maps*,const char*,service**);
118
119int readServiceFile(maps* conf, char* file,service** service,char *name){
120  int t=getServiceFromFile(conf,file,service);
121#ifdef YAML
122  if(t<0){
123    t=getServiceFromYAML(conf,file,service,name);
124  }
125#endif
126  return t;
127}
128
129void translateChar(char* str,char toReplace,char toReplaceBy){
130  int i=0,len=strlen(str);
131  for(i=0;i<len;i++){
132    if(str[i]==toReplace)
133      str[i]=toReplaceBy;
134  }
135}
136
137/**
138 * Create (or append to) an array valued maps
139 * value = "["",""]"
140 */
141int appendMapsToMaps(maps* m,maps* mo,maps* mi,elements* elem){
142  maps* tmpMaps=getMaps(mo,mi->name);
143  map* tmap=getMapType(tmpMaps->content);
144  elements* el=getElements(elem,mi->name);
145  int hasEl=1;
146  if(el==NULL)
147    hasEl=-1;
148  if(tmap==NULL){
149    if(hasEl>0)
150      tmap=getMapType(el->defaults->content);     
151  }
152
153  map* testMap=NULL;
154  if(hasEl>0){
155    testMap=getMap(el->content,"maxOccurs");
156  }else{
157    testMap=createMap("maxOccurs","unbounded");
158  }
159
160  if(testMap!=NULL){
161    if(strncasecmp(testMap->value,"unbounded",9)!=0 && atoi(testMap->value)>1){
162      if(addMapsArrayToMaps(&mo,mi,tmap->name)<0){
163        char emsg[1024];
164        sprintf(emsg,_("You set maximum occurences for <%s> as %i but you tried to use it more than the limit you set. Please correct your ZCFG file or your request."),mi->name,atoi(testMap->value));
165        errorException(m,emsg,"InternalError",NULL);
166        return -1;
167      }
168    }else{
169      if(strncasecmp(testMap->value,"unbounded",9)==0){
170        if(hasEl<0){
171          freeMap(&testMap);
172          free(testMap);
173        }
174        if(addMapsArrayToMaps(&mo,mi,tmap->name)<0){
175          char emsg[1024];
176          map* tmpMap=getMap(mi->content,"length");
177          sprintf(emsg,_("ZOO-Kernel was unable to load your data for %s position %s."),mi->name,tmpMap->value);
178          errorException(m,emsg,"InternalError",NULL);
179          return -1;
180        }
181      }
182      else{
183        char emsg[1024];
184        sprintf(emsg,_("You set maximum occurences for <%s> to one but you tried to use it more than once. Please correct your ZCFG file or your request."),mi->name);
185        errorException(m,emsg,"InternalError",NULL);
186        return -1;
187      }
188    }
189  }
190  return 0;
191}
192
193int recursReaddirF(maps* m,xmlNodePtr n,char *conf_dir,char *prefix,int saved_stdout,int level,void (func) (maps*,xmlNodePtr,service*)){
194  struct dirent *dp;
195  int scount=0;
196
197  if(conf_dir==NULL)
198    return 1;
199  DIR *dirp = opendir(conf_dir);
200  if(dirp==NULL){
201    if(level>0)
202      return 1;
203    else
204      return -1;
205  }
206  char tmp1[25];
207  sprintf(tmp1,"sprefix_%d",level);
208  char levels[17];
209  sprintf(levels,"%d",level);
210  setMapInMaps(m,"lenv","level",levels);
211  while ((dp = readdir(dirp)) != NULL)
212    if((dp->d_type==DT_DIR || dp->d_type==DT_LNK) && dp->d_name[0]!='.' && strstr(dp->d_name,".")==NULL){
213
214      char *tmp=(char*)malloc((strlen(conf_dir)+strlen(dp->d_name)+2)*sizeof(char));
215      sprintf(tmp,"%s/%s",conf_dir,dp->d_name);
216
217      if(prefix!=NULL){
218        prefix=NULL;
219      }
220      prefix=(char*)malloc((strlen(dp->d_name)+2)*sizeof(char));
221      sprintf(prefix,"%s.",dp->d_name);
222     
223      //map* tmpMap=getMapFromMaps(m,"lenv",tmp1);
224     
225      int res;
226      if(prefix!=NULL){
227        setMapInMaps(m,"lenv",tmp1,prefix);
228        char levels1[17];
229        sprintf(levels1,"%d",level+1);
230        setMapInMaps(m,"lenv","level",levels1);
231        res=recursReaddirF(m,n,tmp,prefix,saved_stdout,level+1,func);
232        sprintf(levels1,"%d",level);
233        setMapInMaps(m,"lenv","level",levels1);
234        free(prefix);
235        prefix=NULL;
236      }else
237        res=-1;
238      free(tmp);
239      if(res<0){
240        return res;
241      }
242    }
243    else{
244      if(dp->d_name[0]!='.' && strstr(dp->d_name,".zcfg")!=0){
245        int t;
246        char tmps1[1024];
247        memset(tmps1,0,1024);
248        snprintf(tmps1,1024,"%s/%s",conf_dir,dp->d_name);
249        service* s1=(service*)malloc(SERVICE_SIZE);
250        if(s1 == NULL){ 
251          dup2(saved_stdout,fileno(stdout));
252          errorException(m, _("Unable to allocate memory."),"InternalError",NULL);
253          return -1;
254        }
255#ifdef DEBUG
256        fprintf(stderr,"#################\n%s\n#################\n",tmps1);
257#endif
258        t=readServiceFile(m,tmps1,&s1,dp->d_name);
259
260        if(t<0){
261          map* tmp00=getMapFromMaps(m,"lenv","message");
262          char tmp01[1024];
263          if(tmp00!=NULL)
264            sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),dp->d_name,tmp00->value);
265          else
266            sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),dp->d_name);
267          dup2(saved_stdout,fileno(stdout));
268          errorException(m, tmp01,"InternalError",NULL);
269          freeMaps(&m);
270          free(m);
271          return -1;
272        }
273#ifdef DEBUG
274        dumpService(s1);
275        fflush(stdout);
276        fflush(stderr);
277#endif
278        func(m,n,s1);
279        freeService(&s1);
280        free(s1);
281        scount++;
282      }
283    }
284  (void)closedir(dirp);
285  return 1;
286}
287
288xmlXPathObjectPtr extractFromDoc(xmlDocPtr doc,const char* search){
289  xmlXPathContextPtr xpathCtx;
290  xmlXPathObjectPtr xpathObj;
291  xpathCtx = xmlXPathNewContext(doc);
292  xpathObj = xmlXPathEvalExpression(BAD_CAST search,xpathCtx);
293  xmlXPathFreeContext(xpathCtx);
294  return xpathObj;
295}
296
297void donothing(int sig){
298#ifdef DEBUG
299  fprintf(stderr,"Signal %d after the ZOO-Kernel returned result !\n",sig);
300#endif
301  exit(0);
302}
303
304void sig_handler(int sig){
305  char tmp[100];
306  const char *ssig;
307  switch(sig){
308  case SIGSEGV:
309    ssig="SIGSEGV";
310    break;
311  case SIGTERM:
312    ssig="SIGTERM";
313    break;
314  case SIGINT:
315    ssig="SIGINT";
316    break;
317  case SIGILL:
318    ssig="SIGILL";
319    break;
320  case SIGFPE:
321    ssig="SIGFPE";
322    break;
323  case SIGABRT:
324    ssig="SIGABRT";
325    break;
326  default:
327    ssig="UNKNOWN";
328    break;
329  }
330  sprintf(tmp,_("ZOO Kernel failed to process your request receiving signal %d = %s"),sig,ssig);
331  errorException(NULL, tmp, "InternalError",NULL);
332#ifdef DEBUG
333  fprintf(stderr,"Not this time!\n");
334#endif
335  exit(0);
336}
337
338void loadServiceAndRun(maps **myMap,service* s1,map* request_inputs,maps **inputs,maps** ioutputs,int* eres){
339  char tmps1[1024];
340  char ntmp[1024];
341  maps *m=*myMap;
342  maps *request_output_real_format=*ioutputs;
343  maps *request_input_real_format=*inputs;
344  /**
345   * Extract serviceType to know what kind of service should be loaded
346   */
347  map* r_inputs=NULL;
348#ifndef WIN32
349  getcwd(ntmp,1024);
350#else
351  _getcwd(ntmp,1024);
352#endif
353  r_inputs=getMap(s1->content,"serviceType");
354#ifdef DEBUG
355  fprintf(stderr,"LOAD A %s SERVICE PROVIDER \n",r_inputs->value);
356  fflush(stderr);
357#endif
358  if(strlen(r_inputs->value)==1 && strncasecmp(r_inputs->value,"C",1)==0){
359    r_inputs=getMap(request_inputs,"metapath");
360    if(r_inputs!=NULL)
361      sprintf(tmps1,"%s/%s",ntmp,r_inputs->value);
362    else
363      sprintf(tmps1,"%s/",ntmp);
364    char *altPath=zStrdup(tmps1);
365    r_inputs=getMap(s1->content,"ServiceProvider");
366    sprintf(tmps1,"%s/%s",altPath,r_inputs->value);
367    free(altPath);
368#ifdef DEBUG
369    fprintf(stderr,"Trying to load %s\n",tmps1);
370#endif
371#ifdef WIN32
372    HINSTANCE so = LoadLibraryEx(tmps1,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
373#else
374    void* so = dlopen(tmps1, RTLD_LAZY);
375#endif
376#ifdef WIN32
377    DWORD errstr;
378    errstr = GetLastError();
379#else
380    char *errstr;
381    errstr = dlerror();
382#endif
383#ifdef DEBUG
384    fprintf(stderr,"%s loaded (%d) \n",tmps1,errstr);
385#endif
386    if( so != NULL ) {
387#ifdef DEBUG
388      fprintf(stderr,"Library loaded %s \n",errstr);
389      fprintf(stderr,"Service Shared Object = %s\n",r_inputs->value);
390#endif
391      r_inputs=getMap(s1->content,"serviceType");
392#ifdef DEBUG
393      dumpMap(r_inputs);
394      fprintf(stderr,"%s\n",r_inputs->value);
395      fflush(stderr);
396#endif
397      if(strncasecmp(r_inputs->value,"C-FORTRAN",9)==0){
398        r_inputs=getMap(request_inputs,"Identifier");
399        char fname[1024];
400        sprintf(fname,"%s_",r_inputs->value);
401#ifdef DEBUG
402        fprintf(stderr,"Try to load function %s\n",fname);
403#endif
404#ifdef WIN32
405        typedef int (CALLBACK* execute_t)(char***,char***,char***);
406        execute_t execute=(execute_t)GetProcAddress(so,fname);
407#else
408        typedef int (*execute_t)(char***,char***,char***);
409        execute_t execute=(execute_t)dlsym(so,fname);
410#endif
411#ifdef DEBUG
412#ifdef WIN32
413        errstr = GetLastError();
414#else
415        errstr = dlerror();
416#endif
417        fprintf(stderr,"Function loaded %s\n",errstr);
418#endif 
419
420        char main_conf[10][30][1024];
421        char inputs[10][30][1024];
422        char outputs[10][30][1024];
423        for(int i=0;i<10;i++){
424          for(int j=0;j<30;j++){
425            memset(main_conf[i][j],0,1024);
426            memset(inputs[i][j],0,1024);
427            memset(outputs[i][j],0,1024);
428          }
429        }
430        mapsToCharXXX(m,(char***)main_conf);
431        mapsToCharXXX(request_input_real_format,(char***)inputs);
432        mapsToCharXXX(request_output_real_format,(char***)outputs);
433        *eres=execute((char***)&main_conf[0],(char***)&inputs[0],(char***)&outputs[0]);
434#ifdef DEBUG
435        fprintf(stderr,"Function run successfully \n");
436#endif
437        charxxxToMaps((char***)&outputs[0],&request_output_real_format);
438      }else{
439#ifdef DEBUG
440#ifdef WIN32
441        errstr = GetLastError();
442        fprintf(stderr,"Function %s failed to load because of %d\n",r_inputs->value,errstr);
443#endif
444#endif
445        r_inputs=getMapFromMaps(m,"lenv","Identifier");
446#ifdef DEBUG
447        fprintf(stderr,"Try to load function %s\n",r_inputs->value);
448#endif
449        typedef int (*execute_t)(maps**,maps**,maps**);
450#ifdef WIN32
451        execute_t execute=(execute_t)GetProcAddress(so,r_inputs->value); 
452#else
453        execute_t execute=(execute_t)dlsym(so,r_inputs->value);
454#endif
455
456        if(execute==NULL){
457#ifdef WIN32
458          errstr = GetLastError();
459#else
460          errstr = dlerror();
461#endif
462          char *tmpMsg=(char*)malloc(2048+strlen(r_inputs->value));
463          sprintf(tmpMsg,_("Error occured while running the %s function: %s"),r_inputs->value,errstr);
464          errorException(m, tmpMsg, "InternalError",NULL);
465          free(tmpMsg);
466#ifdef DEBUG
467          fprintf(stderr,"Function %s error %s\n",r_inputs->value,errstr);
468#endif
469          *eres=-1;
470          return;
471        }
472
473#ifdef DEBUG
474#ifdef WIN32
475        errstr = GetLastError();
476#else
477        errstr = dlerror();
478#endif
479        fprintf(stderr,"Function loaded %s\n",errstr);
480#endif 
481
482#ifdef DEBUG
483        fprintf(stderr,"Now run the function \n");
484        fflush(stderr);
485#endif
486        *eres=execute(&m,&request_input_real_format,&request_output_real_format);
487#ifdef DEBUG
488        fprintf(stderr,"Function loaded and returned %d\n",eres);
489        fflush(stderr);
490#endif
491      }
492#ifdef WIN32
493      *ioutputs=dupMaps(&request_output_real_format);
494      FreeLibrary(so);
495#else
496      dlclose(so);
497#endif
498    } else {
499      /**
500       * Unable to load the specified shared library
501       */
502      char tmps[1024];
503#ifdef WIN32
504      DWORD errstr = GetLastError();
505#else
506      char* errstr = dlerror();
507#endif
508      sprintf(tmps,_("C Library can't be loaded %s"),errstr);
509      map* tmps1=createMap("text",tmps);
510      printExceptionReportResponse(m,tmps1);
511      *eres=-1;
512      freeMap(&tmps1);
513      free(tmps1);
514    }
515  }
516  else
517#ifdef USE_PYTHON
518    if(strncasecmp(r_inputs->value,"PYTHON",6)==0){
519      *eres=zoo_python_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
520    }
521    else
522#endif
523       
524#ifdef USE_JAVA
525      if(strncasecmp(r_inputs->value,"JAVA",4)==0){
526        *eres=zoo_java_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
527      }
528      else
529#endif
530
531#ifdef USE_PHP
532        if(strncasecmp(r_inputs->value,"PHP",3)==0){
533          *eres=zoo_php_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
534        }
535        else
536#endif
537           
538           
539#ifdef USE_PERL
540          if(strncasecmp(r_inputs->value,"PERL",4)==0){
541            *eres=zoo_perl_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
542          }
543          else
544#endif
545
546#ifdef USE_JS
547            if(strncasecmp(r_inputs->value,"JS",2)==0){
548              *eres=zoo_js_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
549            }
550            else
551#endif
552
553#ifdef USE_RUBY
554          if(strncasecmp(r_inputs->value,"Ruby",4)==0){
555            *eres=zoo_ruby_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
556          }
557          else
558#endif
559
560              {
561                char tmpv[1024];
562                sprintf(tmpv,_("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),r_inputs->value);
563                map* tmps=createMap("text",tmpv);
564                printExceptionReportResponse(m,tmps);
565                *eres=-1;
566              }
567  *myMap=m;
568  *ioutputs=request_output_real_format;
569}
570
571
572#ifdef WIN32
573/**
574 * createProcess function: create a new process after setting some env variables
575 */
576void createProcess(maps* m,map* request_inputs,service* s1,char* opts,int cpid, maps* inputs,maps* outputs){
577  STARTUPINFO si;
578  PROCESS_INFORMATION pi;
579  ZeroMemory( &si, sizeof(si) );
580  si.cb = sizeof(si);
581  ZeroMemory( &pi, sizeof(pi) );
582  char *tmp=(char *)malloc((1024+cgiContentLength)*sizeof(char));
583  char *tmpq=(char *)malloc((1024+cgiContentLength)*sizeof(char));
584  map *req=getMap(request_inputs,"request");
585  map *id=getMap(request_inputs,"identifier");
586  map *di=getMap(request_inputs,"DataInputs");
587
588  char *dataInputsKVP=getMapsAsKVP(inputs,cgiContentLength,0);
589  char *dataOutputsKVP=getMapsAsKVP(outputs,cgiContentLength,1);
590#ifdef DEBUG
591  fprintf(stderr,"DATAINPUTSKVP %s\n",dataInputsKVP);
592  fprintf(stderr,"DATAOUTPUTSKVP %s\n",dataOutputsKVP);
593#endif
594  map *sid=getMapFromMaps(m,"lenv","sid");
595  map* r_inputs=getMapFromMaps(m,"main","tmpPath");
596  map* r_inputs1=getMap(request_inputs,"metapath");
597  int hasIn=-1;
598  if(r_inputs1==NULL){
599    r_inputs1=createMap("metapath","");
600    hasIn=1;
601  }
602  map* r_inputs2=getMap(request_inputs,"ResponseDocument");
603  if(r_inputs2==NULL)
604    r_inputs2=getMap(request_inputs,"RawDataOutput");
605  map *tmpPath=getMapFromMaps(m,"lenv","cwd");
606
607  map *tmpReq=getMap(request_inputs,"xrequest");
608  if(r_inputs2!=NULL){
609    sprintf(tmp,"\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s&cgiSid=%s\"",r_inputs1->value,req->value,id->value,dataInputsKVP,r_inputs2->name,dataOutputsKVP,sid->value);
610    sprintf(tmpq,"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s",r_inputs1->value,req->value,id->value,dataInputsKVP,r_inputs2->name,dataOutputsKVP);
611  }
612  else{
613    sprintf(tmp,"\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&cgiSid=%s\"",r_inputs1->value,req->value,id->value,dataInputsKVP,sid->value);
614    sprintf(tmpq,"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s",r_inputs1->value,req->value,id->value,dataInputsKVP,sid->value);
615  }
616 
617  if(hasIn>0){
618    freeMap(&r_inputs1);
619    free(r_inputs1);
620  }
621  char *tmp1=zStrdup(tmp);
622  sprintf(tmp,"\"zoo_loader.cgi\" %s \"%s\"",tmp1,sid->value);
623 
624  free(dataInputsKVP);
625  free(dataOutputsKVP);
626#ifdef DEBUG
627  fprintf(stderr,"REQUEST IS : %s \n",tmp);
628#endif
629  SetEnvironmentVariable("CGISID",TEXT(sid->value));
630  SetEnvironmentVariable("QUERY_STRING",TEXT(tmpq));
631  char clen[1000];
632  sprintf(clen,"%d",strlen(tmpq));
633  SetEnvironmentVariable("CONTENT_LENGTH",TEXT(clen));
634 
635  if( !CreateProcess( NULL,             // No module name (use command line)
636                      TEXT(tmp),        // Command line
637                      NULL,             // Process handle not inheritable
638                      NULL,             // Thread handle not inheritable
639                      FALSE,            // Set handle inheritance to FALSE
640                      CREATE_NO_WINDOW, // Apache won't wait until the end
641                      NULL,             // Use parent's environment block
642                      NULL,             // Use parent's starting directory
643                      &si,              // Pointer to STARTUPINFO struct
644                      &pi )             // Pointer to PROCESS_INFORMATION struct
645      ) 
646    { 
647#ifdef DEBUG
648      fprintf( stderr, "CreateProcess failed (%d).\n", GetLastError() );
649#endif
650      return ;
651    }else{
652#ifdef DEBUG
653    fprintf( stderr, "CreateProcess successfull (%d).\n\n\n\n", GetLastError() );
654#endif
655  }
656  CloseHandle( pi.hProcess );
657  CloseHandle( pi.hThread );
658#ifdef DEBUG
659  fprintf(stderr,"CreateProcess finished !\n");
660#endif
661}
662#endif
663
664int runRequest(map** inputs)
665{
666 
667#ifndef USE_GDB
668  (void) signal(SIGSEGV,sig_handler);
669  (void) signal(SIGTERM,sig_handler);
670  (void) signal(SIGINT,sig_handler);
671  (void) signal(SIGILL,sig_handler);
672  (void) signal(SIGFPE,sig_handler);
673  (void) signal(SIGABRT,sig_handler);
674#endif
675
676  map* r_inputs=NULL;
677  map* request_inputs=*inputs;
678  maps* m=NULL;
679  char* REQUEST=NULL;
680  /**
681   * Parsing service specfic configuration file
682   */
683  m=(maps*)malloc(MAPS_SIZE);
684  if(m == NULL){
685    return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
686  }
687  char ntmp[1024];
688#ifndef WIN32
689  getcwd(ntmp,1024);
690#else
691  _getcwd(ntmp,1024);
692#endif
693  r_inputs=getMapOrFill(&request_inputs,"metapath","");
694
695
696  char conf_file[10240];
697  snprintf(conf_file,10240,"%s/%s/main.cfg",ntmp,r_inputs->value);
698  if(conf_read(conf_file,m)==2){
699    errorException(NULL, _("Unable to load the main.cfg file."),"InternalError",NULL);
700    free(m);
701    return 1;
702  }
703#ifdef DEBUG
704  fprintf(stderr, "***** BEGIN MAPS\n"); 
705  dumpMaps(m);
706  fprintf(stderr, "***** END MAPS\n");
707#endif
708
709  map *getPath=getMapFromMaps(m,"main","gettextPath");
710  if(getPath!=NULL){
711    bindtextdomain ("zoo-kernel",getPath->value);
712    bindtextdomain ("zoo-services",getPath->value);   
713  }else{
714    bindtextdomain ("zoo-kernel","/usr/share/locale/");
715    bindtextdomain ("zoo-services","/usr/share/locale/");
716  }
717
718
719  /**
720   * Manage our own error log file (usefull to separate standard apache debug
721   * messages from the ZOO-Kernel ones but also for IIS users to avoid wrong
722   * headers messages returned by the CGI due to wrong redirection of stderr)
723   */
724  FILE * fstde=NULL;
725  map* fstdem=getMapFromMaps(m,"main","logPath");
726  if(fstdem!=NULL)
727    fstde = freopen(fstdem->value, "a+", stderr) ;
728
729  r_inputs=getMap(request_inputs,"language");
730  if(r_inputs==NULL)
731    r_inputs=getMapFromMaps(m,"main","language");
732  if(r_inputs!=NULL){
733    if(isValidLang(m,r_inputs->value)<0){
734      char tmp[1024];
735      sprintf(tmp,_("The value %s is not supported for the <language> parameter"),
736              r_inputs->value);
737      errorException(m, tmp,"InvalidParameterValue","language");
738      freeMaps(&m);
739      free(m);
740      free(REQUEST);
741      return 1;
742
743    }
744    char *tmp=zStrdup(r_inputs->value);
745    setMapInMaps(m,"main","language",tmp);
746#ifdef DEB
747    char tmp2[12];
748    sprintf(tmp2,"%s.utf-8",tmp);
749    translateChar(tmp2,'-','_');
750    setlocale (LC_ALL, tmp2);
751#else
752    translateChar(tmp,'-','_');
753    setlocale (LC_ALL, tmp);
754#endif
755#ifndef WIN32
756    setenv("LC_ALL",tmp,1);
757#else
758    char tmp1[12];
759    sprintf(tmp1,"LC_ALL=%s",tmp);
760    putenv(tmp1);
761#endif
762    free(tmp);
763  }
764  else{
765    setlocale (LC_ALL, "en_US");
766#ifndef WIN32
767    setenv("LC_ALL","en_US",1);
768#else
769    char tmp1[12];
770    sprintf(tmp1,"LC_ALL=en_US");
771    putenv(tmp1);
772#endif
773    setMapInMaps(m,"main","language","en-US");
774  }
775  setlocale (LC_NUMERIC, "en_US");
776  bind_textdomain_codeset("zoo-kernel","UTF-8");
777  textdomain("zoo-kernel");
778  bind_textdomain_codeset("zoo-services","UTF-8");
779  textdomain("zoo-services");
780
781  map* lsoap=getMap(request_inputs,"soap");
782  if(lsoap!=NULL && strcasecmp(lsoap->value,"true")==0)
783    setMapInMaps(m,"main","isSoap","true");
784  else
785    setMapInMaps(m,"main","isSoap","false");
786
787  if(strlen(cgiServerName)>0){
788    char tmpUrl[1024];
789    if(strncmp(cgiServerPort,"80",2)==0){
790      sprintf(tmpUrl,"http://%s%s",cgiServerName,cgiScriptName);
791    }else{
792      sprintf(tmpUrl,"http://%s:%s%s",cgiServerName,cgiServerPort,cgiScriptName);
793    }
794#ifdef DEBUG
795    fprintf(stderr,"*** %s ***\n",tmpUrl);
796#endif
797    setMapInMaps(m,"main","serverAddress",tmpUrl);
798  }
799
800  /**
801   * Check for minimum inputs
802   */
803  r_inputs=getMap(request_inputs,"Request");
804  if(request_inputs==NULL || r_inputs==NULL){ 
805    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue","request");
806    if(count(request_inputs)==1){
807      freeMap(&request_inputs);
808      free(request_inputs);
809    }
810    freeMaps(&m);
811    free(m);
812    return 1;
813  }
814  else{
815    REQUEST=zStrdup(r_inputs->value);
816    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
817       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
818       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
819      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "OperationNotSupported",r_inputs->value);
820      freeMaps(&m);
821      free(m);
822      free(REQUEST);
823      return 1;
824    }
825  }
826  r_inputs=NULL;
827  r_inputs=getMap(request_inputs,"Service");
828  if(r_inputs==NULLMAP){
829    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue","service");
830    freeMaps(&m);
831    free(m);
832    free(REQUEST);
833    return 1;
834  }else{
835    if(strcasecmp(r_inputs->value,"WPS")!=0){
836      errorException(m, _("Unenderstood <service> value, WPS is the only acceptable value."), "InvalidParameterValue","service");
837      freeMaps(&m);
838      free(m);
839      free(REQUEST);
840      return 1;
841    }
842  }
843  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
844    r_inputs=getMap(request_inputs,"Version");
845    if(r_inputs==NULL){ 
846      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue","version");
847      freeMaps(&m);
848      free(m);
849      free(REQUEST);
850      return 1;
851    }else{
852      if(strcasecmp(r_inputs->value,"1.0.0")!=0){
853        errorException(m, _("Unenderstood <version> value, 1.0.0 is the only acceptable value."), "InvalidParameterValue","service");
854        freeMaps(&m);
855        free(m);
856        free(REQUEST);
857        return 1;
858      }
859    } 
860  }else{
861    r_inputs=getMap(request_inputs,"AcceptVersions");
862    if(r_inputs!=NULL){ 
863      if(strncmp(r_inputs->value,"1.0.0",5)!=0){
864        errorException(m, _("Unenderstood <AcceptVersions> value, 1.0.0 is the only acceptable value."), "VersionNegotiationFailed",NULL);
865        freeMaps(&m);
866        free(m);
867        free(REQUEST);
868        return 1;
869      }
870    }
871  }
872
873  r_inputs=getMap(request_inputs,"serviceprovider");
874  if(r_inputs==NULL){
875    addToMap(request_inputs,"serviceprovider","");
876  }
877
878  maps* request_output_real_format=NULL;
879  map* tmpm=getMapFromMaps(m,"main","serverAddress");
880  if(tmpm!=NULL)
881    SERVICE_URL=zStrdup(tmpm->value);
882  else
883    SERVICE_URL=zStrdup(DEFAULT_SERVICE_URL);
884
885  service* s1;
886  int scount=0;
887#ifdef DEBUG
888  dumpMap(r_inputs);
889#endif
890  char conf_dir[1024];
891  int t;
892  char tmps1[1024];
893
894  r_inputs=NULL;
895  r_inputs=getMap(request_inputs,"metapath");
896  if(r_inputs!=NULL)
897    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
898  else
899    snprintf(conf_dir,1024,"%s",ntmp);
900
901  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
902#ifdef DEBUG
903    dumpMap(r_inputs);
904#endif
905    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
906    r_inputs=NULL;
907    r_inputs=getMap(request_inputs,"ServiceProvider");
908    xmlNodePtr n;
909    if(r_inputs!=NULL)
910      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
911    else
912      n = printGetCapabilitiesHeader(doc,"",m);
913    /**
914     * Here we need to close stdout to ensure that not supported chars
915     * has been found in the zcfg and then printed on stdout
916     */
917    int saved_stdout = dup(fileno(stdout));
918    dup2(fileno(stderr),fileno(stdout));
919    if(int res=recursReaddirF(m,n,conf_dir,NULL,saved_stdout,0,printGetCapabilitiesForProcess)<0){
920      freeMaps(&m);
921      free(m);
922      free(REQUEST);
923      free(SERVICE_URL);
924      fflush(stdout);
925      return res;
926    }
927    dup2(saved_stdout,fileno(stdout));
928    printDocument(m,doc,getpid());
929    freeMaps(&m);
930    free(m);
931    free(REQUEST);
932    free(SERVICE_URL);
933    fflush(stdout);
934    return 0;
935  }
936  else{
937    r_inputs=getMap(request_inputs,"Identifier");
938    if(r_inputs==NULL 
939       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
940      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue","identifier");
941      freeMaps(&m);
942      free(m);
943      free(REQUEST);
944      free(SERVICE_URL);
945      return 0;
946    }
947
948    struct dirent *dp;
949    DIR *dirp = opendir(conf_dir);
950    if(dirp==NULL){
951      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue",conf_dir);
952      freeMaps(&m);
953      free(m);
954      free(REQUEST);
955      free(SERVICE_URL);
956      return 0;
957    }
958    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
959      /**
960       * Loop over Identifier list
961       */
962      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
963      r_inputs=NULL;
964      r_inputs=getMap(request_inputs,"ServiceProvider");
965
966      xmlNodePtr n;
967      if(r_inputs!=NULL)
968        n = printDescribeProcessHeader(doc,r_inputs->value,m);
969      else
970        n = printDescribeProcessHeader(doc,"",m);
971
972      r_inputs=getMap(request_inputs,"Identifier");
973     
974      char *orig=zStrdup(r_inputs->value);
975
976      int saved_stdout = dup(fileno(stdout));
977      dup2(fileno(stderr),fileno(stdout));
978      if(strcasecmp("all",orig)==0){
979        if(int res=recursReaddirF(m,n,conf_dir,NULL,saved_stdout,0,printDescribeProcessForProcess)<0)
980          return res;
981      }
982      else{
983        char *saveptr;
984        char *tmps=strtok_r(orig,",",&saveptr);
985       
986        char buff[256];
987        char buff1[1024];
988        while(tmps!=NULL){
989          int hasVal=-1;
990          char *corig=strdup(tmps);
991          if(strstr(corig,".")!=NULL){
992            parseIdentifier(m,conf_dir,corig,buff1);
993            s1=(service*)malloc(SERVICE_SIZE);
994            t=readServiceFile(m,buff1,&s1,corig);
995
996            if(t<0){
997              map* tmp00=getMapFromMaps(m,"lenv","message");
998              char tmp01[1024];
999              if(tmp00!=NULL)
1000                sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),dp->d_name,tmp00->value);
1001              else
1002                sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),dp->d_name);
1003              dup2(saved_stdout,fileno(stdout));
1004              errorException(m, tmp01,"InternalError",NULL);
1005              freeMaps(&m);
1006              free(m);
1007              free(REQUEST);
1008              return 1;
1009            }
1010#ifdef DEBUG
1011            dumpService(s1);
1012#endif
1013            printDescribeProcessForProcess(m,n,s1);
1014            freeService(&s1);
1015            free(s1);
1016            s1=NULL;
1017            scount++;
1018            setMapInMaps(m,"lenv","level","0");
1019          }
1020         
1021          memset(buff,0,256);
1022          snprintf(buff,256,"%s.zcfg",corig);
1023          free(corig);
1024          memset(buff1,0,1024);
1025#ifdef DEBUG
1026          printf("\n#######%s\n########\n",buff);
1027#endif
1028          while ((dp = readdir(dirp)) != NULL){
1029            if( strcasecmp(dp->d_name,buff)==0 ){
1030              memset(buff1,0,1024);
1031              snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
1032              s1=(service*)malloc(SERVICE_SIZE);
1033              if(s1 == NULL){
1034                dup2(saved_stdout,fileno(stdout));
1035                return errorException(m, _("Unable to allocate memory."),"InternalError",NULL);
1036              }
1037#ifdef DEBUG
1038              printf("#################\n(%s) %s\n#################\n",r_inputs->value,buff1);
1039#endif
1040              char *tmp0=zStrdup(dp->d_name);
1041              tmp0[strlen(tmp0)-5]=0;
1042              t=readServiceFile(m,buff1,&s1,tmp0);
1043              free(tmp0);
1044              if(t<0){
1045                map* tmp00=getMapFromMaps(m,"lenv","message");
1046                char tmp01[1024];
1047                if(tmp00!=NULL)
1048                  sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),dp->d_name,tmp00->value);
1049                else
1050                  sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),dp->d_name);
1051                dup2(saved_stdout,fileno(stdout));
1052                errorException(m, tmp01,"InternalError",NULL);
1053                freeMaps(&m);
1054                free(m);
1055                free(orig);
1056                free(REQUEST);
1057                closedir(dirp);
1058                xmlFreeDoc(doc);
1059                return 1;
1060              }
1061#ifdef DEBUG
1062              dumpService(s1);
1063#endif
1064              printDescribeProcessForProcess(m,n,s1);
1065              freeService(&s1);
1066              free(s1);
1067              s1=NULL;
1068              scount++;
1069              hasVal=1;
1070            }
1071          }
1072          if(hasVal<0){
1073            map* tmp00=getMapFromMaps(m,"lenv","message");
1074            char tmp01[1024];
1075            if(tmp00!=NULL)
1076              sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),buff,tmp00->value);
1077            else
1078              sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),buff);
1079            dup2(saved_stdout,fileno(stdout));
1080            errorException(m, tmp01,"InvalidParameterValue","Identifier");
1081            freeMaps(&m);
1082            free(m);
1083            free(orig);
1084            free(REQUEST);
1085            closedir(dirp);
1086            xmlFreeDoc(doc);
1087            return 1;
1088          }
1089          rewinddir(dirp);
1090          tmps=strtok_r(NULL,",",&saveptr);
1091        }
1092      }
1093      closedir(dirp);
1094      fflush(stdout);
1095      dup2(saved_stdout,fileno(stdout));
1096      free(orig);
1097      printDocument(m,doc,getpid());
1098      freeMaps(&m);
1099      free(m);
1100      free(REQUEST);
1101      free(SERVICE_URL);
1102      fflush(stdout);
1103      return 0;
1104    }
1105    else
1106      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
1107        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue","request");
1108#ifdef DEBUG
1109        fprintf(stderr,"No request found %s",REQUEST);
1110#endif 
1111        closedir(dirp);
1112        freeMaps(&m);
1113        free(m);
1114        free(REQUEST);
1115        free(SERVICE_URL);
1116        fflush(stdout);
1117        return 0;
1118      }
1119    closedir(dirp);
1120  }
1121 
1122  s1=NULL;
1123  s1=(service*)malloc(SERVICE_SIZE);
1124  if(s1 == NULL){
1125    freeMaps(&m);
1126    free(m);
1127    free(REQUEST);
1128    free(SERVICE_URL);
1129    return errorException(m, _("Unable to allocate memory."),"InternalError",NULL);
1130  }
1131  r_inputs=getMap(request_inputs,"MetaPath");
1132  if(r_inputs!=NULL)
1133    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
1134  else
1135    snprintf(tmps1,1024,"%s/",ntmp);
1136  r_inputs=getMap(request_inputs,"Identifier");
1137  char *ttmp=zStrdup(tmps1);
1138  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
1139  free(ttmp);
1140#ifdef DEBUG
1141  fprintf(stderr,"Trying to load %s\n", tmps1);
1142#endif
1143  if(strstr(r_inputs->value,".")!=NULL){
1144    char *identifier=zStrdup(r_inputs->value);
1145    parseIdentifier(m,conf_dir,identifier,tmps1);
1146    map* tmpMap=getMapFromMaps(m,"lenv","metapath");
1147    if(tmpMap!=NULL)
1148      addToMap(request_inputs,"metapath",tmpMap->value);
1149    free(identifier);
1150  }else
1151    setMapInMaps(m,"lenv","Identifier",r_inputs->value);
1152  int saved_stdout = dup(fileno(stdout));
1153  dup2(fileno(stderr),fileno(stdout));
1154  t=readServiceFile(m,tmps1,&s1,r_inputs->value);
1155  fflush(stdout);
1156  dup2(saved_stdout,fileno(stdout));
1157  if(t<0){
1158    char *tmpMsg=(char*)malloc(2048+strlen(r_inputs->value));
1159    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
1160    errorException(m, tmpMsg, "InvalidParameterValue","identifier");
1161    free(tmpMsg);
1162    free(s1);
1163    freeMaps(&m);
1164    free(m);
1165    free(REQUEST);
1166    free(SERVICE_URL);
1167    return 0;
1168  }
1169  close(saved_stdout);
1170
1171#ifdef DEBUG
1172  dumpService(s1);
1173#endif
1174  int j;
1175 
1176
1177  /**
1178   * Create the input and output maps data structure
1179   */
1180  int i=0;
1181  HINTERNET hInternet;
1182  HINTERNET res;
1183  hInternet=InternetOpen(
1184#ifndef WIN32
1185                         (LPCTSTR)
1186#endif
1187                         "ZooWPSClient\0",
1188                         INTERNET_OPEN_TYPE_PRECONFIG,
1189                         NULL,NULL, 0);
1190
1191#ifndef WIN32
1192  if(!CHECK_INET_HANDLE(hInternet))
1193    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1194#endif
1195  maps* request_input_real_format=NULL;
1196  maps* tmpmaps = request_input_real_format;
1197  map* postRequest=NULL;
1198  postRequest=getMap(request_inputs,"xrequest");
1199  if(postRequest==NULLMAP){
1200    /**
1201     * Parsing outputs provided as KVP
1202     */
1203    r_inputs=NULL;
1204#ifdef DEBUG
1205    fprintf(stderr,"OUTPUT Parsing ... \n");
1206#endif
1207    r_inputs=getMap(request_inputs,"ResponseDocument"); 
1208    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
1209   
1210#ifdef DEBUG
1211    fprintf(stderr,"OUTPUT Parsing ... \n");
1212#endif
1213    if(r_inputs!=NULL){
1214#ifdef DEBUG
1215      fprintf(stderr,"OUTPUT Parsing start now ... \n");
1216#endif
1217      char cursor_output[10240];
1218      char *cotmp=zStrdup(r_inputs->value);
1219      snprintf(cursor_output,10240,"%s",cotmp);
1220      free(cotmp);
1221      j=0;
1222       
1223      /**
1224       * Put each Output into the outputs_as_text array
1225       */
1226      char * pToken;
1227      maps* tmp_output=NULL;
1228#ifdef DEBUG
1229      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
1230#endif
1231      pToken=strtok(cursor_output,";");
1232      char** outputs_as_text=(char**)malloc(128*sizeof(char*));
1233      if(outputs_as_text == NULL) {
1234        return errorException(m, _("Unable to allocate memory"), "InternalError",NULL);
1235      }
1236      i=0;
1237      while(pToken!=NULL){
1238#ifdef DEBUG
1239        fprintf(stderr,"***%s***\n",pToken);
1240        fflush(stderr);
1241        fprintf(stderr,"***%s***\n",pToken);
1242#endif
1243        outputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
1244        if(outputs_as_text[i] == NULL) {
1245          return errorException(m, _("Unable to allocate memory"), "InternalError",NULL);
1246        }
1247        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
1248        pToken = strtok(NULL,";");
1249        i++;
1250      }
1251      for(j=0;j<i;j++){
1252        char *tmp=zStrdup(outputs_as_text[j]);
1253        free(outputs_as_text[j]);
1254        char *tmpc;
1255        tmpc=strtok(tmp,"@");
1256        int k=0;
1257        while(tmpc!=NULL){
1258          if(k==0){
1259            if(tmp_output==NULL){
1260              tmp_output=(maps*)malloc(MAPS_SIZE);
1261              if(tmp_output == NULL){
1262                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1263              }
1264              tmp_output->name=zStrdup(tmpc);
1265              tmp_output->content=NULL;
1266              tmp_output->next=NULL;
1267            }
1268          }
1269          else{
1270            char *tmpv=strstr(tmpc,"=");
1271            char tmpn[256];
1272            memset(tmpn,0,256);
1273            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1274            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1275#ifdef DEBUG
1276            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
1277#endif
1278            if(tmp_output->content==NULL){
1279              tmp_output->content=createMap(tmpn,tmpv+1);
1280              tmp_output->content->next=NULL;
1281            }
1282            else
1283              addToMap(tmp_output->content,tmpn,tmpv+1);
1284          }
1285          k++;
1286#ifdef DEBUG
1287          fprintf(stderr,"***%s***\n",tmpc);
1288#endif
1289          tmpc=strtok(NULL,"@");
1290        }
1291        if(request_output_real_format==NULL)
1292          request_output_real_format=dupMaps(&tmp_output);
1293        else
1294          addMapsToMaps(&request_output_real_format,tmp_output);
1295        freeMaps(&tmp_output);
1296        free(tmp_output);
1297        tmp_output=NULL;
1298#ifdef DEBUG
1299        dumpMaps(tmp_output);
1300        fflush(stderr);
1301#endif
1302        free(tmp);
1303      }
1304      free(outputs_as_text);
1305    }
1306
1307
1308    /**
1309     * Parsing inputs provided as KVP
1310     */
1311    r_inputs=getMap(request_inputs,"DataInputs");
1312#ifdef DEBUG
1313    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
1314#endif
1315    char cursor_input[40960];
1316    if(r_inputs!=NULL)
1317      snprintf(cursor_input,40960,"%s",r_inputs->value);
1318    else{
1319      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue","DataInputs");
1320      freeMaps(&m);
1321      free(m);
1322      free(REQUEST);
1323      free(SERVICE_URL);
1324      InternetCloseHandle(&hInternet);
1325      freeService(&s1);
1326      free(s1);
1327      return 0;
1328    }
1329    j=0;
1330 
1331    /**
1332     * Put each DataInputs into the inputs_as_text array
1333     */
1334    char *tmp1=zStrdup(cursor_input);
1335    char * pToken;
1336    pToken=strtok(cursor_input,";");
1337    if(pToken!=NULL && strncasecmp(pToken,tmp1,strlen(tmp1))==0){
1338      char* tmp2=url_decode(tmp1);
1339      snprintf(cursor_input,(strlen(tmp2)+1)*sizeof(char),"%s",tmp2);
1340      free(tmp2);
1341      pToken=strtok(cursor_input,";");
1342    }
1343    free(tmp1);
1344
1345    char** inputs_as_text=(char**)malloc(100*sizeof(char*));
1346    if(inputs_as_text == NULL){
1347      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1348    }
1349    i=0;
1350    while(pToken!=NULL){
1351#ifdef DEBUG
1352      fprintf(stderr,"***%s***\n",pToken);
1353#endif
1354      fflush(stderr);
1355#ifdef DEBUG
1356      fprintf(stderr,"***%s***\n",pToken);
1357#endif
1358      inputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
1359      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
1360      if(inputs_as_text[i] == NULL){
1361        return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1362      }
1363      pToken = strtok(NULL,";");
1364      i++;
1365    }
1366
1367    for(j=0;j<i;j++){
1368      char *tmp=zStrdup(inputs_as_text[j]);
1369      free(inputs_as_text[j]);
1370      char *tmpc;
1371      tmpc=strtok(tmp,"@");
1372      while(tmpc!=NULL){
1373#ifdef DEBUG
1374        fprintf(stderr,"***\n***%s***\n",tmpc);
1375#endif
1376        char *tmpv=strstr(tmpc,"=");
1377        char tmpn[256];
1378        memset(tmpn,0,256);
1379        if(tmpv!=NULL){
1380          strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1381          tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1382        }
1383        else{
1384          strncpy(tmpn,tmpc,strlen(tmpc)*sizeof(char));
1385          tmpn[strlen(tmpc)]=0;
1386        }
1387#ifdef DEBUG
1388        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
1389#endif
1390        if(tmpmaps==NULL){
1391          tmpmaps=(maps*)malloc(MAPS_SIZE);
1392          if(tmpmaps == NULL){
1393            return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1394          }
1395          tmpmaps->name=zStrdup(tmpn);
1396          if(tmpv!=NULL){
1397            char *tmpvf=url_decode(tmpv+1);
1398            tmpmaps->content=createMap("value",tmpvf);
1399            free(tmpvf);
1400          }
1401          else
1402            tmpmaps->content=createMap("value","Reference");
1403          tmpmaps->next=NULL;
1404        }
1405        tmpc=strtok(NULL,"@");
1406        while(tmpc!=NULL){
1407#ifdef DEBUG
1408          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
1409#endif
1410          char *tmpv1=strstr(tmpc,"=");
1411#ifdef DEBUG
1412          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1413#endif
1414          char tmpn1[1024];
1415          memset(tmpn1,0,1024);
1416          if(tmpv1!=NULL){
1417            strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
1418            tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
1419            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1420          }
1421          else{
1422            strncpy(tmpn1,tmpc,strlen(tmpc));
1423            tmpn1[strlen(tmpc)]=0;
1424            map* lmap=getLastMap(tmpmaps->content);
1425            char *tmpValue=(char*)malloc((strlen(tmpv)+strlen(tmpc)+1)*sizeof(char));
1426            sprintf(tmpValue,"%s@%s",tmpv+1,tmpc);
1427            free(lmap->value);
1428            lmap->value=zStrdup(tmpValue);
1429            free(tmpValue);
1430            tmpc=strtok(NULL,"@");
1431            continue;
1432          }
1433#ifdef DEBUG
1434          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
1435          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1436#endif
1437          if(strcmp(tmpn1,"xlink:href")!=0)
1438            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1439          else
1440            if(tmpv1!=NULL){
1441              char *tmpx2=url_decode(tmpv1+1);
1442              if(strncasecmp(tmpx2,"http://",7)!=0 &&
1443                 strncasecmp(tmpx2,"ftp://",6)!=0 &&
1444                 strncasecmp(tmpx2,"https://",8)!=0){
1445                char emsg[1024];
1446                sprintf(emsg,_("Unable to find a valid protocol to download the remote file %s"),tmpv1+1);
1447                errorException(m,emsg,"InternalError",NULL);
1448                freeMaps(&m);
1449                free(m);
1450                free(REQUEST);
1451                free(SERVICE_URL);
1452                InternetCloseHandle(&hInternet);
1453                freeService(&s1);
1454                free(s1);
1455                return 0;
1456              }
1457#ifdef DEBUG
1458              fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
1459#endif
1460              addToMap(tmpmaps->content,tmpn1,tmpx2);         
1461#ifndef WIN32
1462              if(CHECK_INET_HANDLE(hInternet))
1463#endif
1464                {
1465                  if(loadRemoteFile(&m,&tmpmaps->content,&hInternet,tmpx2)<0){
1466                    freeMaps(&m);
1467                    free(m);
1468                    free(REQUEST);
1469                    free(SERVICE_URL);
1470                    InternetCloseHandle(&hInternet);
1471                    freeService(&s1);
1472                    free(s1);
1473                    return 0;
1474                  }
1475                }
1476              free(tmpx2);
1477              addToMap(tmpmaps->content,"Reference",tmpv1+1);
1478            }
1479          tmpc=strtok(NULL,"@");
1480        }
1481#ifdef DEBUG
1482        dumpMaps(tmpmaps);
1483        fflush(stderr);
1484#endif
1485        if(request_input_real_format==NULL)
1486          request_input_real_format=dupMaps(&tmpmaps);
1487        else{
1488          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1489          if(testPresence!=NULL){
1490            elements* elem=getElements(s1->inputs,tmpmaps->name);
1491            if(elem!=NULL){
1492              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1493                freeMaps(&m);
1494                free(m);
1495                free(REQUEST);
1496                free(SERVICE_URL);
1497                InternetCloseHandle(&hInternet);
1498                freeService(&s1);
1499                free(s1);
1500                return 0;
1501              }
1502            }
1503          }
1504          else
1505            addMapsToMaps(&request_input_real_format,tmpmaps);
1506        }
1507        freeMaps(&tmpmaps);
1508        free(tmpmaps);
1509        tmpmaps=NULL;
1510        free(tmp);
1511      }
1512    }
1513    free(inputs_as_text);
1514  }
1515  else {
1516    /**
1517     * Parse XML request
1518     */ 
1519    xmlInitParser();
1520#ifdef DEBUG
1521    fflush(stderr);
1522    fprintf(stderr,"BEFORE %s\n",postRequest->value);
1523    fflush(stderr);
1524#endif
1525    xmlDocPtr doc =
1526      xmlParseMemory(postRequest->value,cgiContentLength);
1527#ifdef DEBUG
1528    fprintf(stderr,"AFTER\n");
1529    fflush(stderr);
1530#endif
1531    /**
1532     * Parse every Input in DataInputs node.
1533     */
1534    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1535    xmlNodeSet* tmps=tmpsptr->nodesetval;
1536#ifdef DEBUG
1537    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1538#endif
1539    for(int k=0;k<tmps->nodeNr;k++){
1540      maps *tmpmaps=NULL;
1541      xmlNodePtr cur=tmps->nodeTab[k];
1542      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1543        /**
1544         * A specific Input node.
1545         */
1546#ifdef DEBUG
1547        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1548#endif
1549        xmlNodePtr cur2=cur->children;
1550        while(cur2!=NULL){
1551          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1552            cur2=cur2->next;
1553          if(cur2==NULL)
1554            break;
1555          /**
1556           * Indentifier
1557           */
1558          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1559            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1560            if(tmpmaps==NULL){
1561              tmpmaps=(maps*)malloc(MAPS_SIZE);
1562              if(tmpmaps == NULL){
1563                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1564              }
1565              tmpmaps->name=zStrdup((char*)val);
1566              tmpmaps->content=NULL;
1567              tmpmaps->next=NULL;
1568            }
1569            xmlFree(val);
1570          }
1571          /**
1572           * Title, Asbtract
1573           */
1574          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1575             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1576            xmlChar *val=
1577              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1578            if(tmpmaps==NULL){
1579              tmpmaps=(maps*)malloc(MAPS_SIZE);
1580              if(tmpmaps == NULL){
1581                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1582              }
1583              tmpmaps->name=zStrdup("missingIndetifier");
1584              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1585              tmpmaps->next=NULL;
1586            }
1587            else{
1588              if(tmpmaps->content!=NULL)
1589                addToMap(tmpmaps->content,
1590                         (char*)cur2->name,(char*)val);
1591              else
1592                tmpmaps->content=
1593                  createMap((char*)cur2->name,(char*)val);
1594            }
1595#ifdef DEBUG
1596            dumpMaps(tmpmaps);
1597#endif
1598            xmlFree(val);
1599          }
1600          /**
1601           * InputDataFormChoice (Reference or Data ?)
1602           */
1603          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1604            /**
1605             * Get every attribute from a Reference node
1606             * mimeType, encoding, schema, href, method
1607             * Header and Body gesture should be added here
1608             */
1609#ifdef DEBUG
1610            fprintf(stderr,"REFERENCE\n");
1611#endif
1612            const char *refs[5]={"mimeType","encoding","schema","method","href"};
1613            for(int l=0;l<5;l++){
1614#ifdef DEBUG
1615              fprintf(stderr,"*** %s ***",refs[l]);
1616#endif
1617              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1618              if(val!=NULL && xmlStrlen(val)>0){
1619                if(tmpmaps->content!=NULL)
1620                  addToMap(tmpmaps->content,refs[l],(char*)val);
1621                else
1622                  tmpmaps->content=createMap(refs[l],(char*)val);
1623                map* ltmp=getMap(tmpmaps->content,"method");
1624                if(l==4){
1625                  if(!(ltmp!=NULL && strncmp(ltmp->value,"POST",4)==0)
1626                     && CHECK_INET_HANDLE(hInternet)){
1627                    if(loadRemoteFile(&m,&tmpmaps->content,&hInternet,(char*)val)!=0){
1628                      freeMaps(&m);
1629                      free(m);
1630                      free(REQUEST);
1631                      free(SERVICE_URL);
1632                      InternetCloseHandle(&hInternet);
1633                      freeService(&s1);
1634                      free(s1);
1635                      return 0;
1636                    }
1637                  }
1638                }
1639              }
1640#ifdef DEBUG
1641              fprintf(stderr,"%s\n",val);
1642#endif
1643              xmlFree(val);
1644            }
1645#ifdef POST_DEBUG
1646            fprintf(stderr,"Parse Header and Body from Reference \n");
1647#endif
1648            xmlNodePtr cur3=cur2->children;
1649            /*      HINTERNET hInternetP;
1650                    hInternetP=InternetOpen(
1651                    #ifndef WIN32
1652                    (LPCTSTR)
1653                    #endif
1654                    "ZooWPSClient\0",
1655                    INTERNET_OPEN_TYPE_PRECONFIG,
1656                    NULL,NULL, 0);*/
1657            //hInternet.ihandle[hInternet.nb].header=NULL;
1658            while(cur3!=NULL){
1659              while(cur3!=NULL && cur3->type!=XML_ELEMENT_NODE)
1660                cur3=cur3->next;
1661              if(cur3==NULL)
1662                break;
1663              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1664                const char *ha[2];
1665                ha[0]="key";
1666                ha[1]="value";
1667                int hai;
1668                char *has;
1669                char *key;
1670                for(hai=0;hai<2;hai++){
1671                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1672#ifdef POST_DEBUG
1673                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1674#endif
1675                  if(hai==0){
1676                    key=zStrdup((char*)val);
1677                  }else{
1678                    has=(char*)malloc((4+xmlStrlen(val)+strlen(key))*sizeof(char));
1679                    if(has == NULL){
1680                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1681                    }
1682                    snprintf(has,(3+xmlStrlen(val)+strlen(key)),"%s: %s",key,(char*)val);
1683                    free(key);
1684#ifdef POST_DEBUG
1685                    fprintf(stderr,"%s\n",has);
1686#endif
1687                  }
1688                  xmlFree(val);
1689                }
1690                hInternet.ihandle[hInternet.nb].header=curl_slist_append(hInternet.ihandle[hInternet.nb].header, has);
1691                if(has!=NULL)
1692                  free(has);
1693              }
1694              else{
1695#ifdef POST_DEBUG
1696                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1697#endif
1698                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1699#ifdef POST_DEBUG
1700                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1701#endif
1702                  char *tmp=(char*)malloc(cgiContentLength+1*sizeof(char));
1703                  memset(tmp,0,cgiContentLength);
1704                  xmlNodePtr cur4=cur3->children;
1705                  while(cur4!=NULL){
1706                    while(cur4->type!=XML_ELEMENT_NODE)
1707                      cur4=cur4->next;
1708                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1709                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1710                    xmlDocSetRootElement(bdoc,cur4);
1711                    xmlChar* btmps;
1712                    int bsize;
1713                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1714#ifdef POST_DEBUG
1715                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1716#endif
1717                    if(btmps!=NULL)
1718                      sprintf(tmp,"%s",(char*)btmps);
1719                    xmlFree(btmps);
1720                    cur4=cur4->next;
1721                    xmlFreeDoc(bdoc);
1722                  }
1723                  map *btmp=getMap(tmpmaps->content,"href");
1724                  if(btmp!=NULL){
1725#ifdef POST_DEBUG
1726                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1727                    curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1728#endif
1729                    hInternet.waitingRequests[hInternet.nb]=strdup(tmp);
1730                    InternetOpenUrl(&hInternet,btmp->value,hInternet.waitingRequests[hInternet.nb],strlen(hInternet.waitingRequests[hInternet.nb]),
1731                                    INTERNET_FLAG_NO_CACHE_WRITE,0);
1732                  }
1733                  free(tmp);
1734                }
1735                else
1736                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1737                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1738                    HINTERNET bInternet,res1;
1739                    bInternet=InternetOpen(
1740#ifndef WIN32
1741                                           (LPCTSTR)
1742#endif
1743                                           "ZooWPSClient\0",
1744                                           INTERNET_OPEN_TYPE_PRECONFIG,
1745                                           NULL,NULL, 0);
1746                    if(!CHECK_INET_HANDLE(hInternet))
1747                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1748#ifdef POST_DEBUG
1749                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1750#endif
1751                    bInternet.waitingRequests[0]=strdup((char*)val);
1752                    res1=InternetOpenUrl(&bInternet,bInternet.waitingRequests[0],NULL,0,
1753                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1754                    processDownloads(&bInternet);
1755                    char* tmp=
1756                      (char*)malloc((bInternet.ihandle[0].nDataLen+1)*sizeof(char));
1757                    if(tmp == NULL){
1758                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1759                    }
1760                    size_t bRead;
1761                    InternetReadFile(bInternet.ihandle[0], (LPVOID)tmp,
1762                                     bInternet.ihandle[0].nDataLen, &bRead);
1763                    tmp[bInternet.ihandle[0].nDataLen]=0;
1764                    InternetCloseHandle(&bInternet);
1765                    map *btmp=getMap(tmpmaps->content,"href");
1766                    if(btmp!=NULL){
1767#ifdef POST_DEBUG
1768                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1769#endif
1770                      hInternet.waitingRequests[hInternet.nb]=strdup(tmp);
1771                      res=InternetOpenUrl(&hInternet,btmp->value,hInternet.waitingRequests[hInternet.nb],
1772                                          strlen(hInternet.waitingRequests[hInternet.nb]),
1773                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1774                    }
1775                    free(tmp);
1776                  }
1777              }
1778              cur3=cur3->next;
1779            }
1780#ifdef POST_DEBUG
1781            fprintf(stderr,"Header and Body was parsed from Reference \n");
1782#endif
1783#ifdef DEBUG
1784            dumpMap(tmpmaps->content);
1785            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1786                    cur2->name,cur2->content);
1787#endif
1788          }
1789          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1790#ifdef DEBUG
1791            fprintf(stderr,"DATA\n");
1792#endif
1793            xmlNodePtr cur4=cur2->children;
1794            while(cur4!=NULL){
1795              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1796                cur4=cur4->next;
1797              if(cur4==NULL)
1798                break;
1799              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1800                /**
1801                 * Get every attribute from a LiteralData node
1802                 * dataType , uom
1803                 */
1804                char *list[2];
1805                list[0]=zStrdup("dataType");
1806                list[1]=zStrdup("uom");
1807                for(int l=0;l<2;l++){
1808#ifdef DEBUG
1809                  fprintf(stderr,"*** LiteralData %s ***",list[l]);
1810#endif
1811                  xmlChar *val=xmlGetProp(cur4,BAD_CAST list[l]);
1812                  if(val!=NULL && strlen((char*)val)>0){
1813                    if(tmpmaps->content!=NULL)
1814                      addToMap(tmpmaps->content,list[l],(char*)val);
1815                    else
1816                      tmpmaps->content=createMap(list[l],(char*)val);
1817#ifdef DEBUG
1818                    fprintf(stderr,"%s\n",val);
1819#endif
1820                  }
1821                  xmlFree(val);
1822                  free(list[l]);                 
1823                }
1824              }
1825              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1826                /**
1827                 * Get every attribute from a Reference node
1828                 * mimeType, encoding, schema
1829                 */
1830                const char *coms[3]={"mimeType","encoding","schema"};
1831                for(int l=0;l<3;l++){
1832#ifdef DEBUG
1833                  fprintf(stderr,"*** ComplexData %s ***\n",coms[l]);
1834#endif
1835                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1836                  if(val!=NULL && strlen((char*)val)>0){
1837                    if(tmpmaps->content!=NULL)
1838                      addToMap(tmpmaps->content,coms[l],(char*)val);
1839                    else
1840                      tmpmaps->content=createMap(coms[l],(char*)val);
1841#ifdef DEBUG
1842                    fprintf(stderr,"%s\n",val);
1843#endif
1844                  }
1845                  xmlFree(val);
1846                }
1847              }
1848
1849              map* test=getMap(tmpmaps->content,"encoding");
1850              if(test==NULL){
1851                if(tmpmaps->content!=NULL)
1852                  addToMap(tmpmaps->content,"encoding","utf-8");
1853                else
1854                  tmpmaps->content=createMap("encoding","utf-8");
1855                test=getMap(tmpmaps->content,"encoding");
1856              }
1857
1858              if(strcasecmp(test->value,"base64")!=0){
1859                xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1860                map* ltmp=getMap(tmpmaps->content,"mimeType");
1861                if(mv==NULL || 
1862                   (xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0 &&
1863                    (ltmp==NULL || strncasecmp(ltmp->value,"text/xml",8)==0) )){
1864                  xmlDocPtr doc1=xmlNewDoc(BAD_CAST "1.0");
1865                  int buffersize;
1866                  xmlNodePtr cur5=cur4->children;
1867                  while(cur5!=NULL && cur5->type!=XML_ELEMENT_NODE && cur5->type!=XML_CDATA_SECTION_NODE)
1868                    cur5=cur5->next;
1869                  if(cur5!=NULL && cur5->type!=XML_CDATA_SECTION_NODE){
1870                    xmlDocSetRootElement(doc1,cur5);
1871                    xmlDocDumpFormatMemoryEnc(doc1, &mv, &buffersize, "utf-8", 1);
1872                    char size[1024];
1873                    sprintf(size,"%d",buffersize);
1874                    addToMap(tmpmaps->content,"size",size);
1875                    xmlFreeDoc(doc1);
1876                  }
1877                }
1878                if(mv!=NULL){
1879                  addToMap(tmpmaps->content,"value",(char*)mv);
1880                  xmlFree(mv);
1881                }
1882              }else{
1883                xmlChar* tmp=xmlNodeListGetRawString(doc,cur4->xmlChildrenNode,0);
1884                addToMap(tmpmaps->content,"value",(char*)tmp);
1885                map* tmpv=getMap(tmpmaps->content,"value");
1886                char *res=NULL;
1887                char *curs=tmpv->value;
1888                for(int i=0;i<=strlen(tmpv->value)/64;i++) {
1889                  if(res==NULL)
1890                    res=(char*)malloc(67*sizeof(char));
1891                  else
1892                    res=(char*)realloc(res,(((i+1)*65)+i)*sizeof(char));
1893                  int csize=i*65;
1894                  strncpy(res + csize,curs,64);
1895                  if(i==xmlStrlen(tmp)/64)
1896                    strcat(res,"\n\0");
1897                  else{
1898                    strncpy(res + (((i+1)*64)+i),"\n\0",2);
1899                    curs+=64;
1900                  }
1901                }
1902                free(tmpv->value);
1903                tmpv->value=zStrdup(res);
1904                free(res);
1905                xmlFree(tmp);
1906              }
1907              cur4=cur4->next;
1908            }
1909          }
1910#ifdef DEBUG
1911          fprintf(stderr,"cur2 next \n");
1912          fflush(stderr);
1913#endif
1914          cur2=cur2->next;
1915        }
1916#ifdef DEBUG
1917        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1918        fflush(stderr);
1919#endif
1920
1921        {
1922          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1923          if(testPresence!=NULL){
1924            elements* elem=getElements(s1->inputs,tmpmaps->name);
1925            if(elem!=NULL){
1926              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1927                freeMaps(&m);
1928                free(m);
1929                free(REQUEST);
1930                free(SERVICE_URL);
1931                InternetCloseHandle(&hInternet);
1932                freeService(&s1);
1933                free(s1);
1934                return 0;
1935              }
1936            }
1937          }
1938          else
1939            addMapsToMaps(&request_input_real_format,tmpmaps);
1940        }
1941
1942#ifdef DEBUG
1943        fprintf(stderr,"******TMPMAPS*****\n");
1944        dumpMaps(tmpmaps);
1945        fprintf(stderr,"******REQUESTMAPS*****\n");
1946        dumpMaps(request_input_real_format);
1947#endif
1948        freeMaps(&tmpmaps);
1949        free(tmpmaps);
1950        tmpmaps=NULL;         
1951      }
1952#ifdef DEBUG
1953      dumpMaps(tmpmaps); 
1954#endif
1955    }
1956#ifdef DEBUG
1957    fprintf(stderr,"Search for response document node\n");
1958#endif
1959    xmlXPathFreeObject(tmpsptr);
1960   
1961    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1962    bool asRaw=false;
1963    tmps=tmpsptr->nodesetval;
1964    if(tmps->nodeNr==0){
1965      tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1966      tmps=tmpsptr->nodesetval;
1967      asRaw=true;
1968    }
1969#ifdef DEBUG
1970    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1971#endif
1972    if(asRaw==true){
1973      addToMap(request_inputs,"RawDataOutput","");
1974      xmlNodePtr cur0=tmps->nodeTab[0];
1975      if(cur0->type == XML_ELEMENT_NODE) {
1976       
1977        maps* tmpmaps=(maps*)malloc(MAPS_SIZE);
1978        if(tmpmaps == NULL){
1979          return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1980        }
1981        tmpmaps->name=zStrdup("unknownIdentifier");
1982        tmpmaps->content=NULL;
1983        tmpmaps->next=NULL;
1984       
1985        /**
1986         * Get every attribute from a RawDataOutput node
1987         * mimeType, encoding, schema, uom
1988         */
1989        const char *outs[4]={"mimeType","encoding","schema","uom"};
1990        for(int l=0;l<4;l++){
1991#ifdef DEBUG
1992          fprintf(stderr,"*** %s ***\t",outs[l]);
1993#endif
1994          xmlChar *val=xmlGetProp(cur0,BAD_CAST outs[l]);
1995          if(val!=NULL){
1996            if(strlen((char*)val)>0){
1997              if(tmpmaps->content!=NULL)
1998                addToMap(tmpmaps->content,outs[l],(char*)val);
1999              else
2000                tmpmaps->content=createMap(outs[l],(char*)val);
2001            }
2002            xmlFree(val);
2003          }
2004        }
2005        xmlNodePtr cur2=cur0->children;
2006        while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2007          cur2=cur2->next;
2008        int cur1cnt=0;
2009        while(cur2!=NULL){
2010          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
2011            xmlChar *val=
2012              xmlNodeListGetString(NULL,cur2->xmlChildrenNode,1);
2013            free(tmpmaps->name);
2014            tmpmaps->name=zStrdup((char*)val);
2015          }
2016          cur2=cur2->next;
2017          while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2018            cur2=cur2->next;
2019        }
2020        if(request_output_real_format==NULL)
2021          request_output_real_format=dupMaps(&tmpmaps);
2022        else
2023          addMapsToMaps(&request_output_real_format,tmpmaps);
2024        if(tmpmaps!=NULL){
2025          freeMaps(&tmpmaps);
2026          free(tmpmaps);
2027          tmpmaps=NULL;
2028        }
2029      }
2030    }
2031    else
2032      for(int k=0;k<tmps->nodeNr;k++){
2033        //else
2034        addToMap(request_inputs,"ResponseDocument","");
2035        maps *tmpmaps=NULL;
2036        xmlNodePtr cur=tmps->nodeTab[k];
2037        if(cur->type == XML_ELEMENT_NODE) {
2038          /**
2039           * A specific responseDocument node.
2040           */
2041          if(tmpmaps==NULL){
2042            tmpmaps=(maps*)malloc(MAPS_SIZE);
2043            if(tmpmaps == NULL){
2044              return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2045            }
2046            tmpmaps->name=zStrdup("unknownIdentifier");
2047            tmpmaps->content=NULL;
2048            tmpmaps->next=NULL;
2049          }
2050          /**
2051           * Get every attribute: storeExecuteResponse, lineage, status
2052           */
2053          const char *ress[3]={"storeExecuteResponse","lineage","status"};
2054          xmlChar *val;
2055          for(int l=0;l<3;l++){
2056#ifdef DEBUG
2057            fprintf(stderr,"*** %s ***\t",ress[l]);
2058#endif
2059            val=xmlGetProp(cur,BAD_CAST ress[l]);
2060            if(val!=NULL && strlen((char*)val)>0){
2061              if(tmpmaps->content!=NULL)
2062                addToMap(tmpmaps->content,ress[l],(char*)val);
2063              else
2064                tmpmaps->content=createMap(ress[l],(char*)val);
2065              addToMap(request_inputs,ress[l],(char*)val);
2066            }
2067#ifdef DEBUG
2068            fprintf(stderr,"%s\n",val);
2069#endif
2070            xmlFree(val);
2071          }
2072          xmlNodePtr cur1=cur->children;
2073          while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
2074            cur1=cur1->next;
2075          int cur1cnt=0;
2076          while(cur1){
2077            /**
2078             * Indentifier
2079             */
2080            if(xmlStrncasecmp(cur1->name,BAD_CAST "Identifier",xmlStrlen(cur1->name))==0){
2081              xmlChar *val=
2082                xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
2083              if(tmpmaps==NULL){
2084                tmpmaps=(maps*)malloc(MAPS_SIZE);
2085                if(tmpmaps == NULL){
2086                  return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2087                }
2088                tmpmaps->name=zStrdup((char*)val);
2089                tmpmaps->content=NULL;
2090                tmpmaps->next=NULL;
2091              }
2092              else{
2093                free(tmpmaps->name);
2094                tmpmaps->name=zStrdup((char*)val);
2095              }
2096              if(asRaw==true)
2097                addToMap(request_inputs,"RawDataOutput",(char*)val);
2098              else{
2099                if(cur1cnt==0)
2100                  addToMap(request_inputs,"ResponseDocument",(char*)val);
2101                else{
2102                  map* tt=getMap(request_inputs,"ResponseDocument");
2103                  char* tmp=zStrdup(tt->value);
2104                  free(tt->value);
2105                  tt->value=(char*)malloc((strlen(tmp)+strlen((char*)val)+1)*sizeof(char));
2106                  sprintf(tt->value,"%s;%s",tmp,(char*)val);
2107                  free(tmp);
2108                }
2109              }
2110              cur1cnt+=1;
2111              xmlFree(val);
2112            }
2113            /**
2114             * Title, Asbtract
2115             */
2116            else if(xmlStrncasecmp(cur1->name,BAD_CAST "Title",xmlStrlen(cur1->name))==0 ||
2117                    xmlStrncasecmp(cur1->name,BAD_CAST "Abstract",xmlStrlen(cur1->name))==0){
2118              xmlChar *val=
2119                xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
2120              if(tmpmaps==NULL){
2121                tmpmaps=(maps*)malloc(MAPS_SIZE);
2122                if(tmpmaps == NULL){
2123                  return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2124                }
2125                tmpmaps->name=zStrdup("missingIndetifier");
2126                tmpmaps->content=createMap((char*)cur1->name,(char*)val);
2127                tmpmaps->next=NULL;
2128              }
2129              else{
2130                if(tmpmaps->content!=NULL)
2131                  addToMap(tmpmaps->content,(char*)cur1->name,(char*)val);
2132                else
2133                  tmpmaps->content=createMap((char*)cur1->name,(char*)val);
2134              }
2135              xmlFree(val);
2136            }
2137            else if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
2138              /**
2139               * Get every attribute from a Output node
2140               * mimeType, encoding, schema, uom, asReference
2141               */
2142              const char *outs[5]={"mimeType","encoding","schema","uom","asReference"};
2143              for(int l=0;l<5;l++){
2144#ifdef DEBUG
2145                fprintf(stderr,"*** %s ***\t",outs[l]);
2146#endif
2147                xmlChar *val=xmlGetProp(cur1,BAD_CAST outs[l]);
2148                if(val!=NULL && strlen((char*)val)>0){
2149                  if(tmpmaps->content!=NULL)
2150                    addToMap(tmpmaps->content,outs[l],(char*)val);
2151                  else
2152                    tmpmaps->content=createMap(outs[l],(char*)val);
2153                }
2154#ifdef DEBUG
2155                fprintf(stderr,"%s\n",val);
2156#endif
2157                xmlFree(val);
2158              }
2159              xmlNodePtr cur2=cur1->children;
2160              while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2161                cur2=cur2->next;
2162              while(cur2){
2163                /**
2164                 * Indentifier
2165                 */
2166                if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
2167                  xmlChar *val=
2168                    xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
2169                  if(tmpmaps==NULL){
2170                    tmpmaps=(maps*)malloc(MAPS_SIZE);
2171                    if(tmpmaps == NULL){
2172                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2173                    }
2174                    tmpmaps->name=zStrdup((char*)val);
2175                    tmpmaps->content=NULL;
2176                    tmpmaps->next=NULL;
2177                  }
2178                  else{
2179                    if(tmpmaps->name!=NULL)
2180                      free(tmpmaps->name);
2181                    tmpmaps->name=zStrdup((char*)val);;
2182                  }
2183                  xmlFree(val);
2184                }
2185                /**
2186                 * Title, Asbtract
2187                 */
2188                else if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
2189                        xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
2190                  xmlChar *val=
2191                    xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
2192                  if(tmpmaps==NULL){
2193                    tmpmaps=(maps*)malloc(MAPS_SIZE);
2194                    if(tmpmaps == NULL){
2195                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2196                    }
2197                    tmpmaps->name=zStrdup("missingIndetifier");
2198                    tmpmaps->content=createMap((char*)cur2->name,(char*)val);
2199                    tmpmaps->next=NULL;
2200                  }
2201                  else{
2202                    if(tmpmaps->content!=NULL)
2203                      addToMap(tmpmaps->content,
2204                               (char*)cur2->name,(char*)val);
2205                    else
2206                      tmpmaps->content=
2207                        createMap((char*)cur2->name,(char*)val);
2208                  }
2209                  xmlFree(val);
2210                }
2211                cur2=cur2->next;
2212                while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2213                  cur2=cur2->next;
2214              }
2215            }
2216            cur1=cur1->next;
2217            while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
2218              cur1=cur1->next;
2219          }
2220        }
2221        if(request_output_real_format==NULL)
2222          request_output_real_format=dupMaps(&tmpmaps);
2223        else
2224          addMapsToMaps(&request_output_real_format,tmpmaps);
2225        if(tmpmaps!=NULL){
2226          freeMaps(&tmpmaps);
2227          free(tmpmaps);
2228          tmpmaps=NULL;
2229        }
2230      }
2231    xmlXPathFreeObject(tmpsptr);
2232    xmlFreeDoc(doc);
2233    xmlCleanupParser();
2234  }
2235 
2236  runHttpRequests(&m,&request_input_real_format,&hInternet);
2237
2238  //  if(CHECK_INET_HANDLE(hInternet))
2239  InternetCloseHandle(&hInternet);
2240
2241#ifdef DEBUG
2242  fprintf(stderr,"\n%d\n",__LINE__);
2243  fflush(stderr);
2244  dumpMaps(request_input_real_format);
2245  dumpMaps(request_output_real_format);
2246  dumpMap(request_inputs);
2247  fprintf(stderr,"\n%d\n",__LINE__);
2248  fflush(stderr);
2249#endif
2250
2251  /**
2252   * Ensure that each requested arguments are present in the request
2253   * DataInputs and ResponseDocument / RawDataOutput
2254   */
2255  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,0);
2256  maps *ptr=request_input_real_format;
2257  while(ptr!=NULL){
2258    map *tmp0=getMap(ptr->content,"size");
2259    map *tmp1=getMap(ptr->content,"maximumMegabytes");
2260    if(tmp1!=NULL && tmp0!=NULL){
2261      float i=atof(tmp0->value)/1048576.0;
2262      if(i>=atoi(tmp1->value)){
2263        char tmps[1024];
2264        map* tmpe=createMap("code","FileSizeExceeded");
2265        snprintf(tmps,1024,_("The <%s> parameter has a limited size (%sMB) defined in ZOO ServicesProvider configuration file but the reference you provided exceed this limitation (%fMB), please correct your query or the ZOO Configuration file."),ptr->name,tmp1->value,i);
2266        addToMap(tmpe,"locator",ptr->name);
2267        addToMap(tmpe,"text",tmps);
2268        printExceptionReportResponse(m,tmpe);
2269        freeService(&s1);
2270        free(s1);
2271        freeMap(&tmpe);
2272        free(tmpe);
2273        freeMaps(&m);
2274        free(m);
2275        free(REQUEST);
2276        free(SERVICE_URL);
2277        freeMaps(&request_input_real_format);
2278        free(request_input_real_format);
2279        freeMaps(&request_output_real_format);
2280        free(request_output_real_format);
2281        freeMaps(&tmpmaps);
2282        free(tmpmaps);
2283        return 1;
2284      }
2285    }
2286    ptr=ptr->next;
2287  }
2288
2289  char *dfv1=addDefaultValues(&request_output_real_format,s1->outputs,m,1);
2290  if(strcmp(dfv1,"")!=0 || strcmp(dfv,"")!=0){
2291    char tmps[1024];
2292    map* tmpe=createMap("code","MissingParameterValue");
2293    if(strcmp(dfv,"")!=0){
2294      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);
2295      addToMap(tmpe,"locator",dfv);
2296    }
2297    else if(strcmp(dfv1,"")!=0){
2298      snprintf(tmps,1024,_("The <%s> argument was specified as Output identifier but not defined in the ZOO Configuration File. Please, correct your query or the ZOO Configuration File."),dfv1);
2299      addToMap(tmpe,"locator",dfv1);
2300    }
2301    addToMap(tmpe,"text",tmps);
2302    printExceptionReportResponse(m,tmpe);
2303    freeService(&s1);
2304    free(s1);
2305    freeMap(&tmpe);
2306    free(tmpe);
2307    freeMaps(&m);
2308    free(m);
2309    free(REQUEST);
2310    free(SERVICE_URL);
2311    freeMaps(&request_input_real_format);
2312    free(request_input_real_format);
2313    freeMaps(&request_output_real_format);
2314    free(request_output_real_format);
2315    freeMaps(&tmpmaps);
2316    free(tmpmaps);
2317    return 1;
2318  }
2319  maps* tmpReqI=request_input_real_format;
2320  while(tmpReqI!=NULL){
2321    char name[1024];
2322    if(getMap(tmpReqI->content,"isFile")!=NULL){
2323      if (cgiFormFileName(tmpReqI->name, name, sizeof(name)) == cgiFormSuccess) {
2324        int BufferLen=1024;
2325        cgiFilePtr file;
2326        int targetFile;
2327        char storageNameOnServer[2048];
2328        char fileNameOnServer[64];
2329        char contentType[1024];
2330        char buffer[1024];
2331        char *tmpStr=NULL;
2332        int size;
2333        int got,t;
2334        map *path=getMapFromMaps(m,"main","tmpPath");
2335        cgiFormFileSize(tmpReqI->name, &size);
2336        cgiFormFileContentType(tmpReqI->name, contentType, sizeof(contentType));
2337        if (cgiFormFileOpen(tmpReqI->name, &file) == cgiFormSuccess) {
2338          t=-1;
2339          while(1){
2340            tmpStr=strstr(name+t+1,"\\");
2341            if(NULL==tmpStr)
2342              tmpStr=strstr(name+t+1,"/");
2343            if(NULL!=tmpStr)
2344              t=(int)(tmpStr-name);
2345            else
2346              break;
2347          }
2348          strcpy(fileNameOnServer,name+t+1);
2349         
2350          sprintf(storageNameOnServer,"%s/%s",path->value,fileNameOnServer);
2351#ifdef DEBUG
2352          fprintf(stderr,"Name on server %s\n",storageNameOnServer);
2353          fprintf(stderr,"fileNameOnServer: %s\n",fileNameOnServer);
2354#endif
2355          targetFile = open (storageNameOnServer,O_RDWR|O_CREAT|O_TRUNC,S_IRWXU|S_IRGRP|S_IROTH);
2356          if(targetFile<0){
2357#ifdef DEBUG
2358            fprintf(stderr,"could not create the new file,%s\n",fileNameOnServer);         
2359#endif
2360          }else{
2361            while (cgiFormFileRead(file, buffer, BufferLen, &got) ==cgiFormSuccess){
2362              if(got>0)
2363                write(targetFile,buffer,got);
2364            }
2365          }
2366          addToMap(tmpReqI->content,"lref",storageNameOnServer);
2367          cgiFormFileClose(file);
2368          close(targetFile);
2369#ifdef DEBUG
2370          fprintf(stderr,"File \"%s\" has been uploaded",fileNameOnServer);
2371#endif
2372        }
2373      }
2374    }
2375    tmpReqI=tmpReqI->next;
2376  }
2377
2378  ensureDecodedBase64(&request_input_real_format);
2379
2380#ifdef DEBUG
2381  fprintf(stderr,"REQUEST_INPUTS\n");
2382  dumpMaps(request_input_real_format);
2383  fprintf(stderr,"REQUEST_OUTPUTS\n");
2384  dumpMaps(request_output_real_format);
2385#endif
2386
2387  maps* curs=getMaps(m,"env");
2388  if(curs!=NULL){
2389    map* mapcs=curs->content;
2390    while(mapcs!=NULLMAP){
2391#ifndef WIN32
2392      setenv(mapcs->name,mapcs->value,1);
2393#else
2394#ifdef DEBUG
2395      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2396#endif
2397      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
2398#ifdef DEBUG
2399        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
2400#endif
2401        mapcs->value[strlen(mapcs->value)-1]=0;
2402      }
2403#ifdef DEBUG
2404      fflush(stderr);
2405      fprintf(stderr,"setting variable... %s\n",(
2406#endif
2407                                                 SetEnvironmentVariable(mapcs->name,mapcs->value)
2408#ifdef DEBUG
2409                                                 ==0)? "OK" : "FAILED");
2410#else
2411      ;
2412#endif
2413      char* toto=(char*)malloc((strlen(mapcs->name)+strlen(mapcs->value)+2)*sizeof(char));
2414      sprintf(toto,"%s=%s",mapcs->name,mapcs->value);
2415      putenv(toto);
2416#ifdef DEBUG
2417      fflush(stderr);
2418#endif
2419#endif
2420#ifdef DEBUG
2421      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2422      fflush(stderr);
2423#endif
2424      mapcs=mapcs->next;
2425    }
2426  }
2427 
2428#ifdef DEBUG
2429  dumpMap(request_inputs);
2430#endif
2431
2432  /**
2433   * Need to check if we need to fork to load a status enabled
2434   */
2435  r_inputs=NULL;
2436  map* store=getMap(request_inputs,"storeExecuteResponse");
2437  map* status=getMap(request_inputs,"status");
2438  /**
2439   * 05-007r7 WPS 1.0.0 page 57 :
2440   * 'If status="true" and storeExecuteResponse is "false" then the service
2441   * shall raise an exception.'
2442   */
2443  if(status!=NULL && strcmp(status->value,"true")==0 && 
2444     store!=NULL && strcmp(store->value,"false")==0){
2445    errorException(m, _("Status cannot be set to true with storeExecuteResponse to false. Please, modify your request parameters."), "InvalidParameterValue","storeExecuteResponse");
2446    freeService(&s1);
2447    free(s1);
2448    freeMaps(&m);
2449    free(m);
2450   
2451    freeMaps(&request_input_real_format);
2452    free(request_input_real_format);
2453   
2454    freeMaps(&request_output_real_format);
2455    free(request_output_real_format);
2456   
2457    free(REQUEST);
2458    free(SERVICE_URL);
2459    return 1;
2460  }
2461  r_inputs=getMap(request_inputs,"storeExecuteResponse");
2462  int eres=SERVICE_STARTED;
2463  int cpid=getpid();
2464
2465  /**
2466   * Initialize the specific [lenv] section which contains runtime variables:
2467   *
2468   *  - usid : it is an unique identification number
2469   *  - sid : it is the process idenfitication number (OS)
2470   *  - status : value between 0 and 100 to express the  completude of
2471   * the operations of the running service
2472   *  - message : is a string where you can store error messages, in case
2473   * service is failing, or o provide details on the ongoing operation.
2474   *  - cwd : is the current working directory
2475   *  - soap : is a boolean value, true if the request was contained in a SOAP
2476   * Envelop
2477   *  - sessid : string storing the session identifier (only when cookie is
2478   * used)
2479   *  - cgiSid : only defined on Window platforms (for being able to identify
2480   * the created process)
2481   *
2482   */
2483  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
2484  _tmpMaps->name=zStrdup("lenv");
2485  char tmpBuff[100];
2486  sprintf(tmpBuff,"%i",(cpid+(int)time(NULL)));
2487  _tmpMaps->content=createMap("usid",tmpBuff);
2488  _tmpMaps->next=NULL;
2489  sprintf(tmpBuff,"%i",cpid);
2490  addToMap(_tmpMaps->content,"sid",tmpBuff);
2491  addToMap(_tmpMaps->content,"status","0");
2492  addToMap(_tmpMaps->content,"cwd",ntmp);
2493  addToMap(_tmpMaps->content,"message",_("No message provided"));
2494  map* ltmp=getMap(request_inputs,"soap");
2495  if(ltmp!=NULL)
2496    addToMap(_tmpMaps->content,"soap",ltmp->value);
2497  else
2498    addToMap(_tmpMaps->content,"soap","false");
2499  if(cgiCookie!=NULL && strlen(cgiCookie)>0){
2500    int hasValidCookie=-1;
2501    char *tcook=zStrdup(cgiCookie);
2502    char *tmp=NULL;
2503    map* testing=getMapFromMaps(m,"main","cookiePrefix");
2504    if(testing==NULL){
2505      tmp=zStrdup("ID=");
2506    }else{
2507      tmp=(char*)malloc((strlen(testing->value)+2)*sizeof(char));
2508      sprintf(tmp,"%s=",testing->value);
2509    }
2510    if(strstr(cgiCookie,";")!=NULL){
2511      char *token,*saveptr;
2512      token=strtok_r(cgiCookie,";",&saveptr);
2513      while(token!=NULL){
2514        if(strcasestr(token,tmp)!=NULL){
2515          if(tcook!=NULL)
2516            free(tcook);
2517          tcook=zStrdup(token);
2518          hasValidCookie=1;
2519        }
2520        token=strtok_r(NULL,";",&saveptr);
2521      }
2522    }else{
2523      if(strstr(cgiCookie,"=")!=NULL && strcasestr(cgiCookie,tmp)!=NULL){
2524        tcook=zStrdup(cgiCookie);
2525        hasValidCookie=1;
2526      }
2527      if(tmp!=NULL){
2528        free(tmp);
2529      }
2530    }
2531    if(hasValidCookie>0){
2532      addToMap(_tmpMaps->content,"sessid",strstr(tcook,"=")+1);
2533      char session_file_path[1024];
2534      map *tmpPath=getMapFromMaps(m,"main","sessPath");
2535      if(tmpPath==NULL)
2536        tmpPath=getMapFromMaps(m,"main","tmpPath");
2537      char *tmp1=strtok(tcook,";");
2538      if(tmp1!=NULL)
2539        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(tmp1,"=")+1);
2540      else
2541        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(cgiCookie,"=")+1);
2542      free(tcook);
2543      maps *tmpSess=(maps*)malloc(MAPS_SIZE);
2544      struct stat file_status;
2545      int istat = stat(session_file_path, &file_status);
2546      if(istat==0 && file_status.st_size>0){
2547        conf_read(session_file_path,tmpSess);
2548        addMapsToMaps(&m,tmpSess);
2549        freeMaps(&tmpSess);
2550        free(tmpSess);
2551      }
2552    }
2553  }
2554  addMapsToMaps(&m,_tmpMaps);
2555  freeMaps(&_tmpMaps);
2556  free(_tmpMaps);
2557 
2558#ifdef DEBUG
2559  dumpMap(request_inputs);
2560#endif
2561#ifdef WIN32
2562  char *cgiSidL=NULL;
2563  if(getenv("CGISID")!=NULL)
2564    addToMap(request_inputs,"cgiSid",getenv("CGISID"));
2565  map* test1=getMap(request_inputs,"cgiSid");
2566  if(test1!=NULL){
2567    cgiSid=test1->value;
2568    addToMap(request_inputs,"storeExecuteResponse","true");
2569    addToMap(request_inputs,"status","true");
2570    setMapInMaps(m,"lenv","sid",test1->value);
2571    status=getMap(request_inputs,"status");
2572  }
2573#endif
2574  char *fbkp,*fbkp1;
2575  FILE *f0,*f1;
2576  if(status!=NULL)
2577    if(strcasecmp(status->value,"false")==0)
2578      status=NULLMAP;
2579  if(status==NULLMAP){
2580    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2581  }
2582  else{
2583    int   pid;
2584#ifdef DEBUG
2585    fprintf(stderr,"\nPID : %d\n",cpid);
2586#endif
2587
2588#ifndef WIN32
2589    pid = fork ();
2590#else
2591    if(cgiSid==NULL){
2592      createProcess(m,request_inputs,s1,NULL,cpid,request_input_real_format,request_output_real_format);
2593      pid = cpid;
2594    }else{
2595      pid=0;
2596      cpid=atoi(cgiSid);
2597    }
2598#endif
2599    if (pid > 0) {
2600      /**
2601       * dady :
2602       * set status to SERVICE_ACCEPTED
2603       */
2604#ifdef DEBUG
2605      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
2606#endif
2607      eres=SERVICE_ACCEPTED;
2608    }else if (pid == 0) {
2609      /**
2610       * son : have to close the stdout, stdin and stderr to let the parent
2611       * process answer to http client.
2612       */
2613      r_inputs=getMapFromMaps(m,"main","tmpPath");
2614      map* r_inputs1=getMap(s1->content,"ServiceProvider");
2615      fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2616      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2617      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2618      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
2619#ifdef DEBUG
2620      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
2621      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
2622      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
2623#endif
2624      freopen(flog, "w+", stderr);
2625      f0=freopen(fbkp , "w+", stdout);
2626#ifndef WIN32
2627      fclose(stdin);
2628#endif
2629      free(flog);
2630      /**
2631       * set status to SERVICE_STARTED and flush stdout to ensure full
2632       * content was outputed (the file used to store the ResponseDocument).
2633       * The rewind stdout to restart writing from the bgining of the file,
2634       * this way the data will be updated at the end of the process run.
2635       */
2636      printProcessResponse(m,request_inputs,cpid,s1,r_inputs1->value,SERVICE_STARTED,
2637                           request_input_real_format,request_output_real_format);
2638#ifndef WIN32
2639      fflush(stdout);
2640      rewind(stdout);
2641#else
2642#endif
2643      fbkp1=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2644      sprintf(fbkp1,"%s/%s_final_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2645      f1=freopen(fbkp1 , "w+", stdout);
2646      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2647    } else {
2648      /**
2649       * error server don't accept the process need to output a valid
2650       * error response here !!!
2651       */
2652      eres=-1;
2653      errorException(m, _("Unable to run the child process properly"), "InternalError",NULL);
2654    }
2655  }
2656
2657#ifdef DEBUG
2658  dumpMaps(request_output_real_format);
2659#endif
2660  if(eres!=-1)
2661    outputResponse(s1,request_input_real_format,
2662                   request_output_real_format,request_inputs,
2663                   cpid,m,eres);
2664  fflush(stdout);
2665  /**
2666   * Ensure that if error occurs when freeing memory, no signal will return
2667   * an ExceptionReport document as the result was already returned to the
2668   * client.
2669   */
2670#ifndef USE_GDB
2671  (void) signal(SIGSEGV,donothing);
2672  (void) signal(SIGTERM,donothing);
2673  (void) signal(SIGINT,donothing);
2674  (void) signal(SIGILL,donothing);
2675  (void) signal(SIGFPE,donothing);
2676  (void) signal(SIGABRT,donothing);
2677#endif
2678  if(((int)getpid())!=cpid || cgiSid!=NULL){
2679    fclose(stdout);
2680    fclose(stderr);
2681    unhandleStatus(m);
2682    /**
2683     * Dump back the final file fbkp1 to fbkp
2684     */
2685    fclose(f0);
2686    fclose(f1);
2687    FILE* f2=fopen(fbkp1,"rb");
2688    FILE* f3=fopen(fbkp,"wb+");
2689    free(fbkp);
2690    fseek(f2,0,SEEK_END);
2691    long flen=ftell(f2);
2692    fseek(f2,0,SEEK_SET);
2693    char *tmps1=(char*)malloc((flen+1)*sizeof(char));
2694    fread(tmps1,flen,1,f2);
2695    fwrite(tmps1,1,flen,f3);
2696    fclose(f2);
2697    fclose(f3);
2698    unlink(fbkp1);
2699    free(fbkp1);
2700    free(tmps1);
2701  }
2702
2703  freeService(&s1);
2704  free(s1);
2705  freeMaps(&m);
2706  free(m);
2707 
2708  freeMaps(&request_input_real_format);
2709  free(request_input_real_format);
2710 
2711  freeMaps(&request_output_real_format);
2712  free(request_output_real_format);
2713 
2714  free(REQUEST);
2715  free(SERVICE_URL);
2716#ifdef DEBUG
2717  fprintf(stderr,"Processed response \n");
2718  fflush(stdout);
2719  fflush(stderr);
2720#endif
2721
2722  return 0;
2723}
2724
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