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

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

Fix issue still kept in previous commit

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