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

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

Support metapath embedded in service name. Add support for accessing ZOO-Kernel path subdirectories for full list of available services. Fix issue #98.

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