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

Last change on this file since 392 was 392, checked in by djay, 11 years ago

Add support for Python-3.3.0. Fix issue with cache handling. Fix issue with Cookie identifier detection.

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