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

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

Avoid issue repported on the mailing list.

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