source: trunk/zoo-kernel/zoo_service_loader.c @ 280

Last change on this file since 280 was 280, checked in by djay, 13 years ago

Base of SOAP Envelope support. Primitive cache system. Solving bugs #45, #46, #47, #48, #50

File size: 58.2 KB
Line 
1/**
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2011 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
30extern "C" {
31#include <libxml/tree.h>
32#include <libxml/xmlmemory.h>
33#include <libxml/parser.h>
34#include <libxml/xpath.h>
35#include <libxml/xpathInternals.h>
36}
37
38#include "cgic.h"
39#include "ulinet.h"
40
41#include <libintl.h>
42#include <locale.h>
43#include <string.h>
44
45#include "service.h"
46
47#include "service_internal.h"
48
49#ifdef USE_PYTHON
50#include "service_internal_python.h"
51#endif
52
53#ifdef USE_JAVA
54#include "service_internal_java.h"
55#endif
56
57#ifdef USE_PHP
58#include "service_internal_php.h"
59#endif
60
61#ifdef USE_JS
62#include "service_internal_js.h"
63#endif
64
65#ifdef USE_PERL
66#include "service_internal_perl.h"
67#endif
68
69
70
71#include <dirent.h>
72#include <signal.h>
73#include <unistd.h>
74#ifndef WIN32
75#include <dlfcn.h>
76#include <libgen.h>
77#else
78#include <windows.h>
79#include <direct.h>
80#endif
81#include <fcntl.h>
82#include <time.h>
83#include <stdarg.h>
84
85#define _(String) dgettext ("zoo-kernel",String)
86
87
88void translateChar(char* str,char toReplace,char toReplaceBy){
89  int i=0,len=strlen(str);
90  for(i=0;i<len;i++){
91    if(str[i]==toReplace)
92      str[i]=toReplaceBy;
93  }
94}
95
96xmlXPathObjectPtr extractFromDoc(xmlDocPtr doc,const char* search){
97  xmlXPathContextPtr xpathCtx;
98  xmlXPathObjectPtr xpathObj;
99  xpathCtx = xmlXPathNewContext(doc);
100  xpathObj = xmlXPathEvalExpression(BAD_CAST search,xpathCtx);
101  xmlXPathFreeContext(xpathCtx);
102  return xpathObj;
103}
104
105void donothing(int sig){
106  fprintf(stderr,"Signal %d after the ZOO-Kernel returned result !\n",sig);
107  exit(0);
108}
109
110void sig_handler(int sig){
111  char tmp[100];
112  const char *ssig;
113  switch(sig){
114  case SIGSEGV:
115    ssig="SIGSEGV";
116    break;
117  case SIGTERM:
118    ssig="SIGTERM";
119    break;
120  case SIGINT:
121    ssig="SIGINT";
122    break;
123  case SIGILL:
124    ssig="SIGILL";
125    break;
126  case SIGFPE:
127    ssig="SIGFPE";
128    break;
129  case SIGABRT:
130    ssig="SIGABRT";
131    break;
132  default:
133    ssig="UNKNOWN";
134    break;
135  }
136  sprintf(tmp,_("ZOO Kernel failed to process your request receiving signal %d = %s"),sig,ssig);
137  errorException(NULL, tmp, "InternalError");
138#ifdef DEBUG
139  fprintf(stderr,"Not this time!\n");
140#endif
141  exit(0);
142}
143
144void loadServiceAndRun(maps **myMap,service* s1,map* request_inputs,maps **inputs,maps** ioutputs,int* eres){
145  char tmps1[1024];
146  char ntmp[1024];
147  maps *m=*myMap;
148  maps *request_output_real_format=*ioutputs;
149  maps *request_input_real_format=*inputs;
150  /**
151   * Extract serviceType to know what kind of service should be loaded
152   */
153  map* r_inputs=NULL;
154#ifndef WIN32
155  char* pntmp=getcwd(ntmp,1024);
156#else
157  _getcwd(ntmp,1024);
158#endif
159  r_inputs=getMap(s1->content,"serviceType");
160#ifdef DEBUG
161  fprintf(stderr,"LOAD A %s SERVICE PROVIDER \n",r_inputs->value);
162  fflush(stderr);
163#endif
164  if(strncasecmp(r_inputs->value,"C",1)==0){
165    r_inputs=getMap(request_inputs,"metapath");
166    if(r_inputs!=NULL)
167      sprintf(tmps1,"%s/%s",ntmp,r_inputs->value);
168    else
169      sprintf(tmps1,"%s/",ntmp);
170    char *altPath=strdup(tmps1);
171    r_inputs=getMap(s1->content,"ServiceProvider");
172    sprintf(tmps1,"%s/%s",altPath,r_inputs->value);
173    free(altPath);
174#ifdef DEBUG
175    fprintf(stderr,"Trying to load %s\n",tmps1);
176#endif
177#ifdef WIN32
178    HINSTANCE so = LoadLibraryEx(tmps1,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
179#else
180    void* so = dlopen(tmps1, RTLD_LAZY);
181#endif
182#ifdef DEBUG
183#ifdef WIN32
184    DWORD errstr;
185    errstr = GetLastError();
186    fprintf(stderr,"%s loaded (%d) \n",tmps1,errstr);
187#else
188    char *errstr;
189    errstr = dlerror();
190#endif
191#endif
192
193    if( so != NULL ) {
194#ifdef DEBUG
195      fprintf(stderr,"Library loaded %s \n",errstr);
196      fprintf(stderr,"Service Shared Object = %s\n",r_inputs->value);
197#endif
198      r_inputs=getMap(s1->content,"serviceType");
199#ifdef DEBUG
200      dumpMap(r_inputs);
201      fprintf(stderr,"%s\n",r_inputs->value);
202      fflush(stderr);
203#endif
204      if(strncasecmp(r_inputs->value,"C-FORTRAN",9)==0){
205        r_inputs=getMap(request_inputs,"Identifier");
206        char fname[1024];
207        sprintf(fname,"%s_",r_inputs->value);
208#ifdef DEBUG
209        fprintf(stderr,"Try to load function %s\n",fname);
210#endif
211#ifdef WIN32
212        typedef int (CALLBACK* execute_t)(char***,char***,char***);
213        execute_t execute=(execute_t)GetProcAddress(so,fname);
214#else
215        typedef int (*execute_t)(char***,char***,char***);
216        execute_t execute=(execute_t)dlsym(so,fname);
217#endif
218#ifdef DEBUG
219#ifdef WIN32
220        errstr = GetLastError();
221#else
222        errstr = dlerror();
223#endif
224        fprintf(stderr,"Function loaded %s\n",errstr);
225#endif 
226
227        char main_conf[10][30][1024];
228        char inputs[10][30][1024];
229        char outputs[10][30][1024];
230        for(int i=0;i<10;i++){
231          for(int j=0;j<30;j++){
232            memset(main_conf[i][j],0,1024);
233            memset(inputs[i][j],0,1024);
234            memset(outputs[i][j],0,1024);
235          }
236        }
237        mapsToCharXXX(m,(char***)main_conf);
238        mapsToCharXXX(request_input_real_format,(char***)inputs);
239        mapsToCharXXX(request_output_real_format,(char***)outputs);
240        *eres=execute((char***)&main_conf[0],(char***)&inputs[0],(char***)&outputs[0]);
241#ifdef DEBUG
242        fprintf(stderr,"Function run successfully \n");
243#endif
244        charxxxToMaps((char***)&outputs[0],&request_output_real_format);
245      }else{
246#ifdef DEBUG
247#ifdef WIN32
248        errstr = GetLastError();
249        fprintf(stderr,"Function %s failed to load because of %d\n",r_inputs->value,errstr);
250#endif
251#endif
252        r_inputs=getMap(request_inputs,"Identifier");
253#ifdef DEBUG
254        fprintf(stderr,"Try to load function %s\n",r_inputs->value);
255#endif
256        typedef int (*execute_t)(maps**,maps**,maps**);
257#ifdef WIN32
258        execute_t execute=(execute_t)GetProcAddress(so,r_inputs->value); 
259#else
260        execute_t execute=(execute_t)dlsym(so,r_inputs->value);
261#endif
262
263#ifdef DEBUG
264#ifdef WIN32
265        errstr = GetLastError();
266#else
267        errstr = dlerror();
268#endif
269        fprintf(stderr,"Function loaded %s\n",errstr);
270#endif 
271
272#ifdef DEBUG
273        fprintf(stderr,"Now run the function \n");
274        fflush(stderr);
275#endif
276        *eres=execute(&m,&request_input_real_format,&request_output_real_format);
277#ifdef DEBUG
278        fprintf(stderr,"Function loaded and returned %d\n",eres);
279        fflush(stderr);
280#endif
281      }
282#ifdef WIN32
283      *ioutputs=dupMaps(&request_output_real_format);
284      FreeLibrary(so);
285#else
286      dlclose(so);
287#endif
288    } else {
289      /**
290       * Unable to load the specified shared library
291       */
292      char tmps[1024];
293#ifdef WIN32
294      DWORD errstr = GetLastError();
295#else
296      char* errstr = dlerror();
297#endif
298      sprintf(tmps,_("C Library can't be loaded %s \n"),errstr);
299      map* tmps1=createMap("text",tmps);
300      printExceptionReportResponse(m,tmps1);
301      *eres=-1;
302    }
303  }
304  else
305#ifdef USE_PYTHON
306    if(strncasecmp(r_inputs->value,"PYTHON",6)==0){
307      *eres=zoo_python_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
308    }
309    else
310#endif
311       
312#ifdef USE_JAVA
313      if(strncasecmp(r_inputs->value,"JAVA",4)==0){
314        *eres=zoo_java_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
315      }
316      else
317#endif
318
319#ifdef USE_PHP
320        if(strncasecmp(r_inputs->value,"PHP",3)==0){
321          *eres=zoo_php_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
322        }
323        else
324#endif
325           
326           
327#ifdef USE_PERL
328          if(strncasecmp(r_inputs->value,"PERL",4)==0){
329            *eres=zoo_perl_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
330          }
331          else
332#endif
333
334#ifdef USE_JS
335            if(strncasecmp(r_inputs->value,"JS",2)==0){
336              *eres=zoo_js_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
337            }
338            else
339#endif
340              {
341                char tmpv[1024];
342                sprintf(tmpv,_("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),r_inputs->value);
343                map* tmps=createMap("text",tmpv);
344                printExceptionReportResponse(m,tmps);
345                *eres=-1;
346              }
347  *myMap=m;
348#ifndef WIN32
349  *ioutputs=request_output_real_format;
350#endif
351}
352
353#ifdef WIN32
354/**
355 * createProcess function: create a new process after setting some env variables
356 */
357void createProcess(maps* m,map* request_inputs,service* s1,char* opts,int cpid, maps* inputs,maps* outputs){
358  STARTUPINFO si;
359  PROCESS_INFORMATION pi;
360  ZeroMemory( &si, sizeof(si) );
361  si.cb = sizeof(si);
362  ZeroMemory( &pi, sizeof(pi) );
363  char *tmp=(char *)malloc((1024+cgiContentLength)*sizeof(char));
364  char *tmpq=(char *)malloc((1024+cgiContentLength)*sizeof(char));
365  map *req=getMap(request_inputs,"request");
366  map *id=getMap(request_inputs,"identifier");
367  map *di=getMap(request_inputs,"DataInputs");
368
369  char *dataInputsKVP=getMapsAsKVP(inputs,cgiContentLength,0);
370  char *dataOutputsKVP=getMapsAsKVP(outputs,cgiContentLength,1);
371  fprintf(stderr,"DATAINPUTSKVP %s\n",dataInputsKVP);
372  fprintf(stderr,"DATAOUTPUTSKVP %s\n",dataOutputsKVP);
373  map *sid=getMapFromMaps(m,"lenv","sid");
374  map* r_inputs=getMapFromMaps(m,"main","tmpPath");
375  map* r_inputs1=getMap(s1->content,"ServiceProvider");
376  map* r_inputs2=getMap(s1->content,"ResponseDocument");
377  if(r_inputs2==NULL)
378    r_inputs2=getMap(s1->content,"RawDataOutput");
379  map *tmpPath=getMapFromMaps(m,"lenv","cwd");
380
381  if(r_inputs2!=NULL){
382    sprintf(tmp,"\"request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s&cgiSid=%s\"",req->value,id->value,dataInputsKVP,r_inputs2->name,r_inputs2->value,sid->value);
383        sprintf(tmpq,"request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s",req->value,id->value,dataInputsKVP,r_inputs2->name,dataOutputsKVP);
384  }
385  else{
386    sprintf(tmp,"\"request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&cgiSid=%s\"",req->value,id->value,dataInputsKVP,sid->value);
387    sprintf(tmpq,"request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s",req->value,id->value,dataInputsKVP,sid->value);
388  }
389
390  char *tmp1=strdup(tmp);
391  sprintf(tmp,"zoo_loader.cgi %s \"%s\"",tmp1,sid->value);
392
393  free(dataInputsKVP);
394  free(dataOutputsKVP);
395  fprintf(stderr,"REQUEST IS : %s \n",tmp);
396  SetEnvironmentVariable("CGISID",TEXT(sid->value));
397  SetEnvironmentVariable("QUERY_STRING",TEXT(tmpq));
398  char clen[1000];
399  sprintf(clen,"%d",strlen(tmpq));
400  SetEnvironmentVariable("CONTENT_LENGTH",TEXT(clen));
401
402  if( !CreateProcess( NULL,             // No module name (use command line)
403                      TEXT(tmp),        // Command line
404                      NULL,             // Process handle not inheritable
405                      NULL,             // Thread handle not inheritable
406                      FALSE,            // Set handle inheritance to FALSE
407                      CREATE_NO_WINDOW, // Apache won't wait until the end
408                      NULL,             // Use parent's environment block
409                      NULL,             // Use parent's starting directory
410                      &si,              // Pointer to STARTUPINFO struct
411                      &pi )             // Pointer to PROCESS_INFORMATION struct
412      ) 
413    { 
414      fprintf( stderr, "CreateProcess failed (%d).\n", GetLastError() );
415      return ;
416    }else{
417    fprintf( stderr, "CreateProcess successfull (%d).\n\n\n\n", GetLastError() );
418  }
419  CloseHandle( pi.hProcess );
420  CloseHandle( pi.hThread );
421  fprintf(stderr,"CreateProcess finished !\n");
422}
423#endif
424
425int runRequest(map* request_inputs)
426{
427
428#ifndef USE_GDB
429  (void) signal(SIGSEGV,sig_handler);
430  (void) signal(SIGTERM,sig_handler);
431  (void) signal(SIGINT,sig_handler);
432  (void) signal(SIGILL,sig_handler);
433  (void) signal(SIGFPE,sig_handler);
434  (void) signal(SIGABRT,sig_handler);
435#endif
436
437  map* r_inputs=NULL;
438  maps* m=NULL;
439
440  char* REQUEST=NULL;
441  /**
442   * Parsing service specfic configuration file
443   */
444  m=(maps*)calloc(1,MAPS_SIZE);
445  if(m == NULL){
446    return errorException(m, _("Unable to allocate memory."), "InternalError");
447  }
448  char ntmp[1024];
449#ifndef WIN32
450  char *pntmp=getcwd(ntmp,1024);
451#else
452  _getcwd(ntmp,1024);
453#endif
454  r_inputs=getMap(request_inputs,"metapath");
455  if(r_inputs==NULL){
456    if(request_inputs==NULL)
457      request_inputs=createMap("metapath","");
458    else
459      addToMap(request_inputs,"metapath","");
460#ifdef DEBUG
461    fprintf(stderr,"ADD METAPATH\n");
462    dumpMap(request_inputs);
463#endif
464    r_inputs=getMap(request_inputs,"metapath");
465  }
466  char conf_file[10240];
467  snprintf(conf_file,10240,"%s/%s/main.cfg",ntmp,r_inputs->value);
468  conf_read(conf_file,m);
469#ifdef DEBUG
470  fprintf(stderr, "***** BEGIN MAPS\n"); 
471  dumpMaps(m);
472  fprintf(stderr, "***** END MAPS\n");
473#endif
474
475  bindtextdomain ("zoo-kernel","/usr/share/locale/");
476  bindtextdomain ("zoo-services","/usr/share/locale/");
477 
478  if((r_inputs=getMap(request_inputs,"language"))!=NULL){
479    char *tmp=strdup(r_inputs->value);
480    translateChar(tmp,'-','_');
481    setlocale (LC_ALL, tmp);
482    free(tmp);
483    setMapInMaps(m,"main","language",r_inputs->value);
484  }
485  else{
486    setlocale (LC_ALL, "en_US");
487    setMapInMaps(m,"main","language","en-US");
488  }
489  setlocale (LC_NUMERIC, "en_US");
490  bind_textdomain_codeset("zoo-kernel","UTF-8");
491  textdomain("zoo-kernel");
492  bind_textdomain_codeset("zoo-services","UTF-8");
493  textdomain("zoo-services");
494
495  map* lsoap=getMap(request_inputs,"soap");
496  if(lsoap!=NULL && strcasecmp(lsoap->value,"true")==0)
497    setMapInMaps(m,"main","isSoap","true");
498  else
499    setMapInMaps(m,"main","isSoap","false");
500
501  /**
502   * Check for minimum inputs
503   */
504  r_inputs=getMap(request_inputs,"Request");
505  if(request_inputs==NULL || r_inputs==NULL){ 
506    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue");
507    freeMaps(&m);
508    free(m);
509    freeMap(&request_inputs);
510    free(request_inputs);
511    free(REQUEST);
512    return 1;
513  }
514  else{
515    REQUEST=strdup(r_inputs->value);
516    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
517       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
518       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
519      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
520      freeMaps(&m);
521      free(m);
522      free(REQUEST);
523      return 1;
524    }
525  }
526  r_inputs=NULL;
527  r_inputs=getMap(request_inputs,"Service");
528  if(r_inputs==NULLMAP){
529    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue");
530    freeMaps(&m);
531    free(m);
532    free(REQUEST);
533    return 1;
534  }
535  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
536    r_inputs=getMap(request_inputs,"Version");
537    if(r_inputs==NULL){ 
538      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue");
539      freeMaps(&m);
540      free(m);
541      free(REQUEST);
542      return 1;
543    }
544  }
545
546  r_inputs=getMap(request_inputs,"serviceprovider");
547  if(r_inputs==NULL){
548    addToMap(request_inputs,"serviceprovider","");
549  }
550
551  maps* request_output_real_format=NULL;
552  map* tmpm=getMapFromMaps(m,"main","serverAddress");
553  if(tmpm!=NULL)
554    SERVICE_URL=strdup(tmpm->value);
555  else
556    SERVICE_URL=strdup(DEFAULT_SERVICE_URL);
557
558  service* s1;
559  int scount=0;
560
561#ifdef DEBUG
562  dumpMap(r_inputs);
563#endif
564  char conf_dir[1024];
565  int t;
566  char tmps1[1024];
567
568  r_inputs=NULL;
569  r_inputs=getMap(request_inputs,"metapath");
570  if(r_inputs!=NULL)
571    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
572  else
573    snprintf(conf_dir,1024,"%s",ntmp);
574
575  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
576    struct dirent *dp;
577#ifdef DEBUG
578    dumpMap(r_inputs);
579#endif
580    DIR *dirp = opendir(conf_dir);
581    if(dirp==NULL){
582      return errorException(m, _("The specified path doesn't exist."),"InvalidParameterValue");
583    }
584    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
585    r_inputs=NULL;
586    r_inputs=getMap(request_inputs,"ServiceProvider");
587    xmlNodePtr n;
588    if(r_inputs!=NULL)
589      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
590    else
591      n = printGetCapabilitiesHeader(doc,"",m);
592    /**
593     * Here we need to close stdout to ensure that not supported chars
594     * has been found in the zcfg and then printed on stdout
595     */
596    int saved_stdout = dup(fileno(stdout));
597    dup2(fileno(stderr),fileno(stdout));
598    while ((dp = readdir(dirp)) != NULL)
599      if(strstr(dp->d_name,".zcfg")!=0){
600        memset(tmps1,0,1024);
601        snprintf(tmps1,1024,"%s/%s",conf_dir,dp->d_name);
602        s1=(service*)calloc(1,SERVICE_SIZE);
603        if(s1 == NULL){ 
604          return errorException(m, _("Unable to allocate memory."),"InternalError");
605        }
606#ifdef DEBUG
607        fprintf(stderr,"#################\n%s\n#################\n",tmps1);
608#endif
609        t=getServiceFromFile(tmps1,&s1);
610#ifdef DEBUG
611        dumpService(s1);
612        fflush(stdout);
613        fflush(stderr);
614#endif
615        printGetCapabilitiesForProcess(m,n,s1);
616        freeService(&s1);
617        free(s1);
618        scount++;
619      }
620    (void)closedir(dirp);
621    fflush(stdout);
622    dup2(saved_stdout,fileno(stdout));
623    printDocument(m,doc,getpid());
624    freeMaps(&m);
625    free(m);
626    free(REQUEST);
627    free(SERVICE_URL);
628    fflush(stdout);
629    return 0;
630  }
631  else{
632    r_inputs=getMap(request_inputs,"Identifier");
633    if(r_inputs==NULL 
634       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
635      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue");
636      freeMaps(&m);
637      free(m);
638      free(REQUEST);
639      free(SERVICE_URL);
640      return 0;
641    }
642
643    struct dirent *dp;
644    DIR *dirp = opendir(conf_dir);
645    if(dirp==NULL){
646      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue");
647      freeMaps(&m);
648      free(m);
649      free(REQUEST);
650      free(SERVICE_URL);
651      return 0;
652    }
653    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
654      /**
655       * Loop over Identifier list
656       */
657      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
658      r_inputs=NULL;
659      r_inputs=getMap(request_inputs,"ServiceProvider");
660
661      xmlNodePtr n;
662      if(r_inputs!=NULL)
663        n = printDescribeProcessHeader(doc,r_inputs->value,m);
664      else
665        n = printDescribeProcessHeader(doc,"",m);
666
667      r_inputs=getMap(request_inputs,"Identifier");
668      char *tmps=strtok(r_inputs->value,",");
669     
670      char buff[256];
671      char buff1[1024];
672      int saved_stdout = dup(fileno(stdout));
673      dup2(fileno(stderr),fileno(stdout));
674      while(tmps){
675        memset(buff,0,256);
676        snprintf(buff,256,"%s.zcfg",tmps);
677        memset(buff1,0,1024);
678#ifdef DEBUG
679        fprintf(stderr,"\n#######%s\n########\n",buff1);
680#endif
681        while ((dp = readdir(dirp)) != NULL)
682          if((strcasecmp("all.zcfg",buff)==0 && strstr(dp->d_name,".zcfg")>0)
683             || strcasecmp(dp->d_name,buff)==0){
684            memset(buff1,0,1024);
685            snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
686            s1=(service*)calloc(1,SERVICE_SIZE);
687            if(s1 == NULL){
688              return errorException(m, _("Unable to allocate memory."),"InternalError");
689            }
690#ifdef DEBUG
691            fprintf(stderr,"#################\n%s\n#################\n",buff1);
692#endif
693            t=getServiceFromFile(buff1,&s1);
694#ifdef DEBUG
695            dumpService(s1);
696#endif
697            printDescribeProcessForProcess(m,n,s1,1);
698            freeService(&s1);
699            free(s1);
700            scount++;
701          }
702        rewinddir(dirp);
703        tmps=strtok(NULL,",");
704      }
705      closedir(dirp);
706      fflush(stdout);
707      dup2(saved_stdout,fileno(stdout));
708      printDocument(m,doc,getpid());
709      freeMaps(&m);
710      free(m);
711      free(REQUEST);
712      free(SERVICE_URL);
713      fflush(stdout);
714#ifndef LINUX_FREE_ISSUE
715      if(s1)
716        free(s1);
717#endif
718      return 0;
719    }
720    else
721      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
722        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
723#ifdef DEBUG
724        fprintf(stderr,"No request found %s",REQUEST);
725#endif 
726        closedir(dirp);
727        return 0;
728      }
729    closedir(dirp);
730  }
731 
732  s1=NULL;
733  s1=(service*)calloc(1,SERVICE_SIZE);
734  if(s1 == NULL){
735    freeMaps(&m);
736    free(m);
737    free(REQUEST);
738    free(SERVICE_URL);
739    return errorException(m, _("Unable to allocate memory."),"InternalError");
740  }
741  r_inputs=getMap(request_inputs,"MetaPath");
742  if(r_inputs!=NULL)
743    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
744  else
745    snprintf(tmps1,1024,"%s/",ntmp);
746  r_inputs=getMap(request_inputs,"Identifier");
747  char *ttmp=strdup(tmps1);
748  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
749  free(ttmp);
750#ifdef DEBUG
751  fprintf(stderr,"Trying to load %s\n", tmps1);
752#endif
753  int saved_stdout = dup(fileno(stdout));
754    dup2(fileno(stderr),fileno(stdout));
755  t=getServiceFromFile(tmps1,&s1);
756  fflush(stdout);
757  dup2(saved_stdout,fileno(stdout));
758  if(t<0){
759    char *tmpMsg=(char*)malloc(2048+strlen(r_inputs->value));
760   
761    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
762    errorException(m, tmpMsg, "InvalidParameterValue");
763    free(tmpMsg);
764    freeService(&s1);
765    free(s1);
766    freeMaps(&m);
767    free(m);
768    free(REQUEST);
769    free(SERVICE_URL);
770    return 0;
771  }
772  close(saved_stdout);
773
774#ifdef DEBUG
775  dumpService(s1);
776#endif
777  int j;
778 
779  /**
780   * Create the input maps data structure
781   */
782  int i=0;
783  HINTERNET hInternet;
784  HINTERNET res;
785  hInternet=InternetOpen(
786#ifndef WIN32
787                         (LPCTSTR)
788#endif
789                         "ZooWPSClient\0",
790                         INTERNET_OPEN_TYPE_PRECONFIG,
791                         NULL,NULL, 0);
792
793#ifndef WIN32
794  if(!CHECK_INET_HANDLE(hInternet))
795    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
796#endif
797  maps* request_input_real_format=NULL;
798  maps* tmpmaps = request_input_real_format;
799  map* postRequest=NULL;
800  postRequest=getMap(request_inputs,"xrequest");
801  if(postRequest==NULLMAP){
802    /**
803     * Parsing outputs provided as KVP
804     */
805    r_inputs=NULL;
806#ifdef DEBUG
807    fprintf(stderr,"OUTPUT Parsing ... \n");
808#endif
809    r_inputs=getMap(request_inputs,"ResponseDocument"); 
810    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
811   
812#ifdef DEBUG
813    fprintf(stderr,"OUTPUT Parsing ... \n");
814#endif
815    if(r_inputs!=NULL){
816#ifdef DEBUG
817      fprintf(stderr,"OUTPUT Parsing start now ... \n");
818#endif
819      char cursor_output[10240];
820      char *cotmp=strdup(r_inputs->value);
821      snprintf(cursor_output,10240,"%s",cotmp);
822      free(cotmp);
823      j=0;
824       
825      /**
826       * Put each Output into the outputs_as_text array
827       */
828      char * pToken;
829      maps* tmp_output=NULL;
830#ifdef DEBUG
831      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
832#endif
833      pToken=strtok(cursor_output,";");
834      char** outputs_as_text=(char**)calloc(128,sizeof(char*));
835      if(outputs_as_text == NULL) {
836        return errorException(m, _("Unable to allocate memory"), "InternalError");
837      }
838      i=0;
839      while(pToken!=NULL){
840#ifdef DEBUG
841        fprintf(stderr,"***%s***\n",pToken);
842        fflush(stderr);
843        fprintf(stderr,"***%s***\n",pToken);
844#endif
845        outputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
846        if(outputs_as_text[i] == NULL) {
847          return errorException(m, _("Unable to allocate memory"), "InternalError");
848        }
849        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
850        pToken = strtok(NULL,";");
851        i++;
852      }
853      for(j=0;j<i;j++){
854        char *tmp=strdup(outputs_as_text[j]);
855        free(outputs_as_text[j]);
856        char *tmpc;
857        tmpc=strtok(tmp,"@");
858        int k=0;
859        while(tmpc!=NULL){
860          if(k==0){
861            if(tmp_output==NULL){
862              tmp_output=(maps*)calloc(1,MAPS_SIZE);
863              if(tmp_output == NULL){
864                return errorException(m, _("Unable to allocate memory."), "InternalError");
865              }
866              tmp_output->name=strdup(tmpc);
867              tmp_output->content=NULL;
868              tmp_output->next=NULL;
869            }
870          }
871          else{
872            char *tmpv=strstr(tmpc,"=");
873            char tmpn[256];
874            memset(tmpn,0,256);
875            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
876            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
877#ifdef DEBUG
878            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
879#endif
880            if(tmp_output->content==NULL){
881              tmp_output->content=createMap(tmpn,tmpv+1);
882              tmp_output->content->next=NULL;
883            }
884            else
885              addToMap(tmp_output->content,tmpn,tmpv+1);
886          }
887          k++;
888#ifdef DEBUG
889          fprintf(stderr,"***%s***\n",tmpc);
890#endif
891          tmpc=strtok(NULL,"@");
892        }
893        if(request_output_real_format==NULL)
894          request_output_real_format=dupMaps(&tmp_output);
895        else
896          addMapsToMaps(&request_output_real_format,tmp_output);
897        freeMaps(&tmp_output);
898        free(tmp_output);
899        tmp_output=NULL;
900#ifdef DEBUG
901        dumpMaps(tmp_output);
902        fflush(stderr);
903#endif
904        free(tmp);
905      }
906      free(outputs_as_text);
907    }
908
909
910    /**
911     * Parsing inputs provided as KVP
912     */
913    r_inputs=getMap(request_inputs,"DataInputs");
914#ifdef DEBUG
915    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
916#endif
917    char cursor_input[40960];
918    if(r_inputs!=NULL)
919      snprintf(cursor_input,40960,"%s",r_inputs->value);
920    else{
921      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue");
922      freeMaps(&m);
923      free(m);
924      free(REQUEST);
925      free(SERVICE_URL);
926      InternetCloseHandle(hInternet);
927      freeService(&s1);
928      free(s1);
929      return 0;
930    }
931    j=0;
932 
933    /**
934     * Put each DataInputs into the inputs_as_text array
935     */
936    char * pToken;
937    pToken=strtok(cursor_input,";");
938    char** inputs_as_text=(char**)calloc(100,sizeof(char*));
939    if(inputs_as_text == NULL){
940      return errorException(m, _("Unable to allocate memory."), "InternalError");
941    }
942    i=0;
943    while(pToken!=NULL){
944#ifdef DEBUG
945      fprintf(stderr,"***%s***\n",pToken);
946#endif
947      fflush(stderr);
948#ifdef DEBUG
949      fprintf(stderr,"***%s***\n",pToken);
950#endif
951      inputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
952      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
953      if(inputs_as_text[i] == NULL){
954        return errorException(m, _("Unable to allocate memory."), "InternalError");
955      }
956      pToken = strtok(NULL,";");
957      i++;
958    }
959
960    for(j=0;j<i;j++){
961      char *tmp=strdup(inputs_as_text[j]);
962      free(inputs_as_text[j]);
963      char *tmpc;
964      tmpc=strtok(tmp,"@");
965      while(tmpc!=NULL){
966#ifdef DEBUG
967        fprintf(stderr,"***\n***%s***\n",tmpc);
968#endif
969        char *tmpv=strstr(tmpc,"=");
970        char tmpn[256];
971        memset(tmpn,0,256);
972        if(tmpv!=NULL){
973          strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
974          tmpn[strlen(tmpc)-strlen(tmpv)]=0;
975        }
976        else{
977          strncpy(tmpn,tmpc,strlen(tmpc)*sizeof(char));
978          tmpn[strlen(tmpc)]=0;
979        }
980#ifdef DEBUG
981        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
982#endif
983        if(tmpmaps==NULL){
984          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
985          if(tmpmaps == NULL){
986            return errorException(m, _("Unable to allocate memory."), "InternalError");
987          }
988          tmpmaps->name=strdup(tmpn);
989          if(tmpv!=NULL)
990            tmpmaps->content=createMap("value",tmpv+1);
991          else
992            tmpmaps->content=createMap("value","Reference");
993          tmpmaps->next=NULL;
994        }
995        tmpc=strtok(NULL,"@");
996        while(tmpc!=NULL){
997#ifdef DEBUG
998          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
999#endif
1000          char *tmpv1=strstr(tmpc,"=");
1001#ifdef DEBUG
1002          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1003#endif
1004          char tmpn1[1024];
1005          memset(tmpn1,0,1024);
1006          if(tmpv1!=NULL){
1007            strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
1008            tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
1009            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1010          }
1011          else{
1012            strncpy(tmpn1,tmpc,strlen(tmpc));
1013            tmpn1[strlen(tmpc)]=0;
1014            map* lmap=getLastMap(tmpmaps->content);
1015            char *tmpValue=(char*)calloc((strlen(lmap->value)+strlen(tmpc)+1),sizeof(char));
1016            sprintf(tmpValue,"%s@%s",lmap->value,tmpc);
1017            free(lmap->value);
1018            lmap->value=strdup(tmpValue);
1019            free(tmpValue);
1020            tmpc=strtok(NULL,"@");
1021            continue;
1022          }
1023#ifdef DEBUG
1024          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
1025          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1026#endif
1027          if(strcmp(tmpn1,"xlink:href")!=0)
1028            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1029          else
1030            if(tmpv1!=NULL){
1031              if(strncasecmp(tmpv1+1,"http://",7)!=0 &&
1032                 strncasecmp(tmpv1+1,"ftp://",6)!=0){
1033                char emsg[1024];
1034                sprintf(emsg,_("Unable to find a valid protocol to download the remote file %s"),tmpv1+1);
1035                errorException(m,emsg,"InternalError");
1036                freeMaps(&m);
1037                free(m);
1038                free(REQUEST);
1039                free(SERVICE_URL);
1040                InternetCloseHandle(hInternet);
1041                freeService(&s1);
1042                free(s1);
1043                return 0;
1044              }
1045#ifdef DEBUG
1046              fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
1047#endif
1048              char *tmpx=url_encode(tmpv1+1);
1049              addToMap(tmpmaps->content,tmpn1,tmpx);
1050             
1051#ifndef WIN32
1052              if(CHECK_INET_HANDLE(hInternet))
1053#endif
1054                {
1055                  char* cached=isInCache(m,tmpv1+1);
1056                  if(cached!=NULL){
1057                    fprintf(stderr,"Use cached file: %s\n",cached);
1058                    struct stat f_status;
1059                    int s=stat(cached, &f_status);
1060                    if(s==0){
1061                      map* tmpMap=getMap(tmpmaps->content,"value");
1062                      char* fcontent=(char*)malloc(sizeof(char)*(f_status.st_size+1));
1063                      FILE* f=fopen(cached,"r");
1064                      fread(fcontent,sizeof(char),f_status.st_size,f);
1065                      free(tmpMap->value);
1066                      tmpMap->value=(char*)malloc((f_status.st_size+1)*sizeof(char));
1067                      memmove(tmpMap->value,fcontent,(f_status.st_size)*sizeof(char)); 
1068                      free(fcontent);
1069                    }
1070                  }else{
1071                    res=InternetOpenUrl(hInternet,tmpv1+1,NULL,0,
1072                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1073#ifdef DEBUG
1074                    fprintf(stderr,"(%s) content-length : %d,,res.nDataAlloc %d \n",
1075                            tmpv1+1,res.nDataAlloc,res.nDataLen);
1076#endif
1077                    char* tmpContent=(char*)calloc((res.nDataLen+1),sizeof(char));
1078                    if(tmpContent == NULL){
1079                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1080                    }
1081                    size_t dwRead;
1082                    InternetReadFile(res, (LPVOID)tmpContent,res.nDataLen, &dwRead);
1083                    map* tmpMap=getMap(tmpmaps->content,"value");
1084                    if(tmpMap!=NULL){
1085                      free(tmpMap->value);
1086                      tmpMap->value=(char*)malloc((res.nDataLen+1)*sizeof(char));
1087                      memmove(tmpMap->value,tmpContent,(res.nDataLen)*sizeof(char));
1088                      tmpMap->value[res.nDataLen]=0;
1089                      if(strlen(tmpContent)!=res.nDataLen){
1090                        char tmp[256];
1091                        sprintf(tmp,"%d",res.nDataLen*sizeof(char));
1092                        addToMap(tmpmaps->content,"size",tmp);
1093                      }
1094                      addToCache(m,tmpv1+1,tmpContent,res.nDataLen);
1095                    }
1096                    free(tmpContent);
1097                  }
1098                }
1099              char *tmpx1=url_encode(tmpv1+1);
1100              addToMap(tmpmaps->content,tmpn1,tmpx1);
1101              free(tmpx1);
1102              addToMap(tmpmaps->content,"Reference",tmpv1+1);
1103            }
1104          tmpc=strtok(NULL,"@");
1105        }
1106#ifdef DEBUG
1107        dumpMaps(tmpmaps);
1108        fflush(stderr);
1109#endif
1110        if(request_input_real_format==NULL)
1111          request_input_real_format=dupMaps(&tmpmaps);
1112        else
1113          addMapsToMaps(&request_input_real_format,tmpmaps);
1114        freeMaps(&tmpmaps);
1115        free(tmpmaps);
1116        tmpmaps=NULL;
1117        free(tmp);
1118      }
1119    }
1120    free(inputs_as_text);
1121  }
1122  else {
1123    /**
1124     * Parse XML request
1125     */ 
1126    xmlInitParser();
1127#ifdef DEBUG
1128    fflush(stderr);
1129    fprintf(stderr,"BEFORE %s\n",postRequest->value);
1130    fflush(stderr);
1131#endif
1132    xmlDocPtr doc =
1133      xmlParseMemory(postRequest->value,cgiContentLength);
1134#ifdef DEBUG
1135    fprintf(stderr,"AFTER\n");
1136    fflush(stderr);
1137#endif
1138    /**
1139     * Parse every Input in DataInputs node.
1140     */
1141    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1142    xmlNodeSet* tmps=tmpsptr->nodesetval;
1143#ifdef DEBUG
1144    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1145#endif
1146    for(int k=0;k<tmps->nodeNr;k++){
1147      maps *tmpmaps=NULL;
1148      xmlNodePtr cur=tmps->nodeTab[k];
1149      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1150        /**
1151         * A specific Input node.
1152         */
1153#ifdef DEBUG
1154        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1155#endif
1156        xmlNodePtr cur2=cur->children;
1157        while(cur2!=NULL){
1158          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1159            cur2=cur2->next;
1160          if(cur2==NULL)
1161            break;
1162          /**
1163           * Indentifier
1164           */
1165          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1166            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1167            if(tmpmaps==NULL){
1168              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1169              if(tmpmaps == NULL){
1170                return errorException(m, _("Unable to allocate memory."), "InternalError");
1171              }
1172              tmpmaps->name=strdup((char*)val);
1173              tmpmaps->content=NULL;
1174              tmpmaps->next=NULL;
1175            }
1176            xmlFree(val);
1177          }
1178          /**
1179           * Title, Asbtract
1180           */
1181          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1182             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1183            xmlChar *val=
1184              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1185            if(tmpmaps==NULL){
1186              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1187              if(tmpmaps == NULL){
1188                return errorException(m, _("Unable to allocate memory."), "InternalError");
1189              }
1190              tmpmaps->name=strdup("missingIndetifier");
1191              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1192              tmpmaps->next=NULL;
1193            }
1194            else{
1195              if(tmpmaps->content!=NULL)
1196                addToMap(tmpmaps->content,
1197                         (char*)cur2->name,(char*)val);
1198              else
1199                tmpmaps->content=
1200                  createMap((char*)cur2->name,(char*)val);
1201            }
1202#ifdef DEBUG
1203            dumpMaps(tmpmaps);
1204#endif
1205            xmlFree(val);
1206          }
1207          /**
1208           * InputDataFormChoice (Reference or Data ?)
1209           */
1210          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1211            /**
1212             * Get every attribute from a Reference node
1213             * mimeType, encoding, schema, href, method
1214             * Header and Body gesture should be added here
1215             */
1216#ifdef DEBUG
1217            fprintf(stderr,"REFERENCE\n");
1218#endif
1219            const char *refs[5];
1220            refs[0]="mimeType";
1221            refs[1]="encoding";
1222            refs[2]="schema";
1223            refs[3]="method";
1224            refs[4]="href";
1225            for(int l=0;l<5;l++){
1226#ifdef DEBUG
1227              fprintf(stderr,"*** %s ***",refs[l]);
1228#endif
1229              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1230              if(val!=NULL && xmlStrlen(val)>0){
1231                if(tmpmaps->content!=NULL)
1232                  addToMap(tmpmaps->content,refs[l],(char*)val);
1233                else
1234                  tmpmaps->content=createMap(refs[l],(char*)val);
1235                map* ltmp=getMap(tmpmaps->content,"method");
1236                if(l==4){
1237                  if(!(ltmp!=NULL && strcmp(ltmp->value,"POST")==0)
1238                     && CHECK_INET_HANDLE(hInternet)){
1239                    res=InternetOpenUrl(hInternet,(char*)val,NULL,0,
1240                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1241                    char* tmpContent=
1242                      (char*)calloc((res.nDataLen+1),sizeof(char));
1243                    if(tmpContent == NULL){
1244                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1245                    }
1246                    size_t dwRead;
1247                    InternetReadFile(res, (LPVOID)tmpContent,
1248                                     res.nDataLen, &dwRead);
1249                    tmpContent[res.nDataLen]=0;
1250                    addToMap(tmpmaps->content,"value",tmpContent);
1251                  }
1252                }
1253              }
1254#ifdef DEBUG
1255              fprintf(stderr,"%s\n",val);
1256#endif
1257              xmlFree(val);
1258            }
1259#ifdef POST_DEBUG
1260            fprintf(stderr,"Parse Header and Body from Reference \n");
1261#endif
1262            xmlNodePtr cur3=cur2->children;
1263            hInternet.header=NULL;
1264            while(cur3){
1265              while(cur3!=NULL && cur3->type!=XML_ELEMENT_NODE)
1266                cur2=cur3->next;
1267              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1268                const char *ha[2];
1269                ha[0]="key";
1270                ha[1]="value";
1271                int hai;
1272                char *has;
1273                char *key;
1274                for(hai=0;hai<2;hai++){
1275                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1276#ifdef POST_DEBUG
1277                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1278#endif
1279                  if(hai==0){
1280                    key=(char*)calloc((1+strlen((char*)val)),sizeof(char));
1281                    snprintf(key,1+strlen((char*)val),"%s",(char*)val);
1282                  }else{
1283                    has=(char*)calloc((3+strlen((char*)val)+strlen(key)),sizeof(char));
1284                    if(has == NULL){
1285                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1286                    }
1287                    snprintf(has,(3+strlen((char*)val)+strlen(key)),"%s: %s",key,(char*)val);
1288#ifdef POST_DEBUG
1289                    fprintf(stderr,"%s\n",has);
1290#endif
1291                  }
1292                }
1293                hInternet.header=curl_slist_append(hInternet.header, has);
1294                free(has);
1295              }
1296              else{
1297#ifdef POST_DEBUG
1298                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1299#endif
1300                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1301#ifdef POST_DEBUG
1302                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1303#endif
1304                  char *tmp=new char[cgiContentLength];
1305                  memset(tmp,0,cgiContentLength);
1306                  xmlNodePtr cur4=cur3->children;
1307                  while(cur4!=NULL){
1308                    while(cur4->type!=XML_ELEMENT_NODE)
1309                      cur4=cur4->next;
1310                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1311                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1312                    xmlDocSetRootElement(bdoc,cur4);
1313                    xmlChar* btmps;
1314                    int bsize;
1315                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1316#ifdef POST_DEBUG
1317                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1318#endif
1319                    if(btmps!=NULL)
1320                      sprintf(tmp,"%s",(char*)btmps);
1321                    xmlFreeDoc(bdoc);
1322                    cur4=cur4->next;
1323                  }
1324                  map *btmp=getMap(tmpmaps->content,"href");
1325                  if(btmp!=NULL){
1326#ifdef POST_DEBUG
1327                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1328                    curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1329#endif
1330                    res=InternetOpenUrl(hInternet,btmp->value,tmp,strlen(tmp),
1331                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1332                    char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1333                    if(tmpContent == NULL){
1334                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1335                    }
1336                    size_t dwRead;
1337                    InternetReadFile(res, (LPVOID)tmpContent,
1338                                     res.nDataLen, &dwRead);
1339                    tmpContent[res.nDataLen]=0;
1340                    if(hInternet.header!=NULL)
1341                      curl_slist_free_all(hInternet.header);
1342                    addToMap(tmpmaps->content,"value",tmpContent);
1343#ifdef POST_DEBUG
1344                    fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1345#endif
1346                  }
1347                }
1348                else
1349                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1350                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1351                    HINTERNET bInternet,res1;
1352                    bInternet=InternetOpen(
1353#ifndef WIN32
1354                                           (LPCTSTR)
1355#endif
1356                                           "ZooWPSClient\0",
1357                                           INTERNET_OPEN_TYPE_PRECONFIG,
1358                                           NULL,NULL, 0);
1359                    if(!CHECK_INET_HANDLE(bInternet))
1360                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1361#ifdef POST_DEBUG
1362                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1363#endif
1364                    res1=InternetOpenUrl(bInternet,(char*)val,NULL,0,
1365                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1366                    char* tmp=
1367                      (char*)calloc((res1.nDataLen+1),sizeof(char));
1368                    if(tmp == NULL){
1369                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1370                    }
1371                    size_t bRead;
1372                    InternetReadFile(res1, (LPVOID)tmp,
1373                                     res1.nDataLen, &bRead);
1374                    tmp[res1.nDataLen]=0;
1375                    InternetCloseHandle(bInternet);
1376                    map *btmp=getMap(tmpmaps->content,"href");
1377                    if(btmp!=NULL){
1378#ifdef POST_DEBUG
1379                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1380                      curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1381#endif
1382                      res=InternetOpenUrl(hInternet,btmp->value,tmp,
1383                                          strlen(tmp),
1384                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1385                      char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1386                      if(tmpContent == NULL){
1387                        return errorException(m, _("Unable to allocate memory."), "InternalError");
1388                      }
1389                      size_t dwRead;
1390                      InternetReadFile(res, (LPVOID)tmpContent,
1391                                       res.nDataLen, &dwRead);
1392                      tmpContent[res.nDataLen]=0;
1393                      if(hInternet.header!=NULL)
1394                        curl_slist_free_all(hInternet.header);
1395                      addToMap(tmpmaps->content,"value",tmpContent);
1396#ifdef POST_DEBUG
1397                      fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1398#endif
1399                    }
1400                  }
1401              }
1402              cur3=cur3->next;
1403            }
1404#ifdef POST_DEBUG
1405            fprintf(stderr,"Header and Body was parsed from Reference \n");
1406#endif
1407#ifdef DEBUG
1408            dumpMap(tmpmaps->content);
1409            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1410                    cur2->name,cur2->content);
1411#endif
1412          }
1413          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1414#ifdef DEBUG
1415            fprintf(stderr,"DATA\n");
1416#endif
1417            xmlNodePtr cur4=cur2->children;
1418            while(cur4!=NULL){
1419              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1420                cur4=cur4->next;
1421              if(cur4==NULL)
1422                break;
1423              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1424                /**
1425                 * Get every attribute from a LiteralData node
1426                 * dataType , uom
1427                 */
1428                char *list[2];
1429                list[0]=strdup("dataType");
1430                list[1]=strdup("uom");
1431                for(int l=0;l<2;l++){
1432#ifdef DEBUG
1433                  fprintf(stderr,"*** LiteralData %s ***",list[l]);
1434#endif
1435                  xmlChar *val=xmlGetProp(cur4,BAD_CAST list[l]);
1436                  if(val!=NULL && strlen((char*)val)>0){
1437                    if(tmpmaps->content!=NULL)
1438                      addToMap(tmpmaps->content,list[l],(char*)val);
1439                    else
1440                      tmpmaps->content=createMap(list[l],(char*)val);
1441#ifdef DEBUG
1442                    fprintf(stderr,"%s\n",val);
1443#endif
1444                  }
1445                  xmlFree(val);
1446                  free(list[l]);                 
1447                }
1448              }
1449              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1450                /**
1451                 * Get every attribute from a Reference node
1452                 * mimeType, encoding, schema
1453                 */
1454                const char *coms[3];
1455                coms[0]="mimeType";
1456                coms[1]="encoding";
1457                coms[2]="schema";
1458                for(int l=0;l<3;l++){
1459#ifdef DEBUG
1460                  fprintf(stderr,"*** ComplexData %s ***\n",coms[l]);
1461#endif
1462                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1463                  if(val!=NULL && strlen((char*)val)>0){
1464                    if(tmpmaps->content!=NULL)
1465                      addToMap(tmpmaps->content,coms[l],(char*)val);
1466                    else
1467                      tmpmaps->content=createMap(coms[l],(char*)val);
1468#ifdef DEBUG
1469                    fprintf(stderr,"%s\n",val);
1470#endif
1471                  }
1472                  xmlFree(val);
1473                }
1474              }
1475
1476              map* test=getMap(tmpmaps->content,"encoding");
1477              if(test==NULL){
1478                if(tmpmaps->content!=NULL)
1479                  addToMap(tmpmaps->content,"encoding","utf-8");
1480                else
1481                  tmpmaps->content=createMap("encoding","utf-8");
1482                test=getMap(tmpmaps->content,"encoding");
1483              }
1484
1485              if(strcasecmp(test->value,"base64")!=0){
1486                xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1487                map* ltmp=getMap(tmpmaps->content,"mimeType");
1488                if(mv==NULL || 
1489                   (xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0 &&
1490                    (ltmp==NULL || strncasecmp(ltmp->value,"text/xml",8)==0) )){
1491                  xmlDocPtr doc1=xmlNewDoc(BAD_CAST "1.0");
1492                  int buffersize;
1493                  xmlNodePtr cur5=cur4->children;
1494                  while(cur5!=NULL &&cur5->type!=XML_ELEMENT_NODE)
1495                    cur5=cur5->next;
1496                  xmlDocSetRootElement(doc1,cur5);
1497                  xmlDocDumpFormatMemoryEnc(doc1, &mv, &buffersize, "utf-8", 1);
1498                  char size[1024];
1499                  sprintf(size,"%d",buffersize);
1500                  addToMap(tmpmaps->content,"size",size);
1501                }
1502                addToMap(tmpmaps->content,"value",(char*)mv);
1503                xmlFree(mv);
1504              }else{
1505                xmlChar* tmp=xmlNodeListGetRawString(doc,cur4->xmlChildrenNode,0);
1506                addToMap(tmpmaps->content,"value",(char*)tmp);
1507                map* tmpv=getMap(tmpmaps->content,"value");
1508                char *res=NULL;
1509                char *curs=tmpv->value;
1510                for(int i=0;i<=strlen(tmpv->value)/64;i++) {
1511                  if(res==NULL)
1512                    res=(char*)malloc(67*sizeof(char));
1513                  else
1514                    res=(char*)realloc(res,(((i+1)*65)+i)*sizeof(char));
1515                  int csize=i*65;
1516                  strncpy(res + csize,curs,64);
1517                  if(i==xmlStrlen(tmp)/64)
1518                    strcat(res,"\n\0");
1519                  else{
1520                    strncpy(res + (((i+1)*64)+i),"\n\0",2);
1521                    curs+=64;
1522                  }
1523                }
1524                free(tmpv->value);
1525                tmpv->value=strdup(res);
1526                free(res);
1527                xmlFree(tmp);
1528              }
1529              cur4=cur4->next;
1530            }
1531          }
1532#ifdef DEBUG
1533          fprintf(stderr,"cur2 next \n");
1534          fflush(stderr);
1535#endif
1536          cur2=cur2->next;
1537        }
1538#ifdef DEBUG
1539        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1540        fflush(stderr);
1541#endif
1542        addMapsToMaps(&request_input_real_format,tmpmaps);
1543       
1544#ifdef DEBUG
1545        fprintf(stderr,"******TMPMAPS*****\n");
1546        dumpMaps(tmpmaps);
1547        fprintf(stderr,"******REQUESTMAPS*****\n");
1548        dumpMaps(request_input_real_format);
1549#endif
1550        freeMaps(&tmpmaps);
1551        free(tmpmaps);
1552        tmpmaps=NULL;         
1553      }
1554#ifdef DEBUG
1555      dumpMaps(tmpmaps); 
1556#endif
1557    }
1558#ifdef DEBUG
1559    fprintf(stderr,"Search for response document node\n");
1560#endif
1561    xmlXPathFreeObject(tmpsptr);
1562   
1563    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1564    bool asRaw=false;
1565    tmps=tmpsptr->nodesetval;
1566    if(tmps->nodeNr==0){
1567      tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1568      tmps=tmpsptr->nodesetval;
1569      asRaw=true;
1570    }
1571#ifdef DEBUG
1572    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1573#endif
1574    for(int k=0;k<tmps->nodeNr;k++){
1575      if(asRaw==true)
1576        addToMap(request_inputs,"RawDataOutput","");
1577      else
1578        addToMap(request_inputs,"ResponseDocument","");
1579      maps *tmpmaps=NULL;
1580      xmlNodePtr cur=tmps->nodeTab[k];
1581      if(cur->type == XML_ELEMENT_NODE) {
1582        /**
1583         * A specific responseDocument node.
1584         */
1585        if(tmpmaps==NULL){
1586          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1587          if(tmpmaps == NULL){
1588            return errorException(m, _("Unable to allocate memory."), "InternalError");
1589          }
1590          tmpmaps->name=strdup("unknownIdentifier");
1591          tmpmaps->next=NULL;
1592        }
1593        /**
1594         * Get every attribute from a LiteralData node
1595         * storeExecuteResponse, lineage, status
1596         */
1597        const char *ress[3];
1598        ress[0]="storeExecuteResponse";
1599        ress[1]="lineage";
1600        ress[2]="status";
1601        xmlChar *val;
1602        for(int l=0;l<3;l++){
1603#ifdef DEBUG
1604          fprintf(stderr,"*** %s ***\t",ress[l]);
1605#endif
1606          val=xmlGetProp(cur,BAD_CAST ress[l]);
1607          if(val!=NULL && strlen((char*)val)>0){
1608            if(tmpmaps->content!=NULL)
1609              addToMap(tmpmaps->content,ress[l],(char*)val);
1610            else
1611              tmpmaps->content=createMap(ress[l],(char*)val);
1612            addToMap(request_inputs,ress[l],(char*)val);
1613          }
1614#ifdef DEBUG
1615          fprintf(stderr,"%s\n",val);
1616#endif
1617          xmlFree(val);
1618        }
1619        xmlNodePtr cur1=cur->children;
1620        while(cur1){
1621          /**
1622           * Indentifier
1623           */
1624          if(xmlStrncasecmp(cur1->name,BAD_CAST "Identifier",xmlStrlen(cur1->name))==0){
1625            xmlChar *val=
1626              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
1627            if(tmpmaps==NULL){
1628              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1629              if(tmpmaps == NULL){
1630                return errorException(m, _("Unable to allocate memory."), "InternalError");
1631              }
1632              tmpmaps->name=strdup((char*)val);
1633              tmpmaps->content=NULL;
1634              tmpmaps->next=NULL;
1635            }
1636            else
1637              tmpmaps->name=strdup((char*)val);;
1638            xmlFree(val);
1639          }
1640          /**
1641           * Title, Asbtract
1642           */
1643          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Title",xmlStrlen(cur1->name))==0 ||
1644                  xmlStrncasecmp(cur1->name,BAD_CAST "Abstract",xmlStrlen(cur1->name))==0){
1645            xmlChar *val=
1646              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
1647            if(tmpmaps==NULL){
1648              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1649              if(tmpmaps == NULL){
1650                return errorException(m, _("Unable to allocate memory."), "InternalError");
1651              }
1652              tmpmaps->name=strdup("missingIndetifier");
1653              tmpmaps->content=createMap((char*)cur1->name,(char*)val);
1654              tmpmaps->next=NULL;
1655            }
1656            else{
1657              if(tmpmaps->content!=NULL)
1658                addToMap(tmpmaps->content,
1659                         (char*)cur1->name,(char*)val);
1660              else
1661                tmpmaps->content=
1662                  createMap((char*)cur1->name,(char*)val);
1663            }
1664            xmlFree(val);
1665          }
1666          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
1667            /**
1668             * Get every attribute from a Output node
1669             * mimeType, encoding, schema, uom, asReference
1670             */
1671            const char *outs[5];
1672            outs[0]="mimeType";
1673            outs[1]="encoding";
1674            outs[2]="schema";
1675            outs[3]="uom";
1676            outs[4]="asReference";
1677            for(int l=0;l<5;l++){
1678#ifdef DEBUG
1679              fprintf(stderr,"*** %s ***\t",outs[l]);
1680#endif
1681              val=xmlGetProp(cur1,BAD_CAST outs[l]);
1682              if(val!=NULL && strlen((char*)val)>0){
1683                if(tmpmaps->content!=NULL)
1684                  addToMap(tmpmaps->content,outs[l],(char*)val);
1685                else
1686                  tmpmaps->content=createMap(outs[l],(char*)val);
1687              }
1688#ifdef DEBUG
1689              fprintf(stderr,"%s\n",val);
1690#endif
1691              xmlFree(val);
1692            }
1693           
1694            xmlNodePtr cur2=cur1->children;
1695            while(cur2){
1696              /**
1697               * Indentifier
1698               */
1699              if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1700                xmlChar *val=
1701                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1702                if(tmpmaps==NULL){
1703                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1704                  if(tmpmaps == NULL){
1705                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1706                  }
1707                  tmpmaps->name=strdup((char*)val);
1708                  tmpmaps->content=NULL;
1709                  tmpmaps->next=NULL;
1710                }
1711                else
1712                  tmpmaps->name=strdup((char*)val);;
1713                xmlFree(val);
1714              }
1715              /**
1716               * Title, Asbtract
1717               */
1718              else if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1719                 xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1720                xmlChar *val=
1721                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1722                if(tmpmaps==NULL){
1723                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1724                  if(tmpmaps == NULL){
1725                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1726                  }
1727                  tmpmaps->name=strdup("missingIndetifier");
1728                  tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1729                  tmpmaps->next=NULL;
1730                }
1731                else{
1732                  if(tmpmaps->content!=NULL)
1733                    addToMap(tmpmaps->content,
1734                             (char*)cur2->name,(char*)val);
1735                  else
1736                    tmpmaps->content=
1737                      createMap((char*)cur2->name,(char*)val);
1738                }
1739                xmlFree(val);
1740              }
1741              cur2=cur2->next;
1742            }
1743          }
1744          cur1=cur1->next;
1745        }
1746      }
1747      if(request_output_real_format==NULL)
1748        request_output_real_format=dupMaps(&tmpmaps);
1749      else
1750        addMapsToMaps(&request_output_real_format,tmpmaps);
1751#ifdef DEBUG
1752      dumpMaps(tmpmaps);
1753#endif
1754      freeMaps(&tmpmaps);
1755      free(tmpmaps);
1756    }
1757
1758    xmlXPathFreeObject(tmpsptr);
1759    xmlCleanupParser();
1760  }
1761 
1762  //if(CHECK_INET_HANDLE(hInternet))
1763  InternetCloseHandle(hInternet);
1764
1765#ifdef DEBUG
1766  fprintf(stderr,"\n%i\n",i);
1767  dumpMaps(request_input_real_format);
1768  dumpMaps(request_output_real_format);
1769  dumpMap(request_inputs);
1770  fprintf(stderr,"\n%i\n",i);
1771#endif
1772
1773  /**
1774   * Ensure that each requested arguments are present in the request
1775   * DataInputs and ResponseDocument / RawDataOutput
1776   */
1777  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,0);
1778  char *dfv1=addDefaultValues(&request_output_real_format,s1->outputs,m,1);
1779  if(strcmp(dfv1,"")!=0 || strcmp(dfv,"")!=0){
1780    char tmps[1024];
1781    if(strcmp(dfv,"")!=0){
1782      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);
1783    }
1784    else if(strcmp(dfv1,"")!=0){
1785      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);
1786    }
1787    map* tmpe=createMap("text",tmps);
1788    addToMap(tmpe,"code","MissingParameterValue");
1789    printExceptionReportResponse(m,tmpe);
1790    freeService(&s1);
1791    free(s1);
1792    freeMap(&tmpe);
1793    free(tmpe);
1794    freeMaps(&m);
1795    free(m);
1796    free(REQUEST);
1797    free(SERVICE_URL);
1798    freeMaps(&request_input_real_format);
1799    free(request_input_real_format);
1800    freeMaps(&request_output_real_format);
1801    free(request_output_real_format);
1802    freeMaps(&tmpmaps);
1803    free(tmpmaps);
1804    return 1;
1805  }
1806
1807  ensureDecodedBase64(&request_input_real_format);
1808
1809#ifdef DEBUG
1810  fprintf(stderr,"REQUEST_INPUTS\n");
1811  dumpMaps(request_input_real_format);
1812  fprintf(stderr,"REQUEST_OUTPUTS\n");
1813  dumpMaps(request_output_real_format);
1814#endif
1815
1816  maps* curs=getMaps(m,"env");
1817  if(curs!=NULL){
1818    map* mapcs=curs->content;
1819    while(mapcs!=NULLMAP){
1820#ifndef WIN32
1821      setenv(mapcs->name,mapcs->value,1);
1822#else
1823#ifdef DEBUG
1824      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1825#endif
1826      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
1827#ifdef DEBUG
1828        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
1829#endif
1830        mapcs->value[strlen(mapcs->value)-1]=0;
1831      }
1832#ifdef DEBUG
1833      fflush(stderr);
1834      fprintf(stderr,"setting variable... %s\n",
1835#endif
1836              SetEnvironmentVariable(mapcs->name,mapcs->value)
1837#ifdef DEBUG
1838              ? "OK" : "FAILED");
1839#else
1840      ;
1841#endif
1842#ifdef DEBUG
1843      fflush(stderr);
1844#endif
1845#endif
1846#ifdef DEBUG
1847      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1848      fflush(stderr);
1849#endif
1850      mapcs=mapcs->next;
1851    }
1852  }
1853 
1854#ifdef DEBUG
1855  dumpMap(request_inputs);
1856#endif
1857
1858  /**
1859   * Need to check if we need to fork to load a status enabled
1860   */
1861  r_inputs=NULL;
1862  map* store=getMap(request_inputs,"storeExecuteResponse");
1863  map* status=getMap(request_inputs,"status");
1864  /**
1865   * 05-007r7 WPS 1.0.0 page 57 :
1866   * 'If status="true" and storeExecuteResponse is "false" then the service
1867   * shall raise an exception.'
1868   */
1869  if(status!=NULL && strcmp(status->value,"true")==0 && 
1870     store!=NULL && strcmp(store->value,"false")==0){
1871    errorException(m, _("Status cannot be set to true with storeExecuteResponse to false. Please, modify your request parameters."), "InvalidParameterValue");
1872    freeService(&s1);
1873    free(s1);
1874    freeMaps(&m);
1875    free(m);
1876   
1877    freeMaps(&request_input_real_format);
1878    free(request_input_real_format);
1879   
1880    freeMaps(&request_output_real_format);
1881    free(request_output_real_format);
1882   
1883    free(REQUEST);
1884    free(SERVICE_URL);
1885    return 1;
1886  }
1887  r_inputs=getMap(request_inputs,"storeExecuteResponse");
1888  int eres=SERVICE_STARTED;
1889  int cpid=getpid();
1890
1891  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
1892  _tmpMaps->name=strdup("lenv");
1893  char tmpBuff[100];
1894  sprintf(tmpBuff,"%i",cpid);
1895  _tmpMaps->content=createMap("sid",tmpBuff);
1896  _tmpMaps->next=NULL;
1897  addToMap(_tmpMaps->content,"status","0");
1898  addToMap(_tmpMaps->content,"cwd",ntmp);
1899  map* ltmp=getMap(request_inputs,"soap");
1900  if(ltmp!=NULL)
1901    addToMap(_tmpMaps->content,"soap",ltmp->value);
1902  else
1903    addToMap(_tmpMaps->content,"soap","false");
1904  if(cgiCookie!=NULL && strlen(cgiCookie)>0){
1905    addToMap(_tmpMaps->content,"sessid",strstr(cgiCookie,"=")+1);
1906    char session_file_path[1024];
1907    map *tmpPath=getMapFromMaps(m,"main","sessPath");
1908    if(tmpPath==NULL)
1909      tmpPath=getMapFromMaps(m,"main","tmpPath");
1910    char *tmp1=strtok(cgiCookie,";");
1911    if(tmp1!=NULL)
1912      sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(tmp1,"=")+1);
1913    else
1914      sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(cgiCookie,"=")+1);
1915
1916    maps *tmpSess=(maps*)calloc(1,MAPS_SIZE);
1917    struct stat file_status;
1918    int istat = stat(session_file_path, &file_status);
1919    if(istat==0 && file_status.st_size>0){
1920      conf_read(session_file_path,tmpSess);
1921      addMapsToMaps(&m,tmpSess);
1922      freeMaps(&tmpSess);
1923    }
1924    free(tmpSess);
1925  }
1926  addMapsToMaps(&m,_tmpMaps);
1927  freeMaps(&_tmpMaps);
1928  free(_tmpMaps);
1929
1930#ifdef DEBUG
1931  dumpMap(request_inputs);
1932#endif
1933#ifdef WIN32
1934  char *cgiSidL=NULL;
1935  if(getenv("CGISID")!=NULL)
1936        addToMap(request_inputs,"cgiSid",getenv("CGISID"));
1937  map* test1=getMap(request_inputs,"cgiSid");
1938  if(test1!=NULL){
1939    cgiSid=test1->value;
1940  }
1941  if(cgiSid!=NULL){
1942    addToMap(request_inputs,"storeExecuteResponse","true");
1943    addToMap(request_inputs,"status","true");
1944    status=getMap(request_inputs,"status");
1945    fprintf(stderr,"cgiSID : %s",cgiSid);
1946  }
1947#endif
1948  if(status!=NULL)
1949    if(strcasecmp(status->value,"false")==0)
1950      status=NULL;
1951  if(status==NULLMAP){
1952    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
1953  }
1954  else{
1955    pid_t   pid;
1956#ifdef DEBUG
1957    fprintf(stderr,"\nPID : %d\n",cpid);
1958#endif
1959
1960#ifndef WIN32
1961    pid = fork ();
1962#else
1963    if(cgiSid==NULL){
1964      addToMap(request_inputs,"cgSid",cgiSid);
1965      createProcess(m,request_inputs,s1,NULL,cpid,request_input_real_format,request_output_real_format);
1966      pid = cpid;
1967    }else{
1968      pid=0;
1969      cpid=atoi(cgiSid);
1970    }
1971    fflush(stderr);
1972#endif
1973    if (pid > 0) {
1974      /**
1975       * dady :
1976       * set status to SERVICE_ACCEPTED
1977       */
1978#ifdef DEBUG
1979      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
1980#endif
1981      eres=SERVICE_ACCEPTED;
1982    }else if (pid == 0) {
1983      /**
1984       * son : have to close the stdout, stdin and stderr to let the parent
1985       * process answer to http client.
1986       */
1987      r_inputs=getMapFromMaps(m,"main","tmpPath");
1988      map* r_inputs1=getMap(s1->content,"ServiceProvider");
1989      char* fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1990      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
1991      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1992      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
1993#ifdef DEBUG
1994      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
1995      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
1996      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
1997#endif
1998      freopen(flog,"w+",stderr);
1999      freopen(fbkp , "w+", stdout);
2000      fclose(stdin);
2001      free(fbkp);
2002      free(flog);
2003      /**
2004       * set status to SERVICE_STARTED and flush stdout to ensure full
2005       * content was outputed (the file used to store the ResponseDocument).
2006       * The rewind stdout to restart writing from the bgining of the file,
2007       * this way the data will be updated at the end of the process run.
2008       */
2009      updateStatus(m);
2010      printProcessResponse(m,request_inputs,cpid,
2011                           s1,r_inputs1->value,SERVICE_STARTED,
2012                           request_input_real_format,
2013                           request_output_real_format);
2014#ifndef WIN32
2015      fflush(stdout);
2016      rewind(stdout);
2017#endif
2018
2019      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2020
2021    } else {
2022      /**
2023       * error server don't accept the process need to output a valid
2024       * error response here !!!
2025       */
2026      eres=-1;
2027      errorException(m, _("Unable to run the child process properly"), "InternalError");
2028    }
2029  }
2030
2031#ifdef DEBUG
2032  dumpMaps(request_output_real_format);
2033  fprintf(stderr,"Function loaded and returned %d\n",*eres);
2034  fflush(stderr);
2035#endif
2036  if(eres!=-1)
2037    outputResponse(s1,request_input_real_format,
2038                   request_output_real_format,request_inputs,
2039                   cpid,m,eres);
2040  fflush(stdout);
2041  /**
2042   * Ensure that if error occurs when freeing memory, no signal will return
2043   * an ExceptionReport document as the result was already returned to the
2044   * client.
2045   */
2046#ifndef USE_GDB
2047  (void) signal(SIGSEGV,donothing);
2048  (void) signal(SIGTERM,donothing);
2049  (void) signal(SIGINT,donothing);
2050  (void) signal(SIGILL,donothing);
2051  (void) signal(SIGFPE,donothing);
2052  (void) signal(SIGABRT,donothing);
2053#endif
2054
2055  if(((int)getpid())!=cpid){
2056    fclose(stdout);
2057    fclose(stderr);
2058    unhandleStatus(m);
2059  }
2060
2061  freeService(&s1);
2062  free(s1);
2063  freeMaps(&m);
2064  free(m);
2065 
2066  freeMaps(&request_input_real_format);
2067  free(request_input_real_format);
2068 
2069  freeMaps(&request_output_real_format);
2070  free(request_output_real_format);
2071 
2072  free(REQUEST);
2073  free(SERVICE_URL);
2074#ifdef DEBUG
2075  fprintf(stderr,"Processed response \n");
2076  fflush(stdout);
2077  fflush(stderr);
2078#endif
2079
2080  return 0;
2081}
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