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

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

Add _ method to the zoo Python module to enable translation from zoo-services textdomain. Add gettextPath in the main section of the main.cfg to set the directory to search for language files.

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