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

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

Update serverAddress param of the main section to the requested ZOO-Kernel at runtime in case it was not run from the command line.

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