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

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

Return exceptionReport when the session file cannot be red or written.

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