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

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

Fix issue with namspaces in printExceptionReportResponse when Header were already created.

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