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

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

Fix issue on win32 platform for Python support. Remove dirent.obj dependency from utils/status service. readVSIFile defined when MapServer? is not activated.

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