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

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

Fix ExceptionReport? nodes

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