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

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

Fix issue when passing <\![CDATA[]]> in ComplexData? for text/xml mimeType.

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