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

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

Fixing issue on Linux / Mac OS X about language gesture. Fixing strange issue in some services using MapServer? support on WIN32. Use the MapServer? nmake.opt to make sure to get all the definitions settled correctly.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 65.3 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
634  /**
635   * Check for minimum inputs
636   */
637  r_inputs=getMap(request_inputs,"Request");
638  if(request_inputs==NULL || r_inputs==NULL){ 
639    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue");
640    freeMaps(&m);
641    free(m);
642    return 1;
643  }
644  else{
645    REQUEST=strdup(r_inputs->value);
646    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
647       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
648       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
649      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
650      freeMaps(&m);
651      free(m);
652      free(REQUEST);
653      return 1;
654    }
655  }
656  r_inputs=NULL;
657  r_inputs=getMap(request_inputs,"Service");
658  if(r_inputs==NULLMAP){
659    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue");
660    freeMaps(&m);
661    free(m);
662    free(REQUEST);
663    return 1;
664  }
665  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
666    r_inputs=getMap(request_inputs,"Version");
667    if(r_inputs==NULL){ 
668      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue");
669      freeMaps(&m);
670      free(m);
671      free(REQUEST);
672      return 1;
673    }
674  }
675
676  r_inputs=getMap(request_inputs,"serviceprovider");
677  if(r_inputs==NULL){
678    addToMap(request_inputs,"serviceprovider","");
679  }
680
681  maps* request_output_real_format=NULL;
682  map* tmpm=getMapFromMaps(m,"main","serverAddress");
683  if(tmpm!=NULL)
684    SERVICE_URL=strdup(tmpm->value);
685  else
686    SERVICE_URL=strdup(DEFAULT_SERVICE_URL);
687
688  service* s1;
689  int scount=0;
690#ifdef DEBUG
691  dumpMap(r_inputs);
692#endif
693  char conf_dir[1024];
694  int t;
695  char tmps1[1024];
696
697  r_inputs=NULL;
698  r_inputs=getMap(request_inputs,"metapath");
699  if(r_inputs!=NULL)
700    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
701  else
702    snprintf(conf_dir,1024,"%s",ntmp);
703
704  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
705    struct dirent *dp;
706#ifdef DEBUG
707    dumpMap(r_inputs);
708#endif
709    DIR *dirp = opendir(conf_dir);
710    if(dirp==NULL){
711      return errorException(m, _("The specified path doesn't exist."),"InvalidParameterValue");
712    }
713    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
714    r_inputs=NULL;
715    r_inputs=getMap(request_inputs,"ServiceProvider");
716    xmlNodePtr n;
717    if(r_inputs!=NULL)
718      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
719    else
720      n = printGetCapabilitiesHeader(doc,"",m);
721    /**
722     * Here we need to close stdout to ensure that not supported chars
723     * has been found in the zcfg and then printed on stdout
724     */
725    int saved_stdout = dup(fileno(stdout));
726    dup2(fileno(stderr),fileno(stdout));
727    while ((dp = readdir(dirp)) != NULL)
728      if(strstr(dp->d_name,".zcfg")!=0){
729        memset(tmps1,0,1024);
730        snprintf(tmps1,1024,"%s/%s",conf_dir,dp->d_name);
731        s1=(service*)malloc(SERVICE_SIZE);
732        if(s1 == NULL){ 
733          return errorException(m, _("Unable to allocate memory."),"InternalError");
734        }
735#ifdef DEBUG
736        fprintf(stderr,"#################\n%s\n#################\n",tmps1);
737#endif
738        t=getServiceFromFile(tmps1,&s1);
739#ifdef DEBUG
740        dumpService(s1);
741        fflush(stdout);
742        fflush(stderr);
743#endif
744        printGetCapabilitiesForProcess(m,n,s1);
745        freeService(&s1);
746        free(s1);
747        scount++;
748      }
749    (void)closedir(dirp);
750    fflush(stdout);
751    dup2(saved_stdout,fileno(stdout));
752    printDocument(m,doc,getpid());
753    freeMaps(&m);
754    free(m);
755    free(REQUEST);
756    free(SERVICE_URL);
757    fflush(stdout);
758    return 0;
759  }
760  else{
761    r_inputs=getMap(request_inputs,"Identifier");
762    if(r_inputs==NULL 
763       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
764      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue");
765      freeMaps(&m);
766      free(m);
767      free(REQUEST);
768      free(SERVICE_URL);
769      return 0;
770    }
771
772    struct dirent *dp;
773    DIR *dirp = opendir(conf_dir);
774    if(dirp==NULL){
775      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue");
776      freeMaps(&m);
777      free(m);
778      free(REQUEST);
779      free(SERVICE_URL);
780      return 0;
781    }
782    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
783      /**
784       * Loop over Identifier list
785       */
786      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
787      r_inputs=NULL;
788      r_inputs=getMap(request_inputs,"ServiceProvider");
789
790      xmlNodePtr n;
791      if(r_inputs!=NULL)
792        n = printDescribeProcessHeader(doc,r_inputs->value,m);
793      else
794        n = printDescribeProcessHeader(doc,"",m);
795
796      r_inputs=getMap(request_inputs,"Identifier");
797      char *tmps=strtok(r_inputs->value,",");
798     
799      char buff[256];
800      char buff1[1024];
801      int saved_stdout = dup(fileno(stdout));
802      dup2(fileno(stderr),fileno(stdout));
803      while(tmps){
804        memset(buff,0,256);
805        snprintf(buff,256,"%s.zcfg",tmps);
806        memset(buff1,0,1024);
807#ifdef DEBUG
808        printf("\n#######%s\n########\n",buff1);
809#endif
810        while ((dp = readdir(dirp)) != NULL)
811          if((strcasecmp("all.zcfg",buff)==0 && strstr(dp->d_name,".zcfg")>0)
812             || strcasecmp(dp->d_name,buff)==0){
813            memset(buff1,0,1024);
814            snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
815            s1=(service*)malloc(SERVICE_SIZE);
816            if(s1 == NULL){
817              dup2(saved_stdout,fileno(stdout));
818              return errorException(m, _("Unable to allocate memory."),"InternalError");
819            }
820#ifdef DEBUG
821            printf("#################\n%s\n#################\n",buff1);
822#endif
823            t=getServiceFromFile(buff1,&s1);
824#ifdef DEBUG
825            dumpService(s1);
826#endif
827            printDescribeProcessForProcess(m,n,s1,1);
828            freeService(&s1);
829            free(s1);
830            scount++;
831          }
832        rewinddir(dirp);
833        tmps=strtok(NULL,",");
834      }
835      closedir(dirp);
836      fflush(stdout);
837      dup2(saved_stdout,fileno(stdout));
838      printDocument(m,doc,getpid());
839      freeMaps(&m);
840      free(m);
841      free(REQUEST);
842      free(SERVICE_URL);
843      fflush(stdout);
844      return 0;
845    }
846    else
847      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
848        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
849#ifdef DEBUG
850        fprintf(stderr,"No request found %s",REQUEST);
851#endif 
852        closedir(dirp);
853        freeMaps(&m);
854        free(m);
855        free(REQUEST);
856        free(SERVICE_URL);
857        fflush(stdout);
858        return 0;
859      }
860    closedir(dirp);
861  }
862 
863  s1=NULL;
864  s1=(service*)malloc(SERVICE_SIZE);
865  if(s1 == NULL){
866    freeMaps(&m);
867    free(m);
868    free(REQUEST);
869    free(SERVICE_URL);
870    return errorException(m, _("Unable to allocate memory."),"InternalError");
871  }
872  r_inputs=getMap(request_inputs,"MetaPath");
873  if(r_inputs!=NULL)
874    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
875  else
876    snprintf(tmps1,1024,"%s/",ntmp);
877  r_inputs=getMap(request_inputs,"Identifier");
878  char *ttmp=strdup(tmps1);
879  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
880  free(ttmp);
881#ifdef DEBUG
882  fprintf(stderr,"Trying to load %s\n", tmps1);
883#endif
884  int saved_stdout = dup(fileno(stdout));
885  dup2(fileno(stderr),fileno(stdout));
886  t=getServiceFromFile(tmps1,&s1);
887  fflush(stdout);
888  dup2(saved_stdout,fileno(stdout));
889  if(t<0){
890    char *tmpMsg=(char*)malloc(2048+strlen(r_inputs->value));
891   
892    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
893    errorException(m, tmpMsg, "InvalidParameterValue");
894    free(tmpMsg);
895    free(s1);
896    freeMaps(&m);
897    free(m);
898    free(REQUEST);
899    free(SERVICE_URL);
900    return 0;
901  }
902  close(saved_stdout);
903
904#ifdef DEBUG
905  dumpService(s1);
906#endif
907  int j;
908 
909
910  /**
911   * Create the input and output maps data structure
912   */
913  int i=0;
914  HINTERNET hInternet;
915  HINTERNET res;
916  hInternet=InternetOpen(
917#ifndef WIN32
918                         (LPCTSTR)
919#endif
920                         "ZooWPSClient\0",
921                         INTERNET_OPEN_TYPE_PRECONFIG,
922                         NULL,NULL, 0);
923
924#ifndef WIN32
925  if(!CHECK_INET_HANDLE(hInternet))
926    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
927#endif
928  maps* request_input_real_format=NULL;
929  maps* tmpmaps = request_input_real_format;
930  map* postRequest=NULL;
931  postRequest=getMap(request_inputs,"xrequest");
932  if(postRequest==NULLMAP){
933    /**
934     * Parsing outputs provided as KVP
935     */
936    r_inputs=NULL;
937#ifdef DEBUG
938    fprintf(stderr,"OUTPUT Parsing ... \n");
939#endif
940    r_inputs=getMap(request_inputs,"ResponseDocument"); 
941    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
942   
943#ifdef DEBUG
944    fprintf(stderr,"OUTPUT Parsing ... \n");
945#endif
946    if(r_inputs!=NULL){
947#ifdef DEBUG
948      fprintf(stderr,"OUTPUT Parsing start now ... \n");
949#endif
950      char cursor_output[10240];
951      char *cotmp=strdup(r_inputs->value);
952      snprintf(cursor_output,10240,"%s",cotmp);
953      free(cotmp);
954      j=0;
955       
956      /**
957       * Put each Output into the outputs_as_text array
958       */
959      char * pToken;
960      maps* tmp_output=NULL;
961#ifdef DEBUG
962      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
963#endif
964      pToken=strtok(cursor_output,";");
965      char** outputs_as_text=(char**)malloc(128*sizeof(char*));
966      if(outputs_as_text == NULL) {
967        return errorException(m, _("Unable to allocate memory"), "InternalError");
968      }
969      i=0;
970      while(pToken!=NULL){
971#ifdef DEBUG
972        fprintf(stderr,"***%s***\n",pToken);
973        fflush(stderr);
974        fprintf(stderr,"***%s***\n",pToken);
975#endif
976        outputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
977        if(outputs_as_text[i] == NULL) {
978          return errorException(m, _("Unable to allocate memory"), "InternalError");
979        }
980        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
981        pToken = strtok(NULL,";");
982        i++;
983      }
984      for(j=0;j<i;j++){
985        char *tmp=strdup(outputs_as_text[j]);
986        free(outputs_as_text[j]);
987        char *tmpc;
988        tmpc=strtok(tmp,"@");
989        int k=0;
990        while(tmpc!=NULL){
991          if(k==0){
992            if(tmp_output==NULL){
993              tmp_output=(maps*)malloc(MAPS_SIZE);
994              if(tmp_output == NULL){
995                return errorException(m, _("Unable to allocate memory."), "InternalError");
996              }
997              tmp_output->name=strdup(tmpc);
998              tmp_output->content=NULL;
999              tmp_output->next=NULL;
1000            }
1001          }
1002          else{
1003            char *tmpv=strstr(tmpc,"=");
1004            char tmpn[256];
1005            memset(tmpn,0,256);
1006            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1007            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1008#ifdef DEBUG
1009            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
1010#endif
1011            if(tmp_output->content==NULL){
1012              tmp_output->content=createMap(tmpn,tmpv+1);
1013              tmp_output->content->next=NULL;
1014            }
1015            else
1016              addToMap(tmp_output->content,tmpn,tmpv+1);
1017          }
1018          k++;
1019#ifdef DEBUG
1020          fprintf(stderr,"***%s***\n",tmpc);
1021#endif
1022          tmpc=strtok(NULL,"@");
1023        }
1024        if(request_output_real_format==NULL)
1025          request_output_real_format=dupMaps(&tmp_output);
1026        else
1027          addMapsToMaps(&request_output_real_format,tmp_output);
1028        freeMaps(&tmp_output);
1029        free(tmp_output);
1030        tmp_output=NULL;
1031#ifdef DEBUG
1032        dumpMaps(tmp_output);
1033        fflush(stderr);
1034#endif
1035        free(tmp);
1036      }
1037      free(outputs_as_text);
1038    }
1039
1040
1041    /**
1042     * Parsing inputs provided as KVP
1043     */
1044    r_inputs=getMap(request_inputs,"DataInputs");
1045#ifdef DEBUG
1046    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
1047#endif
1048    char cursor_input[40960];
1049    if(r_inputs!=NULL)
1050      snprintf(cursor_input,40960,"%s",r_inputs->value);
1051    else{
1052      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue");
1053      freeMaps(&m);
1054      free(m);
1055      free(REQUEST);
1056      free(SERVICE_URL);
1057      InternetCloseHandle(hInternet);
1058      freeService(&s1);
1059      free(s1);
1060      return 0;
1061    }
1062    j=0;
1063 
1064    /**
1065     * Put each DataInputs into the inputs_as_text array
1066     */
1067    char *tmp1=strdup(cursor_input);
1068    char * pToken;
1069    pToken=strtok(cursor_input,";");
1070    if(pToken!=NULL && strncasecmp(pToken,tmp1,strlen(tmp1))==0){
1071      char* tmp2=url_decode(tmp1);
1072      snprintf(cursor_input,(strlen(tmp2)+1)*sizeof(char),"%s",tmp2);
1073      free(tmp2);
1074      pToken=strtok(cursor_input,";");
1075    }
1076    free(tmp1);
1077
1078    char** inputs_as_text=(char**)malloc(100*sizeof(char*));
1079    if(inputs_as_text == NULL){
1080      return errorException(m, _("Unable to allocate memory."), "InternalError");
1081    }
1082    i=0;
1083    while(pToken!=NULL){
1084#ifdef DEBUG
1085      fprintf(stderr,"***%s***\n",pToken);
1086#endif
1087      fflush(stderr);
1088#ifdef DEBUG
1089      fprintf(stderr,"***%s***\n",pToken);
1090#endif
1091      inputs_as_text[i]=(char*)malloc((strlen(pToken)+1)*sizeof(char));
1092      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
1093      if(inputs_as_text[i] == NULL){
1094        return errorException(m, _("Unable to allocate memory."), "InternalError");
1095      }
1096      pToken = strtok(NULL,";");
1097      i++;
1098    }
1099
1100    for(j=0;j<i;j++){
1101      char *tmp=strdup(inputs_as_text[j]);
1102      free(inputs_as_text[j]);
1103      char *tmpc;
1104      tmpc=strtok(tmp,"@");
1105      while(tmpc!=NULL){
1106#ifdef DEBUG
1107        fprintf(stderr,"***\n***%s***\n",tmpc);
1108#endif
1109        char *tmpv=strstr(tmpc,"=");
1110        char tmpn[256];
1111        memset(tmpn,0,256);
1112        if(tmpv!=NULL){
1113          strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
1114          tmpn[strlen(tmpc)-strlen(tmpv)]=0;
1115        }
1116        else{
1117          strncpy(tmpn,tmpc,strlen(tmpc)*sizeof(char));
1118          tmpn[strlen(tmpc)]=0;
1119        }
1120#ifdef DEBUG
1121        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
1122#endif
1123        if(tmpmaps==NULL){
1124          tmpmaps=(maps*)malloc(MAPS_SIZE);
1125          if(tmpmaps == NULL){
1126            return errorException(m, _("Unable to allocate memory."), "InternalError");
1127          }
1128          tmpmaps->name=strdup(tmpn);
1129          if(tmpv!=NULL){
1130            char *tmpvf=url_decode(tmpv+1);
1131            tmpmaps->content=createMap("value",tmpvf);
1132            free(tmpvf);
1133          }
1134          else
1135            tmpmaps->content=createMap("value","Reference");
1136          tmpmaps->next=NULL;
1137        }
1138        tmpc=strtok(NULL,"@");
1139        while(tmpc!=NULL){
1140#ifdef DEBUG
1141          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
1142#endif
1143          char *tmpv1=strstr(tmpc,"=");
1144#ifdef DEBUG
1145          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1146#endif
1147          char tmpn1[1024];
1148          memset(tmpn1,0,1024);
1149          if(tmpv1!=NULL){
1150            strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
1151            tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
1152            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1153          }
1154          else{
1155            strncpy(tmpn1,tmpc,strlen(tmpc));
1156            tmpn1[strlen(tmpc)]=0;
1157            map* lmap=getLastMap(tmpmaps->content);
1158            char *tmpValue=(char*)malloc((strlen(tmpv)+strlen(tmpc)+1)*sizeof(char));
1159            sprintf(tmpValue,"%s@%s",tmpv+1,tmpc);
1160            free(lmap->value);
1161            lmap->value=strdup(tmpValue);
1162            free(tmpValue);
1163            tmpc=strtok(NULL,"@");
1164            continue;
1165          }
1166#ifdef DEBUG
1167          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
1168          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
1169#endif
1170          if(strcmp(tmpn1,"xlink:href")!=0)
1171            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
1172          else
1173            if(tmpv1!=NULL){
1174              char *tmpx2=url_decode(tmpv1+1);
1175              if(strncasecmp(tmpx2,"http://",7)!=0 &&
1176                 strncasecmp(tmpx2,"ftp://",6)!=0){
1177                char emsg[1024];
1178                sprintf(emsg,_("Unable to find a valid protocol to download the remote file %s"),tmpv1+1);
1179                errorException(m,emsg,"InternalError");
1180                freeMaps(&m);
1181                free(m);
1182                free(REQUEST);
1183                free(SERVICE_URL);
1184                InternetCloseHandle(hInternet);
1185                freeService(&s1);
1186                free(s1);
1187                return 0;
1188              }
1189#ifdef DEBUG
1190              fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
1191#endif
1192              addToMap(tmpmaps->content,tmpn1,tmpx2);
1193             
1194#ifndef WIN32
1195              if(CHECK_INET_HANDLE(hInternet))
1196#endif
1197                {
1198                  if(loadRemoteFile(m,tmpmaps->content,hInternet,tmpx2)<0){
1199                    freeMaps(&m);
1200                    free(m);
1201                    free(REQUEST);
1202                    free(SERVICE_URL);
1203                    InternetCloseHandle(hInternet);
1204                    freeService(&s1);
1205                    free(s1);
1206                    return 0;
1207                  }
1208                }
1209              free(tmpx2);
1210              addToMap(tmpmaps->content,"Reference",tmpv1+1);
1211            }
1212          tmpc=strtok(NULL,"@");
1213        }
1214#ifdef DEBUG
1215        dumpMaps(tmpmaps);
1216        fflush(stderr);
1217#endif
1218        if(request_input_real_format==NULL)
1219          request_input_real_format=dupMaps(&tmpmaps);
1220        else{
1221          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1222          if(testPresence!=NULL){
1223            elements* elem=getElements(s1->inputs,tmpmaps->name);
1224            if(elem!=NULL){
1225              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1226                freeMaps(&m);
1227                free(m);
1228                free(REQUEST);
1229                free(SERVICE_URL);
1230                InternetCloseHandle(hInternet);
1231                freeService(&s1);
1232                free(s1);
1233                return 0;
1234              }
1235            }
1236          }
1237          else
1238            addMapsToMaps(&request_input_real_format,tmpmaps);
1239        }
1240        freeMaps(&tmpmaps);
1241        free(tmpmaps);
1242        tmpmaps=NULL;
1243        free(tmp);
1244      }
1245    }
1246    free(inputs_as_text);
1247  }
1248  else {
1249    /**
1250     * Parse XML request
1251     */ 
1252    xmlInitParser();
1253#ifdef DEBUG
1254    fflush(stderr);
1255    fprintf(stderr,"BEFORE %s\n",postRequest->value);
1256    fflush(stderr);
1257#endif
1258    xmlDocPtr doc =
1259      xmlParseMemory(postRequest->value,cgiContentLength);
1260#ifdef DEBUG
1261    fprintf(stderr,"AFTER\n");
1262    fflush(stderr);
1263#endif
1264    /**
1265     * Parse every Input in DataInputs node.
1266     */
1267    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1268    xmlNodeSet* tmps=tmpsptr->nodesetval;
1269#ifdef DEBUG
1270    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1271#endif
1272    for(int k=0;k<tmps->nodeNr;k++){
1273      maps *tmpmaps=NULL;
1274      xmlNodePtr cur=tmps->nodeTab[k];
1275      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1276        /**
1277         * A specific Input node.
1278         */
1279#ifdef DEBUG
1280        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1281#endif
1282        xmlNodePtr cur2=cur->children;
1283        while(cur2!=NULL){
1284          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1285            cur2=cur2->next;
1286          if(cur2==NULL)
1287            break;
1288          /**
1289           * Indentifier
1290           */
1291          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1292            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1293            if(tmpmaps==NULL){
1294              tmpmaps=(maps*)malloc(MAPS_SIZE);
1295              if(tmpmaps == NULL){
1296                return errorException(m, _("Unable to allocate memory."), "InternalError");
1297              }
1298              tmpmaps->name=strdup((char*)val);
1299              tmpmaps->content=NULL;
1300              tmpmaps->next=NULL;
1301            }
1302            xmlFree(val);
1303          }
1304          /**
1305           * Title, Asbtract
1306           */
1307          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1308             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1309            xmlChar *val=
1310              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1311            if(tmpmaps==NULL){
1312              tmpmaps=(maps*)malloc(MAPS_SIZE);
1313              if(tmpmaps == NULL){
1314                return errorException(m, _("Unable to allocate memory."), "InternalError");
1315              }
1316              tmpmaps->name=strdup("missingIndetifier");
1317              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1318              tmpmaps->next=NULL;
1319            }
1320            else{
1321              if(tmpmaps->content!=NULL)
1322                addToMap(tmpmaps->content,
1323                         (char*)cur2->name,(char*)val);
1324              else
1325                tmpmaps->content=
1326                  createMap((char*)cur2->name,(char*)val);
1327            }
1328#ifdef DEBUG
1329            dumpMaps(tmpmaps);
1330#endif
1331            xmlFree(val);
1332          }
1333          /**
1334           * InputDataFormChoice (Reference or Data ?)
1335           */
1336          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1337            /**
1338             * Get every attribute from a Reference node
1339             * mimeType, encoding, schema, href, method
1340             * Header and Body gesture should be added here
1341             */
1342#ifdef DEBUG
1343            fprintf(stderr,"REFERENCE\n");
1344#endif
1345            const char *refs[5]={"mimeType","encoding","schema","method","href"};
1346            for(int l=0;l<5;l++){
1347#ifdef DEBUG
1348              fprintf(stderr,"*** %s ***",refs[l]);
1349#endif
1350              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1351              if(val!=NULL && xmlStrlen(val)>0){
1352                if(tmpmaps->content!=NULL)
1353                  addToMap(tmpmaps->content,refs[l],(char*)val);
1354                else
1355                  tmpmaps->content=createMap(refs[l],(char*)val);
1356                map* ltmp=getMap(tmpmaps->content,"method");
1357                if(l==4){
1358                  if(!(ltmp!=NULL && strncmp(ltmp->value,"POST",4)==0)
1359                     && CHECK_INET_HANDLE(hInternet)){
1360                    if(loadRemoteFile(m,tmpmaps->content,hInternet,(char*)val)!=0){
1361                      freeMaps(&m);
1362                      free(m);
1363                      free(REQUEST);
1364                      free(SERVICE_URL);
1365                      InternetCloseHandle(hInternet);
1366                      freeService(&s1);
1367                      free(s1);
1368                      return 0;
1369                    }
1370                  }
1371                }
1372              }
1373#ifdef DEBUG
1374              fprintf(stderr,"%s\n",val);
1375#endif
1376              xmlFree(val);
1377            }
1378#ifdef POST_DEBUG
1379            fprintf(stderr,"Parse Header and Body from Reference \n");
1380#endif
1381            xmlNodePtr cur3=cur2->children;
1382            HINTERNET hInternetP;
1383            hInternetP=InternetOpen(
1384#ifndef WIN32
1385                                   (LPCTSTR)
1386#endif
1387                                   "ZooWPSClient\0",
1388                                   INTERNET_OPEN_TYPE_PRECONFIG,
1389                                   NULL,NULL, 0);
1390            hInternetP.header=NULL;
1391            while(cur3){
1392              while(cur3!=NULL && cur3->type!=XML_ELEMENT_NODE)
1393                cur2=cur3->next;
1394              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1395                const char *ha[2];
1396                ha[0]="key";
1397                ha[1]="value";
1398                int hai;
1399                char *has;
1400                char *key;
1401                for(hai=0;hai<2;hai++){
1402                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1403#ifdef POST_DEBUG
1404                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1405#endif
1406                  if(hai==0){
1407                    key=(char*)malloc((1+strlen((char*)val))*sizeof(char));
1408                    snprintf(key,1+strlen((char*)val),"%s",(char*)val);
1409                  }else{
1410                    has=(char*)malloc((3+strlen((char*)val)+strlen(key))*sizeof(char));
1411                    if(has == NULL){
1412                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1413                    }
1414                    snprintf(has,(3+strlen((char*)val)+strlen(key)),"%s: %s",key,(char*)val);
1415#ifdef POST_DEBUG
1416                    fprintf(stderr,"%s\n",has);
1417#endif
1418                  }
1419                }
1420                hInternetP.header=curl_slist_append(hInternetP.header, has);
1421                if(has!=NULL)
1422                  free(has);
1423              }
1424              else{
1425#ifdef POST_DEBUG
1426                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1427#endif
1428                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1429#ifdef POST_DEBUG
1430                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1431#endif
1432                  char *tmp=new char[cgiContentLength];
1433                  memset(tmp,0,cgiContentLength);
1434                  xmlNodePtr cur4=cur3->children;
1435                  while(cur4!=NULL){
1436                    while(cur4->type!=XML_ELEMENT_NODE)
1437                      cur4=cur4->next;
1438                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1439                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1440                    xmlDocSetRootElement(bdoc,cur4);
1441                    xmlChar* btmps;
1442                    int bsize;
1443                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1444#ifdef POST_DEBUG
1445                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1446#endif
1447                    if(btmps!=NULL)
1448                      sprintf(tmp,"%s",(char*)btmps);
1449                    xmlFreeDoc(bdoc);
1450                    cur4=cur4->next;
1451                  }
1452                  map *btmp=getMap(tmpmaps->content,"href");
1453                  if(btmp!=NULL){
1454#ifdef POST_DEBUG
1455                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1456                    curl_easy_setopt(hInternetP.handle, CURLOPT_VERBOSE, 1);
1457#endif
1458                    res=InternetOpenUrl(hInternetP,btmp->value,tmp,strlen(tmp),
1459                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1460                    char* tmpContent = (char*)malloc((res.nDataLen+1)*sizeof(char));
1461                    if(tmpContent == NULL){
1462                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1463                    }
1464                    size_t dwRead;
1465                    InternetReadFile(res, (LPVOID)tmpContent,
1466                                     res.nDataLen, &dwRead);
1467                    tmpContent[res.nDataLen]=0;
1468                    if(hInternetP.header!=NULL)
1469                      curl_slist_free_all(hInternetP.header);
1470                    addToMap(tmpmaps->content,"value",tmpContent);
1471#ifdef POST_DEBUG
1472                    fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1473#endif
1474                  }
1475                }
1476                else
1477                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1478                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1479                    HINTERNET bInternet,res1;
1480                    bInternet=InternetOpen(
1481#ifndef WIN32
1482                                           (LPCTSTR)
1483#endif
1484                                           "ZooWPSClient\0",
1485                                           INTERNET_OPEN_TYPE_PRECONFIG,
1486                                           NULL,NULL, 0);
1487                    if(!CHECK_INET_HANDLE(bInternet))
1488                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1489#ifdef POST_DEBUG
1490                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1491#endif
1492                    res1=InternetOpenUrl(bInternet,(char*)val,NULL,0,
1493                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1494                    char* tmp=
1495                      (char*)malloc((res1.nDataLen+1)*sizeof(char));
1496                    if(tmp == NULL){
1497                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1498                    }
1499                    size_t bRead;
1500                    InternetReadFile(res1, (LPVOID)tmp,
1501                                     res1.nDataLen, &bRead);
1502                    tmp[res1.nDataLen]=0;
1503                    InternetCloseHandle(bInternet);
1504                    map *btmp=getMap(tmpmaps->content,"href");
1505                    if(btmp!=NULL){
1506#ifdef POST_DEBUG
1507                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1508                      curl_easy_setopt(hInternetP.handle, CURLOPT_VERBOSE, 1);
1509#endif
1510                      res=InternetOpenUrl(hInternetP,btmp->value,tmp,
1511                                          strlen(tmp),
1512                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1513                      char* tmpContent = (char*)malloc((res.nDataLen+1)*sizeof(char));
1514                      if(tmpContent == NULL){
1515                        return errorException(m, _("Unable to allocate memory."), "InternalError");
1516                      }
1517                      size_t dwRead;
1518                      InternetReadFile(res, (LPVOID)tmpContent,
1519                                       res.nDataLen, &dwRead);
1520                      tmpContent[res.nDataLen]=0;
1521                      if(hInternetP.header!=NULL)
1522                        curl_slist_free_all(hInternetP.header);
1523                      addToMap(tmpmaps->content,"value",tmpContent);
1524#ifdef POST_DEBUG
1525                      fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1526#endif
1527                    }
1528                  }
1529              }
1530              cur3=cur3->next;
1531            }
1532            InternetCloseHandle(hInternetP);
1533#ifdef POST_DEBUG
1534            fprintf(stderr,"Header and Body was parsed from Reference \n");
1535#endif
1536#ifdef DEBUG
1537            dumpMap(tmpmaps->content);
1538            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1539                    cur2->name,cur2->content);
1540#endif
1541          }
1542          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1543#ifdef DEBUG
1544            fprintf(stderr,"DATA\n");
1545#endif
1546            xmlNodePtr cur4=cur2->children;
1547            while(cur4!=NULL){
1548              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1549                cur4=cur4->next;
1550              if(cur4==NULL)
1551                break;
1552              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1553                /**
1554                 * Get every attribute from a LiteralData node
1555                 * dataType , uom
1556                 */
1557                char *list[2];
1558                list[0]=strdup("dataType");
1559                list[1]=strdup("uom");
1560                for(int l=0;l<2;l++){
1561#ifdef DEBUG
1562                  fprintf(stderr,"*** LiteralData %s ***",list[l]);
1563#endif
1564                  xmlChar *val=xmlGetProp(cur4,BAD_CAST list[l]);
1565                  if(val!=NULL && strlen((char*)val)>0){
1566                    if(tmpmaps->content!=NULL)
1567                      addToMap(tmpmaps->content,list[l],(char*)val);
1568                    else
1569                      tmpmaps->content=createMap(list[l],(char*)val);
1570#ifdef DEBUG
1571                    fprintf(stderr,"%s\n",val);
1572#endif
1573                  }
1574                  xmlFree(val);
1575                  free(list[l]);                 
1576                }
1577              }
1578              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1579                /**
1580                 * Get every attribute from a Reference node
1581                 * mimeType, encoding, schema
1582                 */
1583                const char *coms[3]={"mimeType","encoding","schema"};
1584                for(int l=0;l<3;l++){
1585#ifdef DEBUG
1586                  fprintf(stderr,"*** ComplexData %s ***\n",coms[l]);
1587#endif
1588                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1589                  if(val!=NULL && strlen((char*)val)>0){
1590                    if(tmpmaps->content!=NULL)
1591                      addToMap(tmpmaps->content,coms[l],(char*)val);
1592                    else
1593                      tmpmaps->content=createMap(coms[l],(char*)val);
1594#ifdef DEBUG
1595                    fprintf(stderr,"%s\n",val);
1596#endif
1597                  }
1598                  xmlFree(val);
1599                }
1600              }
1601
1602              map* test=getMap(tmpmaps->content,"encoding");
1603              if(test==NULL){
1604                if(tmpmaps->content!=NULL)
1605                  addToMap(tmpmaps->content,"encoding","utf-8");
1606                else
1607                  tmpmaps->content=createMap("encoding","utf-8");
1608                test=getMap(tmpmaps->content,"encoding");
1609              }
1610
1611              if(strcasecmp(test->value,"base64")!=0){
1612                xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1613                map* ltmp=getMap(tmpmaps->content,"mimeType");
1614                if(mv==NULL || 
1615                   (xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0 &&
1616                    (ltmp==NULL || strncasecmp(ltmp->value,"text/xml",8)==0) )){
1617                  xmlDocPtr doc1=xmlNewDoc(BAD_CAST "1.0");
1618                  int buffersize;
1619                  xmlNodePtr cur5=cur4->children;
1620                  while(cur5!=NULL &&cur5->type!=XML_ELEMENT_NODE)
1621                    cur5=cur5->next;
1622                  xmlDocSetRootElement(doc1,cur5);
1623                  xmlDocDumpFormatMemoryEnc(doc1, &mv, &buffersize, "utf-8", 1);
1624                  char size[1024];
1625                  sprintf(size,"%d",buffersize);
1626                  addToMap(tmpmaps->content,"size",size);
1627                }
1628                addToMap(tmpmaps->content,"value",(char*)mv);
1629                xmlFree(mv);
1630              }else{
1631                xmlChar* tmp=xmlNodeListGetRawString(doc,cur4->xmlChildrenNode,0);
1632                addToMap(tmpmaps->content,"value",(char*)tmp);
1633                map* tmpv=getMap(tmpmaps->content,"value");
1634                char *res=NULL;
1635                char *curs=tmpv->value;
1636                for(int i=0;i<=strlen(tmpv->value)/64;i++) {
1637                  if(res==NULL)
1638                    res=(char*)malloc(67*sizeof(char));
1639                  else
1640                    res=(char*)realloc(res,(((i+1)*65)+i)*sizeof(char));
1641                  int csize=i*65;
1642                  strncpy(res + csize,curs,64);
1643                  if(i==xmlStrlen(tmp)/64)
1644                    strcat(res,"\n\0");
1645                  else{
1646                    strncpy(res + (((i+1)*64)+i),"\n\0",2);
1647                    curs+=64;
1648                  }
1649                }
1650                free(tmpv->value);
1651                tmpv->value=strdup(res);
1652                free(res);
1653                xmlFree(tmp);
1654              }
1655              cur4=cur4->next;
1656            }
1657          }
1658#ifdef DEBUG
1659          fprintf(stderr,"cur2 next \n");
1660          fflush(stderr);
1661#endif
1662          cur2=cur2->next;
1663        }
1664#ifdef DEBUG
1665        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1666        fflush(stderr);
1667#endif
1668
1669        {
1670          maps* testPresence=getMaps(request_input_real_format,tmpmaps->name);
1671          if(testPresence!=NULL){
1672            elements* elem=getElements(s1->inputs,tmpmaps->name);
1673            if(elem!=NULL){
1674              if(appendMapsToMaps(m,request_input_real_format,tmpmaps,elem)<0){
1675                freeMaps(&m);
1676                free(m);
1677                free(REQUEST);
1678                free(SERVICE_URL);
1679                InternetCloseHandle(hInternet);
1680                freeService(&s1);
1681                free(s1);
1682                return 0;
1683              }
1684            }
1685          }
1686          else
1687            addMapsToMaps(&request_input_real_format,tmpmaps);
1688        }
1689
1690#ifdef DEBUG
1691        fprintf(stderr,"******TMPMAPS*****\n");
1692        dumpMaps(tmpmaps);
1693        fprintf(stderr,"******REQUESTMAPS*****\n");
1694        dumpMaps(request_input_real_format);
1695#endif
1696        freeMaps(&tmpmaps);
1697        free(tmpmaps);
1698        tmpmaps=NULL;         
1699      }
1700#ifdef DEBUG
1701      dumpMaps(tmpmaps); 
1702#endif
1703    }
1704#ifdef DEBUG
1705    fprintf(stderr,"Search for response document node\n");
1706#endif
1707    xmlXPathFreeObject(tmpsptr);
1708   
1709    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1710    bool asRaw=false;
1711    tmps=tmpsptr->nodesetval;
1712    if(tmps->nodeNr==0){
1713      tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1714      tmps=tmpsptr->nodesetval;
1715      asRaw=true;
1716    }
1717#ifdef DEBUG
1718    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1719#endif
1720    for(int k=0;k<tmps->nodeNr;k++){
1721      if(asRaw==true)
1722        addToMap(request_inputs,"RawDataOutput","");
1723      else
1724        addToMap(request_inputs,"ResponseDocument","");
1725      maps *tmpmaps=NULL;
1726      xmlNodePtr cur=tmps->nodeTab[k];
1727      if(cur->type == XML_ELEMENT_NODE) {
1728        /**
1729         * A specific responseDocument node.
1730         */
1731        if(tmpmaps==NULL){
1732          tmpmaps=(maps*)malloc(MAPS_SIZE);
1733          if(tmpmaps == NULL){
1734            return errorException(m, _("Unable to allocate memory."), "InternalError");
1735          }
1736          tmpmaps->name=strdup("unknownIdentifier");
1737          tmpmaps->content=NULL;
1738          tmpmaps->next=NULL;
1739        }
1740        /**
1741         * Get every attribute: storeExecuteResponse, lineage, status
1742         */
1743        const char *ress[3]={"storeExecuteResponse","lineage","status"};
1744        xmlChar *val;
1745        for(int l=0;l<3;l++){
1746#ifdef DEBUG
1747          fprintf(stderr,"*** %s ***\t",ress[l]);
1748#endif
1749          val=xmlGetProp(cur,BAD_CAST ress[l]);
1750          if(val!=NULL && strlen((char*)val)>0){
1751            if(tmpmaps->content!=NULL)
1752              addToMap(tmpmaps->content,ress[l],(char*)val);
1753            else
1754              tmpmaps->content=createMap(ress[l],(char*)val);
1755            addToMap(request_inputs,ress[l],(char*)val);
1756          }
1757#ifdef DEBUG
1758          fprintf(stderr,"%s\n",val);
1759#endif
1760          xmlFree(val);
1761        }
1762        xmlNodePtr cur1=cur->children;
1763        while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
1764          cur1=cur1->next;
1765        int cur1cnt=0;
1766        while(cur1){
1767          /**
1768           * Indentifier
1769           */
1770          if(xmlStrncasecmp(cur1->name,BAD_CAST "Identifier",xmlStrlen(cur1->name))==0){
1771            xmlChar *val=
1772              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
1773            if(tmpmaps==NULL){
1774              tmpmaps=(maps*)malloc(MAPS_SIZE);
1775              if(tmpmaps == NULL){
1776                return errorException(m, _("Unable to allocate memory."), "InternalError");
1777              }
1778              tmpmaps->name=strdup((char*)val);
1779              tmpmaps->content=NULL;
1780              tmpmaps->next=NULL;
1781            }
1782            else{
1783              //free(tmpmaps->name);
1784              tmpmaps->name=strdup((char*)val);
1785            }
1786            if(asRaw==true)
1787              addToMap(request_inputs,"RawDataOutput",(char*)val);
1788            else{
1789              if(cur1cnt==0)
1790                addToMap(request_inputs,"ResponseDocument",(char*)val);
1791              else{
1792                map* tt=getMap(request_inputs,"ResponseDocument");
1793                char* tmp=strdup(tt->value);
1794                free(tt->value);
1795                tt->value=(char*)malloc((strlen(tmp)+strlen((char*)val)+1)*sizeof(char));
1796                sprintf(tt->value,"%s;%s",tmp,(char*)val);
1797                free(tmp);
1798              }
1799            }
1800            cur1cnt+=1;
1801            xmlFree(val);
1802          }
1803          /**
1804           * Title, Asbtract
1805           */
1806          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Title",xmlStrlen(cur1->name))==0 ||
1807                  xmlStrncasecmp(cur1->name,BAD_CAST "Abstract",xmlStrlen(cur1->name))==0){
1808            xmlChar *val=
1809              xmlNodeListGetString(doc,cur1->xmlChildrenNode,1);
1810            if(tmpmaps==NULL){
1811              tmpmaps=(maps*)malloc(MAPS_SIZE);
1812              if(tmpmaps == NULL){
1813                return errorException(m, _("Unable to allocate memory."), "InternalError");
1814              }
1815              tmpmaps->name=strdup("missingIndetifier");
1816              tmpmaps->content=createMap((char*)cur1->name,(char*)val);
1817              tmpmaps->next=NULL;
1818            }
1819            else{
1820              if(tmpmaps->content!=NULL)
1821                addToMap(tmpmaps->content,(char*)cur1->name,(char*)val);
1822              else
1823                tmpmaps->content=createMap((char*)cur1->name,(char*)val);
1824            }
1825            xmlFree(val);
1826          }
1827          else if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
1828            /**
1829             * Get every attribute from a Output node
1830             * mimeType, encoding, schema, uom, asReference
1831             */
1832            const char *outs[5]={"mimeType","encoding","schema","uom","asReference"};
1833            for(int l=0;l<5;l++){
1834#ifdef DEBUG
1835              fprintf(stderr,"*** %s ***\t",outs[l]);
1836#endif
1837              val=xmlGetProp(cur1,BAD_CAST outs[l]);
1838              if(val!=NULL && strlen((char*)val)>0){
1839                if(tmpmaps->content!=NULL)
1840                  addToMap(tmpmaps->content,outs[l],(char*)val);
1841                else
1842                  tmpmaps->content=createMap(outs[l],(char*)val);
1843              }
1844#ifdef DEBUG
1845              fprintf(stderr,"%s\n",val);
1846#endif
1847              xmlFree(val);
1848            }
1849            xmlNodePtr cur2=cur1->children;
1850            while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
1851              cur2=cur2->next;
1852            while(cur2){
1853              /**
1854               * Indentifier
1855               */
1856              if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1857                xmlChar *val=
1858                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1859                if(tmpmaps==NULL){
1860                  tmpmaps=(maps*)malloc(MAPS_SIZE);
1861                  if(tmpmaps == NULL){
1862                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1863                  }
1864                  tmpmaps->name=strdup((char*)val);
1865                  tmpmaps->content=NULL;
1866                  tmpmaps->next=NULL;
1867                }
1868                else{
1869                  if(tmpmaps->name!=NULL)
1870                    free(tmpmaps->name);
1871                  tmpmaps->name=strdup((char*)val);;
1872                }
1873                xmlFree(val);
1874              }
1875              /**
1876               * Title, Asbtract
1877               */
1878              else if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1879                      xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1880                xmlChar *val=
1881                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1882                if(tmpmaps==NULL){
1883                  tmpmaps=(maps*)malloc(MAPS_SIZE);
1884                  if(tmpmaps == NULL){
1885                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1886                  }
1887                  tmpmaps->name=strdup("missingIndetifier");
1888                  tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1889                  tmpmaps->next=NULL;
1890                }
1891                else{
1892                  if(tmpmaps->content!=NULL)
1893                    addToMap(tmpmaps->content,
1894                             (char*)cur2->name,(char*)val);
1895                  else
1896                    tmpmaps->content=
1897                      createMap((char*)cur2->name,(char*)val);
1898                }
1899                xmlFree(val);
1900              }
1901              cur2=cur2->next;
1902              while(cur2!=NULL && cur2->type != XML_ELEMENT_NODE)
1903                cur2=cur2->next;
1904            }
1905          }
1906          cur1=cur1->next;
1907          while(cur1!=NULL && cur1->type != XML_ELEMENT_NODE)
1908            cur1=cur1->next;
1909        }
1910      }
1911      if(request_output_real_format==NULL)
1912        request_output_real_format=dupMaps(&tmpmaps);
1913      else
1914        addMapsToMaps(&request_output_real_format,tmpmaps);
1915      if(tmpmaps!=NULL){
1916        freeMaps(&tmpmaps);
1917        free(tmpmaps);
1918        tmpmaps=NULL;
1919      }
1920    }
1921    xmlXPathFreeObject(tmpsptr);
1922    xmlCleanupParser();
1923  }
1924 
1925
1926  //  if(CHECK_INET_HANDLE(hInternet))
1927  InternetCloseHandle(hInternet);
1928
1929#ifdef DEBUG
1930  fprintf(stderr,"\n%d\n",__LINE__);
1931  fflush(stderr);
1932  dumpMaps(request_input_real_format);
1933  dumpMaps(request_output_real_format);
1934  dumpMap(request_inputs);
1935  fprintf(stderr,"\n%d\n",__LINE__);
1936  fflush(stderr);
1937#endif
1938
1939  /**
1940   * Ensure that each requested arguments are present in the request
1941   * DataInputs and ResponseDocument / RawDataOutput
1942   */
1943  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,0);
1944  char *dfv1=addDefaultValues(&request_output_real_format,s1->outputs,m,1);
1945  if(strcmp(dfv1,"")!=0 || strcmp(dfv,"")!=0){
1946    char tmps[1024];
1947    if(strcmp(dfv,"")!=0){
1948      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);
1949    }
1950    else if(strcmp(dfv1,"")!=0){
1951      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);
1952    }
1953    map* tmpe=createMap("text",tmps);
1954    addToMap(tmpe,"code","MissingParameterValue");
1955    printExceptionReportResponse(m,tmpe);
1956    freeService(&s1);
1957    free(s1);
1958    freeMap(&tmpe);
1959    free(tmpe);
1960    freeMaps(&m);
1961    free(m);
1962    free(REQUEST);
1963    free(SERVICE_URL);
1964    freeMaps(&request_input_real_format);
1965    free(request_input_real_format);
1966    freeMaps(&request_output_real_format);
1967    free(request_output_real_format);
1968    freeMaps(&tmpmaps);
1969    free(tmpmaps);
1970    return 1;
1971  }
1972  maps* tmpReqI=request_input_real_format;
1973  while(tmpReqI!=NULL){
1974    char name[1024];
1975    if(getMap(tmpReqI->content,"isFile")!=NULL){
1976      if (cgiFormFileName(tmpReqI->name, name, sizeof(name)) == cgiFormSuccess) {
1977        int BufferLen=1024;
1978        cgiFilePtr file;
1979        int targetFile;
1980        mode_t mode;
1981        char storageNameOnServer[2048];
1982        char fileNameOnServer[64];
1983        char contentType[1024];
1984        char buffer[1024];
1985        char *tmpStr=NULL;
1986        int size;
1987        int got,t;
1988        map *path=getMapFromMaps(m,"main","tmpPath");
1989        cgiFormFileSize(tmpReqI->name, &size);
1990        cgiFormFileContentType(tmpReqI->name, contentType, sizeof(contentType));
1991        if (cgiFormFileOpen(tmpReqI->name, &file) == cgiFormSuccess) {
1992          t=-1;
1993          while(1){
1994            tmpStr=strstr(name+t+1,"\\");
1995            if(NULL==tmpStr)
1996              tmpStr=strstr(name+t+1,"/");
1997            if(NULL!=tmpStr)
1998              t=(int)(tmpStr-name);
1999            else
2000              break;
2001          }
2002          strcpy(fileNameOnServer,name+t+1);
2003         
2004          sprintf(storageNameOnServer,"%s/%s",path->value,fileNameOnServer);
2005#ifdef DEBUG
2006          fprintf(stderr,"Name on server %s\n",storageNameOnServer);
2007          fprintf(stderr,"fileNameOnServer: %s\n",fileNameOnServer);
2008#endif
2009          mode=S_IRWXU|S_IRGRP|S_IROTH;
2010          targetFile = open (storageNameOnServer,O_RDWR|O_CREAT|O_TRUNC,S_IRWXU|S_IRGRP|S_IROTH);
2011          if(targetFile<0){
2012#ifdef DEBUG
2013            fprintf(stderr,"could not create the new file,%s\n",fileNameOnServer);         
2014#endif
2015          }else{
2016            while (cgiFormFileRead(file, buffer, BufferLen, &got) ==cgiFormSuccess){
2017              if(got>0)
2018                write(targetFile,buffer,got);
2019            }
2020          }
2021          addToMap(tmpReqI->content,"lref",storageNameOnServer);
2022          cgiFormFileClose(file);
2023          close(targetFile);
2024#ifdef DEBUG
2025          fprintf(stderr,"File \"%s\" has been uploaded",fileNameOnServer);
2026#endif
2027        }
2028      }
2029    }
2030    tmpReqI=tmpReqI->next;
2031  }
2032
2033  ensureDecodedBase64(&request_input_real_format);
2034
2035#ifdef DEBUG
2036  fprintf(stderr,"REQUEST_INPUTS\n");
2037  dumpMaps(request_input_real_format);
2038  fprintf(stderr,"REQUEST_OUTPUTS\n");
2039  dumpMaps(request_output_real_format);
2040#endif
2041
2042  maps* curs=getMaps(m,"env");
2043  if(curs!=NULL){
2044    map* mapcs=curs->content;
2045    while(mapcs!=NULLMAP){
2046#ifndef WIN32
2047      setenv(mapcs->name,mapcs->value,1);
2048#else
2049#ifdef DEBUG
2050      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2051#endif
2052      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
2053#ifdef DEBUG
2054        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
2055#endif
2056        mapcs->value[strlen(mapcs->value)-1]=0;
2057      }
2058#ifdef DEBUG
2059      fflush(stderr);
2060      fprintf(stderr,"setting variable... %s\n",(
2061#endif
2062              SetEnvironmentVariable(mapcs->name,mapcs->value)
2063#ifdef DEBUG
2064              ==0)? "OK" : "FAILED");
2065#else
2066      ;
2067#endif
2068      char* toto=(char*)malloc((strlen(mapcs->name)+strlen(mapcs->value)+2)*sizeof(char));
2069      sprintf(toto,"%s=%s",mapcs->name,mapcs->value);
2070      putenv(toto);
2071#ifdef DEBUG
2072      fflush(stderr);
2073#endif
2074#endif
2075#ifdef DEBUG
2076      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
2077      fflush(stderr);
2078#endif
2079      mapcs=mapcs->next;
2080    }
2081  }
2082 
2083#ifdef DEBUG
2084  dumpMap(request_inputs);
2085#endif
2086
2087  /**
2088   * Need to check if we need to fork to load a status enabled
2089   */
2090  r_inputs=NULL;
2091  map* store=getMap(request_inputs,"storeExecuteResponse");
2092  map* status=getMap(request_inputs,"status");
2093  /**
2094   * 05-007r7 WPS 1.0.0 page 57 :
2095   * 'If status="true" and storeExecuteResponse is "false" then the service
2096   * shall raise an exception.'
2097   */
2098  if(status!=NULL && strcmp(status->value,"true")==0 && 
2099     store!=NULL && strcmp(store->value,"false")==0){
2100    errorException(m, _("Status cannot be set to true with storeExecuteResponse to false. Please, modify your request parameters."), "InvalidParameterValue");
2101    freeService(&s1);
2102    free(s1);
2103    freeMaps(&m);
2104    free(m);
2105   
2106    freeMaps(&request_input_real_format);
2107    free(request_input_real_format);
2108   
2109    freeMaps(&request_output_real_format);
2110    free(request_output_real_format);
2111   
2112    free(REQUEST);
2113    free(SERVICE_URL);
2114    return 1;
2115  }
2116  r_inputs=getMap(request_inputs,"storeExecuteResponse");
2117  int eres=SERVICE_STARTED;
2118  int cpid=getpid();
2119
2120  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
2121  _tmpMaps->name=strdup("lenv");
2122  char tmpBuff[100];
2123  sprintf(tmpBuff,"%i",cpid);
2124  _tmpMaps->content=createMap("sid",tmpBuff);
2125  _tmpMaps->next=NULL;
2126  addToMap(_tmpMaps->content,"status","0");
2127  addToMap(_tmpMaps->content,"cwd",ntmp);
2128  map* ltmp=getMap(request_inputs,"soap");
2129  if(ltmp!=NULL)
2130    addToMap(_tmpMaps->content,"soap",ltmp->value);
2131  else
2132    addToMap(_tmpMaps->content,"soap","false");
2133  if(cgiCookie!=NULL && strlen(cgiCookie)>0){
2134    int hasValidCookie=-1;
2135    char *tcook=strdup(cgiCookie);
2136    char *tmp=NULL;
2137    int hasVal=-1;
2138    map* testing=getMapFromMaps(m,"main","cookiePrefix");
2139    if(testing==NULL){
2140      tmp=strdup("ID=");
2141    }else{
2142      tmp=(char*)malloc((strlen(testing->value)+2)*sizeof(char));
2143      sprintf(tmp,"%s=",testing->value);
2144      hasVal=1;
2145    }
2146    if(strstr(cgiCookie,";")!=NULL){
2147      char *token,*saveptr;
2148      token=strtok_r(cgiCookie,";",&saveptr);
2149      while(token!=NULL){
2150        if(strcasestr(token,tmp)!=NULL){
2151          if(tcook!=NULL)
2152            free(tcook);
2153          tcook=strdup(token);
2154          hasValidCookie=1;
2155        }
2156        token=strtok_r(NULL,";",&saveptr);
2157      }
2158    }else{
2159      if(strstr(cgiCookie,"=")!=NULL && strcasestr(cgiCookie,tmp)!=NULL){
2160        tcook=strdup(cgiCookie);
2161        hasValidCookie=1;
2162      }
2163      if(tmp!=NULL){
2164        free(tmp);
2165      }
2166    }
2167    if(hasValidCookie>0){
2168      addToMap(_tmpMaps->content,"sessid",strstr(tcook,"=")+1);
2169      char session_file_path[1024];
2170      map *tmpPath=getMapFromMaps(m,"main","sessPath");
2171      if(tmpPath==NULL)
2172        tmpPath=getMapFromMaps(m,"main","tmpPath");
2173      char *tmp1=strtok(tcook,";");
2174      if(tmp1!=NULL)
2175        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(tmp1,"=")+1);
2176      else
2177        sprintf(session_file_path,"%s/sess_%s.cfg",tmpPath->value,strstr(cgiCookie,"=")+1);
2178      free(tcook);
2179      maps *tmpSess=(maps*)malloc(MAPS_SIZE);
2180      struct stat file_status;
2181      int istat = stat(session_file_path, &file_status);
2182      if(istat==0 && file_status.st_size>0){
2183        conf_read(session_file_path,tmpSess);
2184        addMapsToMaps(&m,tmpSess);
2185        freeMaps(&tmpSess);
2186        free(tmpSess);
2187      }
2188    }
2189  }
2190  addMapsToMaps(&m,_tmpMaps);
2191  freeMaps(&_tmpMaps);
2192  free(_tmpMaps);
2193
2194#ifdef DEBUG
2195  dumpMap(request_inputs);
2196#endif
2197#ifdef WIN32
2198  char *cgiSidL=NULL;
2199  if(getenv("CGISID")!=NULL)
2200    addToMap(request_inputs,"cgiSid",getenv("CGISID"));
2201  map* test1=getMap(request_inputs,"cgiSid");
2202  if(test1!=NULL){
2203    cgiSid=test1->value;
2204    addToMap(request_inputs,"storeExecuteResponse","true");
2205    addToMap(request_inputs,"status","true");
2206    setMapInMaps(m,"lenv","sid",test1->value);
2207    status=getMap(request_inputs,"status");
2208    printf("cgiSid %s\n",cgiSid);
2209  }
2210#endif
2211  int hrstd=-1;
2212  char *fbkp,*fbkp1;
2213  FILE *f0,*f1;
2214  if(status!=NULL)
2215    if(strcasecmp(status->value,"false")==0)
2216      status=NULLMAP;
2217  if(status==NULLMAP){
2218    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2219  }
2220  else{
2221    int   pid;
2222#ifdef DEBUG
2223    fprintf(stderr,"\nPID : %d\n",cpid);
2224#endif
2225
2226#ifndef WIN32
2227    pid = fork ();
2228#else
2229    if(cgiSid==NULL){
2230      createProcess(m,request_inputs,s1,NULL,cpid,request_input_real_format,request_output_real_format);
2231      pid = cpid;
2232    }else{
2233      pid=0;
2234      cpid=atoi(cgiSid);
2235      printf("cgiSid %s\n",cgiSid);
2236    }
2237    //printf("pid cpid %d %d\n",pid,cpid);
2238    //fflush(stderr);
2239#endif
2240    if (pid > 0) {
2241      /**
2242       * dady :
2243       * set status to SERVICE_ACCEPTED
2244       */
2245#ifdef DEBUG
2246      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
2247#endif
2248      eres=SERVICE_ACCEPTED;
2249    }else if (pid == 0) {
2250      /**
2251       * son : have to close the stdout, stdin and stderr to let the parent
2252       * process answer to http client.
2253       */
2254      r_inputs=getMapFromMaps(m,"main","tmpPath");
2255      map* r_inputs1=getMap(s1->content,"ServiceProvider");
2256      fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2257      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2258      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2259      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
2260#ifdef DEBUG
2261      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
2262      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
2263      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
2264#endif
2265      freopen(flog,"w+",stderr);
2266      f0=freopen(fbkp , "w+", stdout);
2267      fclose(stdin);
2268      free(flog);
2269      /**
2270       * set status to SERVICE_STARTED and flush stdout to ensure full
2271       * content was outputed (the file used to store the ResponseDocument).
2272       * The rewind stdout to restart writing from the bgining of the file,
2273       * this way the data will be updated at the end of the process run.
2274       */
2275      printProcessResponse(m,request_inputs,cpid,
2276                           s1,r_inputs1->value,SERVICE_STARTED,
2277                           request_input_real_format,
2278                           request_output_real_format);
2279#ifndef WIN32
2280      fflush(stdout);
2281      rewind(stdout);
2282#else
2283#endif
2284      fbkp1=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+1024)*sizeof(char));
2285      sprintf(fbkp1,"%s/%s_final_%d.xml",r_inputs->value,r_inputs1->value,cpid);
2286      f1=freopen(fbkp1 , "w+", stdout);
2287      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
2288    } else {
2289      /**
2290       * error server don't accept the process need to output a valid
2291       * error response here !!!
2292       */
2293      eres=-1;
2294      errorException(m, _("Unable to run the child process properly"), "InternalError");
2295    }
2296  }
2297
2298#ifdef DEBUG
2299  dumpMaps(request_output_real_format);
2300#endif
2301  if(eres!=-1)
2302    outputResponse(s1,request_input_real_format,
2303                   request_output_real_format,request_inputs,
2304                   cpid,m,eres);
2305  fflush(stdout);
2306  /**
2307   * Ensure that if error occurs when freeing memory, no signal will return
2308   * an ExceptionReport document as the result was already returned to the
2309   * client.
2310   */
2311#ifndef USE_GDB
2312  (void) signal(SIGSEGV,donothing);
2313  (void) signal(SIGTERM,donothing);
2314  (void) signal(SIGINT,donothing);
2315  (void) signal(SIGILL,donothing);
2316  (void) signal(SIGFPE,donothing);
2317  (void) signal(SIGABRT,donothing);
2318#endif
2319
2320  if(((int)getpid())!=cpid){
2321    fclose(stdout);
2322    fclose(stderr);
2323    unhandleStatus(m);
2324    /**
2325     * Dump back the final file fbkp1 to fbkp
2326     */
2327    fclose(f0);
2328    fclose(f1);
2329    FILE* f2=fopen(fbkp1,"rb");
2330    FILE* f3=fopen(fbkp,"wb+");
2331    free(fbkp);
2332    fseek(f2,0,SEEK_END);
2333    long flen=ftell(f2);
2334    fseek(f2,0,SEEK_SET);
2335    char *tmps1=(char*)malloc((flen+1)*sizeof(char));
2336    fread(tmps1,flen,1,f2);
2337    fwrite(tmps1,1,flen,f3);
2338    fclose(f2);
2339    fclose(f3);
2340    unlink(fbkp1);
2341    free(fbkp1);
2342  }
2343
2344  freeService(&s1);
2345  free(s1);
2346  freeMaps(&m);
2347  free(m);
2348 
2349  freeMaps(&request_input_real_format);
2350  free(request_input_real_format);
2351 
2352  freeMaps(&request_output_real_format);
2353  free(request_output_real_format);
2354 
2355  free(REQUEST);
2356  free(SERVICE_URL);
2357#ifdef DEBUG
2358  fprintf(stderr,"Processed response \n");
2359  fflush(stdout);
2360  fflush(stderr);
2361#endif
2362
2363  return 0;
2364}
2365
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