source: trunk/zoo-kernel/zoo_service_loader.c @ 59

Last change on this file since 59 was 59, checked in by djay, 13 years ago

Small fix for binary string support in dupMaps function to ensure that the binary value willbe passed to various laguages correctly. Memory cleanup.

File size: 48.5 KB
Line 
1/**
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2009 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
31extern "C" {
32#include <libxml/tree.h>
33#include <libxml/xmlmemory.h>
34#include <libxml/parser.h>
35#include <libxml/xpath.h>
36#include <libxml/xpathInternals.h>
37}
38
39#include "cgic.h"
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
71
72#include <dirent.h>
73#include <signal.h>
74#include <unistd.h>
75#ifndef WIN32
76#include <dlfcn.h>
77#include <libgen.h>
78#else
79#include <windows.h>
80#include <direct.h>
81#endif
82#include <fcntl.h>
83#include <time.h>
84#include <stdarg.h>
85
86#define _(String) dgettext ("zoo-kernel",String)
87
88
89void *translateChar(char* str,char toReplace,char toReplaceBy){
90  int i=0,len=strlen(str);
91  for(i=0;i<len;i++){
92    if(str[i]==toReplace)
93      str[i]=toReplaceBy;
94  }
95}
96
97xmlXPathObjectPtr extractFromDoc(xmlDocPtr doc,char* search){
98  xmlXPathContextPtr xpathCtx;
99  xmlXPathObjectPtr xpathObj;
100  xpathCtx = xmlXPathNewContext(doc);
101  xpathObj = xmlXPathEvalExpression(BAD_CAST search,xpathCtx);
102  xmlXPathFreeContext(xpathCtx);
103  return xpathObj;
104}
105
106void sig_handler(int sig){
107  char tmp[100];
108  char *ssig;
109  switch(sig){
110  case SIGSEGV:
111    ssig="SIGSEGV";
112    break;
113  case SIGTERM:
114    ssig="SIGTERM";
115    break;
116  case SIGINT:
117    ssig="SIGINT";
118    break;
119  case SIGILL:
120    ssig="SIGILL";
121    break;
122  case SIGFPE:
123    ssig="SIGFPE";
124    break;
125  case SIGABRT:
126    ssig="SIGABRT";
127    break;
128  default:
129    ssig="UNKNOWN";
130    break;
131  }
132  sprintf(tmp,_("ZOO Kernel failed to process your request receiving signal %d = %s"),sig,ssig);
133  errorException(NULL, tmp, "InternalError");
134#ifdef DEBUG
135  fprintf(stderr,"Not this time!\n");
136#endif
137  exit(0);
138}
139
140void *loadServiceAndRun(maps **myMap,service* s1,map* request_inputs,maps **inputs,maps** ioutputs,int* eres){
141  char tmps1[1024];
142  char ntmp[1024];
143  maps *m=*myMap;
144  maps *request_output_real_format=*ioutputs;
145  maps *request_input_real_format=*inputs;
146  /**
147   * Extract serviceType to know what kind of service should be loaded
148   */
149  map* r_inputs=NULL;
150#ifndef WIN32
151  getcwd(ntmp,1024);
152#else
153  _getcwd(ntmp,1024);
154#endif
155  r_inputs=getMap(s1->content,"serviceType");
156#ifdef DEBUG
157  fprintf(stderr,"LOAD A %s SERVICE PROVIDER \n",r_inputs->value);
158  fflush(stderr);
159#endif
160  if(strncasecmp(r_inputs->value,"C",1)==0){
161    r_inputs=getMap(request_inputs,"metapath");
162    if(r_inputs!=NULL)
163      sprintf(tmps1,"%s/%s",ntmp,r_inputs->value);
164    else
165      sprintf(tmps1,"%s/",ntmp);
166    char *altPath=strdup(tmps1);
167    r_inputs=getMap(s1->content,"ServiceProvider");
168    sprintf(tmps1,"%s/%s",altPath,r_inputs->value);
169    free(altPath);
170#ifdef DEBUG
171    fprintf(stderr,"Trying to load %s\n",tmps1);
172#endif
173#ifdef WIN32
174    HINSTANCE so = LoadLibraryEx(tmps1,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
175#else
176    void* so = dlopen(tmps1, RTLD_LAZY);
177#endif
178#ifdef DEBUG
179#ifdef WIN32
180    DWORD errstr;
181    errstr = GetLastError();
182    fprintf(stderr,"%s loaded (%d) \n",tmps1,errstr);
183#else
184    char *errstr;
185    errstr = dlerror();
186#endif
187#endif
188
189    if( so != NULL ) {
190#ifdef DEBUG
191      fprintf(stderr,"Library loaded %s \n",errstr);
192      fprintf(stderr,"Service Shared Object = %s\n",r_inputs->value);
193#endif
194      r_inputs=getMap(s1->content,"serviceType");
195#ifdef DEBUG
196      dumpMap(r_inputs);
197      fprintf(stderr,"%s\n",r_inputs->value);
198      fflush(stderr);
199#endif
200      if(strncasecmp(r_inputs->value,"C-FORTRAN",9)==0){
201#ifdef WIN32
202        //Strange return value needed here !
203        return 1;
204#endif
205        r_inputs=getMap(request_inputs,"Identifier");
206        char fname[1024];
207        sprintf(fname,"%s_",r_inputs->value);
208#ifdef DEBUG
209        fprintf(stderr,"Try to load function %s\n",fname);
210#endif
211#ifdef WIN32
212        typedef int (CALLBACK* execute_t)(char***,char***,char***);
213        execute_t execute=(execute_t)GetProcAddress(so,fname);
214#else
215        typedef int (*execute_t)(char***,char***,char***);
216        execute_t execute=(execute_t)dlsym(so,fname);
217#endif
218#ifdef DEBUG
219#ifdef WIN32
220        errstr = GetLastError();
221#else
222        errstr = dlerror();
223#endif
224        fprintf(stderr,"Function loaded %s\n",errstr);
225#endif 
226
227        char main_conf[10][30][1024];
228        char inputs[10][30][1024];
229        char outputs[10][30][1024];
230        for(int i=0;i<10;i++){
231          for(int j=0;j<30;j++){
232            memset(main_conf[i][j],0,1024);
233            memset(inputs[i][j],0,1024);
234            memset(outputs[i][j],0,1024);
235          }
236        }
237        mapsToCharXXX(m,(char***)main_conf);
238        mapsToCharXXX(request_input_real_format,(char***)inputs);
239        mapsToCharXXX(request_output_real_format,(char***)outputs);
240        *eres=execute((char***)&main_conf[0],(char***)&inputs[0],(char***)&outputs[0]);
241#ifdef DEBUG
242        fprintf(stderr,"Function run successfully \n");
243#endif
244        charxxxToMaps((char***)&outputs[0],&request_output_real_format);
245      }else{
246#ifdef DEBUG
247#ifdef WIN32
248        errstr = GetLastError();
249        fprintf(stderr,"Function %s failed to load because of %d\n",r_inputs->value,errstr);
250#endif
251#endif
252        r_inputs=getMap(request_inputs,"Identifier");
253#ifdef DEBUG
254        fprintf(stderr,"Try to load function %s\n",r_inputs->value);
255#endif
256        typedef int (*execute_t)(maps**,maps**,maps**);
257#ifdef WIN32
258        execute_t execute=(execute_t)GetProcAddress(so,r_inputs->value); 
259#else
260        execute_t execute=(execute_t)dlsym(so,r_inputs->value);
261#endif
262
263#ifdef DEBUG
264#ifdef WIN32
265        errstr = GetLastError();
266#else
267        errstr = dlerror();
268#endif
269        fprintf(stderr,"Function loaded %s\n",errstr);
270#endif 
271
272#ifdef DEBUG
273        fprintf(stderr,"Now run the function \n");
274        fflush(stderr);
275#endif
276        *eres=execute(&m,&request_input_real_format,&request_output_real_format);
277#ifdef DEBUG
278        fprintf(stderr,"Function loaded and returned %d\n",eres);
279        fflush(stderr);
280#endif
281      }
282      dlclose(so);
283    } else {
284      /**
285       * Unable to load the specified shared library
286       */
287      char tmps[1024];
288#ifdef WIN32
289      DWORD errstr = GetLastError();
290#else
291      char* errstr = dlerror();
292#endif
293      sprintf(tmps,_("C Library can't be loaded %s \n"),errstr);
294      map* tmps1=createMap("text",tmps);
295      printExceptionReportResponse(m,tmps1);
296      *eres=-1;
297    }
298  }
299  else
300#ifdef USE_PYTHON
301    if(strncasecmp(r_inputs->value,"PYTHON",6)==0){
302      *eres=zoo_python_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
303    }
304    else
305#endif
306       
307#ifdef USE_JAVA
308      if(strncasecmp(r_inputs->value,"JAVA",4)==0){
309        *eres=zoo_java_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
310      }
311      else
312#endif
313
314#ifdef USE_PHP
315        if(strncasecmp(r_inputs->value,"PHP",3)==0){
316          *eres=zoo_php_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
317        }
318        else
319#endif
320           
321           
322#ifdef USE_PERL
323          if(strncasecmp(r_inputs->value,"PERL",4)==0){
324            *eres=zoo_perl_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
325          }
326          else
327#endif
328
329#ifdef USE_JS
330            if(strncasecmp(r_inputs->value,"JS",2)==0){
331              *eres=zoo_js_support(&m,request_inputs,s1,&request_input_real_format,&request_output_real_format);
332            }
333            else
334#endif
335              {
336                char tmpv[1024];
337                sprintf(tmpv,_("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),r_inputs->value);
338                map* tmps=createMap("text",tmpv);
339                printExceptionReportResponse(m,tmps);
340                *eres=-1;
341              }
342  *myMap=m;
343  *ioutputs=request_output_real_format;
344}
345
346int runRequest(map* request_inputs)
347{
348
349#ifndef USE_GDB
350  (void) signal(SIGSEGV,sig_handler);
351  (void) signal(SIGTERM,sig_handler);
352  (void) signal(SIGINT,sig_handler);
353  (void) signal(SIGILL,sig_handler);
354  (void) signal(SIGFPE,sig_handler);
355  (void) signal(SIGABRT,sig_handler);
356#endif
357
358  map* r_inputs=NULL,*tmps=NULL;
359  maps* m=NULL;
360  int argc=count(request_inputs);
361
362  char* REQUEST=NULL;
363  /**
364   * Parsing service specfic configuration file
365   */
366  m=(maps*)calloc(1,MAPS_SIZE);
367  if(m == NULL){
368    return errorException(m, _("Unable to allocate memory."), "InternalError");
369  }
370  char ntmp[1024];
371#ifndef WIN32
372  getcwd(ntmp,1024);
373#else
374  _getcwd(ntmp,1024);
375#endif
376  r_inputs=getMap(request_inputs,"metapath");
377  if(r_inputs==NULL){
378    if(request_inputs==NULL)
379      request_inputs=createMap("metapath","");
380    else
381      addToMap(request_inputs,"metapath","");
382#ifdef DEBUG
383    fprintf(stderr,"ADD METAPATH\n");
384    dumpMap(request_inputs);
385#endif
386    r_inputs=getMap(request_inputs,"metapath");
387  }
388  char conf_file[10240];
389  snprintf(conf_file,10240,"%s/%s/main.cfg",ntmp,r_inputs->value);
390  conf_read(conf_file,m);
391#ifdef DEBUG
392  fprintf(stderr, "***** BEGIN MAPS\n"); 
393  dumpMaps(m);
394  fprintf(stderr, "***** END MAPS\n");
395#endif
396
397  bindtextdomain ("zoo-kernel","/usr/share/locale/");
398  bindtextdomain ("zoo-services","/usr/share/locale/");
399 
400  if((r_inputs=getMap(request_inputs,"language"))!=NULL){
401    char *tmp=strdup(r_inputs->value);
402    translateChar(tmp,'-','_');
403    setlocale (LC_ALL, tmp);
404    free(tmp);
405    setMapInMaps(m,"main","language",r_inputs->value);
406  }
407  else{
408    setlocale (LC_ALL, "en_US");
409    setMapInMaps(m,"main","language","en-US");
410  }
411  setlocale (LC_NUMERIC, "en_US");
412  bind_textdomain_codeset("zoo-kernel","UTF-8");
413  textdomain("zoo-kernel");
414  bind_textdomain_codeset("zoo-services","UTF-8");
415  textdomain("zoo-services");
416
417
418  /**
419   * Check for minimum inputs
420   */
421  r_inputs=getMap(request_inputs,"Request");
422  if(request_inputs==NULL || r_inputs==NULL){ 
423    errorException(m, _("Parameter <request> was not specified"),"MissingParameterValue");
424    freeMaps(&m);
425    free(m);
426    return 1;
427  }
428  else{
429    REQUEST=strdup(r_inputs->value);
430    if(strncasecmp(r_inputs->value,"GetCapabilities",15)!=0
431       && strncasecmp(r_inputs->value,"DescribeProcess",15)!=0
432       && strncasecmp(r_inputs->value,"Execute",7)!=0){ 
433      errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
434      freeMaps(&m);
435      free(m);
436      free(REQUEST);
437      return 1;
438    }
439  }
440  r_inputs=NULL;
441  r_inputs=getMap(request_inputs,"Service");
442  if(r_inputs==NULLMAP){
443    errorException(m, _("Parameter <service> was not specified"),"MissingParameterValue");
444    freeMaps(&m);
445    free(m);
446    free(REQUEST);
447    return 1;
448  }
449  if(strncasecmp(REQUEST,"GetCapabilities",15)!=0){
450    r_inputs=getMap(request_inputs,"Version");
451    if(r_inputs==NULL){ 
452      errorException(m, _("Parameter <version> was not specified"),"MissingParameterValue");
453      freeMaps(&m);
454      free(m);
455      free(REQUEST);
456      return 1;
457    }
458  }
459
460  r_inputs=getMap(request_inputs,"serviceprovider");
461  if(r_inputs==NULL){
462    addToMap(request_inputs,"serviceprovider","");
463  }
464
465  map* outputs=NULL;
466  maps* request_output_real_format=NULL;
467  map* tmpm=getMapFromMaps(m,"main","serverAddress");
468  if(tmpm!=NULL)
469    SERVICE_URL=strdup(tmpm->value);
470  else
471    SERVICE_URL=DEFAULT_SERVICE_URL;
472
473  service* s[100];
474  service* s1;
475  int scount=0;
476
477#ifdef DEBUG
478  dumpMap(r_inputs);
479#endif
480  char conf_dir[1024];
481  int t;
482  char tmps1[1024];
483
484  r_inputs=NULL;
485  r_inputs=getMap(request_inputs,"metapath");
486  if(r_inputs!=NULL)
487    snprintf(conf_dir,1024,"%s/%s",ntmp,r_inputs->value);
488  else
489    snprintf(conf_dir,1024,"%s",ntmp);
490
491  if(strncasecmp(REQUEST,"GetCapabilities",15)==0){
492    int i=0;
493    struct dirent *dp;
494#ifdef DEBUG
495    dumpMap(r_inputs);
496#endif
497    DIR *dirp = opendir(conf_dir);
498    if(dirp==NULL){
499      return errorException(m, _("The specified path doesn't exist."),"InvalidParameterValue");
500    }
501    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
502    r_inputs=NULL;
503    r_inputs=getMap(request_inputs,"ServiceProvider");
504    xmlNodePtr n;
505    //dumpMap(request_inputs);
506    if(r_inputs!=NULL)
507      n = printGetCapabilitiesHeader(doc,r_inputs->value,m);
508    else
509      n = printGetCapabilitiesHeader(doc,"",m);
510    /**
511     * Strange, here we need to close stdout to ensure that no uneeded
512     * char will be printed (parser issue ?)
513     */
514    int saved_stdout = dup(fileno(stdout));
515    dup2(fileno(stderr),fileno(stdout));
516    while ((dp = readdir(dirp)) != NULL)
517      if(strstr(dp->d_name,".zcfg")!=0){
518        memset(tmps1,0,1024);
519        snprintf(tmps1,1024,"%s/%s",conf_dir,dp->d_name);
520        s1=(service*)calloc(1,SERVICE_SIZE);
521        if(s1 == NULL){ 
522          return errorException(m, _("Unable to allocate memory."),"InternalError");
523        }
524#ifdef DEBUG
525        fprintf(stderr,"#################\n%s\n#################\n",tmps1);
526#endif
527        t=getServiceFromFile(tmps1,&s1);
528#ifdef DEBUG
529        dumpService(s1);
530        fflush(stdout);
531        fflush(stderr);
532#endif
533        printGetCapabilitiesForProcess(m,n,s1);
534        freeService(&s1);
535        free(s1);
536        scount++;
537      }
538    (void)closedir(dirp);
539    fflush(stdout);
540    dup2(saved_stdout,fileno(stdout));
541    printDocument(m,doc,getpid());
542    freeMaps(&m);
543    free(m);
544    free(REQUEST);
545    free(SERVICE_URL);
546    fflush(stdout);
547    return 0;
548  }
549  else{
550    r_inputs=getMap(request_inputs,"Identifier");
551    if(r_inputs==NULL 
552       || strlen(r_inputs->name)==0 || strlen(r_inputs->value)==0){ 
553      errorException(m, _("Mandatory <identifier> was not specified"),"MissingParameterValue");
554      freeMaps(&m);
555      free(m);
556      free(REQUEST);
557      free(SERVICE_URL);
558      return 0;
559    }
560
561    struct dirent *dp;
562    DIR *dirp = opendir(conf_dir);
563    if(dirp==NULL){
564      errorException(m, _("The specified path path doesn't exist."),"InvalidParameterValue");
565      freeMaps(&m);
566      free(m);
567      free(REQUEST);
568      free(SERVICE_URL);
569      return 0;
570    }
571    if(strncasecmp(REQUEST,"DescribeProcess",15)==0){
572      /**
573       * Loop over Identifier list
574       */
575      xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
576      r_inputs=NULL;
577      r_inputs=getMap(request_inputs,"ServiceProvider");
578
579      xmlNodePtr n;
580      if(r_inputs!=NULL)
581        n = printDescribeProcessHeader(doc,r_inputs->value,m);
582      else
583        n = printDescribeProcessHeader(doc,"",m);
584
585      r_inputs=getMap(request_inputs,"Identifier");
586      char *tmps=strtok(r_inputs->value,",");
587     
588      char buff[256];
589      char buff1[1024];
590      int i=0;
591      int j=0;
592      int end=-1;
593      int saved_stdout = dup(fileno(stdout));
594      dup2(fileno(stderr),fileno(stdout));
595      while(tmps){
596        memset(buff,0,256);
597        snprintf(buff,256,"%s.zcfg",tmps);
598        memset(buff1,0,1024);
599#ifdef DEBUG
600        fprintf(stderr,"\n#######%s\n########\n",buff1);
601#endif
602        while ((dp = readdir(dirp)) != NULL)
603          if(strcmp(dp->d_name,buff)==0){
604            memset(buff1,0,1024);
605            snprintf(buff1,1024,"%s/%s",conf_dir,dp->d_name);
606            //s1=(service*)malloc(sizeof(service*));
607            s1=(service*)calloc(1,SERVICE_SIZE);
608            if(s1 == NULL){
609              return errorException(m, _("Unable to allocate memory."),"InternalError");
610            }
611#ifdef DEBUG
612            fprintf(stderr,"#################\n%s\n#################\n",buff1);
613#endif
614            t=getServiceFromFile(buff1,&s1);
615#ifdef DEBUG
616            dumpService(s1);
617#endif
618            printDescribeProcessForProcess(m,n,s1,1);
619            freeService(&s1);
620            free(s1);
621            scount++;
622          }
623        rewinddir(dirp);
624        tmps=strtok(NULL,",");
625      }
626      closedir(dirp);
627      fflush(stdout);
628      dup2(saved_stdout,fileno(stdout));
629      printDocument(m,doc,getpid());
630      freeMaps(&m);
631      free(m);
632      free(REQUEST);
633      free(SERVICE_URL);
634      fflush(stdout);
635      //xmlFree(n);
636#ifndef LINUX_FREE_ISSUE
637      if(s1)
638        free(s1);
639#endif
640      return 0;
641    }
642    else
643      if(strncasecmp(REQUEST,"Execute",strlen(REQUEST))!=0){
644        errorException(m, _("Unenderstood <request> value. Please check that it was set to GetCapabilities, DescribeProcess or Execute."), "InvalidParameterValue");
645#ifdef DEBUG
646        fprintf(stderr,"No request found %s",REQUEST);
647#endif 
648        closedir(dirp);
649        free(s);
650        return 0;
651      }
652    closedir(dirp);
653  }
654 
655  s1=NULL;
656  s1=(service*)calloc(1,SERVICE_SIZE);
657  if(s1 == NULL){
658    freeMaps(&m);
659    free(m);
660    free(REQUEST);
661    free(SERVICE_URL);
662    return errorException(m, _("Unable to allocate memory."),"InternalError");
663  }
664  r_inputs=getMap(request_inputs,"MetaPath");
665  if(r_inputs!=NULL)
666    snprintf(tmps1,1024,"%s/%s",ntmp,r_inputs->value);
667  else
668    snprintf(tmps1,1024,"%s/",ntmp);
669  r_inputs=getMap(request_inputs,"Identifier");
670  char *ttmp=strdup(tmps1);
671  snprintf(tmps1,1024,"%s/%s.zcfg",ttmp,r_inputs->value);
672  free(ttmp);
673#ifdef DEBUG
674  fprintf(stderr,"Trying to load %s\n", tmps1);
675#endif
676  int saved_stdout = dup(fileno(stdout));
677  dup2(fileno(stderr),fileno(stdout));
678  t=getServiceFromFile(tmps1,&s1);
679  fflush(stdout);
680  dup2(saved_stdout,fileno(stdout));
681  if(t<0){
682    char tmpMsg[2048+strlen(r_inputs->value)];
683    sprintf(tmpMsg,_("The value for <indetifier> seems to be wrong (%s). Please, ensure that the process exist using the GetCapabilities request."),r_inputs->value);
684    errorException(m, tmpMsg, "InvalidParameterValue");
685    freeService(&s1);
686    free(s1);
687    freeMaps(&m);
688    free(m);
689    free(REQUEST);
690    free(SERVICE_URL);
691    return 0;
692  }
693  close(saved_stdout);
694
695#ifdef DEBUG
696  dumpService(s1);
697#endif
698  map* inputs=NULL;
699  elements* c_inputs=s1->inputs;
700  int j;
701 
702  /**
703   * Create the input maps data structure
704   */
705  int i=0;
706  HINTERNET hInternet;
707  HINTERNET res;
708  hInternet=InternetOpen(
709#ifndef WIN32
710                         (LPCTSTR)
711#endif
712                         "ZooWPSClient\0",
713                         INTERNET_OPEN_TYPE_PRECONFIG,
714                         NULL,NULL, 0);
715
716#ifndef WIN32
717  if(!CHECK_INET_HANDLE(hInternet))
718    fprintf(stderr,"WARNING : hInternet handle failed to initialize");
719#endif
720  maps* request_input_real_format=NULL;
721  maps* tmpmaps = request_input_real_format;
722  map* postRequest=NULL;
723  postRequest=getMap(request_inputs,"xrequest");
724  if(postRequest==NULLMAP){
725    /**
726     * Parsing outputs provided as KVP
727     */
728    r_inputs=NULL;
729#ifdef DEBUG
730    fprintf(stderr,"OUTPUT Parsing ... \n");
731#endif
732    r_inputs=getMap(request_inputs,"ResponseDocument"); 
733    if(r_inputs==NULL) r_inputs=getMap(request_inputs,"RawDataOutput");
734   
735#ifdef DEBUG
736    fprintf(stderr,"OUTPUT Parsing ... \n");
737#endif
738    if(r_inputs!=NULL){
739#ifdef DEBUG
740      fprintf(stderr,"OUTPUT Parsing start now ... \n");
741#endif
742      char current_output_as_string[10240];
743      char cursor_output[10240];
744      char *cotmp=strdup(r_inputs->value);
745      snprintf(cursor_output,10240,"%s",cotmp);
746      free(cotmp);
747      j=0;
748      map* request_kvp_outputs=NULL;
749       
750      /**
751       * Put each Output into the outputs_as_text array
752       */
753      char * pToken;
754      maps* tmp_output=NULL;
755#ifdef DEBUG
756      fprintf(stderr,"OUTPUT [%s]\n",cursor_output);
757#endif
758      pToken=strtok(cursor_output,";");
759      char** outputs_as_text=(char**)calloc(128,sizeof(char*));
760      if(outputs_as_text == NULL) {
761        return errorException(m, _("Unable to allocate memory"), "InternalError");
762      }
763      i=0;
764      while(pToken!=NULL){
765#ifdef DEBUG
766        fprintf(stderr,"***%s***\n",pToken);
767        fflush(stderr);
768        fprintf(stderr,"***%s***\n",pToken);
769#endif
770        outputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
771        if(outputs_as_text[i] == NULL) {
772          return errorException(m, _("Unable to allocate memory"), "InternalError");
773        }
774        snprintf(outputs_as_text[i],strlen(pToken)+1,"%s",pToken);
775        pToken = strtok(NULL,";");
776        i++;
777      }
778      for(j=0;j<i;j++){
779        char *tmp=strdup(outputs_as_text[j]);
780        free(outputs_as_text[j]);
781        char *tmpc;
782        tmpc=strtok(tmp,"@");
783        int k=0;
784        while(tmpc!=NULL){
785          if(k==0){
786            if(tmp_output==NULL){
787              tmp_output=(maps*)calloc(1,MAPS_SIZE);
788              if(tmp_output == NULL){
789                return errorException(m, _("Unable to allocate memory."), "InternalError");
790              }
791              tmp_output->name=strdup(tmpc);
792              tmp_output->content=NULL;
793              tmp_output->next=NULL;
794            }
795          }
796          else{
797            char *tmpv=strstr(tmpc,"=");
798            char tmpn[256];
799            memset(tmpn,0,256);
800            strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
801            tmpn[strlen(tmpc)-strlen(tmpv)]=0;
802#ifdef DEBUG
803            fprintf(stderr,"OUTPUT DEF [%s]=[%s]\n",tmpn,tmpv+1);
804#endif
805            if(tmp_output->content==NULL){
806              tmp_output->content=createMap(tmpn,tmpv+1);
807              tmp_output->content->next=NULL;
808            }
809            else
810              addToMap(tmp_output->content,tmpn,tmpv+1);
811          }
812          k++;
813#ifdef DEBUG
814          fprintf(stderr,"***%s***\n",tmpc);
815#endif
816          tmpc=strtok(NULL,"@");
817        }
818        if(request_output_real_format==NULL)
819          request_output_real_format=dupMaps(&tmp_output);
820        else
821          addMapsToMaps(&request_output_real_format,tmp_output);
822        freeMaps(&tmp_output);
823        free(tmp_output);
824        tmp_output=NULL;
825#ifdef DEBUG
826        dumpMaps(tmp_output);
827        fflush(stderr);
828#endif
829        //tmp_output=tmp_output->next;
830        free(tmp);
831      }
832      free(outputs_as_text);
833    }
834
835
836    /**
837     * Parsing inputs provided as KVP
838     */
839    r_inputs=getMap(request_inputs,"DataInputs");
840#ifdef DEBUG
841    fprintf(stderr,"DATA INPUTS [%s]\n",r_inputs->value);
842#endif
843    char current_input_as_string[40960];
844    char cursor_input[40960];
845    if(r_inputs!=NULL)
846      snprintf(cursor_input,40960,"%s",r_inputs->value);
847    else{
848      errorException(m, _("Parameter <DataInputs> was not specified"),"MissingParameterValue");
849      freeMaps(&m);
850      free(m);
851      free(REQUEST);
852      free(SERVICE_URL);
853      InternetCloseHandle(hInternet);
854      freeService(&s1);
855      free(s1);
856      return 0;
857    }
858    j=0;
859    map* request_kvp_inputs=NULL;
860 
861    /**
862     * Put each DataInputs into the inputs_as_text array
863     */
864    char * pToken;
865    pToken=strtok(cursor_input,";");
866    char** inputs_as_text=(char**)calloc(100,sizeof(char*));
867    if(inputs_as_text == NULL){
868      return errorException(m, _("Unable to allocate memory."), "InternalError");
869    }
870    i=0;
871    while(pToken!=NULL){
872#ifdef DEBUG
873      fprintf(stderr,"***%s***\n",pToken);
874#endif
875      fflush(stderr);
876#ifdef DEBUG
877      fprintf(stderr,"***%s***\n",pToken);
878#endif
879      inputs_as_text[i]=(char*)calloc(strlen(pToken)+1,sizeof(char));
880      snprintf(inputs_as_text[i],strlen(pToken)+1,"%s",pToken);
881      if(inputs_as_text[i] == NULL){
882        return errorException(m, _("Unable to allocate memory."), "InternalError");
883      }
884      pToken = strtok(NULL,";");
885      i++;
886    }
887
888    for(j=0;j<i;j++){
889      char *tmp=strdup(inputs_as_text[j]);
890      free(inputs_as_text[j]);
891      char *tmpc;
892      tmpc=strtok(tmp,"@");
893      while(tmpc!=NULL){
894#ifdef DEBUG
895        fprintf(stderr,"***\n***%s***\n",tmpc);
896#endif
897        char *tmpv=strstr(tmpc,"=");
898        char tmpn[256];
899        memset(tmpn,0,256);
900        strncpy(tmpn,tmpc,(strlen(tmpc)-strlen(tmpv))*sizeof(char));
901        tmpn[strlen(tmpc)-strlen(tmpv)]=0;
902        int cnt=0;
903#ifdef DEBUG
904        fprintf(stderr,"***\n*** %s = %s ***\n",tmpn,tmpv+1);
905#endif
906        if(tmpmaps==NULL){
907          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
908          if(tmpmaps == NULL){
909            return errorException(m, _("Unable to allocate memory."), "InternalError");
910          }
911          tmpmaps->name=strdup(tmpn);
912          tmpmaps->content=createMap("value",tmpv+1);
913          tmpmaps->next=NULL;
914        }
915        tmpc=strtok(NULL,"@");
916        while(tmpc!=NULL){
917#ifdef DEBUG
918          fprintf(stderr,"*** KVP NON URL-ENCODED \n***%s***\n",tmpc);
919#endif
920          char *tmpv1=strstr(tmpc,"=");
921#ifdef DEBUG
922          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
923#endif
924          char tmpn1[1024];
925          memset(tmpn1,0,1024);
926          strncpy(tmpn1,tmpc,strlen(tmpc)-strlen(tmpv1));
927          tmpn1[strlen(tmpc)-strlen(tmpv1)]=0;
928#ifdef DEBUG
929          fprintf(stderr,"*** NAME NON URL-ENCODED \n***%s***\n",tmpn1);
930          fprintf(stderr,"*** VALUE NON URL-ENCODED \n***%s***\n",tmpv1+1);
931#endif
932          if(strcmp(tmpn1,"xlink:href")!=0)
933            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
934          else{
935#ifdef DEBUG
936            fprintf(stderr,"REQUIRE TO DOWNLOAD A FILE FROM A SERVER : url(%s)\n",tmpv1+1);
937#endif
938#ifndef WIN32
939            if(CHECK_INET_HANDLE(hInternet))
940#endif
941              {
942                res=InternetOpenUrl(hInternet,tmpv1+1,NULL,0,
943                                    INTERNET_FLAG_NO_CACHE_WRITE,0);
944#ifdef DEBUG
945                fprintf(stderr,"(%s) content-length : %d,,res.nDataAlloc %d \n",
946                        tmpv1+1,res.nDataAlloc,res.nDataLen);
947#endif
948                char* tmpContent=(char*)calloc((res.nDataLen+1),sizeof(char));
949                if(tmpContent == NULL){
950                  return errorException(m, _("Unable to allocate memory."), "InternalError");
951                }
952                size_t dwRead;
953                InternetReadFile(res, (LPVOID)tmpContent,res.nDataLen, &dwRead);
954                map* tmpMap=getMap(tmpmaps->content,"value");
955                if(tmpMap!=NULL){
956                  free(tmpMap->value);
957                  tmpMap->value=(char*)malloc((res.nDataLen+1)*sizeof(char));
958                  memmove(tmpMap->value,tmpContent,(res.nDataLen)*sizeof(char));
959                  tmpMap->value[res.nDataLen]=0;
960                  if(strlen(tmpContent)!=res.nDataLen){
961                    char tmp[256];
962                    sprintf(tmp,"%d",res.nDataLen*sizeof(char));
963                    addToMap(tmpmaps->content,"size",tmp);
964                  }
965                }
966                free(tmpContent);
967              }
968            addToMap(tmpmaps->content,tmpn1,tmpv1+1);
969          }
970          tmpc=strtok(NULL,"@");
971        }
972#ifdef DEBUG
973        dumpMaps(tmpmaps);
974        fflush(stderr);
975#endif
976        if(request_input_real_format==NULL)
977          request_input_real_format=dupMaps(&tmpmaps);
978        else
979          addMapsToMaps(&request_input_real_format,tmpmaps);
980        freeMaps(&tmpmaps);
981        free(tmpmaps);
982        tmpmaps=NULL;
983        free(tmp);
984      }
985    }
986    free(inputs_as_text);
987  }
988  else {
989    /**
990     * Parse XML request
991     */ 
992    xmlInitParser();
993#ifdef DEBUG
994    fflush(stderr);
995    fprintf(stderr,"BEFORE %s\n",postRequest->value);
996    fflush(stderr);
997#endif
998    xmlDocPtr doc =
999      xmlParseMemory(postRequest->value,cgiContentLength);
1000#ifdef DEBUG
1001    fprintf(stderr,"AFTER\n");
1002    fflush(stderr);
1003#endif
1004    xmlNodePtr cur = xmlDocGetRootElement(doc);
1005    /**
1006     * Parse every Input in DataInputs node.
1007     */
1008    maps* tempMaps=NULL;
1009    xmlXPathObjectPtr tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='Input']");
1010    xmlNodeSet* tmps=tmpsptr->nodesetval;
1011#ifdef DEBUG
1012    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1013#endif
1014    for(int k=0;k<tmps->nodeNr;k++){
1015      maps *tmpmaps=NULL;
1016      xmlNodePtr cur=tmps->nodeTab[k];
1017      if(tmps->nodeTab[k]->type == XML_ELEMENT_NODE) {
1018        /**
1019         * A specific Input node.
1020         */
1021#ifdef DEBUG
1022        fprintf(stderr, "= element 0 node \"%s\"\n", cur->name);
1023#endif
1024        xmlNodePtr cur2=cur->children;
1025        while(cur2!=NULL){
1026          while(cur2!=NULL && cur2->type!=XML_ELEMENT_NODE)
1027            cur2=cur2->next;
1028          if(cur2==NULL)
1029            break;
1030          /**
1031           * Indentifier
1032           */
1033          if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1034            xmlChar *val= xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1035            if(tmpmaps==NULL){
1036              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1037              if(tmpmaps == NULL){
1038                return errorException(m, _("Unable to allocate memory."), "InternalError");
1039              }
1040              tmpmaps->name=strdup((char*)val);
1041              tmpmaps->content=NULL;
1042              tmpmaps->next=NULL;
1043            }
1044            xmlFree(val);
1045          }
1046          /**
1047           * Title, Asbtract
1048           */
1049          if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1050             xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1051            xmlChar *val=
1052              xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1053            if(tmpmaps==NULL){
1054              tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1055              if(tmpmaps == NULL){
1056                return errorException(m, _("Unable to allocate memory."), "InternalError");
1057              }
1058              tmpmaps->name="missingIndetifier";
1059              tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1060              tmpmaps->next=NULL;
1061            }
1062            else{
1063              if(tmpmaps->content!=NULL)
1064                addToMap(tmpmaps->content,
1065                         (char*)cur2->name,(char*)val);
1066              else
1067                tmpmaps->content=
1068                  createMap((char*)cur2->name,(char*)val);
1069            }
1070#ifdef DEBUG
1071            dumpMaps(tmpmaps);
1072#endif
1073            xmlFree(val);
1074          }
1075          /**
1076           * InputDataFormChoice (Reference or Data ?)
1077           */
1078          if(xmlStrcasecmp(cur2->name,BAD_CAST "Reference")==0){
1079            /**
1080             * Get every attribute from a Reference node
1081             * mimeType, encoding, schema, href, method
1082             * Header and Body gesture should be added here
1083             */
1084#ifdef DEBUG
1085            fprintf(stderr,"REFERENCE\n");
1086#endif
1087            map* referenceMap=NULL;
1088            char *refs[5];
1089            refs[0]="mimeType";
1090            refs[1]="encoding";
1091            refs[2]="schema";
1092            refs[3]="method";
1093            refs[4]="href";
1094            char*url;
1095            for(int l=0;l<5;l++){
1096#ifdef DEBUG
1097              fprintf(stderr,"*** %s ***",refs[l]);
1098#endif
1099              xmlChar *val=xmlGetProp(cur2,BAD_CAST refs[l]);
1100              if(val!=NULL && xmlStrlen(val)>0){
1101                if(tmpmaps->content!=NULL)
1102                  addToMap(tmpmaps->content,refs[l],(char*)val);
1103                else
1104                  tmpmaps->content=createMap(refs[l],(char*)val);
1105                map* ltmp=getMap(tmpmaps->content,"method");
1106                if(l==4){
1107                  if(!(ltmp!=NULL && strcmp(ltmp->value,"POST")==0)
1108                     && CHECK_INET_HANDLE(hInternet)){
1109                    res=InternetOpenUrl(hInternet,(char*)val,NULL,0,
1110                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1111                    char* tmpContent=
1112                      (char*)calloc((res.nDataLen+1),sizeof(char));
1113                    if(tmpContent == NULL){
1114                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1115                    }
1116                    size_t dwRead;
1117                    InternetReadFile(res, (LPVOID)tmpContent,
1118                                     res.nDataLen, &dwRead);
1119                    tmpContent[res.nDataLen]=0;
1120                    addToMap(tmpmaps->content,"value",tmpContent);
1121                  }
1122                }
1123              }
1124#ifdef DEBUG
1125              fprintf(stderr,"%s\n",val);
1126#endif
1127              xmlFree(val);
1128            }
1129#ifdef POST_DEBUG
1130            fprintf(stderr,"Parse Header and Body from Reference \n");
1131#endif
1132            xmlNodePtr cur3=cur2->children;
1133            hInternet.header=NULL;
1134            while(cur3){
1135              if(xmlStrcasecmp(cur3->name,BAD_CAST "Header")==0 ){
1136                xmlNodePtr cur4=cur3;
1137                char *tmp=new char[cgiContentLength];
1138                char *ha[2];
1139                ha[0]="key";
1140                ha[1]="value";
1141                int hai;
1142                char *has;
1143                char *key;
1144                for(hai=0;hai<2;hai++){
1145                  xmlChar *val=xmlGetProp(cur3,BAD_CAST ha[hai]);
1146#ifdef POST_DEBUG
1147                  fprintf(stderr,"%s = %s\n",ha[hai],(char*)val);
1148#endif
1149                  if(hai==0){
1150                    key=(char*)calloc((1+strlen((char*)val)),sizeof(char));
1151                    snprintf(key,1+strlen((char*)val),"%s",(char*)val);
1152                  }else{
1153                    has=(char*)calloc((3+strlen((char*)val)+strlen(key)),sizeof(char));
1154                    if(has == NULL){
1155                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1156                    }
1157                    snprintf(has,(3+strlen((char*)val)+strlen(key)),"%s: %s",key,(char*)val);
1158#ifdef POST_DEBUG
1159                    fprintf(stderr,"%s\n",has);
1160#endif
1161                  }
1162                }
1163                hInternet.header=curl_slist_append(hInternet.header, has);
1164                //free(has);
1165              }
1166              else{
1167#ifdef POST_DEBUG
1168                fprintf(stderr,"Try to fetch the body part of the request ...\n");
1169#endif
1170                if(xmlStrcasecmp(cur3->name,BAD_CAST "Body")==0 ){
1171#ifdef POST_DEBUG
1172                  fprintf(stderr,"Body part found !!!\n",(char*)cur3->content);
1173#endif
1174                  char *tmp=new char[cgiContentLength];
1175                  memset(tmp,0,cgiContentLength);
1176                  xmlNodePtr cur4=cur3->children;
1177                  while(cur4!=NULL){
1178                    xmlDocPtr bdoc = xmlNewDoc(BAD_CAST "1.0");
1179                    bdoc->encoding = xmlCharStrdup ("UTF-8");
1180                    xmlDocSetRootElement(bdoc,cur4);
1181                    xmlChar* btmps;
1182                    int bsize;
1183                    xmlDocDumpMemory(bdoc,&btmps,&bsize);
1184#ifdef POST_DEBUG
1185                    fprintf(stderr,"Body part found !!! %s %s\n",tmp,(char*)btmps);
1186#endif
1187                    if(btmps!=NULL)
1188                      sprintf(tmp,"%s",(char*)btmps);
1189                    xmlFreeDoc(bdoc);
1190                    cur4=cur4->next;
1191                  }
1192                  map *btmp=getMap(tmpmaps->content,"href");
1193                  if(btmp!=NULL){
1194#ifdef POST_DEBUG
1195                    fprintf(stderr,"%s %s\n",btmp->value,tmp);
1196                    curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1197#endif
1198                    res=InternetOpenUrl(hInternet,btmp->value,tmp,strlen(tmp),
1199                                        INTERNET_FLAG_NO_CACHE_WRITE,0);
1200                    char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1201                    if(tmpContent == NULL){
1202                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1203                    }
1204                    size_t dwRead;
1205                    InternetReadFile(res, (LPVOID)tmpContent,
1206                                     res.nDataLen, &dwRead);
1207                    tmpContent[res.nDataLen]=0;
1208                    if(hInternet.header!=NULL)
1209                      curl_slist_free_all(hInternet.header);
1210                    addToMap(tmpmaps->content,"value",tmpContent);
1211#ifdef POST_DEBUG
1212                    fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1213#endif
1214                  }
1215                }
1216                else
1217                  if(xmlStrcasecmp(cur3->name,BAD_CAST "BodyReference")==0 ){
1218                    xmlChar *val=xmlGetProp(cur3,BAD_CAST "href");
1219                    HINTERNET bInternet,res1;
1220                    bInternet=InternetOpen(
1221#ifndef WIN32
1222                                           (LPCTSTR)
1223#endif
1224                                           "ZooWPSClient\0",
1225                                           INTERNET_OPEN_TYPE_PRECONFIG,
1226                                           NULL,NULL, 0);
1227                    if(!CHECK_INET_HANDLE(bInternet))
1228                      fprintf(stderr,"WARNING : hInternet handle failed to initialize");
1229#ifdef POST_DEBUG
1230                    curl_easy_setopt(bInternet.handle, CURLOPT_VERBOSE, 1);
1231#endif
1232                    res1=InternetOpenUrl(bInternet,(char*)val,NULL,0,
1233                                         INTERNET_FLAG_NO_CACHE_WRITE,0);
1234                    char* tmp=
1235                      (char*)calloc((res1.nDataLen+1),sizeof(char));
1236                    if(tmp == NULL){
1237                      return errorException(m, _("Unable to allocate memory."), "InternalError");
1238                    }
1239                    size_t bRead;
1240                    InternetReadFile(res1, (LPVOID)tmp,
1241                                     res1.nDataLen, &bRead);
1242                    tmp[res1.nDataLen]=0;
1243                    InternetCloseHandle(bInternet);
1244                    map *btmp=getMap(tmpmaps->content,"href");
1245                    if(btmp!=NULL){
1246#ifdef POST_DEBUG
1247                      fprintf(stderr,"%s %s\n",btmp->value,tmp);
1248                      curl_easy_setopt(hInternet.handle, CURLOPT_VERBOSE, 1);
1249#endif
1250                      res=InternetOpenUrl(hInternet,btmp->value,tmp,
1251                                          strlen(tmp),
1252                                          INTERNET_FLAG_NO_CACHE_WRITE,0);
1253                      char* tmpContent = (char*)calloc((res.nDataLen+1),sizeof(char));
1254                      if(tmpContent == NULL){
1255                        return errorException(m, _("Unable to allocate memory."), "InternalError");
1256                      }
1257                      size_t dwRead;
1258                      InternetReadFile(res, (LPVOID)tmpContent,
1259                                       res.nDataLen, &dwRead);
1260                      tmpContent[res.nDataLen]=0;
1261                      if(hInternet.header!=NULL)
1262                        curl_slist_free_all(hInternet.header);
1263                      addToMap(tmpmaps->content,"value",tmpContent);
1264#ifdef POST_DEBUG
1265                      fprintf(stderr,"DL CONTENT : (%s)\n",tmpContent);
1266#endif
1267                    }
1268                  }
1269              }
1270              cur3=cur3->next;
1271            }
1272#ifdef POST_DEBUG
1273            fprintf(stderr,"Header and Body was parsed from Reference \n");
1274#endif
1275#ifdef DEBUG
1276            dumpMap(tmpmaps->content);
1277            fprintf(stderr, "= element 2 node \"%s\" = (%s)\n", 
1278                    cur2->name,cur2->content);
1279#endif
1280          }
1281          else if(xmlStrcasecmp(cur2->name,BAD_CAST "Data")==0){
1282#ifdef DEBUG
1283            fprintf(stderr,"DATA\n");
1284#endif
1285            xmlNodePtr cur4=cur2->children;
1286            while(cur4!=NULL){
1287              while(cur4!=NULL &&cur4->type!=XML_ELEMENT_NODE)
1288                cur4=cur4->next;
1289              if(cur4==NULL)
1290                break;
1291              if(xmlStrcasecmp(cur4->name, BAD_CAST "LiteralData")==0){
1292                /**
1293                 * Get every attribute from a LiteralData node
1294                 * dataType , uom
1295                 */
1296                char *lits[2];
1297                lits[0]="dataType";
1298                lits[1]="uom";
1299                for(int l=0;l<2;l++){
1300#ifdef DEBUG
1301                  fprintf(stderr,"*** LiteralData %s ***",lits[l]);
1302#endif
1303                  xmlChar *val=xmlGetProp(cur4,BAD_CAST lits[l]);
1304                  if(val!=NULL && strlen((char*)val)>0){
1305                    if(tmpmaps->content!=NULL)
1306                      addToMap(tmpmaps->content,lits[l],(char*)val);
1307                    else
1308                      tmpmaps->content=createMap(lits[l],(char*)val);
1309                  }
1310#ifdef DEBUG
1311                  fprintf(stderr,"%s\n",val);
1312#endif
1313                  xmlFree(val);
1314                }
1315              }
1316              else if(xmlStrcasecmp(cur4->name, BAD_CAST "ComplexData")==0){
1317                /**
1318                 * Get every attribute from a Reference node
1319                 * mimeType, encoding, schema
1320                 */
1321                char *coms[3];
1322                coms[0]="mimeType";
1323                coms[1]="encoding";
1324                coms[2]="schema";
1325                for(int l=0;l<3;l++){
1326#ifdef DEBUG
1327                  fprintf(stderr,"*** ComplexData %s ***",coms[l]);
1328#endif
1329                  xmlChar *val=xmlGetProp(cur4,BAD_CAST coms[l]);
1330                  if(val!=NULL && strlen((char*)val)>0){
1331                    if(tmpmaps->content!=NULL)
1332                      addToMap(tmpmaps->content,coms[l],(char*)val);
1333                    else
1334                      tmpmaps->content=createMap(coms[l],(char*)val);
1335                  }
1336#ifdef DEBUG
1337                  fprintf(stderr,"%s\n",val);
1338#endif
1339                  xmlFree(val);
1340                }
1341              }
1342              xmlChar* mv=xmlNodeListGetString(doc,cur4->xmlChildrenNode,1);
1343              addToMap(tmpmaps->content,"value",(char*)mv);
1344              xmlFree(mv);
1345              cur4=cur4->next;
1346            }
1347          }
1348#ifdef DEBUG
1349          fprintf(stderr,"cur2 next \n");
1350          fflush(stderr);
1351#endif
1352          cur2=cur2->next;
1353        }
1354#ifdef DEBUG
1355        fprintf(stderr,"ADD MAPS TO REQUEST MAPS !\n");
1356        fflush(stderr);
1357#endif
1358        addMapsToMaps(&request_input_real_format,tmpmaps);
1359       
1360#ifdef DEBUG
1361        fprintf(stderr,"******TMPMAPS*****\n");
1362        dumpMaps(tmpmaps);
1363        fprintf(stderr,"******REQUESTMAPS*****\n");
1364        dumpMaps(request_input_real_format);
1365#endif
1366        freeMaps(&tmpmaps);
1367        free(tmpmaps);
1368        tmpmaps=NULL;         
1369      }
1370#ifdef DEBUG
1371      dumpMaps(tmpmaps); 
1372#endif
1373    }
1374#ifdef DEBUG
1375    fprintf(stderr,"Search for response document node\n");
1376#endif
1377    xmlXPathFreeObject(tmpsptr);
1378    //xmlFree(tmps);
1379    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='ResponseDocument']");
1380    tmps=tmpsptr->nodesetval;
1381#ifdef DEBUG
1382    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1383#endif
1384    for(int k=0;k<tmps->nodeNr;k++){
1385      addToMap(request_inputs,"ResponseDocument","");
1386      request_output_real_format;
1387      maps *tmpmaps=NULL;
1388      xmlNodePtr cur=tmps->nodeTab[k];
1389      if(cur->type == XML_ELEMENT_NODE) {
1390        /**
1391         * A specific responseDocument node.
1392         */
1393        if(tmpmaps==NULL){
1394          tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1395          if(tmpmaps == NULL){
1396            return errorException(m, _("Unable to allocate memory."), "InternalError");
1397          }
1398          tmpmaps->name="unknownIdentifier";
1399          tmpmaps->next=NULL;
1400        }
1401        /**
1402         * Get every attribute from a LiteralData node
1403         * storeExecuteResponse, lineage, status
1404         */
1405        char *ress[3];
1406        ress[0]="storeExecuteResponse";
1407        ress[1]="lineage";
1408        ress[2]="status";
1409        xmlChar *val;
1410        for(int l=0;l<3;l++){
1411#ifdef DEBUG
1412          fprintf(stderr,"*** %s ***\t",ress[l]);
1413#endif
1414          val=xmlGetProp(cur,BAD_CAST ress[l]);
1415          if(val!=NULL && strlen((char*)val)>0){
1416            if(tmpmaps->content!=NULL)
1417              addToMap(tmpmaps->content,ress[l],(char*)val);
1418            else
1419              tmpmaps->content=createMap(ress[l],(char*)val);
1420            addToMap(request_inputs,ress[l],(char*)val);
1421          }
1422#ifdef DEBUG
1423          fprintf(stderr,"%s\n",val);
1424#endif
1425          xmlFree(val);
1426        }
1427        xmlNodePtr cur1=cur->children;
1428        while(cur1){
1429          if(xmlStrncasecmp(cur1->name,BAD_CAST "Output",xmlStrlen(cur1->name))==0){
1430            /**
1431             * Get every attribute from a Output node
1432             * mimeType, encoding, schema, uom, asReference
1433             */
1434            char *outs[5];
1435            outs[0]="mimeType";
1436            outs[1]="encoding";
1437            outs[2]="schema";
1438            outs[3]="uom";
1439            outs[4]="asReference";
1440            for(int l=0;l<5;l++){
1441#ifdef DEBUG
1442              fprintf(stderr,"*** %s ***\t",outs[l]);
1443#endif
1444              val=xmlGetProp(cur1,BAD_CAST outs[l]);
1445              if(val!=NULL && strlen((char*)val)>0){
1446                if(tmpmaps->content!=NULL)
1447                  addToMap(tmpmaps->content,outs[l],(char*)val);
1448                else
1449                  tmpmaps->content=createMap(outs[l],(char*)val);
1450              }
1451#ifdef DEBUG
1452              fprintf(stderr,"%s\n",val);
1453#endif
1454              xmlFree(val);
1455            }
1456           
1457            xmlNodePtr cur2=cur1->children;
1458            while(cur2){
1459              /**
1460               * Indentifier
1461               */
1462              if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1463                xmlChar *val=
1464                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1465                if(tmpmaps==NULL){
1466                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1467                  if(tmpmaps == NULL){
1468                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1469                  }
1470                  tmpmaps->name=strdup((char*)val);
1471                  tmpmaps->content=NULL;
1472                  tmpmaps->next=NULL;
1473                }
1474                else
1475                  tmpmaps->name=strdup((char*)val);;
1476                xmlFree(val);
1477              }
1478              /**
1479               * Title, Asbtract
1480               */
1481              if(xmlStrncasecmp(cur2->name,BAD_CAST "Title",xmlStrlen(cur2->name))==0 ||
1482                 xmlStrncasecmp(cur2->name,BAD_CAST "Abstract",xmlStrlen(cur2->name))==0){
1483                xmlChar *val=
1484                  xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1485                if(tmpmaps==NULL){
1486                  tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1487                  if(tmpmaps == NULL){
1488                    return errorException(m, _("Unable to allocate memory."), "InternalError");
1489                  }
1490                  tmpmaps->name="missingIndetifier";
1491                  tmpmaps->content=createMap((char*)cur2->name,(char*)val);
1492                  tmpmaps->next=NULL;
1493                }
1494                else{
1495                  if(tmpmaps->content!=NULL)
1496                    addToMap(tmpmaps->content,
1497                             (char*)cur2->name,(char*)val);
1498                  else
1499                    tmpmaps->content=
1500                      createMap((char*)cur2->name,(char*)val);
1501                }
1502                xmlFree(val);
1503              }
1504              cur2=cur2->next;
1505            }
1506          }
1507          cur1=cur1->next;
1508        }
1509      }
1510      //xmlFree(cur);
1511      if(request_output_real_format==NULL)
1512        request_output_real_format=tmpmaps;
1513      else
1514        addMapsToMaps(&request_output_real_format,tmpmaps);
1515#ifdef DEBUG
1516      dumpMaps(tmpmaps);
1517#endif
1518    }
1519    xmlXPathFreeObject(tmpsptr);
1520    //xmlFree(tmps);
1521    tmpsptr=extractFromDoc(doc,"/*/*/*[local-name()='RawDataOutput']");
1522    tmps=tmpsptr->nodesetval;
1523#ifdef DEBUG
1524    fprintf(stderr,"*****%d*****\n",tmps->nodeNr);
1525#endif
1526    for(int k=0;k<tmps->nodeNr;k++){
1527      addToMap(request_inputs,"RawDataOutput","");
1528      xmlNodePtr cur1=tmps->nodeTab[k];
1529      xmlChar *val;
1530      /**
1531       * Get every attribute from a Output node
1532       * mimeType, encoding, schema, uom, asReference
1533       */
1534      char *outs[4];
1535      outs[0]="mimeType";
1536      outs[1]="encoding";
1537      outs[2]="schema";
1538      outs[3]="uom";
1539      for(int l=0;l<4;l++){
1540#ifdef DEBUG
1541        fprintf(stderr,"*** %s ***\t",outs[l]);
1542#endif
1543        val=xmlGetProp(cur1,BAD_CAST outs[l]);
1544        if(val!=NULL && strlen((char*)val)>0){
1545          if(tmpmaps==NULL){
1546            tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1547            if(tmpmaps == NULL){
1548              return errorException(m, _("Unable to allocate memory."), "InternalError");
1549            }
1550            tmpmaps->name="unknownIdentifier";
1551            tmpmaps->content=createMap(outs[l],(char*)val);
1552            tmpmaps->next=NULL;
1553          }
1554          else
1555            addToMap(tmpmaps->content,outs[l],(char*)val);
1556        }
1557#ifdef DEBUG
1558        fprintf(stderr,"%s\n",val);
1559#endif
1560        xmlFree(val);
1561      }
1562           
1563      xmlNodePtr cur2=cur1->children;
1564      while(cur2){
1565        /**
1566         * Indentifier
1567         */
1568        if(xmlStrncasecmp(cur2->name,BAD_CAST "Identifier",xmlStrlen(cur2->name))==0){
1569          val=
1570            xmlNodeListGetString(doc,cur2->xmlChildrenNode,1);
1571          if(tmpmaps==NULL){
1572            tmpmaps=(maps*)calloc(1,MAPS_SIZE);
1573            if(tmpmaps == NULL){
1574              return errorException(m, _("Unable to allocate memory."), "InternalError");
1575            }
1576            tmpmaps->name=strdup((char*)val);
1577            tmpmaps->content=NULL;
1578            tmpmaps->next=NULL;
1579          }
1580          else
1581            tmpmaps->name=strdup((char*)val);;
1582          xmlFree(val);
1583        }
1584        cur2=cur2->next;
1585      }
1586      if(request_output_real_format==NULL)
1587        request_output_real_format=tmpmaps;
1588      else
1589        addMapsToMaps(&request_output_real_format,tmpmaps);
1590#ifdef DEBUG
1591      dumpMaps(tmpmaps);
1592#endif
1593    }
1594    xmlXPathFreeObject(tmpsptr);
1595    //xmlFree(tmps);
1596    xmlCleanupParser();
1597  }
1598
1599  //if(CHECK_INET_HANDLE(hInternet))
1600  InternetCloseHandle(hInternet);
1601
1602#ifdef DEBUG
1603  fprintf(stderr,"\n%i\n",i);
1604  dumpMaps(request_input_real_format);
1605  dumpMaps(request_output_real_format);
1606  dumpMap(request_inputs);
1607#endif
1608
1609  /**
1610   * Ensure that each requested arguments are present in the request
1611   * DataInputs and ResponseDocument / RawDataOutput
1612   */ 
1613  char *dfv=addDefaultValues(&request_input_real_format,s1->inputs,m,"inputs");
1614  if(strcmp(dfv,"")!=0){
1615    char tmps[1024];
1616    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);
1617    map* tmpe=createMap("text",tmps);
1618    addToMap(tmpe,"code","MissingParameterValue");
1619    printExceptionReportResponse(m,tmpe);
1620    freeMap(&tmpe);
1621    free(tmpe);
1622    freeMaps(&m);
1623    free(m);
1624    free(REQUEST);
1625    freeMaps(&request_input_real_format);
1626    free(request_input_real_format);
1627    freeMaps(&request_output_real_format);
1628    free(request_output_real_format);
1629    freeMaps(&tmpmaps);
1630    free(tmpmaps);
1631    return 1;
1632  }
1633  addDefaultValues(&request_output_real_format,s1->outputs,m,"outputs");
1634
1635#ifdef DEBUG
1636  fprintf(stderr,"REQUEST_INPUTS\n");
1637  dumpMaps(request_input_real_format);
1638  fprintf(stderr,"REQUEST_OUTPUTS\n");
1639  dumpMaps(request_output_real_format);
1640#endif
1641
1642  maps* curs=getMaps(m,"env");
1643  if(curs!=NULL){
1644    map* mapcs=curs->content;
1645    while(mapcs!=NULLMAP){
1646#ifndef WIN32
1647      setenv(mapcs->name,mapcs->value,1);
1648#else
1649#ifdef DEBUG
1650      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1651#endif
1652      if(mapcs->value[strlen(mapcs->value)-2]=='\r'){
1653#ifdef DEBUG
1654        fprintf(stderr,"[ZOO: Env var finish with \r]\n");
1655#endif
1656        mapcs->value[strlen(mapcs->value)-1]=0;
1657      }
1658#ifdef DEBUG
1659      fflush(stderr);
1660      fprintf(stderr,"setting variable... %s\n",
1661#endif
1662              SetEnvironmentVariable(mapcs->name,mapcs->value)
1663#ifdef DEBUG
1664              ? "OK" : "FAILED");
1665#else
1666      ;
1667#endif
1668#ifdef DEBUG
1669      fflush(stderr);
1670#endif
1671#endif
1672#ifdef DEBUG
1673      fprintf(stderr,"[ZOO: setenv (%s=%s)]\n",mapcs->name,mapcs->value);
1674      fflush(stderr);
1675#endif
1676      mapcs=mapcs->next;
1677    }
1678  }
1679 
1680#ifdef DEBUG
1681  dumpMap(request_inputs);
1682#endif
1683
1684  /**
1685   * Need to check if we need to fork to load a status enabled
1686   */
1687  r_inputs=NULL;
1688  r_inputs=getMap(request_inputs,"storeExecuteResponse");
1689  int eres=SERVICE_STARTED;
1690  int cpid=getpid();
1691 
1692  maps *_tmpMaps=(maps*)malloc(MAPS_SIZE);
1693  _tmpMaps->name=strdup("lenv");
1694  char tmpBuff[100];
1695  sprintf(tmpBuff,"%i",cpid);
1696  _tmpMaps->content=createMap("sid",tmpBuff);
1697  _tmpMaps->next=NULL;
1698  addToMap(_tmpMaps->content,"status","0");
1699  addMapsToMaps(&m,_tmpMaps);
1700  freeMaps(&_tmpMaps);
1701  free(_tmpMaps);
1702
1703#ifdef DEBUG
1704  dumpMap(request_inputs);
1705#endif
1706
1707  if(r_inputs!=NULL)
1708    if(strcasecmp(r_inputs->value,"false")==0)
1709      r_inputs=NULL;
1710  if(r_inputs==NULLMAP){
1711    loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
1712  }
1713  else{
1714    pid_t   pid;
1715#ifdef DEBUG
1716    fprintf(stderr,"\nPID : %d\n",cpid);
1717#endif
1718
1719#ifndef WIN32
1720    pid = fork ();
1721#else
1722    pid = 0;
1723#endif
1724    if (pid > 0) {
1725      /**
1726       * dady :
1727       * set status to SERVICE_ACCEPTED
1728       */
1729#ifdef DEBUG
1730      fprintf(stderr,"father pid continue (origin %d) %d ...\n",cpid,getpid());
1731#endif
1732      eres=SERVICE_ACCEPTED;
1733    }else if (pid == 0) {
1734      /**
1735       * son : have to close the stdout, stdin and stderr to let the parent
1736       * process answer to http client.
1737       */
1738      r_inputs=getMapFromMaps(m,"main","tmpPath");
1739      map* r_inputs1=getMap(s1->content,"ServiceProvider");
1740      char* fbkp=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1741      sprintf(fbkp,"%s/%s_%d.xml",r_inputs->value,r_inputs1->value,cpid);
1742      char* flog=(char*)malloc((strlen(r_inputs->value)+strlen(r_inputs1->value)+100)*sizeof(char));
1743      sprintf(flog,"%s/%s_%d_error.log",r_inputs->value,r_inputs1->value,cpid);
1744#ifdef DEBUG
1745      fprintf(stderr,"RUN IN BACKGROUND MODE \n");
1746      fprintf(stderr,"son pid continue (origin %d) %d ...\n",cpid,getpid());
1747      fprintf(stderr,"\nFILE TO STORE DATA %s\n",r_inputs->value);
1748#endif
1749      freopen(fbkp , "w+", stdout);
1750      fclose(stdin);
1751      freopen(flog,"w+",stderr);
1752      free(fbkp);
1753      free(flog);
1754      /**
1755       * set status to SERVICE_STARTED and flush stdout to ensure full
1756       * content was outputed (the file used to store the ResponseDocument).
1757       * The rewind stdout to restart writing from the bgining of the file,
1758       * this way the data will be updated at the end of the process run.
1759       */
1760      updateStatus(m);
1761      printProcessResponse(m,request_inputs,cpid,
1762                            s1,r_inputs1->value,SERVICE_STARTED,
1763                            request_input_real_format,
1764                            request_output_real_format);
1765      fflush(stdout);
1766      rewind(stdout);
1767
1768      loadServiceAndRun(&m,s1,request_inputs,&request_input_real_format,&request_output_real_format,&eres);
1769
1770    } else {
1771      /**
1772       * error server don't accept the process need to output a valid
1773       * error response here !!!
1774       */
1775      eres=-1;
1776      errorException(m, _("Unable to run the child process properly"), "InternalError");
1777    }
1778       
1779  }
1780
1781#ifdef DEBUG
1782  dumpMaps(request_output_real_format);
1783  fprintf(stderr,"Function loaded and returned %d\n",eres);
1784  fflush(stderr);
1785#endif
1786  if(eres!=-1)
1787    outputResponse(s1,request_input_real_format,
1788                   request_output_real_format,request_inputs,
1789                   cpid,m,eres);
1790
1791  if(((int)getpid())!=cpid){
1792    fclose(stdout);
1793    fclose(stderr);
1794    unhandleStatus(m);
1795  }
1796
1797  freeService(&s1);
1798  free(s1);
1799  freeMaps(&m);
1800  free(m);
1801 
1802  freeMaps(&request_input_real_format);
1803  free(request_input_real_format);
1804 
1805  freeMaps(&request_output_real_format);
1806  free(request_output_real_format);
1807 
1808  free(REQUEST);
1809  free(SERVICE_URL);
1810#ifdef DEBUG
1811  fprintf(stderr,"Processed response \n");
1812  fflush(stdout);
1813  fflush(stderr);
1814#endif
1815
1816  return 0;
1817}
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