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

Last change on this file since 539 was 539, checked in by djay, 9 years ago

Fix yaml service naming. Add javax javaxx optional sections in the main.cfg #105.

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