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

Last change on this file since 362 was 362, checked in by djay, 12 years ago

Fix multiple values for the same identifier.

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