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

Last change on this file since 365 was 365, checked in by djay, 12 years ago

Fix issue to compile on Linux platforms after the previous update, fix issue when @ is present in the value of a DataInputs?.

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