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

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

Remove memory leaks from ZOO-Kernel. Fix issue #99.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 73.3 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        if(t<0){
260          dumpMaps(m);
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    char *tmp=zStrdup(r_inputs->value);
734    setMapInMaps(m,"main","language",tmp);
735#ifdef DEB
736    char tmp2[12];
737    sprintf(tmp2,"%s.utf-8",tmp);
738    translateChar(tmp2,'-','_');
739    setlocale (LC_ALL, tmp2);
740#else
741    translateChar(tmp,'-','_');
742    setlocale (LC_ALL, tmp);
743#endif
744#ifndef WIN32
745    setenv("LC_ALL",tmp,1);
746#else
747    char tmp1[12];
748    sprintf(tmp1,"LC_ALL=%s",tmp);
749    putenv(tmp1);
750#endif
751    free(tmp);
752  }
753  else{
754    setlocale (LC_ALL, "en_US");
755#ifndef WIN32
756    setenv("LC_ALL","en_US",1);
757#else
758    char tmp1[12];
759    sprintf(tmp1,"LC_ALL=en_US");
760    putenv(tmp1);
761#endif
762    setMapInMaps(m,"main","language","en-US");
763  }
764  setlocale (LC_NUMERIC, "en_US");
765  bind_textdomain_codeset("zoo-kernel","UTF-8");
766  textdomain("zoo-kernel");
767  bind_textdomain_codeset("zoo-services","UTF-8");
768  textdomain("zoo-services");
769
770  map* lsoap=getMap(request_inputs,"soap");
771  if(lsoap!=NULL && strcasecmp(lsoap->value,"true")==0)
772    setMapInMaps(m,"main","isSoap","true");
773  else
774    setMapInMaps(m,"main","isSoap","false");
775
776  if(strlen(cgiServerName)>0){
777    char tmpUrl[1024];
778    sprintf(tmpUrl,"http://%s%s",cgiServerName,cgiScriptName);
779#ifdef DEBUG
780    fprintf(stderr,"*** %s ***\n",tmpUrl);
781#endif
782    setMapInMaps(m,"main","serverAddress",tmpUrl);
783  }
784
785  /**
786   * Check for minimum inputs
787   */
788  r_inputs=getMap(request_inputs,"Request");
789  if(request_inputs==NULL || r_inputs==NULL){ 
790    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue","request");
791    if(count(request_inputs)==1){
792      freeMap(&request_inputs);
793      free(request_inputs);
794    }
795    freeMaps(&m);
796    free(m);
797    return 1;
798  }
799  else{
800    REQUEST=zStrdup(r_inputs->value);
801    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
802       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
803       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
804      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue","request");
805      freeMaps(&m);
806      free(m);
807      free(REQUEST);
808      return 1;
809    }
810  }
811  r_inputs=NULL;
812  r_inputs=getMap(request_inputs,"Service");
813  if(r_inputs==NULLMAP){
814    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue","service");
815    freeMaps(&m);
816    free(m);
817    free(REQUEST);
818    return 1;
819  }else{
820    if(strcasecmp(r_inputs->value,"WPS")!=0){
821      errorException(m, _("Unenderstood <service> value, WPS is the only acceptable value."), "InvalidParameterValue","service");
822      freeMaps(&m);
823      free(m);
824      free(REQUEST);
825      return 1;
826    }
827  }
828  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
829    r_inputs=getMap(request_inputs,"Version");
830    if(r_inputs==NULL){ 
831      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue","version");
832      freeMaps(&m);
833      free(m);
834      free(REQUEST);
835      return 1;
836    }else{
837      if(strcasecmp(r_inputs->value,"1.0.0")!=0){
838        errorException(m, _("Unenderstood <version> value, 1.0.0 is the only acceptable value."), "InvalidParameterValue","service");
839        freeMaps(&m);
840        free(m);
841        free(REQUEST);
842        return 1;
843      }
844    } 
845  }
846
847  r_inputs=getMap(request_inputs,"serviceprovider");
848  if(r_inputs==NULL){
849    addToMap(request_inputs,"serviceprovider","");
850  }
851
852  maps* request_output_real_format=NULL;
853  map* tmpm=getMapFromMaps(m,"main","serverAddress");
854  if(tmpm!=NULL)
855    SERVICE_URL=zStrdup(tmpm->value);
856  else
857    SERVICE_URL=zStrdup(DEFAULT_SERVICE_URL);
858
859  service* s1;
860  int scount=0;
861#ifdef DEBUG
862  dumpMap(r_inputs);
863#endif
864  char conf_dir[1024];
865  int t;
866  char tmps1[1024];
867
868  r_inputs=NULL;
869  r_inputs=getMap(request_inputs,"metapath");
870  if(r_inputs!=NULL)
871    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
872  else
873    snprintf(conf_dir,1024,"%s",ntmp);
874
875  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
876#ifdef DEBUG
877    dumpMap(r_inputs);
878#endif
879    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
880    r_inputs=NULL;
881    r_inputs=getMap(request_inputs,"ServiceProvider");
882    xmlNodePtr n;
883    if(r_inputs!=NULL)
884      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
885    else
886      n = printGetCapabilitiesHeader(doc,"",m);
887    /**
888     * Here we need to close stdout to ensure that not supported chars
889     * has been found in the zcfg and then printed on stdout
890     */
891    int saved_stdout = dup(fileno(stdout));
892    dup2(fileno(stderr),fileno(stdout));
893    if(int res=recursReaddirF(m,n,conf_dir,NULL,saved_stdout,0,printGetCapabilitiesForProcess)<0){
894      freeMaps(&m);
895      free(m);
896      free(REQUEST);
897      free(SERVICE_URL);
898      fflush(stdout);
899      return res;
900    }
901    dup2(saved_stdout,fileno(stdout));
902    printDocument(m,doc,getpid());
903    freeMaps(&m);
904    free(m);
905    free(REQUEST);
906    free(SERVICE_URL);
907    fflush(stdout);
908    return 0;
909  }
910  else{
911    r_inputs=getMap(request_inputs,"Identifier");
912    if(r_inputs==NULL 
913       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
914      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue","identifier");
915      freeMaps(&m);
916      free(m);
917      free(REQUEST);
918      free(SERVICE_URL);
919      return 0;
920    }
921
922    struct dirent *dp;
923    DIR *dirp = opendir(conf_dir);
924    if(dirp==NULL){
925      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue",conf_dir);
926      freeMaps(&m);
927      free(m);
928      free(REQUEST);
929      free(SERVICE_URL);
930      return 0;
931    }
932    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
933      /**
934       * Loop over Identifier list
935       */
936      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
937      r_inputs=NULL;
938      r_inputs=getMap(request_inputs,"ServiceProvider");
939
940      xmlNodePtr n;
941      if(r_inputs!=NULL)
942        n = printDescribeProcessHeader(doc,r_inputs->value,m);
943      else
944        n = printDescribeProcessHeader(doc,"",m);
945
946      r_inputs=getMap(request_inputs,"Identifier");
947     
948      char *orig=zStrdup(r_inputs->value);
949
950      int saved_stdout = dup(fileno(stdout));
951      dup2(fileno(stderr),fileno(stdout));
952      if(strcasecmp("all",orig)==0){
953        if(int res=recursReaddirF(m,n,conf_dir,NULL,saved_stdout,0,printDescribeProcessForProcess)<0)
954          return res;
955      }
956      else{
957        char *saveptr;
958        char *tmps=strtok_r(orig,",",&saveptr);
959       
960        char buff[256];
961        char buff1[1024];
962        while(tmps!=NULL){
963          char *corig=strdup(tmps);
964          if(strstr(corig,".")!=NULL){
965            parseIdentifier(m,conf_dir,corig,buff1);
966            s1=(service*)malloc(SERVICE_SIZE);
967            t=readServiceFile(m,buff1,&s1,corig);
968            if(t<0){
969              map* tmp00=getMapFromMaps(m,"lenv","message");
970              char tmp01[1024];
971              if(tmp00!=NULL)
972                sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),dp->d_name,tmp00->value);
973              else
974                sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),dp->d_name);
975              dup2(saved_stdout,fileno(stdout));
976              errorException(m, tmp01,"InternalError",NULL);
977              freeMaps(&m);
978              free(m);
979              return 1;
980            }
981#ifdef DEBUG
982            dumpService(s1);
983#endif
984            printDescribeProcessForProcess(m,n,s1);
985            freeService(&s1);
986            free(s1);
987            s1=NULL;
988            scount++;
989            setMapInMaps(m,"lenv","level","0");
990          }
991          free(corig);
992         
993          memset(buff,0,256);
994          snprintf(buff,256,"%s.zcfg",tmps);
995          memset(buff1,0,1024);
996#ifdef DEBUG
997          printf("\n#######%s\n########\n",buff);
998#endif
999          while ((dp = readdir(dirp)) != NULL)
1000            if( (strcasecmp("all.zcfg",buff)==0 && strstr(dp->d_name,".zcfg")>0)
1001                || strcasecmp(dp->d_name,buff)==0 ){
1002              memset(buff1,0,1024);
1003              snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
1004              s1=(service*)malloc(SERVICE_SIZE);
1005              if(s1 == NULL){
1006                dup2(saved_stdout,fileno(stdout));
1007                return errorException(m, _("Unable to allocate memory."),"InternalError",NULL);
1008              }
1009#ifdef DEBUG
1010              printf("#################\n(%s) %s\n#################\n",r_inputs->value,buff1);
1011#endif
1012              char *tmp0=zStrdup(dp->d_name);
1013              tmp0[strlen(tmp0)-5]=0;
1014              t=readServiceFile(m,buff1,&s1,tmp0);
1015              free(tmp0);
1016              if(t<0){
1017                map* tmp00=getMapFromMaps(m,"lenv","message");
1018                char tmp01[1024];
1019                if(tmp00!=NULL)
1020                  sprintf(tmp01,_("Unable to parse the ZCFG file: %s (%s)"),dp->d_name,tmp00->value);
1021                else
1022                  sprintf(tmp01,_("Unable to parse the ZCFG file: %s."),dp->d_name);
1023                dup2(saved_stdout,fileno(stdout));
1024                errorException(m, tmp01,"InternalError",NULL);
1025                freeMaps(&m);
1026                free(m);
1027                return 1;
1028              }
1029#ifdef DEBUG
1030              dumpService(s1);
1031#endif
1032              printDescribeProcessForProcess(m,n,s1);
1033              freeService(&s1);
1034              free(s1);
1035              s1=NULL;
1036              scount++;
1037            }
1038          rewinddir(dirp);
1039          tmps=strtok_r(NULL,",",&saveptr);
1040        }
1041      }
1042      closedir(dirp);
1043      fflush(stdout);
1044      dup2(saved_stdout,fileno(stdout));
1045      free(orig);
1046      printDocument(m,doc,getpid());
1047      freeMaps(&m);
1048      free(m);
1049      free(REQUEST);
1050      free(SERVICE_URL);
1051      fflush(stdout);
1052      return 0;
1053    }
1054    else
1055      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
1056        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue","request");
1057#ifdef DEBUG
1058        fprintf(stderr,"No request found %s",REQUEST);
1059#endif 
1060        closedir(dirp);
1061        freeMaps(&m);
1062        free(m);
1063        free(REQUEST);
1064        free(SERVICE_URL);
1065        fflush(stdout);
1066        return 0;
1067      }
1068    closedir(dirp);
1069  }
1070 
1071  s1=NULL;
1072  s1=(service*)malloc(SERVICE_SIZE);
1073  if(s1 == NULL){
1074    freeMaps(&m);
1075    free(m);
1076    free(REQUEST);
1077    free(SERVICE_URL);
1078    return errorException(m, _("Unable to allocate memory."),"InternalError",NULL);
1079  }
1080  r_inputs=getMap(request_inputs,"MetaPath");
1081  if(r_inputs!=NULL)
1082    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
1083  else
1084    snprintf(tmps1,1024,"%s/",ntmp);
1085  r_inputs=getMap(request_inputs,"Identifier");
1086  char *ttmp=zStrdup(tmps1);
1087  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
1088  free(ttmp);
1089#ifdef DEBUG
1090  fprintf(stderr,"Trying to load %s\n", tmps1);
1091#endif
1092  if(strstr(r_inputs->value,".")!=NULL){
1093    char *identifier=zStrdup(r_inputs->value);
1094    parseIdentifier(m,conf_dir,identifier,tmps1);
1095    map* tmpMap=getMapFromMaps(m,"lenv","metapath");
1096    if(tmpMap!=NULL)
1097      addToMap(request_inputs,"metapath",tmpMap->value);
1098    free(identifier);
1099  }else
1100    setMapInMaps(m,"lenv","Identifier",r_inputs->value);
1101  int saved_stdout = dup(fileno(stdout));
1102  dup2(fileno(stderr),fileno(stdout));
1103  t=readServiceFile(m,tmps1,&s1,r_inputs->value);
1104  fflush(stdout);
1105  dup2(saved_stdout,fileno(stdout));
1106  if(t<0){
1107    char *tmpMsg=(char*)malloc(2048+strlen(r_inputs->value));
1108    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
1109    errorException(m, tmpMsg, "InvalidParameterValue","identifier");
1110    free(tmpMsg);
1111    free(s1);
1112    freeMaps(&m);
1113    free(m);
1114    free(REQUEST);
1115    free(SERVICE_URL);
1116    return 0;
1117  }
1118  close(saved_stdout);
1119
1120#ifdef DEBUG
1121  dumpService(s1);
1122#endif
1123  int j;
1124 
1125
1126  /**
1127   * Create the input and output maps data structure
1128   */
1129  int i=0;
1130  HINTERNET hInternet;
1131  HINTERNET res;
1132  hInternet=InternetOpen(
1133#ifndef WIN32
1134                         (LPCTSTR)
1135#endif
1136                         "ZooWPSClient\0",
1137                         INTERNET_OPEN_TYPE_PRECONFIG,
1138                         NULL,NULL, 0);
1139
1140#ifndef WIN32
1141  if(!CHECK_INET_HANDLE(hInternet))
1142    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1143#endif
1144  maps* request_input_real_format=NULL;
1145  maps* tmpmaps = request_input_real_format;
1146  map* postRequest=NULL;
1147  postRequest=getMap(request_inputs,"xrequest");
1148  if(postRequest==NULLMAP){
1149    /**
1150     * Parsing outputs provided as KVP
1151     */
1152    r_inputs=NULL;
1153#ifdef DEBUG
1154    fprintf(stderr,"OUTPUT Parsing ... \n");
1155#endif
1156    r_inputs=getMap(request_inputs,"ResponseDocument"); 
1157    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
1158   
1159#ifdef DEBUG
1160    fprintf(stderr,"OUTPUT Parsing ... \n");
1161#endif
1162    if(r_inputs!=NULL){
1163#ifdef DEBUG
1164      fprintf(stderr,"OUTPUT Parsing start now ... \n");
1165#endif
1166      char cursor_output[10240];
1167      char *cotmp=zStrdup(r_inputs->value);
1168      snprintf(cursor_output,10240,"%s",cotmp);
1169      free(cotmp);
1170      j=0;
1171       
1172      /**
1173       * Put each Output into the outputs_as_text array
1174       */
1175      char * pToken;
1176      maps* tmp_output=NULL;
1177#ifdef DEBUG
1178      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
1179#endif
1180      pToken=strtok(cursor_output,";");
1181      char** outputs_as_text=(char**)malloc(128*sizeof(char*));
1182      if(outputs_as_text == NULL) {
1183        return errorException(m, _("Unable to allocate memory"), "InternalError",NULL);
1184      }
1185      i=0;
1186      while(pToken!=NULL){
1187#ifdef DEBUG
1188        fprintf(stderr,"***%s***\n",pToken);
1189        fflush(stderr);
1190        fprintf(stderr,"***%s***\n",pToken);
1191#endif
1192        outputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
1193        if(outputs_as_text[i] == NULL) {
1194          return errorException(m, _("Unable to allocate memory"), "InternalError",NULL);
1195        }
1196        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
1197        pToken = strtok(NULL,";");
1198        i++;
1199      }
1200      for(j=0;j<i;j++){
1201        char *tmp=zStrdup(outputs_as_text[j]);
1202        free(outputs_as_text[j]);
1203        char *tmpc;
1204        tmpc=strtok(tmp,"@");
1205        int k=0;
1206        while(tmpc!=NULL){
1207          if(k==0){
1208            if(tmp_output==NULL){
1209              tmp_output=(maps*)malloc(MAPS_SIZE);
1210              if(tmp_output == NULL){
1211                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1212              }
1213              tmp_output->name=zStrdup(tmpc);
1214              tmp_output->content=NULL;
1215              tmp_output->next=NULL;
1216            }
1217          }
1218          else{
1219            char *tmpv=strstr(tmpc,"=");
1220            char tmpn[256];
1221            memset(tmpn,0,256);
1222            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1223            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1224#ifdef DEBUG
1225            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
1226#endif
1227            if(tmp_output->content==NULL){
1228              tmp_output->content=createMap(tmpn,tmpv+1);
1229              tmp_output->content->next=NULL;
1230            }
1231            else
1232              addToMap(tmp_output->content,tmpn,tmpv+1);
1233          }
1234          k++;
1235#ifdef DEBUG
1236          fprintf(stderr,"***%s***\n",tmpc);
1237#endif
1238          tmpc=strtok(NULL,"@");
1239        }
1240        if(request_output_real_format==NULL)
1241          request_output_real_format=dupMaps(&tmp_output);
1242        else
1243          addMapsToMaps(&request_output_real_format,tmp_output);
1244        freeMaps(&tmp_output);
1245        free(tmp_output);
1246        tmp_output=NULL;
1247#ifdef DEBUG
1248        dumpMaps(tmp_output);
1249        fflush(stderr);
1250#endif
1251        free(tmp);
1252      }
1253      free(outputs_as_text);
1254    }
1255
1256
1257    /**
1258     * Parsing inputs provided as KVP
1259     */
1260    r_inputs=getMap(request_inputs,"DataInputs");
1261#ifdef DEBUG
1262    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
1263#endif
1264    char cursor_input[40960];
1265    if(r_inputs!=NULL)
1266      snprintf(cursor_input,40960,"%s",r_inputs->value);
1267    else{
1268      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue","DataInputs");
1269      freeMaps(&m);
1270      free(m);
1271      free(REQUEST);
1272      free(SERVICE_URL);
1273      InternetCloseHandle(hInternet);
1274      freeService(&s1);
1275      free(s1);
1276      return 0;
1277    }
1278    j=0;
1279 
1280    /**
1281     * Put each DataInputs into the inputs_as_text array
1282     */
1283    char *tmp1=zStrdup(cursor_input);
1284    char * pToken;
1285    pToken=strtok(cursor_input,";");
1286    if(pToken!=NULL && strncasecmp(pToken,tmp1,strlen(tmp1))==0){
1287      char* tmp2=url_decode(tmp1);
1288      snprintf(cursor_input,(strlen(tmp2)+1)*sizeof(char),"%s",tmp2);
1289      free(tmp2);
1290      pToken=strtok(cursor_input,";");
1291    }
1292    free(tmp1);
1293
1294    char** inputs_as_text=(char**)malloc(100*sizeof(char*));
1295    if(inputs_as_text == NULL){
1296      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1297    }
1298    i=0;
1299    while(pToken!=NULL){
1300#ifdef DEBUG
1301      fprintf(stderr,"***%s***\n",pToken);
1302#endif
1303      fflush(stderr);
1304#ifdef DEBUG
1305      fprintf(stderr,"***%s***\n",pToken);
1306#endif
1307      inputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
1308      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
1309      if(inputs_as_text[i] == NULL){
1310        return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1311      }
1312      pToken = strtok(NULL,";");
1313      i++;
1314    }
1315
1316    for(j=0;j<i;j++){
1317      char *tmp=zStrdup(inputs_as_text[j]);
1318      free(inputs_as_text[j]);
1319      char *tmpc;
1320      tmpc=strtok(tmp,"@");
1321      while(tmpc!=NULL){
1322#ifdef DEBUG
1323        fprintf(stderr,"***\n***%s***\n",tmpc);
1324#endif
1325        char *tmpv=strstr(tmpc,"=");
1326        char tmpn[256];
1327        memset(tmpn,0,256);
1328        if(tmpv!=NULL){
1329          strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1330          tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1331        }
1332        else{
1333          strncpy(tmpn,tmpc,strlen(tmpc)*sizeof(char));
1334          tmpn[strlen(tmpc)]=0;
1335        }
1336#ifdef DEBUG
1337        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
1338#endif
1339        if(tmpmaps==NULL){
1340          tmpmaps=(maps*)malloc(MAPS_SIZE);
1341          if(tmpmaps == NULL){
1342            return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1343          }
1344          tmpmaps->name=zStrdup(tmpn);
1345          if(tmpv!=NULL){
1346            char *tmpvf=url_decode(tmpv+1);
1347            tmpmaps->content=createMap("value",tmpvf);
1348            free(tmpvf);
1349          }
1350          else
1351            tmpmaps->content=createMap("value","Reference");
1352          tmpmaps->next=NULL;
1353        }
1354        tmpc=strtok(NULL,"@");
1355        while(tmpc!=NULL){
1356#ifdef DEBUG
1357          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
1358#endif
1359          char *tmpv1=strstr(tmpc,"=");
1360#ifdef DEBUG
1361          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1362#endif
1363          char tmpn1[1024];
1364          memset(tmpn1,0,1024);
1365          if(tmpv1!=NULL){
1366            strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
1367            tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
1368            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1369          }
1370          else{
1371            strncpy(tmpn1,tmpc,strlen(tmpc));
1372            tmpn1[strlen(tmpc)]=0;
1373            map* lmap=getLastMap(tmpmaps->content);
1374            char *tmpValue=(char*)malloc((strlen(tmpv)+strlen(tmpc)+1)*sizeof(char));
1375            sprintf(tmpValue,"%s@%s",tmpv+1,tmpc);
1376            free(lmap->value);
1377            lmap->value=zStrdup(tmpValue);
1378            free(tmpValue);
1379            tmpc=strtok(NULL,"@");
1380            continue;
1381          }
1382#ifdef DEBUG
1383          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
1384          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1385#endif
1386          if(strcmp(tmpn1,"xlink:href")!=0)
1387            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1388          else
1389            if(tmpv1!=NULL){
1390              char *tmpx2=url_decode(tmpv1+1);
1391              if(strncasecmp(tmpx2,"http://",7)!=0 &&
1392                 strncasecmp(tmpx2,"ftp://",6)!=0 &&
1393                 strncasecmp(tmpx2,"https://",8)!=0){
1394                char emsg[1024];
1395                sprintf(emsg,_("Unable to find a valid protocol to download the remote file %s"),tmpv1+1);
1396                errorException(m,emsg,"InternalError",NULL);
1397                freeMaps(&m);
1398                free(m);
1399                free(REQUEST);
1400                free(SERVICE_URL);
1401                InternetCloseHandle(hInternet);
1402                freeService(&s1);
1403                free(s1);
1404                return 0;
1405              }
1406#ifdef DEBUG
1407              fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
1408#endif
1409              addToMap(tmpmaps->content,tmpn1,tmpx2);
1410             
1411#ifndef WIN32
1412              if(CHECK_INET_HANDLE(hInternet))
1413#endif
1414                {
1415                  if(loadRemoteFile(&m,&tmpmaps->content,hInternet,tmpx2)<0){
1416                    freeMaps(&m);
1417                    free(m);
1418                    free(REQUEST);
1419                    free(SERVICE_URL);
1420                    InternetCloseHandle(hInternet);
1421                    freeService(&s1);
1422                    free(s1);
1423                    return 0;
1424                  }
1425                }
1426              free(tmpx2);
1427              addToMap(tmpmaps->content,"Reference",tmpv1+1);
1428            }
1429          tmpc=strtok(NULL,"@");
1430        }
1431#ifdef DEBUG
1432        dumpMaps(tmpmaps);
1433        fflush(stderr);
1434#endif
1435        if(request_input_real_format==NULL)
1436          request_input_real_format=dupMaps(&tmpmaps);
1437        else{
1438          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1439          if(testPresence!=NULL){
1440            elements* elem=getElements(s1->inputs,tmpmaps->name);
1441            if(elem!=NULL){
1442              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1443                freeMaps(&m);
1444                free(m);
1445                free(REQUEST);
1446                free(SERVICE_URL);
1447                InternetCloseHandle(hInternet);
1448                freeService(&s1);
1449                free(s1);
1450                return 0;
1451              }
1452            }
1453          }
1454          else
1455            addMapsToMaps(&request_input_real_format,tmpmaps);
1456        }
1457        freeMaps(&tmpmaps);
1458        free(tmpmaps);
1459        tmpmaps=NULL;
1460        free(tmp);
1461      }
1462    }
1463    free(inputs_as_text);
1464  }
1465  else {
1466    /**
1467     * Parse XML request
1468     */ 
1469    xmlInitParser();
1470#ifdef DEBUG
1471    fflush(stderr);
1472    fprintf(stderr,"BEFORE %s\n",postRequest->value);
1473    fflush(stderr);
1474#endif
1475    xmlDocPtr doc =
1476      xmlParseMemory(postRequest->value,cgiContentLength);
1477#ifdef DEBUG
1478    fprintf(stderr,"AFTER\n");
1479    fflush(stderr);
1480#endif
1481    /**
1482     * Parse every Input in DataInputs node.
1483     */
1484    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1485    xmlNodeSet* tmps=tmpsptr->nodesetval;
1486#ifdef DEBUG
1487    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1488#endif
1489    for(int k=0;k<tmps->nodeNr;k++){
1490      maps *tmpmaps=NULL;
1491      xmlNodePtr cur=tmps->nodeTab[k];
1492      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1493        /**
1494         * A specific Input node.
1495         */
1496#ifdef DEBUG
1497        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1498#endif
1499        xmlNodePtr cur2=cur->children;
1500        while(cur2!=NULL){
1501          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1502            cur2=cur2->next;
1503          if(cur2==NULL)
1504            break;
1505          /**
1506           * Indentifier
1507           */
1508          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1509            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1510            if(tmpmaps==NULL){
1511              tmpmaps=(maps*)malloc(MAPS_SIZE);
1512              if(tmpmaps == NULL){
1513                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1514              }
1515              tmpmaps->name=zStrdup((char*)val);
1516              tmpmaps->content=NULL;
1517              tmpmaps->next=NULL;
1518            }
1519            xmlFree(val);
1520          }
1521          /**
1522           * Title, Asbtract
1523           */
1524          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1525             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1526            xmlChar *val=
1527              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1528            if(tmpmaps==NULL){
1529              tmpmaps=(maps*)malloc(MAPS_SIZE);
1530              if(tmpmaps == NULL){
1531                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1532              }
1533              tmpmaps->name=zStrdup("missingIndetifier");
1534              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1535              tmpmaps->next=NULL;
1536            }
1537            else{
1538              if(tmpmaps->content!=NULL)
1539                addToMap(tmpmaps->content,
1540                         (char*)cur2->name,(char*)val);
1541              else
1542                tmpmaps->content=
1543                  createMap((char*)cur2->name,(char*)val);
1544            }
1545#ifdef DEBUG
1546            dumpMaps(tmpmaps);
1547#endif
1548            xmlFree(val);
1549          }
1550          /**
1551           * InputDataFormChoice (Reference or Data ?)
1552           */
1553          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1554            /**
1555             * Get every attribute from a Reference node
1556             * mimeType, encoding, schema, href, method
1557             * Header and Body gesture should be added here
1558             */
1559#ifdef DEBUG
1560            fprintf(stderr,"REFERENCE\n");
1561#endif
1562            const char *refs[5]={"mimeType","encoding","schema","method","href"};
1563            for(int l=0;l<5;l++){
1564#ifdef DEBUG
1565              fprintf(stderr,"*** %s ***",refs[l]);
1566#endif
1567              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1568              if(val!=NULL && xmlStrlen(val)>0){
1569                if(tmpmaps->content!=NULL)
1570                  addToMap(tmpmaps->content,refs[l],(char*)val);
1571                else
1572                  tmpmaps->content=createMap(refs[l],(char*)val);
1573                map* ltmp=getMap(tmpmaps->content,"method");
1574                if(l==4){
1575                  if(!(ltmp!=NULL && strncmp(ltmp->value,"POST",4)==0)
1576                     && CHECK_INET_HANDLE(hInternet)){
1577                    if(loadRemoteFile(&m,&tmpmaps->content,hInternet,(char*)val)!=0){
1578                      freeMaps(&m);
1579                      free(m);
1580                      free(REQUEST);
1581                      free(SERVICE_URL);
1582                      InternetCloseHandle(hInternet);
1583                      freeService(&s1);
1584                      free(s1);
1585                      return 0;
1586                    }
1587                  }
1588                }
1589              }
1590#ifdef DEBUG
1591              fprintf(stderr,"%s\n",val);
1592#endif
1593              xmlFree(val);
1594            }
1595#ifdef POST_DEBUG
1596            fprintf(stderr,"Parse Header and Body from Reference \n");
1597#endif
1598            xmlNodePtr cur3=cur2->children;
1599            HINTERNET hInternetP;
1600            hInternetP=InternetOpen(
1601#ifndef WIN32
1602                                   (LPCTSTR)
1603#endif
1604                                   "ZooWPSClient\0",
1605                                   INTERNET_OPEN_TYPE_PRECONFIG,
1606                                   NULL,NULL, 0);
1607            hInternetP.header=NULL;
1608            while(cur3!=NULL){
1609              while(cur3!=NULL && cur3->type!=XML_ELEMENT_NODE)
1610                cur3=cur3->next;
1611              if(cur3==NULL)
1612                break;
1613              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1614                const char *ha[2];
1615                ha[0]="key";
1616                ha[1]="value";
1617                int hai;
1618                char *has;
1619                char *key;
1620                for(hai=0;hai<2;hai++){
1621                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1622#ifdef POST_DEBUG
1623                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1624#endif
1625                  if(hai==0){
1626                    key=zStrdup((char*)val);
1627                  }else{
1628                    has=(char*)malloc((4+xmlStrlen(val)+strlen(key))*sizeof(char));
1629                    if(has == NULL){
1630                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1631                    }
1632                    snprintf(has,(3+xmlStrlen(val)+strlen(key)),"%s: %s",key,(char*)val);
1633                    free(key);
1634#ifdef POST_DEBUG
1635                    fprintf(stderr,"%s\n",has);
1636#endif
1637                  }
1638                  xmlFree(val);
1639                }
1640                hInternetP.header=curl_slist_append(hInternetP.header, has);
1641                if(has!=NULL)
1642                  free(has);
1643              }
1644              else{
1645#ifdef POST_DEBUG
1646                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1647#endif
1648                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1649#ifdef POST_DEBUG
1650                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1651#endif
1652                  char *tmp=(char*)malloc(cgiContentLength+1*sizeof(char));
1653                  memset(tmp,0,cgiContentLength);
1654                  xmlNodePtr cur4=cur3->children;
1655                  while(cur4!=NULL){
1656                    while(cur4->type!=XML_ELEMENT_NODE)
1657                      cur4=cur4->next;
1658                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1659                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1660                    xmlDocSetRootElement(bdoc,cur4);
1661                    xmlChar* btmps;
1662                    int bsize;
1663                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1664#ifdef POST_DEBUG
1665                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1666#endif
1667                    if(btmps!=NULL)
1668                      sprintf(tmp,"%s",(char*)btmps);
1669                    xmlFree(btmps);
1670                    cur4=cur4->next;
1671                    xmlFreeDoc(bdoc);
1672                  }
1673                  map *btmp=getMap(tmpmaps->content,"href");
1674                  if(btmp!=NULL){
1675#ifdef POST_DEBUG
1676                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1677                    curl_easy_setopt(hInternetP.handle, CURLOPT_VERBOSE, 1);
1678#endif
1679                    res=InternetOpenUrl(hInternetP,btmp->value,tmp,strlen(tmp),
1680                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1681                    char* tmpContent = (char*)malloc((res.nDataLen+1)*sizeof(char));
1682                    if(tmpContent == NULL){
1683                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1684                    }
1685                    size_t dwRead;
1686                    InternetReadFile(res, (LPVOID)tmpContent,
1687                                     res.nDataLen, &dwRead);
1688                    tmpContent[res.nDataLen]=0;
1689                    if(hInternetP.header!=NULL)
1690                      curl_slist_free_all(hInternetP.header);
1691                    addToMap(tmpmaps->content,"value",tmpContent);
1692                    free(tmpContent);
1693#ifdef POST_DEBUG
1694                    fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1695#endif             
1696                  }
1697                  free(tmp);
1698                }
1699                else
1700                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1701                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1702                    HINTERNET bInternet,res1;
1703                    bInternet=InternetOpen(
1704#ifndef WIN32
1705                                           (LPCTSTR)
1706#endif
1707                                           "ZooWPSClient\0",
1708                                           INTERNET_OPEN_TYPE_PRECONFIG,
1709                                           NULL,NULL, 0);
1710                    if(!CHECK_INET_HANDLE(bInternet))
1711                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1712#ifdef POST_DEBUG
1713                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1714#endif
1715                    res1=InternetOpenUrl(bInternet,(char*)val,NULL,0,
1716                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1717                    char* tmp=
1718                      (char*)malloc((res1.nDataLen+1)*sizeof(char));
1719                    if(tmp == NULL){
1720                      return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1721                    }
1722                    size_t bRead;
1723                    InternetReadFile(res1, (LPVOID)tmp,
1724                                     res1.nDataLen, &bRead);
1725                    tmp[res1.nDataLen]=0;
1726                    InternetCloseHandle(bInternet);
1727                    map *btmp=getMap(tmpmaps->content,"href");
1728                    if(btmp!=NULL){
1729#ifdef POST_DEBUG
1730                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1731                      curl_easy_setopt(hInternetP.handle, CURLOPT_VERBOSE, 1);
1732#endif
1733                      res=InternetOpenUrl(hInternetP,btmp->value,tmp,
1734                                          strlen(tmp),
1735                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1736                      char* tmpContent = (char*)malloc((res.nDataLen+1)*sizeof(char));
1737                      if(tmpContent == NULL){
1738                        return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1739                      }
1740                      size_t dwRead;
1741                      InternetReadFile(res, (LPVOID)tmpContent,
1742                                       res.nDataLen, &dwRead);
1743                      tmpContent[res.nDataLen]=0;
1744                      if(hInternetP.header!=NULL)
1745                        curl_slist_free_all(hInternetP.header);
1746                      addToMap(tmpmaps->content,"value",tmpContent);
1747#ifdef POST_DEBUG
1748                      fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1749#endif
1750                    }
1751                  }
1752              }
1753              cur3=cur3->next;
1754            }
1755            InternetCloseHandle(hInternetP);
1756#ifdef POST_DEBUG
1757            fprintf(stderr,"Header and Body was parsed from Reference \n");
1758#endif
1759#ifdef DEBUG
1760            dumpMap(tmpmaps->content);
1761            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1762                    cur2->name,cur2->content);
1763#endif
1764          }
1765          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1766#ifdef DEBUG
1767            fprintf(stderr,"DATA\n");
1768#endif
1769            xmlNodePtr cur4=cur2->children;
1770            while(cur4!=NULL){
1771              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1772                cur4=cur4->next;
1773              if(cur4==NULL)
1774                break;
1775              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1776                /**
1777                 * Get every attribute from a LiteralData node
1778                 * dataType , uom
1779                 */
1780                char *list[2];
1781                list[0]=zStrdup("dataType");
1782                list[1]=zStrdup("uom");
1783                for(int l=0;l<2;l++){
1784#ifdef DEBUG
1785                  fprintf(stderr,"*** LiteralData %s ***",list[l]);
1786#endif
1787                  xmlChar *val=xmlGetProp(cur4,BAD_CAST list[l]);
1788                  if(val!=NULL && strlen((char*)val)>0){
1789                    if(tmpmaps->content!=NULL)
1790                      addToMap(tmpmaps->content,list[l],(char*)val);
1791                    else
1792                      tmpmaps->content=createMap(list[l],(char*)val);
1793#ifdef DEBUG
1794                    fprintf(stderr,"%s\n",val);
1795#endif
1796                  }
1797                  xmlFree(val);
1798                  free(list[l]);                 
1799                }
1800              }
1801              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1802                /**
1803                 * Get every attribute from a Reference node
1804                 * mimeType, encoding, schema
1805                 */
1806                const char *coms[3]={"mimeType","encoding","schema"};
1807                for(int l=0;l<3;l++){
1808#ifdef DEBUG
1809                  fprintf(stderr,"*** ComplexData %s ***\n",coms[l]);
1810#endif
1811                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1812                  if(val!=NULL && strlen((char*)val)>0){
1813                    if(tmpmaps->content!=NULL)
1814                      addToMap(tmpmaps->content,coms[l],(char*)val);
1815                    else
1816                      tmpmaps->content=createMap(coms[l],(char*)val);
1817#ifdef DEBUG
1818                    fprintf(stderr,"%s\n",val);
1819#endif
1820                  }
1821                  xmlFree(val);
1822                }
1823              }
1824
1825              map* test=getMap(tmpmaps->content,"encoding");
1826              if(test==NULL){
1827                if(tmpmaps->content!=NULL)
1828                  addToMap(tmpmaps->content,"encoding","utf-8");
1829                else
1830                  tmpmaps->content=createMap("encoding","utf-8");
1831                test=getMap(tmpmaps->content,"encoding");
1832              }
1833
1834              if(strcasecmp(test->value,"base64")!=0){
1835                xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1836                map* ltmp=getMap(tmpmaps->content,"mimeType");
1837                if(mv==NULL || 
1838                   (xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0 &&
1839                    (ltmp==NULL || strncasecmp(ltmp->value,"text/xml",8)==0) )){
1840                  xmlDocPtr doc1=xmlNewDoc(BAD_CAST "1.0");
1841                  int buffersize;
1842                  xmlNodePtr cur5=cur4->children;
1843                  while(cur5!=NULL &&cur5->type!=XML_ELEMENT_NODE)
1844                    cur5=cur5->next;
1845                  xmlDocSetRootElement(doc1,cur5);
1846                  xmlDocDumpFormatMemoryEnc(doc1, &mv, &buffersize, "utf-8", 1);
1847                  char size[1024];
1848                  sprintf(size,"%d",buffersize);
1849                  addToMap(tmpmaps->content,"size",size);
1850                  xmlFreeDoc(doc1);
1851                }
1852                addToMap(tmpmaps->content,"value",(char*)mv);
1853                xmlFree(mv);
1854              }else{
1855                xmlChar* tmp=xmlNodeListGetRawString(doc,cur4->xmlChildrenNode,0);
1856                addToMap(tmpmaps->content,"value",(char*)tmp);
1857                map* tmpv=getMap(tmpmaps->content,"value");
1858                char *res=NULL;
1859                char *curs=tmpv->value;
1860                for(int i=0;i<=strlen(tmpv->value)/64;i++) {
1861                  if(res==NULL)
1862                    res=(char*)malloc(67*sizeof(char));
1863                  else
1864                    res=(char*)realloc(res,(((i+1)*65)+i)*sizeof(char));
1865                  int csize=i*65;
1866                  strncpy(res + csize,curs,64);
1867                  if(i==xmlStrlen(tmp)/64)
1868                    strcat(res,"\n\0");
1869                  else{
1870                    strncpy(res + (((i+1)*64)+i),"\n\0",2);
1871                    curs+=64;
1872                  }
1873                }
1874                free(tmpv->value);
1875                tmpv->value=zStrdup(res);
1876                free(res);
1877                xmlFree(tmp);
1878              }
1879              cur4=cur4->next;
1880            }
1881          }
1882#ifdef DEBUG
1883          fprintf(stderr,"cur2 next \n");
1884          fflush(stderr);
1885#endif
1886          cur2=cur2->next;
1887        }
1888#ifdef DEBUG
1889        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1890        fflush(stderr);
1891#endif
1892
1893        {
1894          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1895          if(testPresence!=NULL){
1896            elements* elem=getElements(s1->inputs,tmpmaps->name);
1897            if(elem!=NULL){
1898              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1899                freeMaps(&m);
1900                free(m);
1901                free(REQUEST);
1902                free(SERVICE_URL);
1903                InternetCloseHandle(hInternet);
1904                freeService(&s1);
1905                free(s1);
1906                return 0;
1907              }
1908            }
1909          }
1910          else
1911            addMapsToMaps(&request_input_real_format,tmpmaps);
1912        }
1913
1914#ifdef DEBUG
1915        fprintf(stderr,"******TMPMAPS*****\n");
1916        dumpMaps(tmpmaps);
1917        fprintf(stderr,"******REQUESTMAPS*****\n");
1918        dumpMaps(request_input_real_format);
1919#endif
1920        freeMaps(&tmpmaps);
1921        free(tmpmaps);
1922        tmpmaps=NULL;         
1923      }
1924#ifdef DEBUG
1925      dumpMaps(tmpmaps); 
1926#endif
1927    }
1928#ifdef DEBUG
1929    fprintf(stderr,"Search for response document node\n");
1930#endif
1931    xmlXPathFreeObject(tmpsptr);
1932   
1933    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1934    bool asRaw=false;
1935    tmps=tmpsptr->nodesetval;
1936    if(tmps->nodeNr==0){
1937      tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1938      tmps=tmpsptr->nodesetval;
1939      asRaw=true;
1940    }
1941#ifdef DEBUG
1942    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1943#endif
1944    for(int k=0;k<tmps->nodeNr;k++){
1945      if(asRaw==true)
1946        addToMap(request_inputs,"RawDataOutput","");
1947      else
1948        addToMap(request_inputs,"ResponseDocument","");
1949      maps *tmpmaps=NULL;
1950      xmlNodePtr cur=tmps->nodeTab[k];
1951      if(cur->type == XML_ELEMENT_NODE) {
1952        /**
1953         * A specific responseDocument node.
1954         */
1955        if(tmpmaps==NULL){
1956          tmpmaps=(maps*)malloc(MAPS_SIZE);
1957          if(tmpmaps == NULL){
1958            return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
1959          }
1960          tmpmaps->name=zStrdup("unknownIdentifier");
1961          tmpmaps->content=NULL;
1962          tmpmaps->next=NULL;
1963        }
1964        /**
1965         * Get every attribute: storeExecuteResponse, lineage, status
1966         */
1967        const char *ress[3]={"storeExecuteResponse","lineage","status"};
1968        xmlChar *val;
1969        for(int l=0;l<3;l++){
1970#ifdef DEBUG
1971          fprintf(stderr,"*** %s ***\t",ress[l]);
1972#endif
1973          val=xmlGetProp(cur,BAD_CAST ress[l]);
1974          if(val!=NULL && strlen((char*)val)>0){
1975            if(tmpmaps->content!=NULL)
1976              addToMap(tmpmaps->content,ress[l],(char*)val);
1977            else
1978              tmpmaps->content=createMap(ress[l],(char*)val);
1979            addToMap(request_inputs,ress[l],(char*)val);
1980          }
1981#ifdef DEBUG
1982          fprintf(stderr,"%s\n",val);
1983#endif
1984          xmlFree(val);
1985        }
1986        xmlNodePtr cur1=cur->children;
1987        while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
1988          cur1=cur1->next;
1989        int cur1cnt=0;
1990        while(cur1){
1991          /**
1992           * Indentifier
1993           */
1994          if(xmlStrncasecmp(cur1->name,BAD_CAST "Identifier",xmlStrlen(cur1->name))==0){
1995            xmlChar *val=
1996              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
1997            if(tmpmaps==NULL){
1998              tmpmaps=(maps*)malloc(MAPS_SIZE);
1999              if(tmpmaps == NULL){
2000                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2001              }
2002              tmpmaps->name=zStrdup((char*)val);
2003              tmpmaps->content=NULL;
2004              tmpmaps->next=NULL;
2005            }
2006            else{
2007              //free(tmpmaps->name);
2008              tmpmaps->name=zStrdup((char*)val);
2009            }
2010            if(asRaw==true)
2011              addToMap(request_inputs,"RawDataOutput",(char*)val);
2012            else{
2013              if(cur1cnt==0)
2014                addToMap(request_inputs,"ResponseDocument",(char*)val);
2015              else{
2016                map* tt=getMap(request_inputs,"ResponseDocument");
2017                char* tmp=zStrdup(tt->value);
2018                free(tt->value);
2019                tt->value=(char*)malloc((strlen(tmp)+strlen((char*)val)+1)*sizeof(char));
2020                sprintf(tt->value,"%s;%s",tmp,(char*)val);
2021                free(tmp);
2022              }
2023            }
2024            cur1cnt+=1;
2025            xmlFree(val);
2026          }
2027          /**
2028           * Title, Asbtract
2029           */
2030          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Title",xmlStrlen(cur1->name))==0 ||
2031                  xmlStrncasecmp(cur1->name,BAD_CAST "Abstract",xmlStrlen(cur1->name))==0){
2032            xmlChar *val=
2033              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
2034            if(tmpmaps==NULL){
2035              tmpmaps=(maps*)malloc(MAPS_SIZE);
2036              if(tmpmaps == NULL){
2037                return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2038              }
2039              tmpmaps->name=zStrdup("missingIndetifier");
2040              tmpmaps->content=createMap((char*)cur1->name,(char*)val);
2041              tmpmaps->next=NULL;
2042            }
2043            else{
2044              if(tmpmaps->content!=NULL)
2045                addToMap(tmpmaps->content,(char*)cur1->name,(char*)val);
2046              else
2047                tmpmaps->content=createMap((char*)cur1->name,(char*)val);
2048            }
2049            xmlFree(val);
2050          }
2051          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
2052            /**
2053             * Get every attribute from a Output node
2054             * mimeType, encoding, schema, uom, asReference
2055             */
2056            const char *outs[5]={"mimeType","encoding","schema","uom","asReference"};
2057            for(int l=0;l<5;l++){
2058#ifdef DEBUG
2059              fprintf(stderr,"*** %s ***\t",outs[l]);
2060#endif
2061              val=xmlGetProp(cur1,BAD_CAST outs[l]);
2062              if(val!=NULL && strlen((char*)val)>0){
2063                if(tmpmaps->content!=NULL)
2064                  addToMap(tmpmaps->content,outs[l],(char*)val);
2065                else
2066                  tmpmaps->content=createMap(outs[l],(char*)val);
2067              }
2068#ifdef DEBUG
2069              fprintf(stderr,"%s\n",val);
2070#endif
2071              xmlFree(val);
2072            }
2073            xmlNodePtr cur2=cur1->children;
2074            while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2075              cur2=cur2->next;
2076            while(cur2){
2077              /**
2078               * Indentifier
2079               */
2080              if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
2081                xmlChar *val=
2082                  xmlNodeListGetString(doc,cur2->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                  if(tmpmaps->name!=NULL)
2094                    free(tmpmaps->name);
2095                  tmpmaps->name=zStrdup((char*)val);;
2096                }
2097                xmlFree(val);
2098              }
2099              /**
2100               * Title, Asbtract
2101               */
2102              else if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
2103                      xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
2104                xmlChar *val=
2105                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
2106                if(tmpmaps==NULL){
2107                  tmpmaps=(maps*)malloc(MAPS_SIZE);
2108                  if(tmpmaps == NULL){
2109                    return errorException(m, _("Unable to allocate memory."), "InternalError",NULL);
2110                  }
2111                  tmpmaps->name=zStrdup("missingIndetifier");
2112                  tmpmaps->content=createMap((char*)cur2->name,(char*)val);
2113                  tmpmaps->next=NULL;
2114                }
2115                else{
2116                  if(tmpmaps->content!=NULL)
2117                    addToMap(tmpmaps->content,
2118                             (char*)cur2->name,(char*)val);
2119                  else
2120                    tmpmaps->content=
2121                      createMap((char*)cur2->name,(char*)val);
2122                }
2123                xmlFree(val);
2124              }
2125              cur2=cur2->next;
2126              while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
2127                cur2=cur2->next;
2128            }
2129          }
2130          cur1=cur1->next;
2131          while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
2132            cur1=cur1->next;
2133        }
2134      }
2135      if(request_output_real_format==NULL)
2136        request_output_real_format=dupMaps(&tmpmaps);
2137      else
2138        addMapsToMaps(&request_output_real_format,tmpmaps);
2139      if(tmpmaps!=NULL){
2140        freeMaps(&tmpmaps);
2141        free(tmpmaps);
2142        tmpmaps=NULL;
2143      }
2144    }
2145    xmlXPathFreeObject(tmpsptr);
2146    xmlFreeDoc(doc);
2147    xmlCleanupParser();
2148  }
2149 
2150
2151  //  if(CHECK_INET_HANDLE(hInternet))
2152  InternetCloseHandle(hInternet);
2153
2154#ifdef DEBUG
2155  fprintf(stderr,"\n%d\n",__LINE__);
2156  fflush(stderr);
2157  dumpMaps(request_input_real_format);
2158  dumpMaps(request_output_real_format);
2159  dumpMap(request_inputs);
2160  fprintf(stderr,"\n%d\n",__LINE__);
2161  fflush(stderr);
2162#endif
2163
2164  /**
2165   * Ensure that each requested arguments are present in the request
2166   * DataInputs and ResponseDocument / RawDataOutput
2167   */
2168  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,0);
2169  maps *ptr=request_input_real_format;
2170  while(ptr!=NULL){
2171    map *tmp0=getMap(ptr->content,"size");
2172    map *tmp1=getMap(ptr->content,"maximumMegabytes");
2173    if(tmp1!=NULL && tmp0!=NULL){
2174      float i=atof(tmp0->value)/1048576.0;
2175      if(i>=atoi(tmp1->value)){
2176        char tmps[1024];
2177        map* tmpe=createMap("code","FileSizeExceeded");
2178        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);
2179        addToMap(tmpe,"locator",ptr->name);
2180        addToMap(tmpe,"text",tmps);
2181        printExceptionReportResponse(m,tmpe);
2182        freeService(&s1);
2183        free(s1);
2184        freeMap(&tmpe);
2185        free(tmpe);
2186        freeMaps(&m);
2187        free(m);
2188        free(REQUEST);
2189        free(SERVICE_URL);
2190        freeMaps(&request_input_real_format);
2191        free(request_input_real_format);
2192        freeMaps(&request_output_real_format);
2193        free(request_output_real_format);
2194        freeMaps(&tmpmaps);
2195        free(tmpmaps);
2196        return 1;
2197      }
2198    }
2199    ptr=ptr->next;
2200  }
2201
2202  char *dfv1=addDefaultValues(&request_output_real_format,s1->outputs,m,1);
2203  if(strcmp(dfv1,"")!=0 || strcmp(dfv,"")!=0){
2204    char tmps[1024];
2205    map* tmpe=createMap("code","MissingParameterValue");
2206    if(strcmp(dfv,"")!=0){
2207      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);
2208      addToMap(tmpe,"locator",dfv);
2209    }
2210    else if(strcmp(dfv1,"")!=0){
2211      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);
2212      addToMap(tmpe,"locator",dfv1);
2213    }
2214    addToMap(tmpe,"text",tmps);
2215    printExceptionReportResponse(m,tmpe);
2216    freeService(&s1);
2217    free(s1);
2218    freeMap(&tmpe);
2219    free(tmpe);
2220    freeMaps(&m);
2221    free(m);
2222    free(REQUEST);
2223    free(SERVICE_URL);
2224    freeMaps(&request_input_real_format);
2225    free(request_input_real_format);
2226    freeMaps(&request_output_real_format);
2227    free(request_output_real_format);
2228    freeMaps(&tmpmaps);
2229    free(tmpmaps);
2230    return 1;
2231  }
2232  maps* tmpReqI=request_input_real_format;
2233  while(tmpReqI!=NULL){
2234    char name[1024];
2235    if(getMap(tmpReqI->content,"isFile")!=NULL){
2236      if (cgiFormFileName(tmpReqI->name, name, sizeof(name)) == cgiFormSuccess) {
2237        int BufferLen=1024;
2238        cgiFilePtr file;
2239        int targetFile;
2240        char storageNameOnServer[2048];
2241        char fileNameOnServer[64];
2242        char contentType[1024];
2243        char buffer[1024];
2244        char *tmpStr=NULL;
2245        int size;
2246        int got,t;
2247        map *path=getMapFromMaps(m,"main","tmpPath");
2248        cgiFormFileSize(tmpReqI->name, &size);
2249        cgiFormFileContentType(tmpReqI->name, contentType, sizeof(contentType));
2250        if (cgiFormFileOpen(tmpReqI->name, &file) == cgiFormSuccess) {
2251          t=-1;
2252          while(1){
2253            tmpStr=strstr(name+t+1,"\\");
2254            if(NULL==tmpStr)
2255              tmpStr=strstr(name+t+1,"/");
2256            if(NULL!=tmpStr)
2257              t=(int)(tmpStr-name);
2258            else
2259              break;
2260          }
2261          strcpy(fileNameOnServer,name+t+1);
2262         
2263          sprintf(storageNameOnServer,"%s/%s",path->value,fileNameOnServer);
2264#ifdef DEBUG
2265          fprintf(stderr,"Name on server %s\n",storageNameOnServer);
2266          fprintf(stderr,"fileNameOnServer: %s\n",fileNameOnServer);
2267#endif
2268          targetFile = open (storageNameOnServer,O_RDWR|O_CREAT|O_TRUNC,S_IRWXU|S_IRGRP|S_IROTH);
2269          if(targetFile<0){
2270#ifdef DEBUG
2271            fprintf(stderr,"could not create the new file,%s\n",fileNameOnServer);         
2272#endif
2273          }else{
2274            while (cgiFormFileRead(file, buffer, BufferLen, &got) ==cgiFormSuccess){
2275              if(got>0)
2276                write(targetFile,buffer,got);
2277            }
2278          }
2279          addToMap(tmpReqI->content,"lref",storageNameOnServer);
2280          cgiFormFileClose(file);
2281          close(targetFile);
2282#ifdef DEBUG
2283          fprintf(stderr,"File \"%s\" has been uploaded",fileNameOnServer);
2284#endif
2285        }
2286      }
2287    }
2288    tmpReqI=tmpReqI->next;
2289  }
2290
2291  ensureDecodedBase64(&request_input_real_format);
2292
2293#ifdef DEBUG
2294  fprintf(stderr,"REQUEST_INPUTS\n");
2295  dumpMaps(request_input_real_format);
2296  fprintf(stderr,"REQUEST_OUTPUTS\n");
2297  dumpMaps(request_output_real_format);
2298#endif
2299
2300  maps* curs=getMaps(m,"env");
2301  if(curs!=NULL){
2302    map* mapcs=curs->content;
2303    while(mapcs!=NULLMAP){
2304#ifndef WIN32
2305      setenv(mapcs->name,mapcs->value,1);
2306#else
2307#ifdef DEBUG
2308      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2309#endif
2310      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
2311#ifdef DEBUG
2312        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
2313#endif
2314        mapcs->value[strlen(mapcs->value)-1]=0;
2315      }
2316#ifdef DEBUG
2317      fflush(stderr);
2318      fprintf(stderr,"setting variable... %s\n",(
2319#endif
2320              SetEnvironmentVariable(mapcs->name,mapcs->value)
2321#ifdef DEBUG
2322              ==0)? "OK" : "FAILED");
2323#else
2324      ;
2325#endif
2326      char* toto=(char*)malloc((strlen(mapcs->name)+strlen(mapcs->value)+2)*sizeof(char));
2327      sprintf(toto,"%s=%s",mapcs->name,mapcs->value);
2328      putenv(toto);
2329#ifdef DEBUG
2330      fflush(stderr);
2331#endif
2332#endif
2333#ifdef DEBUG
2334      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2335      fflush(stderr);
2336#endif
2337      mapcs=mapcs->next;
2338    }
2339  }
2340 
2341#ifdef DEBUG
2342  dumpMap(request_inputs);
2343#endif
2344
2345  /**
2346   * Need to check if we need to fork to load a status enabled
2347   */
2348  r_inputs=NULL;
2349  map* store=getMap(request_inputs,"storeExecuteResponse");
2350  map* status=getMap(request_inputs,"status");
2351  /**
2352   * 05-007r7 WPS 1.0.0 page 57 :
2353   * 'If status="true" and storeExecuteResponse is "false" then the service
2354   * shall raise an exception.'
2355   */
2356  if(status!=NULL && strcmp(status->value,"true")==0 && 
2357     store!=NULL && strcmp(store->value,"false")==0){
2358    errorException(m, _("Status cannot be set to true with storeExecuteResponse to false. Please, modify your request parameters."), "InvalidParameterValue","storeExecuteResponse");
2359    freeService(&s1);
2360    free(s1);
2361    freeMaps(&m);
2362    free(m);
2363   
2364    freeMaps(&request_input_real_format);
2365    free(request_input_real_format);
2366   
2367    freeMaps(&request_output_real_format);
2368    free(request_output_real_format);
2369   
2370    free(REQUEST);
2371    free(SERVICE_URL);
2372    return 1;
2373  }
2374  r_inputs=getMap(request_inputs,"storeExecuteResponse");
2375  int eres=SERVICE_STARTED;
2376  int cpid=getpid();
2377
2378  /**
2379   * Initialize the specific [lenv] section which contains runtime variables:
2380   *
2381   *  - usid : it is an unique identification number
2382   *  - sid : it is the process idenfitication number (OS)
2383   *  - status : value between 0 and 100 to express the  completude of
2384   * the operations of the running service
2385   *  - message : is a string where you can store error messages, in case
2386   * service is failing, or o provide details on the ongoing operation.
2387   *  - cwd : is the current working directory
2388   *  - soap : is a boolean value, true if the request was contained in a SOAP
2389   * Envelop
2390   *  - sessid : string storing the session identifier (only when cookie is
2391   * used)
2392   *  - cgiSid : only defined on Window platforms (for being able to identify
2393   * the created process)
2394   *
2395   */
2396  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
2397  _tmpMaps->name=zStrdup("lenv");
2398  char tmpBuff[100];
2399  sprintf(tmpBuff,"%i",(cpid+(int)time(NULL)));
2400  _tmpMaps->content=createMap("usid",tmpBuff);
2401  _tmpMaps->next=NULL;
2402  sprintf(tmpBuff,"%i",cpid);
2403  addToMap(_tmpMaps->content,"sid",tmpBuff);
2404  addToMap(_tmpMaps->content,"status","0");
2405  addToMap(_tmpMaps->content,"cwd",ntmp);
2406  addToMap(_tmpMaps->content,"message",_("No message provided"));
2407  map* ltmp=getMap(request_inputs,"soap");
2408  if(ltmp!=NULL)
2409    addToMap(_tmpMaps->content,"soap",ltmp->value);
2410  else
2411    addToMap(_tmpMaps->content,"soap","false");
2412  if(cgiCookie!=NULL && strlen(cgiCookie)>0){
2413    int hasValidCookie=-1;
2414    char *tcook=zStrdup(cgiCookie);
2415    char *tmp=NULL;
2416    map* testing=getMapFromMaps(m,"main","cookiePrefix");
2417    if(testing==NULL){
2418      tmp=zStrdup("ID=");
2419    }else{
2420      tmp=(char*)malloc((strlen(testing->value)+2)*sizeof(char));
2421      sprintf(tmp,"%s=",testing->value);
2422    }
2423    if(strstr(cgiCookie,";")!=NULL){
2424      char *token,*saveptr;
2425      token=strtok_r(cgiCookie,";",&saveptr);
2426      while(token!=NULL){
2427        if(strcasestr(token,tmp)!=NULL){
2428          if(tcook!=NULL)
2429            free(tcook);
2430          tcook=zStrdup(token);
2431          hasValidCookie=1;
2432        }
2433        token=strtok_r(NULL,";",&saveptr);
2434      }
2435    }else{
2436      if(strstr(cgiCookie,"=")!=NULL && strcasestr(cgiCookie,tmp)!=NULL){
2437        tcook=zStrdup(cgiCookie);
2438        hasValidCookie=1;
2439      }
2440      if(tmp!=NULL){
2441        free(tmp);
2442      }
2443    }
2444    if(hasValidCookie>0){
2445      addToMap(_tmpMaps->content,"sessid",strstr(tcook,"=")+1);
2446      char session_file_path[1024];
2447      map *tmpPath=getMapFromMaps(m,"main","sessPath");
2448      if(tmpPath==NULL)
2449        tmpPath=getMapFromMaps(m,"main","tmpPath");
2450      char *tmp1=strtok(tcook,";");
2451      if(tmp1!=NULL)
2452        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(tmp1,"=")+1);
2453      else
2454        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(cgiCookie,"=")+1);
2455      free(tcook);
2456      maps *tmpSess=(maps*)malloc(MAPS_SIZE);
2457      struct stat file_status;
2458      int istat = stat(session_file_path, &file_status);
2459      if(istat==0 && file_status.st_size>0){
2460        conf_read(session_file_path,tmpSess);
2461        addMapsToMaps(&m,tmpSess);
2462        freeMaps(&tmpSess);
2463        free(tmpSess);
2464      }
2465    }
2466  }
2467  addMapsToMaps(&m,_tmpMaps);
2468  freeMaps(&_tmpMaps);
2469  free(_tmpMaps);
2470 
2471#ifdef DEBUG
2472  dumpMap(request_inputs);
2473#endif
2474#ifdef WIN32
2475  char *cgiSidL=NULL;
2476  if(getenv("CGISID")!=NULL)
2477    addToMap(request_inputs,"cgiSid",getenv("CGISID"));
2478  map* test1=getMap(request_inputs,"cgiSid");
2479  if(test1!=NULL){
2480    cgiSid=test1->value;
2481    addToMap(request_inputs,"storeExecuteResponse","true");
2482    addToMap(request_inputs,"status","true");
2483    setMapInMaps(m,"lenv","sid",test1->value);
2484    status=getMap(request_inputs,"status");
2485  }
2486#endif
2487  char *fbkp,*fbkp1;
2488  FILE *f0,*f1;
2489  if(status!=NULL)
2490    if(strcasecmp(status->value,"false")==0)
2491      status=NULLMAP;
2492  if(status==NULLMAP){
2493    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2494  }
2495  else{
2496    int   pid;
2497#ifdef DEBUG
2498    fprintf(stderr,"\nPID : %d\n",cpid);
2499#endif
2500
2501#ifndef WIN32
2502    pid = fork ();
2503#else
2504    if(cgiSid==NULL){
2505      createProcess(m,request_inputs,s1,NULL,cpid,request_input_real_format,request_output_real_format);
2506      pid = cpid;
2507    }else{
2508      pid=0;
2509      cpid=atoi(cgiSid);
2510    }
2511#endif
2512    if (pid > 0) {
2513      /**
2514       * dady :
2515       * set status to SERVICE_ACCEPTED
2516       */
2517#ifdef DEBUG
2518      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
2519#endif
2520      eres=SERVICE_ACCEPTED;
2521    }else if (pid == 0) {
2522      /**
2523       * son : have to close the stdout, stdin and stderr to let the parent
2524       * process answer to http client.
2525       */
2526      r_inputs=getMapFromMaps(m,"main","tmpPath");
2527      map* r_inputs1=getMap(s1->content,"ServiceProvider");
2528      fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2529      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2530      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2531      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
2532#ifdef DEBUG
2533      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
2534      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
2535      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
2536#endif
2537      freopen(flog, "w+", stderr);
2538      f0=freopen(fbkp , "w+", stdout);
2539#ifndef WIN32
2540      fclose(stdin);
2541#endif
2542      free(flog);
2543      /**
2544       * set status to SERVICE_STARTED and flush stdout to ensure full
2545       * content was outputed (the file used to store the ResponseDocument).
2546       * The rewind stdout to restart writing from the bgining of the file,
2547       * this way the data will be updated at the end of the process run.
2548       */
2549      printProcessResponse(m,request_inputs,cpid,s1,r_inputs1->value,SERVICE_STARTED,
2550                           request_input_real_format,request_output_real_format);
2551#ifndef WIN32
2552      fflush(stdout);
2553      rewind(stdout);
2554#else
2555#endif
2556      fbkp1=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2557      sprintf(fbkp1,"%s/%s_final_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2558      f1=freopen(fbkp1 , "w+", stdout);
2559      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2560    } else {
2561      /**
2562       * error server don't accept the process need to output a valid
2563       * error response here !!!
2564       */
2565      eres=-1;
2566      errorException(m, _("Unable to run the child process properly"), "InternalError",NULL);
2567    }
2568  }
2569
2570#ifdef DEBUG
2571  dumpMaps(request_output_real_format);
2572#endif
2573  if(eres!=-1)
2574    outputResponse(s1,request_input_real_format,
2575                   request_output_real_format,request_inputs,
2576                   cpid,m,eres);
2577  fflush(stdout);
2578  /**
2579   * Ensure that if error occurs when freeing memory, no signal will return
2580   * an ExceptionReport document as the result was already returned to the
2581   * client.
2582   */
2583#ifndef USE_GDB
2584  (void) signal(SIGSEGV,donothing);
2585  (void) signal(SIGTERM,donothing);
2586  (void) signal(SIGINT,donothing);
2587  (void) signal(SIGILL,donothing);
2588  (void) signal(SIGFPE,donothing);
2589  (void) signal(SIGABRT,donothing);
2590#endif
2591  if(((int)getpid())!=cpid || cgiSid!=NULL){
2592    fclose(stdout);
2593    fclose(stderr);
2594    unhandleStatus(m);
2595    /**
2596     * Dump back the final file fbkp1 to fbkp
2597     */
2598    fclose(f0);
2599    fclose(f1);
2600    FILE* f2=fopen(fbkp1,"rb");
2601    FILE* f3=fopen(fbkp,"wb+");
2602    free(fbkp);
2603    fseek(f2,0,SEEK_END);
2604    long flen=ftell(f2);
2605    fseek(f2,0,SEEK_SET);
2606    char *tmps1=(char*)malloc((flen+1)*sizeof(char));
2607    fread(tmps1,flen,1,f2);
2608    fwrite(tmps1,1,flen,f3);
2609    fclose(f2);
2610    fclose(f3);
2611    unlink(fbkp1);
2612    free(fbkp1);
2613    free(tmps1);
2614  }
2615
2616  freeService(&s1);
2617  free(s1);
2618  freeMaps(&m);
2619  free(m);
2620 
2621  freeMaps(&request_input_real_format);
2622  free(request_input_real_format);
2623 
2624  freeMaps(&request_output_real_format);
2625  free(request_output_real_format);
2626 
2627  free(REQUEST);
2628  free(SERVICE_URL);
2629#ifdef DEBUG
2630  fprintf(stderr,"Processed response \n");
2631  fflush(stdout);
2632  fflush(stderr);
2633#endif
2634
2635  return 0;
2636}
2637
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