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

Last change on this file since 967 was 967, checked in by djay, 3 years ago

Add support for the two inputs / outputs syntaxes discussed in SWG in both the ZOO-Kernel and the HTML basic UI. Update documentation, add a section for the ZOO-API in Python language section. Rename variables in service.c to ease readabiliy.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 101.1 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2020 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 
25extern "C" int yylex ();
26extern "C" int crlex ();
27
28#ifdef META_DB
29#include "ogrsf_frmts.h"
30#if GDAL_VERSION_MAJOR >= 2
31#include <gdal_priv.h>
32#endif
33#endif
34
35#ifdef USE_OTB
36#include "service_internal_otb.h"
37#endif
38
39#ifdef USE_R
40#include "service_internal_r.h"
41#endif
42
43#ifdef USE_HPC
44#include "service_internal_hpc.h"
45#endif
46
47#ifdef USE_PYTHON
48#include "service_internal_python.h"
49#endif
50
51#include "cgic.h"
52
53#include <libxml/tree.h>
54#include <libxml/xmlmemory.h>
55#include <libxml/parser.h>
56#include <libxml/xpath.h>
57#include <libxml/xpathInternals.h>
58
59#include "ulinet.h"
60
61#include <libintl.h>
62#include <locale.h>
63#include <string.h>
64
65#include "service_internal.h"
66#include "server_internal.h"
67#include "response_print.h"
68#include "request_parser.h"
69#include "service.h"
70
71#ifdef USE_JSON
72#include "caching.h"
73#endif
74#include "sqlapi.h"
75
76#ifdef META_DB
77#include "meta_sql.h"
78#endif
79
80#ifdef USE_SAGA
81#include "service_internal_saga.h"
82#endif
83
84#ifdef USE_JAVA
85#include "service_internal_java.h"
86#endif
87
88#ifdef USE_PHP
89#include "service_internal_php.h"
90#endif
91
92#ifdef USE_JS
93#include "service_internal_js.h"
94#endif
95
96#ifdef USE_RUBY
97#include "service_internal_ruby.h"
98#endif
99
100#ifdef USE_PERL
101#include "service_internal_perl.h"
102#endif
103
104#ifdef USE_MONO
105#include "service_internal_mono.h"
106#endif
107
108#if defined(USE_CALLBACK) || defined(USE_JSON)
109#include "service_callback.h"
110#endif
111
112#ifdef USE_JSON
113#include "service_json.h"
114#include "json_tokener.h"
115#endif
116
117#include <dirent.h>
118#include <signal.h>
119#ifndef WIN32
120#include <execinfo.h>
121#endif
122#include <unistd.h>
123#ifndef WIN32
124#include <dlfcn.h>
125#include <libgen.h>
126#else
127#include <windows.h>
128#include <direct.h>
129#include <sys/types.h>
130#include <sys/stat.h>
131#include <unistd.h>
132#define pid_t int;
133#endif
134#include <fcntl.h>
135#include <time.h>
136#include <stdarg.h>
137
138#include <libxml/tree.h>
139#include <libxml/parser.h>
140#include <libxml/xpath.h>
141#include <libxml/xpathInternals.h>
142
143#include <libxslt/xslt.h>
144#include <libxslt/xsltInternals.h>
145#include <libxslt/transform.h>
146#include <libxslt/xsltutils.h>
147
148#ifndef WIN32
149extern char **environ;
150#endif
151
152
153#ifdef WIN32
154extern "C"
155{
156  __declspec (dllexport) char *strcasestr (char const *a, char const *b)
157#ifndef USE_MS
158  {
159    char *x = zStrdup (a);
160    char *y = zStrdup (b);
161
162      x = _strlwr (x);
163      y = _strlwr (y);
164    char *pos = strstr (x, y);
165    char *ret = pos == NULL ? NULL : (char *) (a + (pos - x));
166      free (x);
167      free (y);
168      return ret;
169  };
170#else
171   ;
172#endif
173}
174#endif
175
176/**
177 * Translation function for zoo-kernel
178 */
179#define _(String) dgettext ("zoo-kernel",String)
180/**
181 * Translation function for zoo-service
182 */
183#define __(String) dgettext ("zoo-service",String)
184
185#ifdef WIN32
186#ifndef PROGRAMNAME
187#define PROGRAMNAME "zoo_loader.cgi"
188#endif
189#endif
190
191
192/**
193 * Replace a char by another one in a string
194 *
195 * @param str the string to update
196 * @param toReplace the char to replace
197 * @param toReplaceBy the char that will be used
198 */
199void
200translateChar (char *str, char toReplace, char toReplaceBy)
201{
202  int i = 0, len = strlen (str);
203  for (i = 0; i < len; i++)
204    {
205      if (str[i] == toReplace)
206        str[i] = toReplaceBy;
207    }
208}
209
210/**
211 * Dump back the final file fbkp1 to fbkp
212 *
213 * @param m the conf maps containing the main.cfg settings
214 * @param fbkp the string corresponding to the name of the file
215 * @param fbkp1 the string corresponding to the name of the file
216 */
217int dumpBackFinalFile(maps* m,char* fbkp,char* fbkp1)
218{
219  FILE *f2 = fopen (fbkp1, "rb");
220#ifndef RELY_ON_DB
221  semid lid = getShmLockId (m, 1);
222  if (lid < 0)
223    return -1;
224  lockShm (lid);
225#endif
226  FILE *f3 = fopen (fbkp, "wb+");
227  free (fbkp);
228  fseek (f2, 0, SEEK_END);
229  long flen = ftell (f2);
230  fseek (f2, 0, SEEK_SET);
231  char *tmps1 = (char *) malloc ((flen + 1) * sizeof (char));
232  fread (tmps1, flen, 1, f2);
233#ifdef WIN32
234  /* knut: I think this block can be dropped; pchr may be NULL if result is not in XML format
235  char *pchr=strrchr(tmps1,'>');
236  flen=strlen(tmps1)-strlen(pchr)+1;
237  tmps1[flen]=0;
238  */
239#endif
240  fwrite (tmps1, 1, flen, f3);
241  fclose (f2);
242  fclose (f3);
243  free(tmps1);
244  return 1;
245}
246
247/**
248 * Recursivelly parse zcfg starting from the ZOO-Kernel cwd.
249 * Call the func function given in arguments after parsing the ZCFG file.
250 *
251 * @param m the conf maps containing the main.cfg settings
252 * @param r the registry containing profiles hierarchy
253 * @param n the root XML Node to add the sub-elements
254 * @param conf_dir the location of the main.cfg file (basically cwd)
255 * @param prefix the current prefix if any, or NULL
256 * @param saved_stdout the saved stdout identifier
257 * @param level the current level (number of sub-directories to reach the
258 * current path)
259 * @param func a pointer to a function having 4 parameters
260 *  (registry*, maps*, xmlNodePtr and service*).
261 * @see inheritance, readServiceFile
262 */
263int
264recursReaddirF ( maps * m, registry *r, void* doc1, void* n1, char *conf_dir,
265                 //( maps * m, registry *r, xmlDocPtr doc, xmlNodePtr n, char *conf_dir,
266                 char *prefix, int saved_stdout, int level,
267                 void (func) (registry *, maps *, void*, void*, service *) )
268                 //void (func) (registry *, maps *, xmlDocPtr, xmlNodePtr, service *) )
269{
270  struct dirent *dp;
271  int scount = 0;
272  xmlDocPtr doc=(xmlDocPtr) doc1;
273  xmlNodePtr n=(xmlNodePtr) n1;
274
275  if (conf_dir == NULL)
276    return 1;
277  DIR *dirp = opendir (conf_dir);
278  if (dirp == NULL)
279    {
280      if (level > 0)
281        return 1;
282      else
283        return -1;
284    }
285  char tmp1[25];
286  sprintf (tmp1, "sprefix_%d", level);
287  char levels[17];
288  sprintf (levels, "%d", level);
289  setMapInMaps (m, "lenv", "level", levels);
290  while ((dp = readdir (dirp)) != NULL)
291    if ((dp->d_type == DT_DIR || dp->d_type == DT_LNK) && dp->d_name[0] != '.'
292        && strstr (dp->d_name, ".") == NULL)
293      {
294
295        char *tmp =
296          (char *) malloc ((strlen (conf_dir) + strlen (dp->d_name) + 2) *
297                           sizeof (char));
298        sprintf (tmp, "%s/%s", conf_dir, dp->d_name);
299
300        if (prefix != NULL)
301          {
302            prefix = NULL;
303          }
304        prefix = (char *) malloc ((strlen (dp->d_name) + 2) * sizeof (char));
305        sprintf (prefix, "%s.", dp->d_name);
306
307        //map* tmpMap=getMapFromMaps(m,"lenv",tmp1);
308
309        int res;
310        if (prefix != NULL)
311          {
312            setMapInMaps (m, "lenv", tmp1, prefix);
313            char levels1[17];
314            sprintf (levels1, "%d", level + 1);
315            setMapInMaps (m, "lenv", "level", levels1);
316            res =
317              recursReaddirF (m, r, doc, n, tmp, prefix, saved_stdout, level + 1,
318                              func);
319            sprintf (levels1, "%d", level);
320            setMapInMaps (m, "lenv", "level", levels1);
321            free (prefix);
322            prefix = NULL;
323          }
324        else
325          res = -1;
326        free (tmp);
327        if (res < 0)
328          {
329            return res;
330          }
331      }
332    else
333      {
334        char* extn = strstr(dp->d_name, ".zcfg");
335        if(dp->d_name[0] != '.' && extn != NULL && strlen(extn) == 5 && strlen(dp->d_name)>6)
336          {
337            int t;
338            char tmps1[1024];
339            memset (tmps1, 0, 1024);
340            snprintf (tmps1, 1024, "%s/%s", conf_dir, dp->d_name);
341
342            char *tmpsn = (char*)malloc((strlen(dp->d_name)-4)*sizeof(char));//zStrdup (dp->d_name);
343            memset (tmpsn, 0, strlen(dp->d_name)-4);
344            snprintf(tmpsn,strlen(dp->d_name)-4,"%s",dp->d_name);
345           
346            map* import = getMapFromMaps (m, IMPORTSERVICE, tmpsn);
347            if (import == NULL || import->value == NULL || zoo_path_compare(tmps1, import->value) != 0 ) { // service is not in [include] block
348              service *s1 = createService();
349              if (s1 == NULL)
350                {
351                  zDup2 (saved_stdout, fileno (stdout));
352                  errorException (m, _("Unable to allocate memory"),
353                                  "InternalError", NULL);
354                  return -1;
355                }
356  #ifdef DEBUG
357              fprintf (stderr, "#################\n%s\n#################\n",
358                       tmps1);
359  #endif
360              t = readServiceFile (m, tmps1, &s1, tmpsn);
361              free (tmpsn);
362              if (t < 0)
363                {
364                  map *tmp00 = getMapFromMaps (m, "lenv", "message");
365                  char tmp01[1024];
366                  if (tmp00 != NULL)
367                    sprintf (tmp01, _("Unable to parse the ZCFG file: %s (%s)"),
368                             dp->d_name, tmp00->value);
369                  else
370                    sprintf (tmp01, _("Unable to parse the ZCFG file: %s."),
371                             dp->d_name);
372                  zDup2 (saved_stdout, fileno (stdout));
373                  errorException (m, tmp01, "InternalError", NULL);
374                  return -1;
375                }
376  #ifdef DEBUG
377              dumpService (s1);
378              fflush (stdout);
379              fflush (stderr);
380  #endif
381              if(s1!=NULL)
382                inheritance(r,&s1);
383              func (r, m, doc, n, s1);
384              freeService (&s1);
385              free (s1);
386              scount++;
387            }
388          }
389      }
390  (void) closedir (dirp);
391  return 1;
392}
393
394/**
395 * When th zcfg file is not found, print error message and cleanup memory
396 * @param zooRegistry the populated registry
397 * @param m the maps pointer to the content of main.cfg file
398 * @param zcfg the zcfg file name
399 * @param code the string determining the nature of the error
400 * @param locator the string determining which parameter the error refer to
401 * @param orig the service name
402 * @param corig the current service name (in case multiple services was parsed)
403 * @param funcError the function used to print the error back
404 */
405void exitAndCleanUp(registry* zooRegistry, maps* m,
406                    const char* zcfg,const char* code,const char* locator,
407                    char* orig,char* corig,
408                    void (funcError) (maps*, map*)){
409  map *tmp00 = getMapFromMaps (m, "lenv", "message");
410  char tmp01[1024];
411  if (tmp00 != NULL)
412    sprintf (tmp01,
413             _("Unable to parse the ZCFG file: %s (%s)"),
414             zcfg, tmp00->value);
415  else
416    sprintf (tmp01,
417             _("Unable to parse the ZCFG file: %s."),
418             zcfg);
419 
420  map* errormap = createMap("text", tmp01);
421  map* tmpMap=getMapFromMaps(m,"main","executionType");
422  char* errorCode=(char*)code;
423  if(tmpMap!=NULL && strncasecmp(tmpMap->value,"json",4)==0)
424    errorCode="NoSuchProcess";
425
426  addToMap(errormap,"code", errorCode);
427  addToMap(errormap,"locator", locator);
428  funcError(m,errormap);
429  freeMaps (&m);
430  free (m);
431  if(zooRegistry!=NULL){
432    freeRegistry(&zooRegistry);
433    free(zooRegistry);
434  }
435  free (orig);
436  if (corig != NULL)
437    free (corig);
438  //xmlFreeDoc (doc);
439  xmlCleanupParser ();
440  zooXmlCleanupNs ();
441  freeMap(&errormap);
442  free(errormap);
443}
444
445
446/**
447 * Search services from various possible sources
448 *
449 * @param zopRegistry the populated registry
450 * @param m the maps pointer to the content of main.cfg file
451 * @param r_inputs the service(s) name(s)
452 * @param func the function used to print the result back
453 * @param doc the xml document or NULL (for json)
454 * @param n the xmlNode of JSON object pointer to the current element
455 * @param conf_dir the directory where the main.cfg has been found
456 * @param request_inputs the map pointer to the request KVP if any
457 * @param funcError the function used to print the error back
458 * @return 0 in case of success, 1 otherwise
459 */
460int fetchServicesForDescription(registry* zooRegistry, maps* m, char* r_inputs,
461                                void (func) (registry *, maps *, void*, void*, service *),
462                                void* doc, void* n, char* conf_dir, map* request_inputs,
463                                void (funcError) (maps*, map*) ){
464  char *orig = zStrdup (r_inputs);
465  service* s1=NULL;
466  int saved_stdout = zDup (fileno (stdout));
467  int t;
468  int scount = 0;
469  struct dirent *dp;
470
471  zDup2 (fileno (stderr), fileno (stdout)); 
472  if (strcasecmp ("all", orig) == 0)
473    {
474      maps* imports = getMaps(m, IMPORTSERVICE); 
475      if (imports != NULL) {       
476        map* zcfg = imports->content;
477           
478        while (zcfg != NULL) {
479          if (zcfg->value != NULL) {
480            service* svc = (service*) malloc(SERVICE_SIZE);
481            if (svc == NULL || readServiceFile(m, zcfg->value, &svc, zcfg->name) < 0) {
482              // pass over silently
483              zcfg = zcfg->next;
484              continue;
485            }
486            inheritance(zooRegistry, &svc);
487#ifdef USE_HPC
488            addNestedOutputs(&svc);
489#endif
490
491            func(zooRegistry, m, doc, n, svc);
492            freeService(&svc);
493            free(svc);                             
494          }
495          zcfg = zcfg->next;
496        }           
497      }
498      if (int res =
499          recursReaddirF (m, zooRegistry, doc, n, conf_dir, NULL, saved_stdout, 0,
500                          func) < 0)
501        return res;
502#ifdef META_DB
503      fetchServicesFromDb(zooRegistry,m,doc,n,func,0);
504      close_sql(m,0);
505#endif
506    }
507  else
508    {
509      DIR *dirp = opendir (conf_dir);
510      char *saveptr;
511      char *tmps = strtok_r (orig, ",", &saveptr);
512
513      char buff[256];
514      char buff1[1024];
515      while (tmps != NULL)
516        {
517          int hasVal = -1;
518          char *corig = zStrdup (tmps);
519          map* import = getMapFromMaps (m, IMPORTSERVICE, corig);   
520          if (import != NULL && import->value != NULL) 
521            {
522#ifdef META_DB                 
523              service* s2=extractServiceFromDb(m,import->name,0);
524              if(s2==NULL){
525#endif
526                s1 = createService();
527                t = readServiceFile (m, import->value, &s1, import->name);
528
529                if (t < 0) // failure reading zcfg
530                  {
531                    zDup2 (saved_stdout, fileno (stdout));
532                    exitAndCleanUp(zooRegistry, m,
533                                   tmps,"InvalidParameterValue","identifier",
534                                   orig,corig,
535                                   funcError);
536                    return 1;
537                  }
538#ifdef DEBUG
539                dumpService (s1);
540#endif
541                inheritance(zooRegistry,&s1);
542#ifdef USE_HPC
543                addNestedOutputs(&s1);
544#endif
545                func (zooRegistry, m, doc, n, s1);
546                freeService (&s1);
547                free (s1);
548                s1 = NULL;
549                scount++;
550                hasVal = 1;               
551#ifdef META_DB
552              }
553#endif
554            }
555          else if (strstr (corig, ".") != NULL)
556            {
557              parseIdentifier (m, conf_dir, corig, buff1);
558              map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
559              if (tmpMap != NULL)
560                addToMap (request_inputs, "metapath", tmpMap->value);
561              map *tmpMapI = getMapFromMaps (m, "lenv", "Identifier");
562              /**
563               * No support for dot in service name stored in metadb!?
564               #ifdef META_DB
565               service* s2=extractServiceFromDb(m,tmpMapI->value,0);
566               if(s2==NULL){
567               #endif
568              */
569              s1 = createService();
570              t = readServiceFile (m, buff1, &s1, tmpMapI->value);
571              if (t < 0)
572                {
573                  zDup2 (saved_stdout, fileno (stdout));
574                  exitAndCleanUp(zooRegistry, m,
575                                 tmps,"InvalidParameterValue","identifier",
576                                 orig,corig,
577                                 funcError);
578                  return 1;
579                }
580#ifdef DEBUG
581              dumpService (s1);
582#endif
583              inheritance(zooRegistry,&s1);
584#ifdef USE_HPC
585              addNestedOutputs(&s1);
586#endif
587              func (zooRegistry, m, doc, n, s1);
588              freeService (&s1);
589              free (s1);
590              s1 = NULL;
591              scount++;
592              hasVal = 1;
593              setMapInMaps (m, "lenv", "level", "0");
594            }
595          else
596            {
597#ifdef META_DB
598              _init_sql(m,"metadb");
599              //FAILED CONNECTING DB
600              if(getMapFromMaps(m,"lenv","dbIssue")!=NULL){
601                fprintf(stderr,"ERROR CONNECTING METADB");
602              }
603              service* s2=extractServiceFromDb(m,corig,0);
604              if(s2!=NULL){
605                inheritance(zooRegistry,&s2);
606#ifdef USE_HPC
607                addNestedOutputs(&s2);
608#endif
609                func (zooRegistry,m, doc, n, s2);
610                freeService (&s2);
611                free (s2);
612                s2 = NULL;
613                hasVal = 1;
614              }else /*TOTO*/{
615#endif
616                memset (buff, 0, 256);
617                snprintf (buff, 256, "%s.zcfg", corig);
618                memset (buff1, 0, 1024);
619#ifdef DEBUG
620                printf ("\n#######%s\n########\n", buff);
621#endif
622                while ((dp = readdir (dirp)) != NULL)
623                  {
624                    if (strcasecmp (dp->d_name, buff) == 0)
625                      {
626                        memset (buff1, 0, 1024);
627                        snprintf (buff1, 1024, "%s/%s", conf_dir,
628                                  dp->d_name);
629                        s1 = createService();
630                        if (s1 == NULL)
631                          {
632                            zDup2 (saved_stdout, fileno (stdout));
633                            map* errormap = createMap("text", _("Unable to allocate memory"));
634                            addToMap(errormap,"code", "InternalError");
635                            addToMap(errormap,"locator", "NULL");
636                            funcError(m,errormap);
637                            return -1;
638                          }
639#ifdef DEBUG_SERVICE_CONF
640                        fprintf
641                          (stderr,"#################\n(%s) %s\n#################\n",
642                           r_inputs->value, buff1);
643#endif
644                        char *tmp0 = zStrdup (dp->d_name);
645                        tmp0[strlen (tmp0) - 5] = 0;
646                        t = readServiceFile (m, buff1, &s1, tmp0);
647                        free (tmp0);
648                        if (t < 0)
649                          {
650                            zDup2 (saved_stdout, fileno (stdout));
651                            exitAndCleanUp(zooRegistry, m,
652                                           buff,"InternalError","NULL",
653                                           orig,corig,
654                                           funcError);
655                            return 1;
656                          }
657#ifdef DEBUG
658                        dumpService (s1);
659#endif
660                        inheritance(zooRegistry,&s1);
661#ifdef USE_HPC
662                        addNestedOutputs(&s1);
663#endif
664                        func (zooRegistry,m, doc, n, s1);
665                        freeService (&s1);
666                        free (s1);
667                        s1 = NULL;
668                        scount++;
669                        hasVal = 1;
670                      }
671                  }
672#ifdef META_DB
673              }
674#endif
675            }                 
676          if (hasVal < 0)
677            {
678              zDup2 (saved_stdout, fileno (stdout));
679              exitAndCleanUp(zooRegistry, m,
680                             buff,"InvalidParameterValue","Identifier",
681                             orig,corig,
682                             funcError);
683              return 1;
684            }
685          rewinddir (dirp);
686          tmps = strtok_r (NULL, ",", &saveptr);
687          if (corig != NULL)
688            free (corig);
689        }                 
690    }
691  fflush (stdout);
692  zDup2 (saved_stdout, fileno (stdout));
693  zClose(saved_stdout);
694  free (orig);
695  return 0;
696}
697
698/**
699 * Run every HTTP request to download inputs passed as reference
700 *
701 * @param conf the maps pointing to the main.cfg file content
702 * @param inputs the maps pointing to the inputs provided in the request
703 */
704int loadHttpRequests(maps* conf,maps* inputs){
705  // Resolve reference
706  // TODO: add erro gesture
707  int eres;
708  maps* tmpMaps=getMaps(conf,"http_requests");
709  if(tmpMaps!=NULL){
710    map* lenMap=getMap(tmpMaps->content,"length");
711    int len=0;
712    if(lenMap!=NULL){
713      len=atoi(lenMap->value);
714    }
715    HINTERNET hInternet;
716    HINTERNET res;
717    if(len>0)
718      hInternet = InternetOpen (
719#ifndef WIN32
720                                (LPCTSTR)
721#endif
722                                "ZOO-Project WPS Client\0",
723                                INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
724    for(int j=0;j<len;j++){
725      map* tmpUrl=getMapArray(tmpMaps->content,"url",j);
726      map* tmpInput=getMapArray(tmpMaps->content,"input",j);
727      maps* currentMaps=getMaps(inputs,tmpInput->value);
728      loadRemoteFile(&conf,&currentMaps->content,&hInternet,tmpUrl->value);
729      addIntToMap(currentMaps->content,"Order",hInternet.nb);
730      addToMap(currentMaps->content,"Reference",tmpUrl->value);
731    }
732    if(len>0){
733      map* error=NULL;
734      runHttpRequests(&conf,&inputs,&hInternet,&error);
735      InternetCloseHandle(&hInternet);
736    }
737  }
738  return 0;
739}
740
741/**
742 * Initialize environment sections, load env, and populate lenv and renv.
743 *
744 * @param conf the maps pointing to the main.cfg file content
745 * @param request_inputs the map pointing to the request KVP
746 * @param cPath a string pointing to the cwd
747 * @param request a string pointing to the request key (xrequest or jrequest)
748 */
749void initAllEnvironment(maps* conf,map* request_inputs,
750                        const char* cPath,const char* request){
751  // Define each env variable in runing environment
752  maps *curs = getMaps (conf, "env");
753  if (curs != NULL) {
754    map *mapcs = curs->content;
755    while (mapcs != NULLMAP)
756      {
757#ifndef WIN32
758        setenv (mapcs->name, mapcs->value, 1);
759#ifdef DEBUG
760        fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
761                 mapcs->value);
762#endif
763#else
764        if (mapcs->value[strlen (mapcs->value) - 2] == '\r')
765          {
766#ifdef DEBUG
767            fprintf (stderr, "[ZOO: Env var finish with \r]\n");
768#endif
769            mapcs->value[strlen (mapcs->value) - 1] = 0;
770          }
771#ifdef DEBUG
772        if (SetEnvironmentVariable (mapcs->name, mapcs->value) == 0)
773          {
774            fflush (stderr);
775            fprintf (stderr, "setting variable... %s\n", "OK");
776          }
777        else
778          {
779            fflush (stderr);
780            fprintf (stderr, "setting variable... %s\n", "OK");
781          }
782#else
783        SetEnvironmentVariable (mapcs->name, mapcs->value);
784#endif
785        char *toto =
786          (char *)
787          malloc ((strlen (mapcs->name) + strlen (mapcs->value) +
788                   2) * sizeof (char));
789        sprintf (toto, "%s=%s", mapcs->name, mapcs->value);
790        _putenv (toto);
791#ifdef DEBUG
792        fflush (stderr);
793#endif
794#endif
795
796#ifdef DEBUG
797        fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
798                 mapcs->value);
799        fflush (stderr);
800#endif
801        mapcs = mapcs->next;
802      }
803  }
804
805           
806
807  int eres = SERVICE_STARTED;
808  int cpid = zGetpid ();
809
810  // Create a map containing a copy of the request map
811  maps *_tmpMaps = createMaps("request");
812  addMapToMap(&_tmpMaps->content,request_inputs);
813  addMapsToMaps (&conf, _tmpMaps);
814  freeMaps (&_tmpMaps);
815  free (_tmpMaps);
816  /**
817   * Initialize the specific [lenv] section which contains runtime variables:
818   *
819   *  - usid : it is an universally unique identifier 
820   *  - osid : it is an idenfitication number
821   *  - sid : it is the process idenfitication number (OS)
822   *  - uusid : it is an universally unique identifier
823   *  - status : value between 0 and 100 to express the  completude of
824   * the operations of the running service
825   *  - message : is a string where you can store error messages, in case
826   * service is failing, or o provide details on the ongoing operation.
827   *  - cwd : the current working directory or servicePath if defined
828   *  - soap : is a boolean value, true if the request was contained in a SOAP
829   * Envelop
830   *  - sessid : string storing the session identifier (only when cookie is
831   * used)
832   *  - cgiSid : only defined on Window platforms (for being able to identify
833   * the created process)
834   *
835   */
836  _tmpMaps = createMaps("lenv");
837  char tmpBuff[100];
838  struct ztimeval tp;
839  if (zGettimeofday (&tp, NULL) == 0)
840    sprintf (tmpBuff, "%i", (cpid + ((int) tp.tv_sec + (int) tp.tv_usec)));
841  else
842    sprintf (tmpBuff, "%i", (cpid + (int) time (NULL)));
843  _tmpMaps->content = createMap ("osid", tmpBuff);
844  sprintf (tmpBuff, "%i", cpid);
845  addToMap (_tmpMaps->content, "sid", tmpBuff);
846  char* tmpUuid=get_uuid();
847  addToMap (_tmpMaps->content, "uusid", tmpUuid);
848  addToMap (_tmpMaps->content, "usid", tmpUuid);
849  free(tmpUuid);
850  addToMap (_tmpMaps->content, "status", "0");
851  map* cwdMap0=getMapFromMaps(conf,"main","servicePath");
852  if(cwdMap0!=NULL){
853    addToMap (_tmpMaps->content, "cwd", cwdMap0->value);
854    addToMap (_tmpMaps->content, "rcwd", cPath);
855  }
856  else
857    addToMap (_tmpMaps->content, "cwd", cPath);
858  addToMap (_tmpMaps->content, "message", _("No message provided"));
859  map *ltmp = getMap (request_inputs, "soap");
860  if (ltmp != NULL)
861    addToMap (_tmpMaps->content, "soap", ltmp->value);
862  else
863    addToMap (_tmpMaps->content, "soap", "false");
864
865  // Parse the session file and add it to the main maps
866  char* originalCookie=NULL;
867  if (cgiCookie != NULL && strlen (cgiCookie) > 0)
868    {
869      int hasValidCookie = -1;
870      char *tcook = originalCookie = zStrdup (cgiCookie);
871      map *testing = getMapFromMaps (conf, "main", "cookiePrefix");
872      parseCookie(&conf,originalCookie);
873      map *sessId=getMapFromMaps(conf,"cookies",
874                                 (testing==NULL?"ID":testing->value));
875      if (sessId!=NULL)
876        {
877          addToMap (_tmpMaps->content, "sessid", sessId->value);
878          char session_file_path[1024];
879          map *tmpPath = getMapFromMaps (conf, "main", "sessPath");
880          if (tmpPath == NULL)
881            tmpPath = getMapFromMaps (conf, "main", "tmpPath");
882          char *tmp1 = strtok (tcook, ";");
883          if (tmp1 != NULL)
884            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
885                     sessId->value);
886          else
887            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
888                     sessId->value);
889          free (tcook);
890          maps *tmpSess = (maps *) malloc (MAPS_SIZE);
891          tmpSess->child=NULL;
892          struct stat file_status;
893          int istat = stat (session_file_path, &file_status);
894          if (istat == 0 && file_status.st_size > 0)
895            {
896              int saved_stdout = zDup (fileno (stdout));
897              zDup2 (fileno (stderr), fileno (stdout));
898              conf_read (session_file_path, tmpSess);
899              addMapsToMaps (&conf, tmpSess);
900              freeMaps (&tmpSess);
901              fflush(stdout);
902              zDup2 (saved_stdout, fileno (stdout));
903              zClose(saved_stdout);
904            }
905          free (tmpSess);
906        }
907    }
908  addMapsToMaps (&conf, _tmpMaps);
909  freeMaps (&_tmpMaps);
910  free (_tmpMaps);
911  maps* bmap=NULL;
912#ifdef DEBUG
913  dumpMap (request_inputs);
914#endif
915  int ei = 1;
916 
917  _tmpMaps = createMaps("renv");
918
919#ifdef WIN32
920  LPVOID orig = GetEnvironmentStrings();
921  LPTSTR s = (LPTSTR) orig;
922 
923  while (*s != NULL) {
924    char* env = strdup(s);
925    char* delim = strchr(env,'=');
926    if (delim != NULL) {
927      char* val = delim+1;
928      *delim = '\0';           
929      if(_tmpMaps->content == NULL) {
930        _tmpMaps->content = createMap(env,val);
931      }
932      else {
933        addToMap(_tmpMaps->content,env,val);
934      }                 
935    }
936    s += strlen(s)+1;
937  } 
938  FreeEnvironmentStrings((LPCH)orig);   
939#else
940  char **orig = environ;
941  char *s=*orig;
942 
943  if(orig!=NULL)
944    for (; s; ei++ ) {
945      if(strstr(s,"=")!=NULL && strlen(strstr(s,"="))>1){
946        int len=strlen(s);
947        char* tmpName=zStrdup(s);
948        char* tmpValue=strstr(s,"=")+1;
949        char* tmpName1=(char*)malloc((1+(len-(strlen(tmpValue)+1)))*sizeof(char));
950        snprintf(tmpName1,(len-strlen(tmpValue)),"%s",tmpName);
951        if(_tmpMaps->content == NULL)
952          _tmpMaps->content = createMap (tmpName1,tmpValue);
953        else
954          addToMap (_tmpMaps->content,tmpName1,tmpValue);
955        free(tmpName1);
956        free(tmpName);
957      }
958      s = *(orig+ei);
959    } 
960#endif
961 
962  if(_tmpMaps->content!=NULL && getMap(_tmpMaps->content,"HTTP_COOKIE")!=NULL){
963    addToMap(_tmpMaps->content,"HTTP_COOKIE1",&cgiCookie[0]);
964  }
965  addMapsToMaps (&conf, _tmpMaps);
966  freeMaps (&_tmpMaps);
967  free (_tmpMaps);
968  map* postRequest=getMap(request_inputs,request);
969  if(postRequest!=NULL)
970    setMapInMaps (conf, "renv", request, postRequest->value);
971#ifdef WIN32
972  char *cgiSidL = NULL;
973  if (getenv ("CGISID") != NULL)
974    addToMap (request_inputs, "cgiSid", getenv ("CGISID"));
975
976  char* usidp;
977  if ( (usidp = getenv("USID")) != NULL ) {
978    setMapInMaps (conf, "lenv", "usid", usidp);
979  }
980
981  map *test1 = getMap (request_inputs, "cgiSid");
982  if (test1 != NULL){
983    cgiSid = zStrdup(test1->value);
984    addToMap (request_inputs, "storeExecuteResponse", "true");
985    addToMap (request_inputs, "status", "true");
986    setMapInMaps (conf, "lenv", "osid", test1->value);
987    status = getMap (request_inputs, "status");
988  }
989  test1 = getMap (request_inputs, "usid");
990  if (test1 != NULL){
991    setMapInMaps (conf, "lenv", "usid", test1->value);
992    setMapInMaps (conf, "lenv", "uusid", test1->value);
993  }
994#endif
995 
996}
997
998/**
999 * Signal handling function which simply call exit(0).
1000 *
1001 * @param sig the signal number
1002 */
1003void
1004donothing (int sig)
1005{
1006#ifdef DEBUG
1007  fprintf (stderr, "Signal %d after the ZOO-Kernel returned result!\n", sig);
1008#endif
1009  exit (0);
1010}
1011
1012/**
1013 * Signal handling function which create an ExceptionReport node containing the
1014 * information message corresponding to the signal number.
1015 *
1016 * @param sig the signal number
1017 */
1018void
1019sig_handler (int sig)
1020{
1021 
1022  char tmp[100];
1023  const char *ssig;
1024  switch (sig)
1025    {
1026    case SIGSEGV:
1027      ssig = "SIGSEGV";
1028      break;
1029    case SIGTERM:
1030      ssig = "SIGTERM";
1031      break;
1032    case SIGINT:
1033      ssig = "SIGINT";
1034      break;
1035    case SIGILL:
1036      ssig = "SIGILL";
1037      break;
1038    case SIGFPE:
1039      ssig = "SIGFPE";
1040      break;
1041    case SIGABRT:
1042      ssig = "SIGABRT";
1043      break;
1044    default:
1045      ssig = "UNKNOWN";
1046      break;
1047    }
1048  sprintf (tmp,
1049           _
1050           ("ZOO Kernel failed to process your request, receiving signal %d = %s "),
1051           sig, ssig);
1052  errorException (NULL, tmp, "InternalError", NULL);
1053#ifdef DEBUG
1054  fprintf (stderr, "Not this time!\n");
1055#endif
1056  exit (0);
1057}
1058
1059#ifdef USE_JSON
1060  /**
1061   * Signal handling function which create an ExceptionReport node containing the
1062   * information message corresponding to the signal number.
1063   *
1064   * @param sig the signal number
1065   */
1066void json_sig_handler (int sig){
1067  char tmp[100];
1068  const char *ssig;
1069  switch (sig)
1070    {
1071    case SIGSEGV:
1072      ssig = "SIGSEGV";
1073      break;
1074    case SIGTERM:
1075      ssig = "SIGTERM";
1076      break;
1077    case SIGINT:
1078      ssig = "SIGINT";
1079      break;
1080    case SIGILL:
1081      ssig = "SIGILL";
1082      break;
1083    case SIGFPE:
1084      ssig = "SIGFPE";
1085      break;
1086    case SIGABRT:
1087      ssig = "SIGABRT";
1088      break;
1089    default:
1090      ssig = "UNKNOWN";
1091      break;
1092    }
1093  sprintf (tmp,
1094           _
1095           ("ZOO Kernel failed to process your request, receiving signal %d = %s "),
1096           sig, ssig);
1097  map* tmpMap=createMap("decode","suze");
1098  maps* tmpMaps=createMaps("lenv");
1099  setMapInMaps(tmpMaps,"lenv","message",tmp);
1100  setMapInMaps(tmpMaps,"lenv","status","failed");
1101  printExceptionReportResponseJ(tmpMaps,tmpMap);
1102  //errorException (NULL, tmp, "InternalError", NULL);
1103#ifdef DEBUG
1104  fprintf (stderr, "Not this time!\n");
1105#endif
1106  exit (0);
1107}
1108 
1109#endif
1110
1111/**
1112 * Load a service provider and run the service function.
1113 *
1114 * @param myMap the conf maps containing the main.cfg settings
1115 * @param s1 the service structure
1116 * @param request_inputs map storing all the request parameters
1117 * @param inputs the inputs maps
1118 * @param ioutputs the outputs maps
1119 * @param eres the result returned by the service execution
1120 */
1121void
1122loadServiceAndRun (maps ** myMap, service * s1, map * request_inputs,
1123                   maps ** inputs, maps ** ioutputs, int *eres)
1124{
1125  char tmps1[1024];
1126  char ntmp[1024];
1127  maps *m = *myMap;
1128  maps *request_output_real_format = *ioutputs;
1129  maps *request_input_real_format = *inputs;
1130  /**
1131   * Extract serviceType to know what kind of service should be loaded
1132   */
1133  map *r_inputs = NULL;
1134  map* cwdMap=getMapFromMaps(m,"main","servicePath");
1135  if(cwdMap!=NULL){
1136    sprintf(ntmp,"%s",cwdMap->value);
1137  }else{
1138#ifndef WIN32
1139    getcwd (ntmp, 1024);
1140#else
1141    _getcwd (ntmp, 1024);
1142#endif
1143  }
1144  r_inputs = getMap (s1->content, "serviceType");
1145#ifdef DEBUG
1146  fprintf (stderr, "LOAD A %s SERVICE PROVIDER \n", r_inputs->value);
1147  fflush (stderr);
1148#endif
1149
1150  map* libp = getMapFromMaps(m, "main", "libPath"); 
1151  if (strlen (r_inputs->value) == 1
1152      && strncasecmp (r_inputs->value, "C", 1) == 0)
1153  {
1154     if (libp != NULL && libp->value != NULL) {
1155            r_inputs = getMap (s1->content, "ServiceProvider");
1156                sprintf (tmps1, "%s/%s", libp->value, r_inputs->value);
1157         }
1158     else {     
1159        r_inputs = getMap (request_inputs, "metapath");
1160        if (r_inputs != NULL)
1161          sprintf (tmps1, "%s/%s", ntmp, r_inputs->value);
1162        else
1163          sprintf (tmps1, "%s/", ntmp);
1164         
1165        char *altPath = zStrdup (tmps1);
1166        r_inputs = getMap (s1->content, "ServiceProvider");
1167        sprintf (tmps1, "%s/%s", altPath, r_inputs->value);
1168        free (altPath);
1169         }
1170#ifdef DEBUG
1171      fprintf (stderr, "Trying to load %s\n", tmps1);
1172#endif
1173#ifdef WIN32
1174      HINSTANCE so =
1175        LoadLibraryEx (tmps1, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
1176#else
1177      void *so = dlopen (tmps1, RTLD_LAZY);
1178#endif
1179#ifdef WIN32
1180      char* errstr = getLastErrorMessage();
1181#else
1182      char *errstr;
1183      errstr = dlerror ();
1184#endif
1185#ifdef DEBUG
1186          fprintf (stderr, "%s loaded (%s) \n", tmps1, errstr);
1187#endif
1188      if (so != NULL)
1189        {
1190#ifdef DEBUG
1191          fprintf (stderr, "Library loaded %s \n", errstr);
1192          fprintf (stderr, "Service Shared Object = %s\n", r_inputs->value);
1193#endif
1194          r_inputs = getMap (s1->content, "serviceType");
1195#ifdef DEBUG
1196          dumpMap (r_inputs);
1197          fprintf (stderr, "%s\n", r_inputs->value);
1198          fflush (stderr);
1199#endif
1200          if (strncasecmp (r_inputs->value, "C-FORTRAN", 9) == 0)
1201            {
1202              r_inputs = getMap (request_inputs, "Identifier");
1203              char fname[1024];
1204              sprintf (fname, "%s_", r_inputs->value);
1205#ifdef DEBUG
1206              fprintf (stderr, "Try to load function %s\n", fname);
1207#endif
1208#ifdef WIN32
1209              typedef int (CALLBACK * execute_t) (char ***, char ***,
1210                                                  char ***);
1211              execute_t execute = (execute_t) GetProcAddress (so, fname);
1212#else
1213              typedef int (*execute_t) (char ***, char ***, char ***);
1214              execute_t execute = (execute_t) dlsym (so, fname);
1215#endif
1216#ifdef DEBUG
1217#ifdef WIN32
1218                          errstr = getLastErrorMessage();
1219#else
1220              errstr = dlerror ();
1221#endif
1222              fprintf (stderr, "Function loaded %s\n", errstr);
1223#endif
1224
1225              char main_conf[10][30][1024];
1226              char inputs[10][30][1024];
1227              char outputs[10][30][1024];
1228              for (int i = 0; i < 10; i++)
1229                {
1230                  for (int j = 0; j < 30; j++)
1231                    {
1232                      memset (main_conf[i][j], 0, 1024);
1233                      memset (inputs[i][j], 0, 1024);
1234                      memset (outputs[i][j], 0, 1024);
1235                    }
1236                }
1237              mapsToCharXXX (m, (char ***) main_conf);
1238              mapsToCharXXX (request_input_real_format, (char ***) inputs);
1239              mapsToCharXXX (request_output_real_format, (char ***) outputs);
1240              *eres =
1241                execute ((char ***) &main_conf[0], (char ***) &inputs[0],
1242                         (char ***) &outputs[0]);
1243#ifdef DEBUG
1244              fprintf (stderr, "Function run successfully \n");
1245#endif
1246              charxxxToMaps ((char ***) &outputs[0],
1247                             &request_output_real_format);
1248            }
1249          else
1250            {
1251#ifdef DEBUG
1252#ifdef WIN32
1253                          errstr = getLastErrorMessage();
1254              fprintf (stderr, "Function %s failed to load because of %s\n",
1255                       r_inputs->value, errstr);
1256#endif
1257#endif
1258              r_inputs = getMapFromMaps (m, "lenv", "Identifier");
1259#ifdef DEBUG
1260              fprintf (stderr, "Try to load function %s\n", r_inputs->value);
1261#endif
1262              typedef int (*execute_t) (maps **, maps **, maps **);
1263#ifdef WIN32
1264              execute_t execute =
1265                (execute_t) GetProcAddress (so, r_inputs->value);
1266#else
1267              execute_t execute = (execute_t) dlsym (so, r_inputs->value);
1268#endif
1269
1270              if (execute == NULL)
1271                {
1272#ifdef WIN32
1273                                  errstr = getLastErrorMessage();
1274#else
1275                  errstr = dlerror ();
1276#endif
1277                  char *tmpMsg =
1278                    (char *) malloc (2048 + strlen (r_inputs->value));
1279                  sprintf (tmpMsg,
1280                           _
1281                           ("Error occurred while running the %s function: %s"),
1282                           r_inputs->value, errstr);
1283                  errorException (m, tmpMsg, "InternalError", NULL);
1284                  free (tmpMsg);
1285#ifdef DEBUG
1286                  fprintf (stderr, "Function %s error %s\n", r_inputs->value,
1287                           errstr);
1288#endif
1289                  *eres = -1;
1290                  return;
1291                }
1292
1293#ifdef DEBUG
1294#ifdef WIN32
1295                          errstr = getLastErrorMessage();
1296#else
1297              errstr = dlerror ();
1298#endif
1299              fprintf (stderr, "Function loaded %s\n", errstr);
1300#endif
1301
1302#ifdef DEBUG
1303              fprintf (stderr, "Now run the function \n");
1304              fflush (stderr);
1305#endif
1306              *eres =
1307                execute (&m, &request_input_real_format,
1308                         &request_output_real_format);
1309#ifdef DEBUG
1310              fprintf (stderr, "Function loaded and returned %d\n", eres);
1311              fflush (stderr);
1312#endif
1313            }
1314#ifdef WIN32
1315          *ioutputs = dupMaps (&request_output_real_format);
1316          FreeLibrary (so);
1317#else
1318          dlclose (so);
1319#endif
1320        }
1321      else
1322        {
1323      /**
1324       * Unable to load the specified shared library
1325       */
1326          char tmps[1024];
1327#ifdef WIN32
1328                  errstr = getLastErrorMessage();
1329#else
1330              errstr = dlerror ();
1331#endif
1332          sprintf (tmps, _("Unable to load C Library %s"), errstr);
1333          errorException(m,tmps,"InternalError",NULL);
1334          *eres = -1;
1335        }
1336    }
1337  else
1338
1339#ifdef USE_HPC
1340  if (strncasecmp (r_inputs->value, "HPC", 3) == 0)
1341    {
1342      *eres =
1343        zoo_hpc_support (&m, request_inputs, s1,
1344                            &request_input_real_format,
1345                            &request_output_real_format);
1346    }
1347  else
1348#endif
1349
1350#ifdef USE_SAGA
1351  if (strncasecmp (r_inputs->value, "SAGA", 4) == 0)
1352    {
1353      *eres =
1354        zoo_saga_support (&m, request_inputs, s1,
1355                            &request_input_real_format,
1356                            &request_output_real_format);
1357    }
1358  else
1359#endif
1360
1361#ifdef USE_OTB
1362  if (strncasecmp (r_inputs->value, "OTB", 3) == 0)
1363    {
1364      *eres =
1365        zoo_otb_support (&m, request_inputs, s1,
1366                            &request_input_real_format,
1367                            &request_output_real_format);
1368    }
1369  else
1370#endif
1371#ifdef USE_PYTHON
1372  if (strncasecmp (r_inputs->value, "PYTHON", 6) == 0)
1373    {             
1374      *eres =
1375        zoo_python_support (&m, request_inputs, s1,
1376                            &request_input_real_format,
1377                            &request_output_real_format);         
1378    }
1379  else
1380#endif
1381
1382#ifdef USE_R
1383  if (strncasecmp (r_inputs->value, "R", 6) == 0)
1384    {     
1385      *eres =
1386        zoo_r_support (&m, request_inputs, s1,
1387                            &request_input_real_format,
1388                            &request_output_real_format);
1389    }
1390  else
1391#endif
1392
1393#ifdef USE_JAVA
1394  if (strncasecmp (r_inputs->value, "JAVA", 4) == 0)
1395    {
1396      *eres =
1397        zoo_java_support (&m, request_inputs, s1, &request_input_real_format,
1398                          &request_output_real_format);
1399    }
1400  else
1401#endif
1402
1403#ifdef USE_PHP
1404  if (strncasecmp (r_inputs->value, "PHP", 3) == 0)
1405    {
1406      *eres =
1407        zoo_php_support (&m, request_inputs, s1, &request_input_real_format,
1408                         &request_output_real_format);         
1409    }
1410  else
1411#endif
1412
1413
1414#ifdef USE_PERL
1415  if (strncasecmp (r_inputs->value, "PERL", 4) == 0)
1416    {
1417      *eres =
1418        zoo_perl_support (&m, request_inputs, s1, &request_input_real_format,
1419                          &request_output_real_format);
1420    }
1421  else
1422#endif
1423
1424#ifdef USE_JS
1425  if (strncasecmp (r_inputs->value, "JS", 2) == 0)
1426    {
1427      *eres =
1428        zoo_js_support (&m, request_inputs, s1, &request_input_real_format,
1429                        &request_output_real_format);
1430    }
1431  else
1432#endif
1433
1434#ifdef USE_RUBY
1435  if (strncasecmp (r_inputs->value, "Ruby", 4) == 0)
1436    {
1437      *eres =
1438        zoo_ruby_support (&m, request_inputs, s1, &request_input_real_format,
1439                          &request_output_real_format);
1440    }
1441  else
1442#endif
1443
1444#ifdef USE_MONO
1445  if (strncasecmp (r_inputs->value, "Mono", 4) == 0)
1446    {
1447      *eres =
1448        zoo_mono_support (&m, request_inputs, s1, &request_input_real_format,
1449                          &request_output_real_format);
1450    }
1451  else
1452#endif
1453
1454    {
1455      char tmpv[1024];
1456      sprintf (tmpv,
1457               _
1458               ("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),
1459               r_inputs->value);
1460      errorException (m, tmpv, "InternalError", NULL);
1461      *eres = -1;
1462    }
1463  *myMap = m;
1464  *ioutputs = request_output_real_format; 
1465}
1466
1467
1468#ifdef WIN32
1469/**
1470 * createProcess function: create a new process after setting some env variables
1471 */
1472void
1473createProcess (maps * m, map * request_inputs, service * s1, char *opts,
1474               int cpid, maps * inputs, maps * outputs)
1475{
1476  STARTUPINFO si;
1477  PROCESS_INFORMATION pi;
1478  ZeroMemory (&si, sizeof (si));
1479  si.cb = sizeof (si);
1480  ZeroMemory (&pi, sizeof (pi));
1481  char *tmp = (char *) malloc ((1024 + cgiContentLength) * sizeof (char));
1482  char *tmpq = (char *) malloc ((1024 + cgiContentLength) * sizeof (char));
1483  map *req = getMap (request_inputs, "request");
1484  map *id = getMap (request_inputs, "identifier");
1485  map *di = getMap (request_inputs, "DataInputs");
1486
1487  // The required size for the dataInputsKVP and dataOutputsKVP buffers
1488  // may exceed cgiContentLength, hence a 2 kb extension. However, a
1489  // better solution would be to have getMapsAsKVP() determine the required
1490  // buffer size before allocating memory.     
1491  char *dataInputsKVP = getMapsAsKVP (inputs, cgiContentLength + 2048, 0);
1492  char *dataOutputsKVP = getMapsAsKVP (outputs, cgiContentLength + 2048, 1);
1493#ifdef DEBUG
1494  fprintf (stderr, "DATAINPUTSKVP %s\n", dataInputsKVP);
1495  fprintf (stderr, "DATAOUTPUTSKVP %s\n", dataOutputsKVP);
1496#endif
1497  map *sid = getMapFromMaps (m, "lenv", "osid");
1498  map *usid = getMapFromMaps (m, "lenv", "usid");
1499  map *r_inputs = getMapFromMaps (m, "main", "tmpPath");
1500  map *r_inputs1 = getMap (request_inputs, "metapath");
1501 
1502  int hasIn = -1;
1503  if (r_inputs1 == NULL)
1504    {
1505      r_inputs1 = createMap ("metapath", "");
1506      hasIn = 1;
1507    }
1508  map *r_inputs2 = getMap (request_inputs, "ResponseDocument");
1509  if (r_inputs2 == NULL)
1510    r_inputs2 = getMap (request_inputs, "RawDataOutput");
1511  map *tmpPath = getMapFromMaps (m, "lenv", "cwd");
1512
1513  map *tmpReq = getMap (request_inputs, "xrequest");
1514
1515  if(r_inputs2 != NULL && tmpReq != NULL) {
1516    const char key[] = "rfile=";
1517    char* kvp = (char*) malloc((FILENAME_MAX + strlen(key))*sizeof(char));
1518    char* filepath = kvp + strlen(key);
1519    strncpy(kvp, key, strlen(key));
1520    addToCache(m, tmpReq->value, tmpReq->value, "text/xml", strlen(tmpReq->value), 
1521               filepath, FILENAME_MAX);
1522    if (filepath == NULL) {
1523      errorException( m, _("Unable to cache HTTP POST Execute request."), "InternalError", NULL); 
1524      return;
1525    }   
1526    sprintf(tmp,"\"metapath=%s&%s&cgiSid=%s&usid=%s\"",
1527            r_inputs1->value,kvp,sid->value,usid->value);
1528    sprintf(tmpq,"metapath=%s&%s",
1529            r_inputs1->value,kvp);
1530    free(kvp); 
1531  }
1532  else if (r_inputs2 != NULL)
1533    {
1534      sprintf (tmp,
1535               "\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s&cgiSid=%s&usid=%s\"",
1536               r_inputs1->value, req->value, id->value, dataInputsKVP,
1537               r_inputs2->name, dataOutputsKVP, sid->value, usid->value);
1538      sprintf (tmpq,
1539               "metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s",
1540               r_inputs1->value, req->value, id->value, dataInputsKVP,
1541               r_inputs2->name, dataOutputsKVP);                   
1542    }
1543  else
1544    {
1545      sprintf (tmp,
1546               "\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&cgiSid=%s&usid=%s\"",
1547               r_inputs1->value, req->value, id->value, dataInputsKVP,
1548               sid->value, usid->value);
1549      sprintf (tmpq,
1550               "metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s",
1551               r_inputs1->value, req->value, id->value, dataInputsKVP,
1552               sid->value);   
1553    }
1554
1555  if (hasIn > 0)
1556    {
1557      freeMap (&r_inputs1);
1558      free (r_inputs1);
1559    }
1560  char *tmp1 = zStrdup (tmp);
1561  sprintf (tmp, "\"%s\" %s \"%s\"", PROGRAMNAME, tmp1, sid->value); 
1562  free (dataInputsKVP);
1563  free (dataOutputsKVP);
1564#ifdef DEBUG
1565  fprintf (stderr, "REQUEST IS : %s \n", tmp);
1566#endif
1567
1568  usid = getMapFromMaps (m, "lenv", "usid");
1569  if (usid != NULL && usid->value != NULL) {
1570    SetEnvironmentVariable("USID", TEXT (usid->value));
1571  }
1572  SetEnvironmentVariable ("CGISID", TEXT (sid->value));
1573  SetEnvironmentVariable ("QUERY_STRING", TEXT (tmpq));
1574  // knut: Prevent REQUEST_METHOD=POST in background process call to cgic:main
1575  // (process hangs when reading cgiIn):
1576  SetEnvironmentVariable("REQUEST_METHOD", "GET");
1577  SetEnvironmentVariable("CONTENT_TYPE", "text/plain");
1578 
1579  char clen[1000];
1580  sprintf (clen, "%d", strlen (tmpq));
1581  SetEnvironmentVariable ("CONTENT_LENGTH", TEXT (clen));
1582
1583  // ref. https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx
1584  if (!CreateProcess (NULL,     // No module name (use command line)
1585                      TEXT (tmp),       // Command line
1586                      NULL,     // Process handle not inheritable
1587                      NULL,     // Thread handle not inheritable
1588                      FALSE,    // Set handle inheritance to FALSE
1589                      CREATE_NO_WINDOW, // Apache won't wait until the end
1590                      NULL,     // Use parent's environment block
1591                      NULL,     // Use parent's starting directory
1592                      &si,      // Pointer to STARTUPINFO struct
1593                      &pi)      // Pointer to PROCESS_INFORMATION struct
1594    )
1595    {
1596#ifdef DEBUG
1597      fprintf (stderr, "CreateProcess failed (%d).\n", GetLastError ());
1598#endif
1599      if (tmp != NULL) {
1600        free(tmp);
1601      }
1602      if (tmpq != NULL) {
1603        free(tmpq);
1604      }         
1605      return;
1606    }
1607  else
1608    {
1609#ifdef DEBUG
1610      fprintf (stderr, "CreateProcess successful (%d).\n\n\n\n",
1611               GetLastError ());
1612#endif
1613    }
1614  CloseHandle (pi.hProcess);
1615  CloseHandle (pi.hThread);
1616 
1617  if (tmp != NULL) {
1618    free(tmp);
1619  }
1620  if (tmpq != NULL) {
1621    free(tmpq);
1622  }
1623 
1624#ifdef DEBUG
1625  fprintf (stderr, "CreateProcess finished !\n");
1626#endif
1627}
1628#endif
1629
1630/**
1631 * Process the request.
1632 *
1633 * @param inputs the request parameters map
1634 * @return 0 on sucess, other value on failure
1635 * @see conf_read,recursReaddirF
1636 */
1637int
1638runRequest (map ** inputs)
1639{
1640 
1641#ifndef USE_GDB
1642#ifndef WIN32
1643  signal (SIGCHLD, SIG_IGN);
1644#endif 
1645  signal (SIGSEGV, sig_handler);
1646  signal (SIGTERM, sig_handler);
1647  signal (SIGINT, sig_handler);
1648  signal (SIGILL, sig_handler);
1649  signal (SIGFPE, sig_handler);
1650  signal (SIGABRT, sig_handler);
1651#endif
1652
1653 
1654  map *r_inputs = NULL;
1655  map *request_inputs = *inputs;
1656#ifdef IGNORE_METAPATH
1657  addToMap(request_inputs, "metapath", "");
1658#endif 
1659  maps *m = NULL;
1660  char *REQUEST = NULL;
1661  /**
1662   * Parsing service specfic configuration file
1663   */
1664  m = (maps *) malloc (MAPS_SIZE);
1665  if (m == NULL)
1666    {
1667      return errorException (NULL, _("Unable to allocate memory"),
1668                             "InternalError", NULL);
1669    }
1670  m->child=NULL;
1671  char ntmp[1024];
1672#ifndef ETC_DIR
1673#ifndef WIN32
1674  getcwd (ntmp, 1024);
1675#else
1676  _getcwd (ntmp, 1024);
1677#endif
1678#else
1679  sprintf(ntmp,"%s",ETC_DIR);
1680#endif
1681  r_inputs = getMapOrFill (&request_inputs, "metapath", "");
1682
1683  char conf_file[10240];
1684  snprintf (conf_file, 10240, "%s/%s/main.cfg", ntmp, r_inputs->value);
1685  if (conf_read (conf_file, m) == 2)
1686    {
1687      errorException (NULL, _("Unable to load the main.cfg file."),
1688                      "InternalError", NULL);
1689      free (m);
1690      return 1;
1691    }
1692#ifdef DEBUG
1693  fprintf (stderr, "***** BEGIN MAPS\n");
1694  dumpMaps (m);
1695  fprintf (stderr, "***** END MAPS\n");
1696#endif
1697
1698  map *getPath = getMapFromMaps (m, "main", "gettextPath");
1699  if (getPath != NULL)
1700    {
1701      bindtextdomain ("zoo-kernel", getPath->value);
1702      bindtextdomain ("zoo-services", getPath->value);
1703    }
1704  else
1705    {
1706      bindtextdomain ("zoo-kernel", LOCALEDIR);
1707      bindtextdomain ("zoo-services", LOCALEDIR);
1708    }
1709
1710  /**
1711   * Manage our own error log file (usefull to separate standard apache debug
1712   * messages from the ZOO-Kernel ones but also for IIS users to avoid wrong
1713   * headers messages returned by the CGI due to wrong redirection of stderr)
1714   */
1715  FILE *fstde = NULL;
1716  map *fstdem = getMapFromMaps (m, "main", "logPath");
1717  if (fstdem != NULL)
1718    fstde = freopen (fstdem->value, "a+", stderr);
1719
1720  /**
1721   * Language gesture
1722   */
1723  r_inputs = getMap (request_inputs, "language");
1724  if (r_inputs == NULL)
1725    r_inputs = getMap (request_inputs, "AcceptLanguages");
1726  if (r_inputs == NULL)
1727    r_inputs = getMapFromMaps (m, "main", "language");
1728  if (r_inputs != NULL)
1729    {
1730      if (isValidLang (m, r_inputs->value) < 0)
1731        {
1732          char tmp[1024];
1733          sprintf (tmp,
1734                   _
1735                   ("The value %s is not supported for the <language> parameter"),
1736                   r_inputs->value);
1737          errorException (m, tmp, "InvalidParameterValue", "language");
1738          freeMaps (&m);
1739          free (m);
1740          free (REQUEST);
1741          return 1;
1742
1743        }
1744      char *tmp = zStrdup (r_inputs->value);
1745      setMapInMaps (m, "main", "language", tmp);
1746#ifdef DEB
1747      char tmp2[12];
1748      sprintf (tmp2, "%s.utf-8", tmp);
1749      translateChar (tmp2, '-', '_');
1750      setlocale (LC_ALL, tmp2);
1751#else
1752      translateChar (tmp, '-', '_');
1753      setlocale (LC_ALL, tmp);
1754#endif
1755#ifndef WIN32
1756      setenv ("LC_ALL", tmp, 1);
1757#else
1758      char tmp1[13];
1759      sprintf (tmp1, "LC_ALL=%s", tmp);
1760      _putenv (tmp1);
1761#endif
1762      free (tmp);
1763    }
1764  else
1765    {
1766      setlocale (LC_ALL, "en_US");
1767#ifndef WIN32
1768      setenv ("LC_ALL", "en_US", 1);
1769#else
1770      char tmp1[13];
1771      sprintf (tmp1, "LC_ALL=en_US");
1772      _putenv (tmp1);
1773#endif
1774      setMapInMaps (m, "main", "language", "en-US");
1775    }
1776  setlocale (LC_NUMERIC, "C");
1777#ifndef WIN32
1778  setenv ("LC_NUMERIC", "C", 1);
1779#else
1780  char tmp1[17];
1781  sprintf (tmp1, "LC_NUMERIC=C");
1782  _putenv (tmp1);
1783#endif
1784  bind_textdomain_codeset ("zoo-kernel", "UTF-8");
1785  textdomain ("zoo-kernel");
1786  bind_textdomain_codeset ("zoo-services", "UTF-8");
1787  textdomain ("zoo-services");
1788
1789  map *lsoap = getMap (request_inputs, "soap");
1790  if (lsoap != NULL && strcasecmp (lsoap->value, "true") == 0)
1791    setMapInMaps (m, "main", "isSoap", "true");
1792  else
1793    setMapInMaps (m, "main", "isSoap", "false");
1794
1795  if(strlen(cgiServerName)>0)
1796    {
1797      char tmpUrl[1024];
1798       
1799      if ( getenv("HTTPS") != NULL && strncmp(getenv("HTTPS"), "on", 2) == 0 ) {
1800        // Knut: check if non-empty instead of "on"?           
1801        if ( strncmp(cgiServerPort, "443", 3) == 0 ) { 
1802          sprintf(tmpUrl, "https://%s%s", cgiServerName, cgiScriptName);
1803        }
1804        else {
1805          sprintf(tmpUrl, "https://%s:%s%s", cgiServerName, cgiServerPort, cgiScriptName);
1806        }
1807      }
1808      else {
1809        if ( strncmp(cgiServerPort, "80", 2) == 0 ) { 
1810          sprintf(tmpUrl, "http://%s%s", cgiServerName, cgiScriptName);
1811        }
1812        else {
1813          sprintf(tmpUrl, "http://%s:%s%s", cgiServerName, cgiServerPort, cgiScriptName);
1814        }
1815      }
1816#ifdef DEBUG
1817      fprintf(stderr,"*** %s ***\n",tmpUrl);
1818#endif
1819      if(getMapFromMaps(m,"main","proxied")==NULL)
1820        setMapInMaps(m,"main","serverAddress",tmpUrl);
1821      else
1822        setMapInMaps(m,"lenv","serverAddress",tmpUrl);
1823    }
1824
1825  // CORS Support
1826  if(strncasecmp(cgiRequestMethod,"OPTIONS",7)==0){
1827    map* cors=getMapFromMaps(m,"main","cors");
1828    if(cors!=NULL && strncasecmp(cors->value,"true",4)==0){
1829      char *encoding=getEncoding(m);
1830      printHeaders(m);
1831      printf("Content-Type: text/plain; charset=%s\r\nStatus: 200 OK\r\n\r\n",encoding);
1832      printf(_("CORS is enabled.\r\n"));
1833      freeMaps (&m);
1834      free (m);
1835      fflush (stdout);
1836      return 3;
1837    }
1838  }
1839
1840  // Populate the Registry
1841  char conf_dir[1024];
1842  int t;
1843  char tmps1[1024];
1844  r_inputs = NULL;
1845  r_inputs = getMap (request_inputs, "metapath");
1846  map* cwdMap0=getMapFromMaps(m,"main","servicePath");
1847  if (r_inputs != NULL)
1848    if(cwdMap0!=NULL)
1849      snprintf (conf_dir, 1024, "%s/%s", cwdMap0->value, r_inputs->value);
1850    else
1851      snprintf (conf_dir, 1024, "%s/%s", ntmp, r_inputs->value);
1852  else
1853    if(cwdMap0!=NULL)
1854      snprintf (conf_dir, 1024, "%s", cwdMap0->value);
1855    else
1856      snprintf (conf_dir, 1024, "%s", ntmp);
1857  map* reg = getMapFromMaps (m, "main", "registry");
1858  registry* zooRegistry=NULL;
1859  if(reg!=NULL){
1860#ifndef WIN32
1861    int saved_stdout = zDup (fileno (stdout));
1862    zDup2 (fileno (stderr), fileno (stdout));
1863#endif
1864    if(createRegistry (m,&zooRegistry,reg->value)<0){
1865      map *message=getMapFromMaps(m,"lenv","message");
1866      map *type=getMapFromMaps(m,"lenv","type");
1867#ifndef WIN32
1868      zDup2 (saved_stdout, fileno (stdout));
1869#endif
1870      errorException (m, message->value,
1871                      type->value, NULL);
1872      return 0;
1873    }
1874#ifndef WIN32
1875    zDup2 (saved_stdout, fileno (stdout));
1876    zClose(saved_stdout);
1877#endif
1878  }
1879
1880  int eres = SERVICE_STARTED;
1881  int cpid = zGetpid ();
1882  maps* bmap=NULL;
1883  char *fbkp, *fbkpid, *fbkpres, *fbkp1, *flog;
1884  FILE *f0, *f1;
1885  HINTERNET hInternet;
1886  service *s1;
1887  maps *request_output_real_format = NULL;
1888  maps *request_input_real_format = NULL;
1889
1890  setMapInMaps(m,"main","executionType","xml");
1891  if((strlen(cgiQueryString)>0 && cgiQueryString[0]=='/') /*&& strstr(cgiAccept,"json")!=NULL*/){
1892    //
1893    // OGC API - Processes starts here
1894    //
1895#ifndef USE_JSON
1896    errorException (m, _("OGC API - Processes is not supported by this ZOO-Kernel, please contact the service provider."), "InternalError", NULL);
1897    return 1;
1898#else
1899#ifndef USE_GDB
1900#ifndef WIN32
1901    signal (SIGCHLD, SIG_IGN);
1902#endif 
1903    signal (SIGSEGV, json_sig_handler);
1904    signal (SIGTERM, json_sig_handler);
1905    signal (SIGINT, json_sig_handler);
1906    signal (SIGILL, json_sig_handler);
1907    signal (SIGFPE, json_sig_handler);
1908    signal (SIGABRT, json_sig_handler);
1909#endif
1910    setMapInMaps(m,"main","executionType","json");
1911    r_inputs = getMapOrFill (&request_inputs, "metapath", "");
1912    char conf_file1[10240];
1913    maps* m1 = (maps *) malloc (MAPS_SIZE);
1914    snprintf (conf_file1, 10240, "%s/%s/oas.cfg", ntmp, r_inputs->value);
1915    if (conf_read (conf_file1, m1) == 2)
1916      {
1917        errorException (NULL, _("Unable to load the oas.cfg file."),
1918                        "InternalError", NULL);
1919        free (m);
1920        return 1;
1921      }
1922    addMapsToMaps(&m,m1);
1923    map* pmTmp0=getMapFromMaps(m,"openapi","full_html_support");
1924    if(strstr(cgiQueryString,".html")==NULL && strstr(cgiAccept,"text/html")!=NULL && pmTmp0!=NULL && strncasecmp(pmTmp0->value,"true",4)==0){
1925      map* pmTmpUrl=getMapFromMaps(m,"openapi","rootUrl");
1926      char* pacTmpUrl=NULL;
1927      if(strcmp(cgiQueryString,"/")!=0){
1928         pacTmpUrl=(char*)malloc((strlen(cgiQueryString)+strlen(pmTmpUrl->value)+6)*sizeof(char));
1929         sprintf(pacTmpUrl,"%s%s.html",pmTmpUrl->value,cgiQueryString);
1930      }
1931      else{
1932        pacTmpUrl=(char*)malloc((strlen(pmTmpUrl->value)+6)*sizeof(char));
1933        sprintf(pacTmpUrl,"%s/index.html",pmTmpUrl->value);
1934      }
1935      setMapInMaps(m,"headers","Location",pacTmpUrl);
1936      printHeaders(m);
1937      printf("Status: 302 Moved permanently \r\n\r\n");
1938      fflush(stdout);
1939      free(pacTmpUrl);
1940      return 1;
1941    }
1942    json_object *res=json_object_new_object();
1943    setMapInMaps(m,"headers","Content-Type","application/json;charset=UTF-8");
1944    /* - Root url */
1945    if(cgiContentLength==1){
1946      map* tmpMap=getMapFromMaps(m,"main","serverAddress");
1947      json_object *res1=json_object_new_array();
1948      const char* urls[4]={
1949        "/","/api","/conformance","/processes"
1950      };
1951      map* tmpUrl=getMapFromMaps(m,"openapi","rootUrl");
1952      for(int kk=0;kk<4;kk++){
1953        maps* tmpMaps=getMaps(m,urls[kk]);
1954        if(tmpMaps!=NULL){
1955          json_object *res2;
1956          res2=mapToJson(tmpMaps->content);
1957          char* tmpStr=(char*) malloc((strlen(tmpUrl->value)+strlen(urls[kk])+2)*sizeof(char));
1958          sprintf(tmpStr,"%s%s",tmpUrl->value,urls[kk]);
1959          json_object_object_add(res2,"href",json_object_new_string(tmpStr));
1960          free(tmpStr);
1961          json_object_array_add(res1,res2);
1962
1963          map* pmTmp=getMap(tmpMaps->content,"title");
1964          char *pacTitle=NULL;
1965          if(pmTmp!=NULL)
1966            pacTitle=zStrdup(pmTmp->value);
1967          char* pacTmp=(char*) malloc((strlen(urls[kk])+6)*sizeof(char));
1968          sprintf(pacTmp,"%s.html",urls[kk]);
1969          tmpMaps=getMaps(m,pacTmp);
1970          if(tmpMaps==NULL && strncasecmp(pacTmp,"/.html",6)==0)
1971            tmpMaps=getMaps(m,"/index.html");
1972          if(tmpMaps!=NULL){
1973            json_object *res3;
1974            res3=mapToJson(tmpMaps->content);
1975            if(getMap(tmpMaps->content,"title")==NULL && pacTitle!=NULL){
1976              json_object_object_add(res3,"title",json_object_new_string(pacTitle));
1977            }
1978            char* tmpStr=NULL;
1979            if(strncasecmp(pacTmp,"/.html",6)==0){
1980              tmpStr=(char*) malloc((strlen(tmpUrl->value)+12)*sizeof(char));
1981              sprintf(tmpStr,"%s/index.html",tmpUrl->value);
1982            }else{
1983              tmpStr=(char*) malloc((strlen(tmpUrl->value)+strlen(urls[kk])+6)*sizeof(char));
1984              sprintf(tmpStr,"%s%s.html",tmpUrl->value,urls[kk]);
1985            }
1986            json_object_object_add(res3,"href",json_object_new_string(tmpStr));
1987            free(tmpStr);
1988            json_object_array_add(res1,res3);
1989          }
1990          free(pacTmp);
1991          if(pacTitle!=NULL)
1992            free(pacTitle);       
1993        }
1994      }
1995      map* pmTmp=getMapFromMaps(m,"identification","title");
1996      if(pmTmp!=NULL)
1997        json_object_object_add(res,"title",json_object_new_string(pmTmp->value));
1998      pmTmp=getMapFromMaps(m,"identification","abstract");
1999      if(pmTmp!=NULL)
2000        json_object_object_add(res,"description",json_object_new_string(pmTmp->value));
2001      json_object_object_add(res,"links",res1);
2002    }else if(strcmp(cgiQueryString,"/conformance")==0){
2003      /* - /conformance url */
2004      map* rootUrl=getMapFromMaps(m,"conformsTo","rootUrl");
2005      json_object *res1=json_object_new_array();
2006      map* length=getMapFromMaps(m,"conformsTo","length");
2007      maps* tmpMaps=getMaps(m,"conformsTo");
2008      for(int kk=0;kk<atoi(length->value);kk++){
2009        map* tmpMap1=getMapArray(tmpMaps->content,"link",kk);
2010        json_object *res2;
2011        if(tmpMap1!=NULL){
2012          char* tmpStr=(char*) malloc((strlen(rootUrl->value)+strlen(tmpMap1->value)+1)*sizeof(char));
2013          sprintf(tmpStr,"%s%s",rootUrl->value,tmpMap1->value);
2014          json_object_array_add(res1,json_object_new_string(tmpStr));
2015        }
2016      }
2017      json_object_object_add(res,"conformsTo",res1);
2018    }else if(strncasecmp(cgiQueryString,"/api",4)==0){
2019      if(strstr(cgiQueryString,".html")==NULL)
2020        produceApi(m,res);
2021      else{     
2022        char* pacTmp=(char*)malloc(9*sizeof(char));
2023        sprintf(pacTmp,"%s",cgiQueryString+1);
2024        map* pmTmp=getMapFromMaps(m,pacTmp,"href");
2025        free(pacTmp);
2026        if(pmTmp!=NULL)
2027          setMapInMaps(m,"headers","Location",pmTmp->value);
2028      } 
2029    }else if(strcmp(cgiQueryString,"/processes")==0 || strcmp(cgiQueryString,"/processes/")==0){
2030      /* - /processes */
2031      setMapInMaps(m,"lenv","requestType","desc");
2032      json_object *res3=json_object_new_array();
2033      int saved_stdout = zDup (fileno (stdout));
2034      zDup2 (fileno (stderr), fileno (stdout));
2035      if (int res0 =             
2036          recursReaddirF (m, NULL, res3, NULL, ntmp, NULL, saved_stdout, 0,
2037                          printGetCapabilitiesForProcessJ) < 0)
2038        {
2039        }     
2040      zDup2 (saved_stdout, fileno (stdout));
2041      zClose(saved_stdout);
2042      res=res3;
2043      //json_object_object_add(res,"processes",res3);
2044    }else{
2045      service* s1=NULL;
2046      int t=0;
2047      if(strstr(cgiQueryString,"/processes/")==NULL){
2048        map* error=createMap("code","BadRequest");
2049        addToMap(error,"message",_("The ressource is not available"));
2050        //setMapInMaps(conf,"lenv","status_code","404 Bad Request");
2051        printExceptionReportResponseJ(m,error);
2052        freeMaps (&m);
2053        free (m);
2054        free (REQUEST);
2055        xmlCleanupParser ();
2056        zooXmlCleanupNs ();                     
2057        return 1;
2058      } else
2059        if(strstr(cgiQueryString,"/jobs")==NULL && strstr(cgiQueryString,"/jobs/")==NULL){
2060          /* - /processes/{id}/ */
2061          DIR *dirp = opendir (ntmp);
2062          json_object *res3=json_object_new_object();
2063          char *orig = zStrdup (strstr(cgiQueryString,"/processes/")+11);
2064          if(orig[strlen(orig)-1]=='/')
2065            orig[strlen(orig)-1]=0;
2066          json_object* res1=json_object_new_object();
2067          setMapInMaps(m,"lenv","requestType","GetCapabilities");
2068          int t=fetchServicesForDescription(NULL, m, orig,
2069                                            printGetCapabilitiesForProcessJ,
2070                                            NULL, (void*) res3, ntmp,
2071                                            request_inputs,
2072                                            printExceptionReportResponseJ);
2073          if(t==1){
2074            /*map* error=createMap("code","BadRequest");
2075              addToMap(error,"message",_("Failed to acces the requested service"));
2076              printExceptionReportResponseJ(m,error);*/
2077            return 1;
2078          }
2079          res=json_object_get(res3);
2080        }else{ 
2081          char* queryString=zStrdup(cgiQueryString);
2082          int len0=strlen(strstr(cgiQueryString,"/processes/")+11);
2083          int len1=strlen(cgiQueryString)-strlen(strstr(cgiQueryString,"/job"));
2084          char* cIdentifier=(char*)malloc((len1-10)*sizeof(char));
2085          int cnt=0;
2086          for(int j=11;j<len1;j++){
2087            cIdentifier[cnt]=cgiQueryString[j];
2088            cIdentifier[cnt+1]=0;
2089            cnt++;
2090          }
2091          char tmps1[1024];
2092          map* import = getMapFromMaps (m, IMPORTSERVICE, cIdentifier); 
2093          if (import != NULL && import->value != NULL) { 
2094            strncpy(tmps1, import->value, 1024);
2095            setMapInMaps (m, "lenv", "Identifier", cIdentifier);
2096            setMapInMaps (m, "lenv", "oIdentifier", cIdentifier);
2097          } 
2098          else {
2099            snprintf (tmps1, 1024, "%s/%s.zcfg", ntmp, cIdentifier);
2100#ifdef DEBUG
2101            fprintf (stderr, "Trying to load %s\n", tmps1);
2102#endif
2103            if (strstr (cIdentifier, ".") != NULL)
2104              {
2105                setMapInMaps (m, "lenv", "oIdentifier", cIdentifier);
2106                char *identifier = zStrdup (cIdentifier);
2107                parseIdentifier (m, ntmp, identifier, tmps1);
2108                map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
2109                if (tmpMap != NULL)
2110                  addToMap (request_inputs, "metapath", tmpMap->value);
2111                free (identifier);
2112              }
2113            else
2114              {
2115                setMapInMaps (m, "lenv", "oIdentifier", cIdentifier);
2116                setMapInMaps (m, "lenv", "Identifier", cIdentifier);
2117              }
2118          }
2119
2120          r_inputs = getMapFromMaps (m, "lenv", "Identifier");
2121
2122#ifdef META_DB
2123          int metadb_id=_init_sql(m,"metadb");
2124          //FAILED CONNECTING DB
2125          if(getMapFromMaps(m,"lenv","dbIssue")!=NULL || metadb_id<0){
2126            fprintf(stderr,"ERROR CONNECTING METADB\n");
2127          }
2128          if(metadb_id>=0)
2129            s1=extractServiceFromDb(m,cIdentifier,0);
2130          if(s1!=NULL){
2131            inheritance(zooRegistry,&s1);
2132#ifdef USE_HPC
2133            addNestedOutputs(&s1);
2134#endif
2135            if(zooRegistry!=NULL){
2136              freeRegistry(&zooRegistry);
2137              free(zooRegistry);
2138            }
2139          }else /* Not found in MetaDB */{
2140#endif
2141            s1 = createService();
2142            if (s1 == NULL)
2143              {
2144                freeMaps (&m);
2145                free (m);
2146                if(zooRegistry!=NULL){
2147                  freeRegistry(&zooRegistry);
2148                  free(zooRegistry);
2149                }
2150                free (REQUEST);
2151                free (SERVICE_URL);
2152                map* error=createMap("code","InternalError");
2153                addToMap(error,"message",_("Unable to allocate memory"));
2154                setMapInMaps(m,"lenv","status_code","404 Bad Request");
2155                printExceptionReportResponseJ(m,error);
2156
2157                return 1; /*errorException (m, _("Unable to allocate memory"),
2158                            "InternalError", NULL);*/
2159              }
2160
2161            int saved_stdout = zDup (fileno (stdout));
2162            zDup2 (fileno (stderr), fileno (stdout));
2163            t = readServiceFile (m, tmps1, &s1, cIdentifier);
2164            if(t>=0){
2165              inheritance(zooRegistry,&s1);
2166#ifdef USE_HPC
2167              addNestedOutputs(&s1);
2168#endif
2169            }
2170            if(zooRegistry!=NULL){
2171              freeRegistry(&zooRegistry);
2172              free(zooRegistry);
2173            }
2174            fflush(stderr);
2175            fflush (stdout);
2176            zDup2 (saved_stdout, fileno (stdout));
2177            zClose (saved_stdout);
2178            if (t < 0)
2179              {
2180                r_inputs = getMapFromMaps (m, "lenv", "oIdentifier");
2181                if(r_inputs!=NULL){
2182                  char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
2183                  sprintf (tmpMsg,
2184                           _
2185                           ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
2186                           r_inputs->value);
2187                  map* error=createMap("code","NoSuchProcess");
2188                  addToMap(error,"message",tmpMsg);
2189                  //setMapInMaps(conf,"lenv","status_code","404 Bad Request");
2190                  printExceptionReportResponseJ(m,error);
2191
2192                  //errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
2193                  free (tmpMsg);
2194                  free (s1);
2195                  freeMaps (&m);
2196                  free (m);
2197                  free (REQUEST);
2198                  free (SERVICE_URL);
2199                  return 0;
2200                }
2201              }
2202#ifdef META_DB
2203          }
2204#endif
2205          if(strstr(cgiQueryString,"/jobs/")!=NULL && strlen(strstr(cgiQueryString,"/jobs/"))>6) {
2206            /* - /jobs/{jobID} and /jobs/{jobID}/result urls */
2207            if(strstr(cgiQueryString,"/results")!=NULL){
2208              // In case the service has run, then forward request to target result file
2209              char* jobId=zStrdup(strstr(cgiQueryString,"/jobs/")+6);
2210              jobId[strlen(jobId)-8]=0;
2211              char *sid=getStatusId(m,jobId);
2212              if(sid==NULL){
2213                map* error=createMap("code","NoSuchJob");
2214                addToMap(error,"message",_("The JobID from the request does not match any of the Jobs running on this server"));
2215                printExceptionReportResponseJ(m,error);
2216                return 1;
2217              }else{
2218                if(isRunning(m,jobId)>0){
2219                  map* error=createMap("code","ResultNotReady");
2220                  addToMap(error,"message",_("The job is still running."));
2221                  printExceptionReportResponseJ(m,error);
2222                  return 1;
2223                }else{
2224                  char *Url0=getResultPath(m,jobId);
2225                  map *cIdentifier = getMapFromMaps (m, "lenv", "oIdentifier");
2226                  zStatStruct f_status;
2227                  int s=zStat(Url0, &f_status);
2228                  if(s==0 && f_status.st_size>0){
2229                    if(f_status.st_size>15){
2230                      json_object* pjoTmp=json_readFile(m,Url0);
2231                      json_object* pjoCode=NULL;
2232                      json_object* pjoMessage=NULL;
2233                      if(pjoTmp!=NULL &&
2234                         json_object_object_get_ex(pjoTmp,"code",&pjoCode)!=FALSE &&
2235                         json_object_object_get_ex(pjoTmp,"description",&pjoMessage)!=FALSE){
2236                        map* error=createMap("code",json_object_get_string(pjoCode));
2237                        addToMap(error,"message",json_object_get_string(pjoMessage));
2238                        printExceptionReportResponseJ(m,error);
2239                        return 1;                       
2240                      }else{
2241
2242                        map* tmpPath = getMapFromMaps (m, "main", "tmpUrl");
2243                        Url0=(char*) realloc(Url0,(strlen(tmpPath->value)+
2244                                                   strlen(cIdentifier->value)+
2245                                                   strlen(jobId)+8)*sizeof(char));
2246                        sprintf(Url0,"%s/%s_%s.json",tmpPath->value,
2247                                cIdentifier->value,jobId);
2248                        setMapInMaps(m,"headers","Location",Url0);
2249                      }
2250                      free(Url0);
2251                    }else{
2252                      // Service Failed
2253                      map* statusInfo=createMap("JobID",jobId);
2254                      readFinalRes(m,jobId,statusInfo);
2255                      {
2256                        map* pmStatus=getMap(statusInfo,"status");
2257                        if(pmStatus!=NULL)
2258                          setMapInMaps(m,"lenv","status",pmStatus->value);
2259                      }
2260                      char* tmpStr=_getStatus(m,jobId);
2261                      if(tmpStr!=NULL && strncmp(tmpStr,"-1",2)!=0){
2262                        char *tmpStr1=zStrdup(tmpStr);
2263                        char *tmpStr0=zStrdup(strstr(tmpStr,"|")+1);
2264                        free(tmpStr);
2265                        tmpStr1[strlen(tmpStr1)-strlen(tmpStr0)-1]='\0';
2266                        addToMap(statusInfo,"PercentCompleted",tmpStr1);
2267                        addToMap(statusInfo,"Message",tmpStr0);
2268                        setMapInMaps(m,"lenv","PercentCompleted",tmpStr1);
2269                        setMapInMaps(m,"lenv","Message",tmpStr0);
2270                        free(tmpStr0);
2271                        free(tmpStr1);
2272                      }
2273                      map* error=createMap("code","NoApplicableCode");
2274                      addToMap(error,"message",_("The service failed to execute."));
2275                      printExceptionReportResponseJ(m,error);
2276                      return 1;
2277                    }
2278
2279                  }else{
2280                    map* error=createMap("code","NoSuchJob");
2281                    addToMap(error,"message",_("The JobID seem to be running on this server but not for this process id"));
2282                    printExceptionReportResponseJ(m,error);
2283                    return 1;
2284                  }
2285                }
2286              }
2287            }else{
2288              char* tmpUrl=strstr(cgiQueryString,"/jobs/");
2289              if(tmpUrl!=NULL && strlen(tmpUrl)>6){
2290                if(strncasecmp(cgiRequestMethod,"DELETE",6)==0){
2291                  char* jobId=zStrdup(strstr(cgiQueryString,"/jobs/")+6);
2292                  setMapInMaps(m,"lenv","gs_usid",jobId);
2293                  setMapInMaps(m,"lenv","file.statusFile",json_getStatusFilePath(m));
2294                  runDismiss(m,jobId);
2295                  map* pmError=getMapFromMaps(m,"lenv","error");
2296                  if(pmError!=NULL && strncasecmp(pmError->value,"true",4)==0){
2297                    printExceptionReportResponseJ(m,getMapFromMaps(m,"lenv","code"));
2298                    return 1;
2299                  }
2300                  else{
2301                    setMapInMaps(m,"lenv","gs_location","false");
2302                    res=createStatus(m,SERVICE_DISMISSED);
2303                  }
2304                }else{
2305                  char* jobId=zStrdup(strstr(cgiQueryString,"/jobs/")+6);
2306                  res=printJobStatus(m,jobId);
2307                  free(jobId);
2308                }
2309              }
2310            }
2311          }else{
2312            /* - /jobs url */
2313            if(strcasecmp(cgiRequestMethod,"get")==0){
2314              /* - /jobs List (GET) */
2315              res=printJobList(m);
2316            }else if(strcasecmp(cgiRequestMethod,"post")==0){
2317              /* - /jobs Execution (POST) */
2318              eres = SERVICE_STARTED;
2319              initAllEnvironment(m,request_inputs,ntmp,"jrequest");
2320              map* req=getMapFromMaps(m,"renv","jrequest");
2321              json_object *jobj = NULL;
2322              const char *mystring = NULL;
2323              int slen = 0;
2324              enum json_tokener_error jerr;
2325              struct json_tokener* tok=json_tokener_new();
2326              do {
2327                mystring = req->value;  // get JSON string, e.g. read from file, etc...
2328                slen = strlen(mystring);
2329                jobj = json_tokener_parse_ex(tok, mystring, slen);
2330              } while ((jerr = json_tokener_get_error(tok)) == json_tokener_continue);
2331              if (jerr != json_tokener_success) {
2332                map* pamError=createMap("code","InvalidParameterValue");
2333                const char* pcTmpErr=json_tokener_error_desc(jerr);
2334                const char* pccErr=_("ZOO-Kernel cannot parse your POST data: %s");
2335                char* pacMessage=(char*)malloc((strlen(pcTmpErr)+strlen(pccErr)+1)*sizeof(char));
2336                sprintf(pacMessage,pccErr,pcTmpErr);
2337                addToMap(pamError,"message",pacMessage);
2338                printExceptionReportResponseJ(m,pamError);
2339                fprintf(stderr, "Error: %s\n", json_tokener_error_desc(jerr));
2340                return 1;
2341              }
2342              if (tok->char_offset < slen){
2343                map* pamError=createMap("code","InvalidParameterValue");
2344                const char* pcTmpErr="None";
2345                const char* pccErr=_("ZOO-Kernel cannot parse your POST data: %s");
2346                char* pacMessage=(char*)malloc((strlen(pcTmpErr)+strlen(pccErr)+1)*sizeof(char));
2347                sprintf(pacMessage,pccErr,pcTmpErr);
2348                addToMap(pamError,"message",pacMessage);
2349                printExceptionReportResponseJ(m,pamError);
2350                fprintf(stderr, "Error: %s\n", json_tokener_error_desc(jerr));
2351                return 1;
2352              }
2353              //maps* inputs_real_format=NULL, *outputs_real_format= NULL;
2354              parseJRequest(m,s1,jobj,request_inputs,&request_input_real_format,&request_output_real_format);
2355              map* preference=getMapFromMaps(m,"renv","HTTP_PREFER");
2356              map* mode=getMap(request_inputs,"mode");
2357              if((preference!=NULL && strcasecmp(preference->value,"respond-async")==0) ||
2358                 (mode!=NULL && strncasecmp(mode->value,"async",5)==0)) {
2359                int pid;
2360#ifdef DEBUG
2361                fprintf (stderr, "\nPID : %d\n", cpid);
2362#endif
2363#ifndef WIN32
2364                pid = fork ();
2365#else
2366                if (cgiSid == NULL)
2367                  {
2368                    createProcess (m, request_inputs, s1, NULL, cpid,
2369                                   request_input_real_format,
2370                                   request_output_real_format);
2371                    pid = cpid;
2372                  }
2373                else
2374                  {
2375                    pid = 0;
2376                    cpid = atoi (cgiSid);
2377                    updateStatus(m,0,_("Initializing"));
2378                  }
2379#endif
2380                if (pid > 0)
2381                  {
2382                    //
2383                    // dady :
2384                    // set status to SERVICE_ACCEPTED
2385                    //
2386#ifdef DEBUG
2387                    fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
2388                             zGetpid ());
2389#endif
2390                    eres = SERVICE_ACCEPTED;
2391                    createStatusFile(m,eres);
2392                    //invokeBasicCallback(m,SERVICE_ACCEPTED);
2393                    printHeaders(m);
2394                    printf("Status: 201 Created \r\n\r\n");
2395                    return 1;
2396                  }
2397                else if (pid == 0)
2398                  {
2399                    eres = SERVICE_STARTED;
2400                    //
2401                    // son : have to close the stdout, stdin and stderr to let the parent
2402                    // process answer to http client.
2403                    //
2404                    map* oid = getMapFromMaps (m, "lenv", "oIdentifier");
2405                    map* usid = getMapFromMaps (m, "lenv", "uusid");
2406                    map* tmpm = getMapFromMaps (m, "lenv", "osid");
2407                    int cpid = atoi (tmpm->value);
2408                    pid=cpid;
2409                    r_inputs = getMapFromMaps (m, "main", "tmpPath");
2410                    setMapInMaps (m, "lenv", "async","true");
2411                    map* r_inputs1 = createMap("ServiceName", s1->name);
2412                    // Create the filename for the result file (.res)
2413                    fbkpres =
2414                      (char *)
2415                      malloc ((strlen (r_inputs->value) +
2416                               strlen (usid->value) + 7) * sizeof (char));                   
2417                    sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
2418                    bmap = createMaps("status");
2419                    bmap->content=createMap("usid",usid->value);
2420                    addToMap(bmap->content,"sid",tmpm->value);
2421                    addIntToMap(bmap->content,"pid",zGetpid());
2422         
2423                    // Create PID file referencing the OS process identifier
2424                    fbkpid =
2425                      (char *)
2426                      malloc ((strlen (r_inputs->value) +
2427                               strlen (usid->value) + 7) * sizeof (char));
2428                    sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
2429                    setMapInMaps (m, "lenv", "file.pid", fbkpid);
2430
2431                    f0 = freopen (fbkpid, "w+",stdout);
2432                    printf("%d",zGetpid());
2433                    fflush(stdout);
2434
2435                    // Create SID file referencing the semaphore name
2436                    fbkp =
2437                      (char *)
2438                      malloc ((strlen (r_inputs->value) + strlen (oid->value) +
2439                               strlen (usid->value) + 7) * sizeof (char));
2440                    sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
2441                    setMapInMaps (m, "lenv", "file.sid", fbkp);
2442                    FILE* f2 = freopen (fbkp, "w+",stdout);
2443                    printf("%s",tmpm->value);
2444                    fflush(f2);
2445                    free(fbkp);
2446
2447                    fbkp =
2448                      (char *)
2449                      malloc ((strlen (r_inputs->value) + strlen (oid->value) +
2450                               strlen (usid->value) + 7) * sizeof (char));
2451                    sprintf (fbkp, "%s/%s_%s.json", r_inputs->value, oid->value,
2452                             usid->value);
2453                    setMapInMaps (m, "lenv", "file.responseInit", fbkp);
2454                    flog =
2455                      (char *)
2456                      malloc ((strlen (r_inputs->value) + strlen (oid->value) +
2457                               strlen (usid->value) + 13) * sizeof (char));
2458                    sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
2459                             oid->value, usid->value);
2460                    setMapInMaps (m, "lenv", "file.log", flog);
2461#ifdef DEBUG
2462                    fprintf (stderr, "RUN IN BACKGROUND MODE \n");
2463                    fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
2464                             zGetpid ());
2465                    fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
2466#endif
2467                    freopen (flog, "w+", stderr);
2468                    fflush (stderr);
2469                    f0 = freopen (fbkp, "w+", stdout);
2470                    rewind (stdout);
2471#ifndef WIN32
2472                    fclose (stdin);
2473#endif
2474#ifdef RELY_ON_DB
2475                    init_sql(m);
2476                    recordServiceStatus(m);
2477#endif
2478#ifdef USE_CALLBACK
2479                    invokeCallback(m,NULL,NULL,0,0);
2480#endif
2481                    invokeBasicCallback(m,SERVICE_STARTED);
2482                    createStatusFile(m,SERVICE_STARTED);
2483                    fbkp1 =
2484                      (char *)
2485                      malloc ((strlen (r_inputs->value) + strlen (oid->value) +
2486                               strlen (usid->value) + 15) * sizeof (char));
2487                    sprintf (fbkp1, "%s/%s_final_%s.json", r_inputs->value,
2488                             oid->value, usid->value);
2489                    setMapInMaps (m, "lenv", "file.responseFinal", fbkp1);
2490
2491                    f1 = freopen (fbkp1, "w+", stdout);
2492
2493                    map* serviceTypeMap=getMap(s1->content,"serviceType");
2494                    if(serviceTypeMap!=NULL)
2495                      setMapInMaps (m, "lenv", "serviceType", serviceTypeMap->value);
2496
2497                    char *flenv =
2498                      (char *)
2499                      malloc ((strlen (r_inputs->value) + 
2500                               strlen (usid->value) + 12) * sizeof (char));
2501                    sprintf (flenv, "%s/%s_lenv.cfg", r_inputs->value, usid->value);
2502                    maps* lenvMaps=getMaps(m,"lenv");
2503                    dumpMapsToFile(lenvMaps,flenv,1);
2504                    free(flenv);
2505
2506                    map* testMap=getMapFromMaps(m,"main","memory");
2507                    loadHttpRequests(m,request_input_real_format);
2508
2509                    if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,NULL)<0)
2510                      return -1;
2511                    loadServiceAndRun (&m, s1, request_inputs,
2512                                       &request_input_real_format,
2513                                       &request_output_real_format, &eres);
2514                    setMapInMaps(m,"lenv","force","true");
2515                    createStatusFile(m,eres);
2516                    setMapInMaps(m,"lenv","force","false");
2517                    setMapInMaps(m,"lenv","no-headers","true");
2518                    fflush(stdout);
2519                    rewind(stdout);
2520                    res=printJResult(m,s1,request_output_real_format,eres);
2521                    const char* jsonStr0=json_object_to_json_string_ext(res,JSON_C_TO_STRING_PLAIN);
2522                    if(getMapFromMaps(m,"lenv","jsonStr")==NULL)
2523                      setMapInMaps(m,"lenv","jsonStr",jsonStr0);
2524                    invokeBasicCallback(m,eres);
2525                  }
2526              }else{
2527                loadHttpRequests(m,request_input_real_format);
2528                if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,NULL)<0)
2529                  return -1;
2530                loadServiceAndRun (&m,s1,request_inputs,
2531                                   &request_input_real_format,
2532                                   &request_output_real_format,&eres);
2533                res=printJResult(m,s1,request_output_real_format,eres);
2534              }
2535
2536           
2537            }//else error
2538           
2539          }
2540        }
2541    }
2542    map* pmHasPrinted=getMapFromMaps(m,"lenv","hasPrinted");
2543    if(res!=NULL && (pmHasPrinted==NULL || strncasecmp(pmHasPrinted->value,"false",5)==0)){
2544      if(getMapFromMaps(m,"lenv","no-headers")==NULL){
2545        printHeaders(m);
2546        printf("Status: 200 OK \r\n\r\n");
2547      }
2548      const char* jsonStr=json_object_to_json_string_ext(res,JSON_C_TO_STRING_PLAIN);
2549      printf(jsonStr);
2550      printf("\n");
2551      fflush(stdout);
2552    }
2553    //return 1;
2554#endif
2555  }else{
2556    //
2557    // WPS 1.0.0 and 2.0.0 starts here
2558    //
2559    setMapInMaps(m,"main","executionType","xml");
2560    //Check for minimum inputs
2561    map* version=getMap(request_inputs,"version");
2562    if(version==NULL)
2563      version=getMapFromMaps(m,"main","version");
2564    setMapInMaps(m,"main","rversion",version->value);
2565    int vid=getVersionId(version->value);
2566    if(vid<0)
2567      vid=0;
2568    map* err=NULL;
2569    const char **vvr=(const char**)requests[vid];
2570    checkValidValue(request_inputs,&err,"request",vvr,1);
2571    const char *vvs[]={
2572      "WPS",
2573      NULL
2574    };
2575    if(err!=NULL){
2576      checkValidValue(request_inputs,&err,"service",(const char**)vvs,1);
2577      printExceptionReportResponse (m, err);
2578      freeMap(&err);
2579      free(err);
2580      if (count (request_inputs) == 1)
2581        {
2582          freeMap (&request_inputs);
2583          free (request_inputs);
2584        }
2585      freeMaps (&m);
2586      free (m);
2587      return 1;
2588    }
2589    checkValidValue(request_inputs,&err,"service",(const char**)vvs,1);
2590
2591    const char *vvv[]={
2592      "1.0.0",
2593      "2.0.0",
2594      NULL
2595    };
2596    r_inputs = getMap (request_inputs, "Request");
2597    if(r_inputs!=NULL)
2598      REQUEST = zStrdup (r_inputs->value);
2599    int reqId=-1;
2600    if (strncasecmp (REQUEST, "GetCapabilities", 15) != 0){
2601      checkValidValue(request_inputs,&err,"version",(const char**)vvv,1);
2602      int j=0;
2603      for(j=0;j<nbSupportedRequests;j++){
2604        if(requests[vid][j]!=NULL && requests[vid][j+1]!=NULL){
2605          if(j<nbReqIdentifier && strncasecmp(REQUEST,requests[vid][j+1],strlen(requests[vid][j+1]))==0){
2606            checkValidValue(request_inputs,&err,"identifier",NULL,1);
2607            reqId=j+1;
2608            break;
2609          }
2610          else
2611            if(j>=nbReqIdentifier && j<nbReqIdentifier+nbReqJob && 
2612               strncasecmp(REQUEST,requests[vid][j+1],strlen(requests[vid][j+1]))==0){
2613              checkValidValue(request_inputs,&err,"jobid",NULL,1);
2614              reqId=j+1;
2615              break;
2616            }
2617        }else
2618          break;
2619      }
2620    }else{
2621      checkValidValue(request_inputs,&err,"AcceptVersions",(const char**)vvv,-1);
2622      map* version1=getMap(request_inputs,"AcceptVersions");
2623      if(version1!=NULL){
2624        if(strstr(version1->value,schemas[1][0])!=NULL){
2625          addToMap(request_inputs,"version",schemas[1][0]);
2626          setMapInMaps(m,"main","rversion",schemas[1][0]);
2627        }
2628        else{
2629          addToMap(request_inputs,"version",version1->value);
2630          setMapInMaps(m,"main","rversion",version1->value);
2631        }
2632        version=getMap(request_inputs,"version");
2633      }
2634    }
2635    if(err!=NULL){
2636      printExceptionReportResponse (m, err);
2637      freeMap(&err);
2638      free(err);
2639      if (count (request_inputs) == 1)
2640        {
2641          freeMap (&request_inputs);
2642          free (request_inputs);
2643        }
2644      free(REQUEST);
2645      freeMaps (&m);
2646      free (m);
2647      return 1;
2648    }
2649
2650    r_inputs = getMap (request_inputs, "serviceprovider");
2651    if (r_inputs == NULL)
2652      {
2653        addToMap (request_inputs, "serviceprovider", "");
2654      }
2655
2656    map *tmpm = getMapFromMaps (m, "main", "serverAddress");
2657    if (tmpm != NULL)
2658      SERVICE_URL = zStrdup (tmpm->value);
2659    else
2660      SERVICE_URL = zStrdup (DEFAULT_SERVICE_URL);
2661
2662
2663    int scount = 0;
2664#ifdef DEBUG
2665    dumpMap (r_inputs);
2666#endif
2667
2668    if (strncasecmp (REQUEST, "GetCapabilities", 15) == 0)
2669      {
2670#ifdef DEBUG
2671        dumpMap (r_inputs);
2672#endif
2673        xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
2674        xmlNodePtr n=printGetCapabilitiesHeader(doc,m,(version!=NULL?version->value:"1.0.0"));
2675        /**
2676         * Here we need to close stdout to ensure that unsupported chars
2677         * has been found in the zcfg and then printed on stdout
2678         */
2679        int saved_stdout = zDup (fileno (stdout));
2680        zDup2 (fileno (stderr), fileno (stdout));
2681
2682        maps* imports = getMaps(m, IMPORTSERVICE);
2683        if (imports != NULL) {       
2684          map* zcfg = imports->content;
2685       
2686          while (zcfg != NULL) {
2687            if (zcfg->value != NULL) {
2688              service* svc = (service*) malloc(SERVICE_SIZE);
2689              if (svc == NULL || readServiceFile(m, zcfg->value, &svc, zcfg->name) < 0) {
2690                // pass over silently
2691                zcfg = zcfg->next;
2692                continue;
2693              }
2694              inheritance(zooRegistry, &svc);
2695              printGetCapabilitiesForProcess(zooRegistry, m, doc, n, svc);
2696              freeService(&svc);
2697              free(svc);                             
2698            }
2699            zcfg = zcfg->next;
2700          }           
2701        }
2702
2703        if (int res =             
2704            recursReaddirF (m, zooRegistry, doc, n, conf_dir, NULL, saved_stdout, 0,
2705                            printGetCapabilitiesForProcess) < 0)
2706          {
2707            freeMaps (&m);
2708            free (m);
2709            if(zooRegistry!=NULL){
2710              freeRegistry(&zooRegistry);
2711              free(zooRegistry);
2712            }
2713            free (REQUEST);
2714            free (SERVICE_URL);
2715            fflush (stdout);
2716            return res;
2717          }
2718        fflush (stdout);
2719        zDup2 (saved_stdout, fileno (stdout));
2720#ifdef META_DB
2721        fetchServicesFromDb(zooRegistry,m,doc,n,printGetCapabilitiesForProcess,1);
2722        close_sql(m,0);
2723#endif     
2724        printDocument (m, doc, zGetpid ());
2725        freeMaps (&m);
2726        free (m);
2727        if(zooRegistry!=NULL){
2728          freeRegistry(&zooRegistry);
2729          free(zooRegistry);
2730        }
2731        free (REQUEST);
2732        free (SERVICE_URL);
2733        fflush (stdout);
2734        return 0;
2735      }
2736    else
2737      {
2738        r_inputs = getMap (request_inputs, "JobId");
2739        if(reqId>nbReqIdentifier){
2740          if (strncasecmp (REQUEST, "GetStatus", 9) == 0 ||
2741              strncasecmp (REQUEST, "GetResult", 9) == 0){
2742            runGetStatus(m,r_inputs->value,REQUEST);
2743#ifdef RELY_ON_DB
2744            map* dsNb=getMapFromMaps(m,"lenv","ds_nb");
2745            if(dsNb!=NULL && atoi(dsNb->value)>1)
2746              close_sql(m,1);
2747            close_sql(m,0);
2748#endif
2749         
2750            freeMaps (&m);
2751            free(m);
2752            if(zooRegistry!=NULL){
2753              freeRegistry(&zooRegistry);
2754              free(zooRegistry);
2755            }
2756            free (REQUEST);
2757            free (SERVICE_URL);
2758            return 0;
2759          }
2760          else
2761            if (strncasecmp (REQUEST, "Dismiss", strlen(REQUEST)) == 0){
2762              runDismiss(m,r_inputs->value);
2763              freeMaps (&m);
2764              free (m);
2765              if(zooRegistry!=NULL){
2766                freeRegistry(&zooRegistry);
2767                free(zooRegistry);
2768              }
2769              free (REQUEST);
2770              free (SERVICE_URL);
2771              return 0;
2772           
2773            }
2774          return 0;
2775        }
2776        if(reqId<=nbReqIdentifier){
2777          r_inputs = getMap (request_inputs, "Identifier");
2778
2779          struct dirent *dp;
2780          DIR *dirp = opendir (conf_dir);
2781          if (dirp == NULL)
2782            {
2783              errorException (m, _("The specified path does not exist."),
2784                              "InternalError", NULL);
2785              freeMaps (&m);
2786              free (m);
2787              if(zooRegistry!=NULL){
2788                freeRegistry(&zooRegistry);
2789                free(zooRegistry);
2790              }
2791              free (REQUEST);
2792              free (SERVICE_URL);
2793              return 0;
2794            }
2795          if (strncasecmp (REQUEST, "DescribeProcess", 15) == 0)
2796            {
2797              /**
2798               * Loop over Identifier list
2799               */
2800              xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
2801              r_inputs = NULL;
2802              r_inputs = getMap (request_inputs, "version");
2803#ifdef DEBUG
2804              fprintf(stderr," ** DEBUG %s %d \n",__FILE__,__LINE__);
2805              fflush(stderr);
2806#endif
2807              xmlNodePtr n = printWPSHeader(doc,m,"DescribeProcess",
2808                                            root_nodes[vid][1],(version!=NULL?version->value:"1.0.0"),1);
2809
2810              r_inputs = getMap (request_inputs, "Identifier");
2811
2812              fetchServicesForDescription(zooRegistry, m, r_inputs->value,
2813                                          printDescribeProcessForProcess,
2814                                          (void*) doc, (void*) n, conf_dir,
2815                                          request_inputs,printExceptionReportResponse);
2816
2817              printDocument (m, doc, zGetpid ());
2818              freeMaps (&m);
2819              free (m);
2820              if(zooRegistry!=NULL){
2821                freeRegistry(&zooRegistry);
2822                free(zooRegistry);
2823              }
2824              free (REQUEST);
2825              free (SERVICE_URL);
2826              fflush (stdout);
2827#ifdef META_DB
2828              close_sql(m,0);
2829              //end_sql();
2830#endif
2831              return 0;
2832            }
2833          else if (strncasecmp (REQUEST, "Execute", strlen (REQUEST)) != 0)
2834            {
2835              map* version=getMapFromMaps(m,"main","rversion");
2836              int vid=getVersionId(version->value);         
2837              int len = 0;
2838              int j = 0;
2839              for(j=0;j<nbSupportedRequests;j++){
2840                if(requests[vid][j]!=NULL)
2841                  len+=strlen(requests[vid][j])+2;
2842                else{
2843                  len+=4;
2844                  break;
2845                }
2846              }
2847              char *tmpStr=(char*)malloc(len*sizeof(char));
2848              int it=0;
2849              for(j=0;j<nbSupportedRequests;j++){
2850                if(requests[vid][j]!=NULL){
2851                  if(it==0){
2852                    sprintf(tmpStr,"%s",requests[vid][j]);
2853                    it++;
2854                  }else{
2855                    char *tmpS=zStrdup(tmpStr);
2856                    if(j+1<nbSupportedRequests && requests[vid][j+1]==NULL){
2857                      sprintf(tmpStr,"%s and %s",tmpS,requests[vid][j]);
2858                    }else{
2859                      sprintf(tmpStr,"%s, %s",tmpS,requests[vid][j]);
2860                 
2861                    }
2862                    free(tmpS);
2863                  }
2864                }
2865                else{
2866                  len+=4;
2867                  break;
2868                }
2869              }
2870              char* message=(char*)malloc((61+len)*sizeof(char));
2871              sprintf(message,"The <request> value was not recognized. Allowed values are %s.",tmpStr);
2872              errorException (m,_(message),"InvalidParameterValue", "request");
2873#ifdef DEBUG
2874              fprintf (stderr, "No request found %s", REQUEST);
2875#endif
2876              closedir (dirp);
2877              freeMaps (&m);
2878              free (m);
2879              if(zooRegistry!=NULL){
2880                freeRegistry(&zooRegistry);
2881                free(zooRegistry);
2882              }
2883              free (REQUEST);
2884              free (SERVICE_URL);
2885              fflush (stdout);
2886              return 0;
2887            }
2888          closedir (dirp);
2889        }
2890      }
2891
2892    map *postRequest = NULL;
2893    postRequest = getMap (request_inputs, "xrequest");
2894 
2895    if(vid==1 && postRequest==NULL){
2896      errorException (m,_("Unable to run Execute request using the GET HTTP method"),"InvalidParameterValue", "request"); 
2897      freeMaps (&m);
2898      free (m);
2899      if(zooRegistry!=NULL){
2900        freeRegistry(&zooRegistry);
2901        free(zooRegistry);
2902      }
2903      free (REQUEST);
2904      free (SERVICE_URL);
2905      fflush (stdout);
2906      return 0;
2907    }
2908    s1 = NULL;
2909 
2910    r_inputs = getMap (request_inputs, "Identifier");
2911    map* import = getMapFromMaps (m, IMPORTSERVICE, r_inputs->value); 
2912    if (import != NULL && import->value != NULL) { 
2913      strncpy(tmps1, import->value, 1024);
2914      setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
2915      setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
2916    } 
2917    else {
2918      snprintf (tmps1, 1024, "%s/%s.zcfg", conf_dir, r_inputs->value);
2919#ifdef DEBUG
2920      fprintf (stderr, "Trying to load %s\n", tmps1);
2921#endif
2922      if (strstr (r_inputs->value, ".") != NULL)
2923        {
2924          char *identifier = zStrdup (r_inputs->value);
2925          parseIdentifier (m, conf_dir, identifier, tmps1);
2926          map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
2927          if (tmpMap != NULL)
2928            addToMap (request_inputs, "metapath", tmpMap->value);
2929          free (identifier);
2930        }
2931      else
2932        {
2933          setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
2934          setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
2935        }
2936    }
2937
2938    r_inputs = getMapFromMaps (m, "lenv", "Identifier");
2939 
2940#ifdef META_DB
2941    int metadb_id=_init_sql(m,"metadb");
2942    //FAILED CONNECTING DB
2943    if(getMapFromMaps(m,"lenv","dbIssue")!=NULL || metadb_id<0){
2944      fprintf(stderr,"ERROR CONNECTING METADB\n");
2945    }
2946    if(metadb_id>=0)
2947      s1=extractServiceFromDb(m,r_inputs->value,0);
2948    //close_sql(m,0);
2949    if(s1!=NULL){
2950      inheritance(zooRegistry,&s1);
2951#ifdef USE_HPC
2952      addNestedOutputs(&s1);
2953#endif
2954      if(zooRegistry!=NULL){
2955        freeRegistry(&zooRegistry);
2956        free(zooRegistry);
2957      }
2958    }else /* Not found in MetaDB */{
2959#endif
2960      s1 = createService();
2961      if (s1 == NULL)
2962        {
2963          freeMaps (&m);
2964          free (m);
2965          if(zooRegistry!=NULL){
2966            freeRegistry(&zooRegistry);
2967            free(zooRegistry);
2968          }
2969          free (REQUEST);
2970          free (SERVICE_URL);
2971          return errorException (m, _("Unable to allocate memory"),
2972                                 "InternalError", NULL);
2973        }
2974
2975      int saved_stdout = zDup (fileno (stdout));
2976      zDup2 (fileno (stderr), fileno (stdout));
2977      t = readServiceFile (m, tmps1, &s1, r_inputs->value);
2978      if(t>=0){
2979        inheritance(zooRegistry,&s1);
2980#ifdef USE_HPC
2981        addNestedOutputs(&s1);
2982#endif
2983      }
2984      if(zooRegistry!=NULL){
2985        freeRegistry(&zooRegistry);
2986        free(zooRegistry);
2987      }
2988      fflush (stdout);
2989      zDup2 (saved_stdout, fileno (stdout));
2990      if (t < 0)
2991        {
2992          char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
2993          sprintf (tmpMsg,
2994                   _
2995                   ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
2996                   r_inputs->value);
2997          errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
2998          free (tmpMsg);
2999          free (s1);
3000          freeMaps (&m);
3001          free (m);
3002          free (REQUEST);
3003          free (SERVICE_URL);
3004          return 0;
3005        }
3006      zClose (saved_stdout);
3007#ifdef META_DB
3008    }
3009#endif
3010 
3011#ifdef DEBUG
3012    dumpService (s1);
3013#endif
3014    int j;
3015
3016
3017    /**
3018     * Create the input and output maps data structure
3019     */
3020    int i = 0;
3021    HINTERNET res;
3022    hInternet = InternetOpen (
3023#ifndef WIN32
3024                              (LPCTSTR)
3025#endif
3026                              "ZooWPSClient\0",
3027                              INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
3028
3029#ifndef WIN32
3030    if (!CHECK_INET_HANDLE (hInternet))
3031      fprintf (stderr, "WARNING : hInternet handle failed to initialize");
3032#endif
3033    maps *tmpmaps = request_input_real_format;
3034
3035    if(parseRequest(&m,&request_inputs,s1,&request_input_real_format,&request_output_real_format,&hInternet)<0){
3036      freeMaps (&m);
3037      free (m);
3038      free (REQUEST);
3039      free (SERVICE_URL);
3040      InternetCloseHandle (&hInternet);
3041      freeService (&s1);
3042      free (s1);
3043      return 0;
3044    }
3045    //InternetCloseHandle (&hInternet);
3046
3047    initAllEnvironment(m,request_inputs,ntmp,"xrequest");
3048
3049
3050#ifdef DEBUG
3051    dumpMap (request_inputs);
3052#endif
3053
3054    map *status = getMap (request_inputs, "status");
3055    if(vid==0){
3056      // Need to check if we need to fork to load a status enabled
3057      r_inputs = NULL;
3058      map *store = getMap (request_inputs, "storeExecuteResponse");
3059      /**
3060       * 05-007r7 WPS 1.0.0 page 57 :
3061       * 'If status="true" and storeExecuteResponse is "false" then the service
3062       * shall raise an exception.'
3063       */
3064      if (status != NULL && strcmp (status->value, "true") == 0 &&
3065          store != NULL && strcmp (store->value, "false") == 0)
3066        {
3067          errorException (m,
3068                          _
3069                          ("The status parameter cannot be set to true if storeExecuteResponse is set to false. Please modify your request parameters."),
3070                          "InvalidParameterValue", "storeExecuteResponse");
3071          freeService (&s1);
3072          free (s1);
3073          freeMaps (&m);
3074          free (m);
3075       
3076          freeMaps (&request_input_real_format);
3077          free (request_input_real_format);
3078       
3079          freeMaps (&request_output_real_format);
3080          free (request_output_real_format);
3081
3082          free (REQUEST);
3083          free (SERVICE_URL);
3084          return 1;
3085        }
3086      r_inputs = getMap (request_inputs, "storeExecuteResponse");
3087    }else{
3088      // Define status depending on the WPS 2.0.0 mode attribute
3089      status = getMap (request_inputs, "mode");
3090      map* mode=getMap(s1->content,"mode");
3091      if(strcasecmp(status->value,"async")==0){
3092        if(mode!=NULL && strcasecmp(mode->value,"async")==0)
3093          addToMap(request_inputs,"status","true");
3094        else{
3095          if(mode!=NULL){
3096            // see ref. http://docs.opengeospatial.org/is/14-065/14-065.html#61
3097            errorException (m,_("The process does not permit the desired execution mode."),"NoSuchMode", mode->value); 
3098            fflush (stdout);
3099            freeMaps (&m);
3100            free (m);
3101            if(zooRegistry!=NULL){
3102              freeRegistry(&zooRegistry);
3103              free(zooRegistry);
3104            }
3105            freeMaps (&request_input_real_format);
3106            free (request_input_real_format);
3107            freeMaps (&request_output_real_format);
3108            free (request_output_real_format);
3109            free (REQUEST);
3110            free (SERVICE_URL);
3111            return 0;
3112          }else
3113            addToMap(request_inputs,"status","true");
3114        }
3115      }
3116      else{
3117        if(strcasecmp(status->value,"auto")==0){
3118          if(mode!=NULL){
3119            if(strcasecmp(mode->value,"async")==0)
3120              addToMap(request_inputs,"status","false");
3121            else
3122              addToMap(request_inputs,"status","true");
3123          }
3124          else
3125            addToMap(request_inputs,"status","false");
3126        }else
3127          addToMap(request_inputs,"status","false");
3128      }
3129      status = getMap (request_inputs, "status");
3130    }
3131
3132    if (status != NULL)
3133      if (strcasecmp (status->value, "false") == 0)
3134        status = NULLMAP;
3135    if (status == NULLMAP)
3136      {
3137        if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
3138          freeService (&s1);
3139          free (s1);
3140          freeMaps (&m);
3141          free (m);
3142          free (REQUEST);
3143          free (SERVICE_URL);
3144          freeMaps (&request_input_real_format);
3145          free (request_input_real_format);
3146          freeMaps (&request_output_real_format);
3147          free (request_output_real_format);
3148          freeMaps (&tmpmaps);
3149          free (tmpmaps);
3150          return -1;
3151        }
3152        map* testMap=getMapFromMaps(m,"main","memory");
3153        if(testMap==NULL || strcasecmp(testMap->value,"load")!=0)
3154          dumpMapsValuesToFiles(&m,&request_input_real_format);
3155        loadServiceAndRun (&m, s1, request_inputs, &request_input_real_format,
3156                           &request_output_real_format, &eres);   
3157
3158#ifdef META_DB
3159        close_sql(m,0);     
3160#endif     
3161      }
3162    else
3163      {
3164        int pid;
3165#ifdef DEBUG
3166        fprintf (stderr, "\nPID : %d\n", cpid);
3167#endif
3168#ifndef WIN32
3169        pid = fork ();
3170#else
3171        if (cgiSid == NULL)
3172          {
3173            createProcess (m, request_inputs, s1, NULL, cpid,
3174                           request_input_real_format,
3175                           request_output_real_format);
3176            pid = cpid;
3177          }
3178        else
3179          {
3180            pid = 0;
3181            cpid = atoi (cgiSid);
3182            updateStatus(m,0,_("Initializing"));
3183          }
3184#endif
3185        if (pid > 0)
3186          {
3187            //
3188            // dady :
3189            // set status to SERVICE_ACCEPTED
3190            //
3191#ifdef DEBUG
3192            fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
3193                     zGetpid ());
3194#endif
3195            eres = SERVICE_ACCEPTED;
3196          }
3197        else if (pid == 0)
3198          {
3199            eres = SERVICE_ACCEPTED;
3200            //
3201            // son : have to close the stdout, stdin and stderr to let the parent
3202            // process answer to http client.
3203            //
3204            map* usid = getMapFromMaps (m, "lenv", "uusid");
3205            map* tmpm = getMapFromMaps (m, "lenv", "osid");
3206            int cpid = atoi (tmpm->value);
3207            pid=cpid;
3208            r_inputs = getMapFromMaps (m, "main", "tmpPath");
3209            setMapInMaps (m, "lenv", "async","true");
3210            map* r_inputs1 = createMap("ServiceName", s1->name);
3211
3212            // Create the filename for the result file (.res)
3213            fbkpres =
3214              (char *)
3215              malloc ((strlen (r_inputs->value) +
3216                       strlen (usid->value) + 7) * sizeof (char));                   
3217            sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
3218            bmap = createMaps("status");
3219            bmap->content=createMap("usid",usid->value);
3220            addToMap(bmap->content,"sid",tmpm->value);
3221            addIntToMap(bmap->content,"pid",zGetpid());
3222         
3223            // Create PID file referencing the OS process identifier
3224            fbkpid =
3225              (char *)
3226              malloc ((strlen (r_inputs->value) +
3227                       strlen (usid->value) + 7) * sizeof (char));
3228            sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
3229            setMapInMaps (m, "lenv", "file.pid", fbkpid);
3230
3231            f0 = freopen (fbkpid, "w+",stdout);
3232            printf("%d",zGetpid());
3233            fflush(stdout);
3234
3235            // Create SID file referencing the semaphore name
3236            fbkp =
3237              (char *)
3238              malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
3239                       strlen (usid->value) + 7) * sizeof (char));
3240            sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
3241            setMapInMaps (m, "lenv", "file.sid", fbkp);
3242            FILE* f2 = freopen (fbkp, "w+",stdout);
3243            printf("%s",tmpm->value);
3244            fflush(f2);
3245            free(fbkp);
3246
3247            fbkp =
3248              (char *)
3249              malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
3250                       strlen (usid->value) + 7) * sizeof (char));
3251            sprintf (fbkp, "%s/%s_%s.xml", r_inputs->value, r_inputs1->value,
3252                     usid->value);
3253            setMapInMaps (m, "lenv", "file.responseInit", fbkp);
3254            flog =
3255              (char *)
3256              malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
3257                       strlen (usid->value) + 13) * sizeof (char));
3258            sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
3259                     r_inputs1->value, usid->value);
3260            setMapInMaps (m, "lenv", "file.log", flog);
3261#ifdef DEBUG
3262            fprintf (stderr, "RUN IN BACKGROUND MODE \n");
3263            fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
3264                     zGetpid ());
3265            fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
3266#endif
3267            freopen (flog, "w+", stderr);
3268            fflush (stderr);
3269            f0 = freopen (fbkp, "w+", stdout);
3270            rewind (stdout);
3271#ifndef WIN32
3272            fclose (stdin);
3273#endif
3274#ifdef RELY_ON_DB
3275            init_sql(m);
3276            recordServiceStatus(m);
3277#endif
3278#ifdef USE_CALLBACK
3279            invokeCallback(m,NULL,NULL,0,0);
3280#endif
3281            if(vid==0){
3282              //
3283              // set status to SERVICE_STARTED and flush stdout to ensure full
3284              // content was outputed (the file used to store the ResponseDocument).
3285              // Then, rewind stdout to restart writing from the begining of the file.
3286              // This way, the data will be updated at the end of the process run.
3287              //
3288              printProcessResponse (m, request_inputs, cpid, s1, r_inputs1->value,
3289                                    SERVICE_STARTED, request_input_real_format,
3290                                    request_output_real_format);
3291              fflush (stdout);
3292#ifdef RELY_ON_DB
3293              recordResponse(m,fbkp);
3294#endif
3295            }
3296
3297            fflush (stderr);
3298
3299            fbkp1 =
3300              (char *)
3301              malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
3302                       strlen (usid->value) + 13) * sizeof (char));
3303            sprintf (fbkp1, "%s/%s_final_%s.xml", r_inputs->value,
3304                     r_inputs1->value, usid->value);
3305            setMapInMaps (m, "lenv", "file.responseFinal", fbkp1);
3306
3307            f1 = freopen (fbkp1, "w+", stdout);
3308
3309            map* serviceTypeMap=getMap(s1->content,"serviceType");
3310            if(serviceTypeMap!=NULL)
3311              setMapInMaps (m, "lenv", "serviceType", serviceTypeMap->value);
3312
3313            char *flenv =
3314              (char *)
3315              malloc ((strlen (r_inputs->value) + 
3316                       strlen (usid->value) + 12) * sizeof (char));
3317            sprintf (flenv, "%s/%s_lenv.cfg", r_inputs->value, usid->value);
3318            maps* lenvMaps=getMaps(m,"lenv");
3319            dumpMapsToFile(lenvMaps,flenv,0);
3320            free(flenv);
3321
3322#ifdef USE_CALLBACK
3323            invokeCallback(m,request_input_real_format,NULL,1,0);
3324#endif
3325            if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
3326              freeService (&s1);
3327              free (s1);
3328              fflush (stdout);
3329              fflush (stderr);
3330              fclose (f0);
3331              fclose (f1);
3332              if(dumpBackFinalFile(m,fbkp,fbkp1)<0)
3333                return -1;
3334#ifndef RELY_ON_DB
3335              dumpMapsToFile(bmap,fbkpres,1);
3336              removeShmLock (m, 1);
3337#else
3338              recordResponse(m,fbkp1);
3339#ifdef USE_CALLBACK
3340              invokeCallback(m,NULL,NULL,7,0);
3341#endif
3342#endif
3343              zUnlink (fbkpid);
3344              unhandleStatus (m);
3345#ifdef RELY_ON_DB
3346#ifdef META_DB
3347              cleanupCallbackThreads();
3348              close_sql(m,1);
3349#endif
3350              close_sql(m,0);
3351#endif
3352              freeMaps (&m);
3353              free (m);
3354              free (REQUEST);
3355              free (SERVICE_URL);
3356              freeMaps (&request_input_real_format);
3357              free (request_input_real_format);
3358              freeMaps (&request_output_real_format);
3359              free (request_output_real_format);
3360              freeMaps (&tmpmaps);
3361              free (tmpmaps);
3362              return -1;
3363            }
3364            if(getMapFromMaps(m,"lenv","mapError")!=NULL){
3365              setMapInMaps(m,"lenv","message",_("Issue with geographic data"));
3366#ifdef USE_CALLBACK
3367              invokeCallback(m,NULL,NULL,7,0);
3368#endif
3369              eres=-1;//SERVICE_FAILED;
3370            }else{
3371              map* testMap=getMapFromMaps(m,"main","memory");
3372              if(testMap==NULL || strcasecmp(testMap->value,"load")!=0)
3373                dumpMapsValuesToFiles(&m,&request_input_real_format);
3374              loadServiceAndRun (&m, s1, request_inputs,
3375                                 &request_input_real_format,
3376                                 &request_output_real_format, &eres);
3377            }
3378          }
3379        else
3380          {
3381            /**
3382             * error server don't accept the process need to output a valid
3383             * error response here !!!
3384             */
3385            eres = -1;
3386            errorException (m, _("Unable to run the child process properly"),
3387                            "InternalError", NULL);
3388          }
3389      }
3390       
3391#ifdef DEBUG
3392    fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
3393    dumpMaps (request_output_real_format);
3394    fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
3395#endif
3396    fflush(stdout);
3397    rewind(stdout);
3398
3399    if (eres != -1)
3400      outputResponse (s1, request_input_real_format,
3401                      request_output_real_format, request_inputs,
3402                      cpid, m, eres);
3403    fflush (stdout);
3404  }
3405  /**
3406   * Ensure that if error occurs when freeing memory, no signal will return
3407   * an ExceptionReport document as the result was already returned to the
3408   * client.
3409   */
3410#ifndef USE_GDB
3411  signal (SIGSEGV, donothing);
3412  signal (SIGTERM, donothing);
3413  signal (SIGINT, donothing);
3414  signal (SIGILL, donothing);
3415  signal (SIGFPE, donothing);
3416  signal (SIGABRT, donothing);
3417#endif
3418    fprintf(stderr,"%s %d \n",__FILE__,__LINE__);
3419    fflush(stderr);
3420
3421  if (((int) zGetpid ()) != cpid || cgiSid != NULL)
3422    {
3423    fprintf(stderr,"%s %d \n",__FILE__,__LINE__);
3424    fflush(stderr);
3425      if (eres == SERVICE_SUCCEEDED)
3426#ifdef USE_CALLBACK
3427        invokeCallback(m,NULL,request_output_real_format,5,1);
3428#endif
3429      fflush(stderr);
3430      fflush(stdout);
3431
3432      fclose (stdout);
3433
3434      fclose (f0);
3435
3436      fclose (f1);
3437
3438      if(dumpBackFinalFile(m,fbkp,fbkp1)<0)
3439        return -1;
3440      zUnlink (fbkpid);
3441      switch(eres){
3442      default:
3443      case SERVICE_FAILED:
3444        setMapInMaps(bmap,"status","status",wpsStatus[1]);
3445        setMapInMaps(m,"lenv","fstate",wpsStatus[1]);
3446        break;
3447      case SERVICE_SUCCEEDED:
3448        setMapInMaps(bmap,"status","status",wpsStatus[0]);
3449        setMapInMaps(m,"lenv","fstate",wpsStatus[0]);
3450        break;
3451      }     
3452#ifndef RELY_ON_DB
3453      dumpMapsToFile(bmap,fbkpres,1);
3454      removeShmLock (m, 1);
3455#else
3456      recordResponse(m,fbkp1);
3457      if (eres == SERVICE_SUCCEEDED)
3458#ifdef USE_CALLBACK
3459        invokeCallback(m,NULL,request_output_real_format,6,0);
3460#endif
3461#endif
3462      freeMaps(&bmap);
3463      free(bmap);
3464      zUnlink (fbkp1);
3465      unhandleStatus (m);
3466#if defined(USE_JSON) || defined(USE_CALLBACK)
3467      cleanupCallbackThreads();
3468#endif
3469
3470#ifdef RELY_ON_DB
3471#ifdef META_DB
3472      close_sql(m,1);
3473#endif
3474      close_sql(m,0);
3475      end_sql();
3476#endif
3477      free(fbkpid);
3478      free(fbkpres);
3479      free (fbkp1);
3480      if(cgiSid!=NULL)
3481        free(cgiSid);
3482      map* tMap=getMapFromMaps(m,"main","executionType");
3483      if(tMap!=NULL && strncasecmp(tMap->value,"xml",3)==0)
3484        InternetCloseHandle (&hInternet);
3485      fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
3486      fflush(stderr);
3487      fclose (stderr);
3488      zUnlink (flog);
3489      free (flog);
3490    }
3491  else{
3492    //InternetCloseHandle (&hInternet); 
3493#ifdef META_DB
3494    close_sql(m,0);
3495#endif
3496  }
3497 
3498  freeService (&s1);
3499  free (s1);
3500  freeMaps (&m);
3501  free (m);
3502
3503  freeMaps (&request_input_real_format);
3504  free (request_input_real_format);
3505
3506  freeMaps (&request_output_real_format);
3507  free (request_output_real_format);
3508
3509  free (REQUEST);
3510  free (SERVICE_URL);
3511
3512#ifdef DEBUG
3513  fprintf (stderr, "Processed response \n");
3514  fflush (stdout);
3515  fflush (stderr);
3516#endif
3517
3518  if (((int) zGetpid ()) != cpid || cgiSid != NULL)
3519    {
3520      exit (0);
3521    }
3522
3523  return 0;
3524}
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