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

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

Fix issue when passing Inputs Reference in POST request.

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