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

Last change on this file since 656 was 656, checked in by djay, 9 years ago

Small fixes.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 65.0 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2008-2013 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 USE_OTB
29#include "service_internal_otb.h"
30#else
31#define length(x) (sizeof(x) / sizeof(x[0]))
32#endif
33
34#include "cgic.h"
35
36extern "C"
37{
38#include <libxml/tree.h>
39#include <libxml/xmlmemory.h>
40#include <libxml/parser.h>
41#include <libxml/xpath.h>
42#include <libxml/xpathInternals.h>
43}
44
45#include "ulinet.h"
46
47#include <libintl.h>
48#include <locale.h>
49#include <string.h>
50
51#include "service.h"
52
53#include "service_internal.h"
54#include "server_internal.h"
55#include "response_print.h"
56#include "request_parser.h"
57#include "sqlapi.h"
58
59#ifdef USE_PYTHON
60#include "service_internal_python.h"
61#endif
62
63#ifdef USE_SAGA
64#include "service_internal_saga.h"
65#endif
66
67#ifdef USE_JAVA
68#include "service_internal_java.h"
69#endif
70
71#ifdef USE_PHP
72#include "service_internal_php.h"
73#endif
74
75#ifdef USE_JS
76#include "service_internal_js.h"
77#endif
78
79#ifdef USE_RUBY
80#include "service_internal_ruby.h"
81#endif
82
83#ifdef USE_PERL
84#include "service_internal_perl.h"
85#endif
86
87#include <dirent.h>
88#include <signal.h>
89#include <unistd.h>
90#ifndef WIN32
91#include <dlfcn.h>
92#include <libgen.h>
93#else
94#include <windows.h>
95#include <direct.h>
96#include <sys/types.h>
97#include <sys/stat.h>
98#include <unistd.h>
99#define pid_t int;
100#endif
101#include <fcntl.h>
102#include <time.h>
103#include <stdarg.h>
104
105#ifdef WIN32
106extern "C"
107{
108  __declspec (dllexport) char *strcasestr (char const *a, char const *b)
109#ifndef USE_MS
110  {
111    char *x = zStrdup (a);
112    char *y = zStrdup (b);
113
114      x = _strlwr (x);
115      y = _strlwr (y);
116    char *pos = strstr (x, y);
117    char *ret = pos == NULL ? NULL : (char *) (a + (pos - x));
118      free (x);
119      free (y);
120      return ret;
121  };
122#else
123   ;
124#endif
125}
126#endif
127
128/**
129 * Translation function for zoo-kernel
130 */
131#define _(String) dgettext ("zoo-kernel",String)
132/**
133 * Translation function for zoo-service
134 */
135#define __(String) dgettext ("zoo-service",String)
136
137#ifdef WIN32
138  #ifndef PROGRAMNAME
139    #define PROGRAMNAME "zoo_loader.cgi"
140  #endif
141#endif
142
143extern int getServiceFromFile (maps *, const char *, service **);
144
145/**
146 * Parse the service file using getServiceFromFile or use getServiceFromYAML
147 * if YAML support was activated.
148 *
149 * @param conf the conf maps containing the main.cfg settings
150 * @param file the file name to parse
151 * @param service the service to update witht the file content
152 * @param name the service name
153 * @return true if the file can be parsed or false
154 * @see getServiceFromFile, getServiceFromYAML
155 */
156int
157readServiceFile (maps * conf, char *file, service ** service, char *name)
158{
159  int t = getServiceFromFile (conf, file, service);
160#ifdef YAML
161  if (t < 0)
162    {
163      t = getServiceFromYAML (conf, file, service, name);
164    }
165#endif
166  return t;
167}
168
169/**
170 * Replace a char by another one in a string
171 *
172 * @param str the string to update
173 * @param toReplace the char to replace
174 * @param toReplaceBy the char that will be used
175 */
176void
177translateChar (char *str, char toReplace, char toReplaceBy)
178{
179  int i = 0, len = strlen (str);
180  for (i = 0; i < len; i++)
181    {
182      if (str[i] == toReplace)
183        str[i] = toReplaceBy;
184    }
185}
186
187
188/**
189 * Create the profile registry.
190 *
191 * The profile registry is optional (created only if the registry key is
192 * available in the [main] section of the main.cfg file) and can be used to
193 * store the profiles hierarchy. The registry is a directory which should
194 * contain the following sub-directories:
195 *  * concept: direcotry containing .html files describing concept
196 *  * generic: directory containing .zcfg files for wps:GenericProcess
197 *  * implementation: directory containing .zcfg files for wps:Process
198 *
199 * @param m the conf maps containing the main.cfg settings
200 * @param r the registry to update
201 * @param reg_dir the resgitry
202 * @param saved_stdout the saved stdout identifier
203 * @return 0 if the resgitry is null or was correctly updated, -1 on failure
204 */
205int
206createRegistry (maps* m,registry ** r, char *reg_dir, int saved_stdout)
207{
208  struct dirent *dp;
209  int scount = 0;
210
211  if (reg_dir == NULL)
212    return 0;
213  DIR *dirp = opendir (reg_dir);
214  if (dirp == NULL)
215    {
216      return -1;
217    }
218  while ((dp = readdir (dirp)) != NULL){
219    if ((dp->d_type == DT_DIR || dp->d_type == DT_LNK) && dp->d_name[0] != '.')
220      {
221
222        char * tmpName =
223          (char *) malloc ((strlen (reg_dir) + strlen (dp->d_name) + 2) *
224                           sizeof (char));
225        sprintf (tmpName, "%s/%s", reg_dir, dp->d_name);
226       
227        DIR *dirp1 = opendir (tmpName);
228        struct dirent *dp1;
229        while ((dp1 = readdir (dirp1)) != NULL){
230          char* extn = strstr(dp1->d_name, ".zcfg");
231          if(dp1->d_name[0] != '.' && extn != NULL && strlen(extn) == 5)
232            {
233              int t;
234              char *tmps1=
235                (char *) malloc ((strlen (tmpName) + strlen (dp1->d_name) + 2) *
236                                 sizeof (char));
237              sprintf (tmps1, "%s/%s", tmpName, dp1->d_name);
238              char *tmpsn = zStrdup (dp1->d_name);
239              tmpsn[strlen (tmpsn) - 5] = 0;
240              service* s1 = (service *) malloc (SERVICE_SIZE);
241              if (s1 == NULL)
242                {
243                  dup2 (saved_stdout, fileno (stdout));
244                  errorException (m, _("Unable to allocate memory."),
245                                  "InternalError", NULL);
246                  return -1;
247                }
248              t = readServiceFile (m, tmps1, &s1, tmpsn);
249              free (tmpsn);
250              if (t < 0)
251                {
252                  map *tmp00 = getMapFromMaps (m, "lenv", "message");
253                  char tmp01[1024];
254                  if (tmp00 != NULL)
255                    sprintf (tmp01, _("Unable to parse the ZCFG file: %s (%s)"),
256                             dp1->d_name, tmp00->value);
257                  else
258                    sprintf (tmp01, _("Unable to parse the ZCFG file: %s."),
259                             dp1->d_name);
260                  dup2 (saved_stdout, fileno (stdout));
261                  errorException (m, tmp01, "InternalError", NULL);
262                  return -1;
263                }
264#ifdef DEBUG
265              dumpService (s1);
266              fflush (stdout);
267              fflush (stderr);
268#endif
269              if(strncasecmp(dp->d_name,"implementation",14)==0){
270                inheritance(*r,&s1);
271              }
272              addServiceToRegistry(r,dp->d_name,s1);
273              freeService (&s1);
274              free (s1);
275              scount++;
276            }
277        }
278        (void) closedir (dirp1);
279      }
280  }
281  (void) closedir (dirp);
282  return 0;
283}
284
285/**
286 * Recursivelly parse zcfg starting from the ZOO-Kernel cwd.
287 * Call the func function given in arguments after parsing the ZCFG file.
288 *
289 * @param m the conf maps containing the main.cfg settings
290 * @param r the registry containing profiles hierarchy
291 * @param n the root XML Node to add the sub-elements
292 * @param conf_dir the location of the main.cfg file (basically cwd)
293 * @param prefix the current prefix if any, or NULL
294 * @param saved_stdout the saved stdout identifier
295 * @param level the current level (number of sub-directories to reach the
296 * current path)
297 * @see inheritance, readServiceFile
298 */
299int
300recursReaddirF (maps * m, registry *r, xmlNodePtr n, char *conf_dir, char *prefix,
301                int saved_stdout, int level, void (func) (maps *, xmlNodePtr,
302                                                          service *))
303{
304  struct dirent *dp;
305  int scount = 0;
306
307  if (conf_dir == NULL)
308    return 1;
309  DIR *dirp = opendir (conf_dir);
310  if (dirp == NULL)
311    {
312      if (level > 0)
313        return 1;
314      else
315        return -1;
316    }
317  char tmp1[25];
318  sprintf (tmp1, "sprefix_%d", level);
319  char levels[17];
320  sprintf (levels, "%d", level);
321  setMapInMaps (m, "lenv", "level", levels);
322  while ((dp = readdir (dirp)) != NULL)
323    if ((dp->d_type == DT_DIR || dp->d_type == DT_LNK) && dp->d_name[0] != '.'
324        && strstr (dp->d_name, ".") == NULL)
325      {
326
327        char *tmp =
328          (char *) malloc ((strlen (conf_dir) + strlen (dp->d_name) + 2) *
329                           sizeof (char));
330        sprintf (tmp, "%s/%s", conf_dir, dp->d_name);
331
332        if (prefix != NULL)
333          {
334            prefix = NULL;
335          }
336        prefix = (char *) malloc ((strlen (dp->d_name) + 2) * sizeof (char));
337        sprintf (prefix, "%s.", dp->d_name);
338
339        //map* tmpMap=getMapFromMaps(m,"lenv",tmp1);
340
341        int res;
342        if (prefix != NULL)
343          {
344            setMapInMaps (m, "lenv", tmp1, prefix);
345            char levels1[17];
346            sprintf (levels1, "%d", level + 1);
347            setMapInMaps (m, "lenv", "level", levels1);
348            res =
349              recursReaddirF (m, r, n, tmp, prefix, saved_stdout, level + 1,
350                              func);
351            sprintf (levels1, "%d", level);
352            setMapInMaps (m, "lenv", "level", levels1);
353            free (prefix);
354            prefix = NULL;
355          }
356        else
357          res = -1;
358        free (tmp);
359        if (res < 0)
360          {
361            return res;
362          }
363      }
364    else
365      {
366        char* extn = strstr(dp->d_name, ".zcfg");
367        if(dp->d_name[0] != '.' && extn != NULL && strlen(extn) == 5)
368          {
369            int t;
370            char tmps1[1024];
371            memset (tmps1, 0, 1024);
372            snprintf (tmps1, 1024, "%s/%s", conf_dir, dp->d_name);
373            service *s1 = (service *) malloc (SERVICE_SIZE);
374            if (s1 == NULL)
375              {
376                dup2 (saved_stdout, fileno (stdout));
377                errorException (m, _("Unable to allocate memory."),
378                                "InternalError", NULL);
379                return -1;
380              }
381#ifdef DEBUG
382            fprintf (stderr, "#################\n%s\n#################\n",
383                     tmps1);
384#endif
385            char *tmpsn = zStrdup (dp->d_name);
386            tmpsn[strlen (tmpsn) - 5] = 0;
387            t = readServiceFile (m, tmps1, &s1, tmpsn);
388            free (tmpsn);
389            if (t < 0)
390              {
391                map *tmp00 = getMapFromMaps (m, "lenv", "message");
392                char tmp01[1024];
393                if (tmp00 != NULL)
394                  sprintf (tmp01, _("Unable to parse the ZCFG file: %s (%s)"),
395                           dp->d_name, tmp00->value);
396                else
397                  sprintf (tmp01, _("Unable to parse the ZCFG file: %s."),
398                           dp->d_name);
399                dup2 (saved_stdout, fileno (stdout));
400                errorException (m, tmp01, "InternalError", NULL);
401                return -1;
402              }
403#ifdef DEBUG
404            dumpService (s1);
405            fflush (stdout);
406            fflush (stderr);
407#endif
408            inheritance(r,&s1);
409            func (m, n, s1);
410            freeService (&s1);
411            free (s1);
412            scount++;
413          }
414      }
415  (void) closedir (dirp);
416  return 1;
417}
418
419/**
420 * Signal handling function which simply call exit(0).
421 *
422 * @param sig the signal number
423 */
424void
425donothing (int sig)
426{
427#ifdef DEBUG
428  fprintf (stderr, "Signal %d after the ZOO-Kernel returned result!\n", sig);
429#endif
430  exit (0);
431}
432
433/**
434 * Signal handling function which create an ExceptionReport node containing the
435 * information message corresponding to the signal number.
436 *
437 * @param sig the signal number
438 */
439void
440sig_handler (int sig)
441{
442  char tmp[100];
443  const char *ssig;
444  switch (sig)
445    {
446    case SIGSEGV:
447      ssig = "SIGSEGV";
448      break;
449    case SIGTERM:
450      ssig = "SIGTERM";
451      break;
452    case SIGINT:
453      ssig = "SIGINT";
454      break;
455    case SIGILL:
456      ssig = "SIGILL";
457      break;
458    case SIGFPE:
459      ssig = "SIGFPE";
460      break;
461    case SIGABRT:
462      ssig = "SIGABRT";
463      break;
464    default:
465      ssig = "UNKNOWN";
466      break;
467    }
468  sprintf (tmp,
469           _
470           ("ZOO Kernel failed to process your request, receiving signal %d = %s"),
471           sig, ssig);
472  errorException (NULL, tmp, "InternalError", NULL);
473#ifdef DEBUG
474  fprintf (stderr, "Not this time!\n");
475#endif
476  exit (0);
477}
478
479/**
480 * Load a service provider and run the service function.
481 *
482 * @param myMap the conf maps containing the main.cfg settings
483 * @param s1 the service structure
484 * @param request_inputs map storing all the request parameters
485 * @param inputs the inputs maps
486 * @param ioutputs the outputs maps
487 * @param eres the result returned by the service execution
488 */
489void
490loadServiceAndRun (maps ** myMap, service * s1, map * request_inputs,
491                   maps ** inputs, maps ** ioutputs, int *eres)
492{
493  char tmps1[1024];
494  char ntmp[1024];
495  maps *m = *myMap;
496  maps *request_output_real_format = *ioutputs;
497  maps *request_input_real_format = *inputs;
498  /**
499   * Extract serviceType to know what kind of service should be loaded
500   */
501  map *r_inputs = NULL;
502#ifndef WIN32
503  getcwd (ntmp, 1024);
504#else
505  _getcwd (ntmp, 1024);
506#endif
507  r_inputs = getMap (s1->content, "serviceType");
508#ifdef DEBUG
509  fprintf (stderr, "LOAD A %s SERVICE PROVIDER \n", r_inputs->value);
510  fflush (stderr);
511#endif
512
513  map* libp = getMapFromMaps(m, "main", "libPath");
514 
515  if (strlen (r_inputs->value) == 1
516      && strncasecmp (r_inputs->value, "C", 1) == 0)
517  {
518     if (libp != NULL && libp->value != NULL) {
519            r_inputs = getMap (s1->content, "ServiceProvider");
520                sprintf (tmps1, "%s/%s", libp->value, r_inputs->value);
521         }
522     else {     
523        r_inputs = getMap (request_inputs, "metapath");
524        if (r_inputs != NULL)
525          sprintf (tmps1, "%s/%s", ntmp, r_inputs->value);
526        else
527          sprintf (tmps1, "%s/", ntmp);
528         
529        char *altPath = zStrdup (tmps1);
530        r_inputs = getMap (s1->content, "ServiceProvider");
531        sprintf (tmps1, "%s/%s", altPath, r_inputs->value);
532        free (altPath);
533         }
534#ifdef DEBUG
535      fprintf (stderr, "Trying to load %s\n", tmps1);
536#endif
537#ifdef WIN32
538      HINSTANCE so =
539        LoadLibraryEx (tmps1, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
540#else
541      void *so = dlopen (tmps1, RTLD_LAZY);
542#endif
543#ifdef WIN32
544      char* errstr = getLastErrorMessage();
545#else
546      char *errstr;
547      errstr = dlerror ();
548#endif
549#ifdef DEBUG
550          fprintf (stderr, "%s loaded (%s) \n", tmps1, errstr);
551#endif
552      if (so != NULL)
553        {
554#ifdef DEBUG
555          fprintf (stderr, "Library loaded %s \n", errstr);
556          fprintf (stderr, "Service Shared Object = %s\n", r_inputs->value);
557#endif
558          r_inputs = getMap (s1->content, "serviceType");
559#ifdef DEBUG
560          dumpMap (r_inputs);
561          fprintf (stderr, "%s\n", r_inputs->value);
562          fflush (stderr);
563#endif
564          if (strncasecmp (r_inputs->value, "C-FORTRAN", 9) == 0)
565            {
566              r_inputs = getMap (request_inputs, "Identifier");
567              char fname[1024];
568              sprintf (fname, "%s_", r_inputs->value);
569#ifdef DEBUG
570              fprintf (stderr, "Try to load function %s\n", fname);
571#endif
572#ifdef WIN32
573              typedef int (CALLBACK * execute_t) (char ***, char ***,
574                                                  char ***);
575              execute_t execute = (execute_t) GetProcAddress (so, fname);
576#else
577              typedef int (*execute_t) (char ***, char ***, char ***);
578              execute_t execute = (execute_t) dlsym (so, fname);
579#endif
580#ifdef DEBUG
581#ifdef WIN32
582                          errstr = getLastErrorMessage();
583#else
584              errstr = dlerror ();
585#endif
586              fprintf (stderr, "Function loaded %s\n", errstr);
587#endif
588
589              char main_conf[10][30][1024];
590              char inputs[10][30][1024];
591              char outputs[10][30][1024];
592              for (int i = 0; i < 10; i++)
593                {
594                  for (int j = 0; j < 30; j++)
595                    {
596                      memset (main_conf[i][j], 0, 1024);
597                      memset (inputs[i][j], 0, 1024);
598                      memset (outputs[i][j], 0, 1024);
599                    }
600                }
601              mapsToCharXXX (m, (char ***) main_conf);
602              mapsToCharXXX (request_input_real_format, (char ***) inputs);
603              mapsToCharXXX (request_output_real_format, (char ***) outputs);
604              *eres =
605                execute ((char ***) &main_conf[0], (char ***) &inputs[0],
606                         (char ***) &outputs[0]);
607#ifdef DEBUG
608              fprintf (stderr, "Function run successfully \n");
609#endif
610              charxxxToMaps ((char ***) &outputs[0],
611                             &request_output_real_format);
612            }
613          else
614            {
615#ifdef DEBUG
616#ifdef WIN32
617                          errstr = getLastErrorMessage();
618              fprintf (stderr, "Function %s failed to load because of %s\n",
619                       r_inputs->value, errstr);
620#endif
621#endif
622              r_inputs = getMapFromMaps (m, "lenv", "Identifier");
623#ifdef DEBUG
624              fprintf (stderr, "Try to load function %s\n", r_inputs->value);
625#endif
626              typedef int (*execute_t) (maps **, maps **, maps **);
627#ifdef WIN32
628              execute_t execute =
629                (execute_t) GetProcAddress (so, r_inputs->value);
630#else
631              execute_t execute = (execute_t) dlsym (so, r_inputs->value);
632#endif
633
634              if (execute == NULL)
635                {
636#ifdef WIN32
637                                  errstr = getLastErrorMessage();
638#else
639                  errstr = dlerror ();
640#endif
641                  char *tmpMsg =
642                    (char *) malloc (2048 + strlen (r_inputs->value));
643                  sprintf (tmpMsg,
644                           _
645                           ("Error occured while running the %s function: %s"),
646                           r_inputs->value, errstr);
647                  errorException (m, tmpMsg, "InternalError", NULL);
648                  free (tmpMsg);
649#ifdef DEBUG
650                  fprintf (stderr, "Function %s error %s\n", r_inputs->value,
651                           errstr);
652#endif
653                  *eres = -1;
654                  return;
655                }
656
657#ifdef DEBUG
658#ifdef WIN32
659                          errstr = getLastErrorMessage();
660#else
661              errstr = dlerror ();
662#endif
663              fprintf (stderr, "Function loaded %s\n", errstr);
664#endif
665
666#ifdef DEBUG
667              fprintf (stderr, "Now run the function \n");
668              fflush (stderr);
669#endif
670              *eres =
671                execute (&m, &request_input_real_format,
672                         &request_output_real_format);
673#ifdef DEBUG
674              fprintf (stderr, "Function loaded and returned %d\n", eres);
675              fflush (stderr);
676#endif
677            }
678#ifdef WIN32
679          *ioutputs = dupMaps (&request_output_real_format);
680          FreeLibrary (so);
681#else
682          dlclose (so);
683#endif
684        }
685      else
686        {
687      /**
688       * Unable to load the specified shared library
689       */
690          char tmps[1024];
691#ifdef WIN32
692                  errstr = getLastErrorMessage();
693#else
694              errstr = dlerror ();
695#endif
696          sprintf (tmps, _("Unable to load C Library %s"), errstr);
697          errorException(m,tmps,"InternalError",NULL);
698          *eres = -1;
699        }
700    }
701  else
702
703#ifdef USE_SAGA
704  if (strncasecmp (r_inputs->value, "SAGA", 6) == 0)
705    {
706      *eres =
707        zoo_saga_support (&m, request_inputs, s1,
708                            &request_input_real_format,
709                            &request_output_real_format);
710    }
711  else
712#endif
713
714#ifdef USE_OTB
715  if (strncasecmp (r_inputs->value, "OTB", 6) == 0)
716    {
717      *eres =
718        zoo_otb_support (&m, request_inputs, s1,
719                            &request_input_real_format,
720                            &request_output_real_format);
721    }
722  else
723#endif
724
725#ifdef USE_PYTHON
726  if (strncasecmp (r_inputs->value, "PYTHON", 6) == 0)
727    {
728      *eres =
729        zoo_python_support (&m, request_inputs, s1,
730                            &request_input_real_format,
731                            &request_output_real_format);
732    }
733  else
734#endif
735
736#ifdef USE_JAVA
737  if (strncasecmp (r_inputs->value, "JAVA", 4) == 0)
738    {
739      *eres =
740        zoo_java_support (&m, request_inputs, s1, &request_input_real_format,
741                          &request_output_real_format);
742    }
743  else
744#endif
745
746#ifdef USE_PHP
747  if (strncasecmp (r_inputs->value, "PHP", 3) == 0)
748    {
749      *eres =
750        zoo_php_support (&m, request_inputs, s1, &request_input_real_format,
751                         &request_output_real_format);
752    }
753  else
754#endif
755
756
757#ifdef USE_PERL
758  if (strncasecmp (r_inputs->value, "PERL", 4) == 0)
759    {
760      *eres =
761        zoo_perl_support (&m, request_inputs, s1, &request_input_real_format,
762                          &request_output_real_format);
763    }
764  else
765#endif
766
767#ifdef USE_JS
768  if (strncasecmp (r_inputs->value, "JS", 2) == 0)
769    {
770      *eres =
771        zoo_js_support (&m, request_inputs, s1, &request_input_real_format,
772                        &request_output_real_format);
773    }
774  else
775#endif
776
777#ifdef USE_RUBY
778  if (strncasecmp (r_inputs->value, "Ruby", 4) == 0)
779    {
780      *eres =
781        zoo_ruby_support (&m, request_inputs, s1, &request_input_real_format,
782                          &request_output_real_format);
783    }
784  else
785#endif
786
787    {
788      char tmpv[1024];
789      sprintf (tmpv,
790               _
791               ("Programming Language (%s) set in ZCFG file is not currently supported by ZOO Kernel.\n"),
792               r_inputs->value);
793      errorException (m, tmpv, "InternalError", NULL);
794      *eres = -1;
795    }
796  *myMap = m;
797  *ioutputs = request_output_real_format;
798}
799
800
801#ifdef WIN32
802/**
803 * createProcess function: create a new process after setting some env variables
804 */
805void
806createProcess (maps * m, map * request_inputs, service * s1, char *opts,
807               int cpid, maps * inputs, maps * outputs)
808{
809  STARTUPINFO si;
810  PROCESS_INFORMATION pi;
811  ZeroMemory (&si, sizeof (si));
812  si.cb = sizeof (si);
813  ZeroMemory (&pi, sizeof (pi));
814  char *tmp = (char *) malloc ((1024 + cgiContentLength) * sizeof (char));
815  char *tmpq = (char *) malloc ((1024 + cgiContentLength) * sizeof (char));
816  map *req = getMap (request_inputs, "request");
817  map *id = getMap (request_inputs, "identifier");
818  map *di = getMap (request_inputs, "DataInputs");
819
820  // The required size for the dataInputsKVP and dataOutputsKVP buffers
821  // may exceed cgiContentLength, hence a 2 kb extension. However, a
822  // better solution would be to have getMapsAsKVP() determine the required
823  // buffer size before allocating memory.     
824  char *dataInputsKVP = getMapsAsKVP (inputs, cgiContentLength + 2048, 0);
825  char *dataOutputsKVP = getMapsAsKVP (outputs, cgiContentLength + 2048, 1);
826#ifdef DEBUG
827  fprintf (stderr, "DATAINPUTSKVP %s\n", dataInputsKVP);
828  fprintf (stderr, "DATAOUTPUTSKVP %s\n", dataOutputsKVP);
829#endif
830  map *sid = getMapFromMaps (m, "lenv", "sid");
831  map *r_inputs = getMapFromMaps (m, "main", "tmpPath");
832  map *r_inputs1 = getMap (request_inputs, "metapath");
833 
834  int hasIn = -1;
835  if (r_inputs1 == NULL)
836    {
837      r_inputs1 = createMap ("metapath", "");
838      hasIn = 1;
839    }
840  map *r_inputs2 = getMap (request_inputs, "ResponseDocument");
841  if (r_inputs2 == NULL)
842    r_inputs2 = getMap (request_inputs, "RawDataOutput");
843  map *tmpPath = getMapFromMaps (m, "lenv", "cwd");
844
845  map *tmpReq = getMap (request_inputs, "xrequest");
846 
847  if(r_inputs2 != NULL && tmpReq != NULL) {
848        const char key[] = "rfile=";
849        char* kvp = (char*) malloc((FILENAME_MAX + strlen(key))*sizeof(char));
850        char* filepath = kvp + strlen(key);
851        strncpy(kvp, key, strlen(key));
852        addToCache(m, tmpReq->value, tmpReq->value, "text/xml", strlen(tmpReq->value), 
853                   filepath, FILENAME_MAX);                               
854    if (filepath == NULL) {
855        errorException( m, _("Unable to cache HTTP POST Execute request."), "InternalError", NULL); 
856                return;
857    }   
858        sprintf(tmp,"\"metapath=%s&%s&cgiSid=%s",
859                r_inputs1->value,kvp,sid->value);
860    sprintf(tmpq,"metapath=%s&%s",
861                r_inputs1->value,kvp);
862        free(kvp);             
863  }
864  else if (r_inputs2 != NULL)
865    {
866      sprintf (tmp,
867               "\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s&cgiSid=%s",
868               r_inputs1->value, req->value, id->value, dataInputsKVP,
869               r_inputs2->name, dataOutputsKVP, sid->value);
870      sprintf (tmpq,
871               "metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&%s=%s",
872               r_inputs1->value, req->value, id->value, dataInputsKVP,
873               r_inputs2->name, dataOutputsKVP);                   
874    }
875  else
876    {
877      sprintf (tmp,
878               "\"metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s&cgiSid=%s",
879               r_inputs1->value, req->value, id->value, dataInputsKVP,
880               sid->value);
881      sprintf (tmpq,
882               "metapath=%s&request=%s&service=WPS&version=1.0.0&Identifier=%s&DataInputs=%s",
883               r_inputs1->value, req->value, id->value, dataInputsKVP,
884               sid->value);   
885    }
886
887  if (hasIn > 0)
888    {
889      freeMap (&r_inputs1);
890      free (r_inputs1);
891    }
892  char *tmp1 = zStrdup (tmp);
893  sprintf (tmp, "\"%s\" %s \"%s\"", PROGRAMNAME, tmp1, sid->value); 
894  free (dataInputsKVP);
895  free (dataOutputsKVP);
896#ifdef DEBUG
897  fprintf (stderr, "REQUEST IS : %s \n", tmp);
898#endif
899
900  map* usid = getMapFromMaps (m, "lenv", "usid");
901  if (usid != NULL && usid->value != NULL) {
902    SetEnvironmentVariable("USID", TEXT (usid->value));
903  }
904
905  SetEnvironmentVariable ("CGISID", TEXT (sid->value));
906  SetEnvironmentVariable ("QUERY_STRING", TEXT (tmpq));
907  // knut: Prevent REQUEST_METHOD=POST in background process call to cgic:main (process hangs when reading cgiIn):
908  SetEnvironmentVariable("REQUEST_METHOD", "GET");
909 
910  char clen[1000];
911  sprintf (clen, "%d", strlen (tmpq));
912  SetEnvironmentVariable ("CONTENT_LENGTH", TEXT (clen));
913
914  if (!CreateProcess (NULL,     // No module name (use command line)
915                      TEXT (tmp),       // Command line
916                      NULL,     // Process handle not inheritable
917                      NULL,     // Thread handle not inheritable
918                      FALSE,    // Set handle inheritance to FALSE
919                      CREATE_NO_WINDOW, // Apache won't wait until the end
920                      NULL,     // Use parent's environment block
921                      NULL,     // Use parent's starting directory
922                      &si,      // Pointer to STARTUPINFO struct
923                      &pi)      // Pointer to PROCESS_INFORMATION struct
924    )
925    {
926#ifdef DEBUG
927      fprintf (stderr, "CreateProcess failed (%d).\n", GetLastError ());
928#endif
929      if (tmp != NULL) {
930        free(tmp);
931      }
932      if (tmpq != NULL) {
933        free(tmpq);
934      }         
935      return;
936    }
937  else
938    {
939#ifdef DEBUG
940      fprintf (stderr, "CreateProcess successful (%d).\n\n\n\n",
941               GetLastError ());
942#endif
943    }
944  CloseHandle (pi.hProcess);
945  CloseHandle (pi.hThread);
946 
947  if (tmp != NULL) {
948    free(tmp);
949  }
950  if (tmpq != NULL) {
951    free(tmpq);
952  }
953 
954#ifdef DEBUG
955  fprintf (stderr, "CreateProcess finished !\n");
956#endif
957}
958#endif
959
960/**
961 * Process the request.
962 *
963 * @param inputs the request parameters map
964 * @return 0 on sucess, other value on failure
965 * @see conf_read,recursReaddirF
966 */
967int
968runRequest (map ** inputs)
969{
970
971#ifndef USE_GDB
972#ifndef WIN32
973  signal (SIGCHLD, SIG_IGN);
974#endif 
975  signal (SIGSEGV, sig_handler);
976  signal (SIGTERM, sig_handler);
977  signal (SIGINT, sig_handler);
978  signal (SIGILL, sig_handler);
979  signal (SIGFPE, sig_handler);
980  signal (SIGABRT, sig_handler);
981#endif
982
983  map *r_inputs = NULL;
984  map *request_inputs = *inputs;
985#ifdef IGNORE_METAPATH
986  addToMap(request_inputs, "metapath", "");
987#endif 
988  maps *m = NULL;
989  char *REQUEST = NULL;
990  /**
991   * Parsing service specfic configuration file
992   */
993  m = (maps *) malloc (MAPS_SIZE);
994  if (m == NULL)
995    {
996      return errorException (m, _("Unable to allocate memory."),
997                             "InternalError", NULL);
998    }
999  char ntmp[1024];
1000#ifndef WIN32
1001  getcwd (ntmp, 1024);
1002#else
1003  _getcwd (ntmp, 1024);
1004#endif
1005  r_inputs = getMapOrFill (&request_inputs, "metapath", "");
1006
1007  char conf_file[10240];
1008  snprintf (conf_file, 10240, "%s/%s/main.cfg", ntmp, r_inputs->value);
1009  if (conf_read (conf_file, m) == 2)
1010    {
1011      errorException (NULL, _("Unable to load the main.cfg file."),
1012                      "InternalError", NULL);
1013      free (m);
1014      return 1;
1015    }
1016#ifdef DEBUG
1017  fprintf (stderr, "***** BEGIN MAPS\n");
1018  dumpMaps (m);
1019  fprintf (stderr, "***** END MAPS\n");
1020#endif
1021
1022  map *getPath = getMapFromMaps (m, "main", "gettextPath");
1023  if (getPath != NULL)
1024    {
1025      bindtextdomain ("zoo-kernel", getPath->value);
1026      bindtextdomain ("zoo-services", getPath->value);
1027    }
1028  else
1029    {
1030      bindtextdomain ("zoo-kernel", "/usr/share/locale/");
1031      bindtextdomain ("zoo-services", "/usr/share/locale/");
1032    }
1033
1034
1035  /**
1036   * Manage our own error log file (usefull to separate standard apache debug
1037   * messages from the ZOO-Kernel ones but also for IIS users to avoid wrong
1038   * headers messages returned by the CGI due to wrong redirection of stderr)
1039   */
1040  FILE *fstde = NULL;
1041  map *fstdem = getMapFromMaps (m, "main", "logPath");
1042  if (fstdem != NULL)
1043    fstde = freopen (fstdem->value, "a+", stderr);
1044
1045  r_inputs = getMap (request_inputs, "language");
1046  if (r_inputs == NULL)
1047    r_inputs = getMap (request_inputs, "AcceptLanguages");
1048  if (r_inputs == NULL)
1049    r_inputs = getMapFromMaps (m, "main", "language");
1050  if (r_inputs != NULL)
1051    {
1052      if (isValidLang (m, r_inputs->value) < 0)
1053        {
1054          char tmp[1024];
1055          sprintf (tmp,
1056                   _
1057                   ("The value %s is not supported for the <language> parameter"),
1058                   r_inputs->value);
1059          errorException (m, tmp, "InvalidParameterValue", "language");
1060          freeMaps (&m);
1061          free (m);
1062          free (REQUEST);
1063          return 1;
1064
1065        }
1066      char *tmp = zStrdup (r_inputs->value);
1067      setMapInMaps (m, "main", "language", tmp);
1068#ifdef DEB
1069      char tmp2[12];
1070      sprintf (tmp2, "%s.utf-8", tmp);
1071      translateChar (tmp2, '-', '_');
1072      setlocale (LC_ALL, tmp2);
1073#else
1074      translateChar (tmp, '-', '_');
1075      setlocale (LC_ALL, tmp);
1076#endif
1077#ifndef WIN32
1078      setenv ("LC_ALL", tmp, 1);
1079#else
1080      char tmp1[12];
1081      sprintf (tmp1, "LC_ALL=%s", tmp);
1082      putenv (tmp1);
1083#endif
1084      free (tmp);
1085    }
1086  else
1087    {
1088      setlocale (LC_ALL, "en_US");
1089#ifndef WIN32
1090      setenv ("LC_ALL", "en_US", 1);
1091#else
1092      char tmp1[12];
1093      sprintf (tmp1, "LC_ALL=en_US");
1094      putenv (tmp1);
1095#endif
1096      setMapInMaps (m, "main", "language", "en-US");
1097    }
1098  setlocale (LC_NUMERIC, "en_US");
1099  bind_textdomain_codeset ("zoo-kernel", "UTF-8");
1100  textdomain ("zoo-kernel");
1101  bind_textdomain_codeset ("zoo-services", "UTF-8");
1102  textdomain ("zoo-services");
1103
1104  map *lsoap = getMap (request_inputs, "soap");
1105  if (lsoap != NULL && strcasecmp (lsoap->value, "true") == 0)
1106    setMapInMaps (m, "main", "isSoap", "true");
1107  else
1108    setMapInMaps (m, "main", "isSoap", "false");
1109
1110  if(strlen(cgiServerName)>0)
1111    {
1112      char tmpUrl[1024];
1113       
1114      if ( getenv("HTTPS") != NULL && strncmp(getenv("HTTPS"), "on", 2) == 0 ) { // Knut: check if non-empty instead of "on"?           
1115        if ( strncmp(cgiServerPort, "443", 3) == 0 ) { 
1116          sprintf(tmpUrl, "https://%s%s", cgiServerName, cgiScriptName);
1117        }
1118        else {
1119          sprintf(tmpUrl, "https://%s:%s%s", cgiServerName, cgiServerPort, cgiScriptName);
1120        }
1121      }
1122      else {
1123        if ( strncmp(cgiServerPort, "80", 2) == 0 ) { 
1124          sprintf(tmpUrl, "http://%s%s", cgiServerName, cgiScriptName);
1125        }
1126        else {
1127          sprintf(tmpUrl, "http://%s:%s%s", cgiServerName, cgiServerPort, cgiScriptName);
1128        }
1129      }
1130#ifdef DEBUG
1131      fprintf(stderr,"*** %s ***\n",tmpUrl);
1132#endif
1133      setMapInMaps(m,"main","serverAddress",tmpUrl);
1134    }
1135
1136  //Check for minimum inputs
1137  map* version=getMap(request_inputs,"version");
1138  if(version==NULL)
1139    version=getMapFromMaps(m,"main","version");
1140  setMapInMaps(m,"main","rversion",version->value);
1141  int vid=getVersionId(version->value);
1142  if(vid<0)
1143    vid=0;
1144  map* err=NULL;
1145  const char **vvr=(const char**)requests[vid];
1146  checkValidValue(request_inputs,&err,"request",vvr,1);
1147  const char *vvs[]={
1148    "WPS",
1149    NULL
1150  };
1151  if(err!=NULL){
1152    checkValidValue(request_inputs,&err,"service",(const char**)vvs,1);
1153    printExceptionReportResponse (m, err);
1154    freeMap(&err);
1155    free(err);
1156    if (count (request_inputs) == 1)
1157      {
1158        freeMap (&request_inputs);
1159        free (request_inputs);
1160      }
1161    freeMaps (&m);
1162    free (m);
1163    return 1;
1164  }
1165  checkValidValue(request_inputs,&err,"service",(const char**)vvs,1);
1166
1167  const char *vvv[]={
1168    "1.0.0",
1169    "2.0.0",
1170    NULL
1171  };
1172  r_inputs = getMap (request_inputs, "Request");
1173  REQUEST = zStrdup (r_inputs->value);
1174  int reqId=-1;
1175  if (strncasecmp (REQUEST, "GetCapabilities", 15) != 0){
1176    checkValidValue(request_inputs,&err,"version",(const char**)vvv,1);
1177    int j=0;
1178    for(j=0;j<nbSupportedRequests;j++){
1179      if(requests[vid][j]!=NULL && requests[vid][j+1]!=NULL){
1180        if(j<nbReqIdentifier && strncasecmp(REQUEST,requests[vid][j+1],strlen(REQUEST))==0){
1181          checkValidValue(request_inputs,&err,"identifier",NULL,1);
1182          reqId=j+1;
1183          break;
1184        }
1185        else
1186          if(j>=nbReqIdentifier && j<nbReqIdentifier+nbReqJob && 
1187             strncasecmp(REQUEST,requests[vid][j+1],strlen(REQUEST))==0){
1188            checkValidValue(request_inputs,&err,"jobid",NULL,1);
1189            reqId=j+1;
1190            break;
1191          }
1192      }else
1193        break;
1194    }
1195  }else{
1196    checkValidValue(request_inputs,&err,"AcceptVersions",(const char**)vvv,-1);
1197    map* version=getMap(request_inputs,"AcceptVersions");
1198    if(version!=NULL){
1199      if(strstr(version->value,schemas[1][0])!=NULL)
1200        addToMap(request_inputs,"version",schemas[1][0]);
1201      else
1202        addToMap(request_inputs,"version",version->value);
1203    }
1204  }
1205  if(err!=NULL){
1206    printExceptionReportResponse (m, err);
1207    freeMap(&err);
1208    free(err);
1209    if (count (request_inputs) == 1)
1210      {
1211        freeMap (&request_inputs);
1212        free (request_inputs);
1213      }
1214    free(REQUEST);
1215    freeMaps (&m);
1216    free (m);
1217    return 1;
1218  }
1219
1220  r_inputs = getMap (request_inputs, "serviceprovider");
1221  if (r_inputs == NULL)
1222    {
1223      addToMap (request_inputs, "serviceprovider", "");
1224    }
1225
1226  maps *request_output_real_format = NULL;
1227  map *tmpm = getMapFromMaps (m, "main", "serverAddress");
1228  if (tmpm != NULL)
1229    SERVICE_URL = zStrdup (tmpm->value);
1230  else
1231    SERVICE_URL = zStrdup (DEFAULT_SERVICE_URL);
1232
1233
1234
1235  service *s1;
1236  int scount = 0;
1237#ifdef DEBUG
1238  dumpMap (r_inputs);
1239#endif
1240  char conf_dir[1024];
1241  int t;
1242  char tmps1[1024];
1243
1244  r_inputs = NULL;
1245  r_inputs = getMap (request_inputs, "metapath");
1246 
1247  if (r_inputs != NULL)
1248    snprintf (conf_dir, 1024, "%s/%s", ntmp, r_inputs->value);
1249  else
1250    snprintf (conf_dir, 1024, "%s", ntmp);
1251
1252  map* reg = getMapFromMaps (m, "main", "registry");
1253  registry* zooRegistry=NULL;
1254  if(reg!=NULL){
1255    int saved_stdout = dup (fileno (stdout));
1256    dup2 (fileno (stderr), fileno (stdout));
1257    createRegistry (m,&zooRegistry,reg->value,saved_stdout);
1258    dup2 (saved_stdout, fileno (stdout));
1259  }
1260
1261  if (strncasecmp (REQUEST, "GetCapabilities", 15) == 0)
1262    {
1263#ifdef DEBUG
1264      dumpMap (r_inputs);
1265#endif
1266      xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
1267      xmlNodePtr n=printGetCapabilitiesHeader(doc,m,(version!=NULL?version->value:"1.0.0"));
1268      /**
1269       * Here we need to close stdout to ensure that unsupported chars
1270       * has been found in the zcfg and then printed on stdout
1271       */
1272      int saved_stdout = dup (fileno (stdout));
1273      dup2 (fileno (stderr), fileno (stdout));
1274      if (int res =               
1275          recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
1276                          printGetCapabilitiesForProcess) < 0)
1277        {
1278          freeMaps (&m);
1279          free (m);
1280          if(zooRegistry!=NULL){
1281            freeRegistry(&zooRegistry);
1282            free(zooRegistry);
1283          }
1284          free (REQUEST);
1285          free (SERVICE_URL);
1286          fflush (stdout);
1287          return res;
1288        }
1289      fflush (stdout);
1290      dup2 (saved_stdout, fileno (stdout));
1291      printDocument (m, doc, getpid ());
1292      freeMaps (&m);
1293      free (m);
1294      if(zooRegistry!=NULL){
1295        freeRegistry(&zooRegistry);
1296        free(zooRegistry);
1297      }
1298      free (REQUEST);
1299      free (SERVICE_URL);
1300      fflush (stdout);
1301      return 0;
1302    }
1303  else
1304    {
1305      r_inputs = getMap (request_inputs, "JobId");
1306      if(reqId>nbReqIdentifier){
1307        if (strncasecmp (REQUEST, "GetStatus", strlen(REQUEST)) == 0 ||
1308            strncasecmp (REQUEST, "GetResult", strlen(REQUEST)) == 0){
1309          runGetStatus(m,r_inputs->value,REQUEST);
1310          freeMaps (&m);
1311          free (m);
1312          if(zooRegistry!=NULL){
1313            freeRegistry(&zooRegistry);
1314            free(zooRegistry);
1315          }
1316          free (REQUEST);
1317          free (SERVICE_URL);
1318          return 0;
1319        }
1320        else
1321          if (strncasecmp (REQUEST, "Dismiss", strlen(REQUEST)) == 0){
1322            runDismiss(m,r_inputs->value);
1323            freeMaps (&m);
1324            free (m);
1325            if(zooRegistry!=NULL){
1326              freeRegistry(&zooRegistry);
1327              free(zooRegistry);
1328            }
1329            free (REQUEST);
1330            free (SERVICE_URL);
1331            return 0;
1332           
1333          }
1334        return 0;
1335      }
1336      if(reqId<=nbReqIdentifier){
1337        r_inputs = getMap (request_inputs, "Identifier");
1338
1339        struct dirent *dp;
1340        DIR *dirp = opendir (conf_dir);
1341        if (dirp == NULL)
1342          {
1343            errorException (m, _("The specified path path does not exist."),
1344                            "InvalidParameterValue", conf_dir);
1345            freeMaps (&m);
1346            free (m);
1347            if(zooRegistry!=NULL){
1348              freeRegistry(&zooRegistry);
1349              free(zooRegistry);
1350            }
1351            free (REQUEST);
1352            free (SERVICE_URL);
1353            return 0;
1354          }
1355        if (strncasecmp (REQUEST, "DescribeProcess", 15) == 0)
1356          {
1357            /**
1358             * Loop over Identifier list
1359             */
1360            xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
1361            r_inputs = NULL;
1362            r_inputs = getMap (request_inputs, "version");
1363            xmlNodePtr n = printWPSHeader(doc,m,"DescribeProcess",
1364                                          root_nodes[vid][1],(version!=NULL?version->value:"1.0.0"),1);
1365
1366            r_inputs = getMap (request_inputs, "Identifier");
1367
1368            char *orig = zStrdup (r_inputs->value);
1369
1370            int saved_stdout = dup (fileno (stdout));
1371            dup2 (fileno (stderr), fileno (stdout));
1372            if (strcasecmp ("all", orig) == 0)
1373              {
1374                if (int res =
1375                    recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
1376                                    printDescribeProcessForProcess) < 0)
1377                  return res;
1378              }
1379            else
1380              {
1381                char *saveptr;
1382                char *tmps = strtok_r (orig, ",", &saveptr);
1383
1384                char buff[256];
1385                char buff1[1024];
1386                while (tmps != NULL)
1387                  {
1388                    int hasVal = -1;
1389                    char *corig = zStrdup (tmps);
1390                    if (strstr (corig, ".") != NULL)
1391                      {
1392
1393                        parseIdentifier (m, conf_dir, corig, buff1);
1394                        map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
1395                        if (tmpMap != NULL)
1396                          addToMap (request_inputs, "metapath", tmpMap->value);
1397                        map *tmpMapI = getMapFromMaps (m, "lenv", "Identifier");
1398
1399                        s1 = (service *) malloc (SERVICE_SIZE);
1400                        t = readServiceFile (m, buff1, &s1, tmpMapI->value);
1401                        if (t < 0)
1402                          {
1403                            map *tmp00 = getMapFromMaps (m, "lenv", "message");
1404                            char tmp01[1024];
1405                            if (tmp00 != NULL)
1406                              sprintf (tmp01,
1407                                       _
1408                                       ("Unable to parse the ZCFG file for the following ZOO-Service: %s. Message: %s"),
1409                                       tmps, tmp00->value);
1410                            else
1411                              sprintf (tmp01,
1412                                       _
1413                                       ("Unable to parse the ZCFG file for the following ZOO-Service: %s."),
1414                                       tmps);
1415                            dup2 (saved_stdout, fileno (stdout));
1416                            errorException (m, tmp01, "InvalidParameterValue",
1417                                            "identifier");
1418                            freeMaps (&m);
1419                            free (m);
1420                            if(zooRegistry!=NULL){
1421                              freeRegistry(&zooRegistry);
1422                              free(zooRegistry);
1423                            }
1424                            free (REQUEST);
1425                            free (corig);
1426                            free (orig);
1427                            free (SERVICE_URL);
1428                            free (s1);
1429                            closedir (dirp);
1430                            xmlFreeDoc (doc);
1431                            xmlCleanupParser ();
1432                            zooXmlCleanupNs ();
1433                            return 1;
1434                          }
1435#ifdef DEBUG
1436                        dumpService (s1);
1437#endif
1438                        inheritance(zooRegistry,&s1);
1439                        printDescribeProcessForProcess (m, n, s1);
1440                        freeService (&s1);
1441                        free (s1);
1442                        s1 = NULL;
1443                        scount++;
1444                        hasVal = 1;
1445                        setMapInMaps (m, "lenv", "level", "0");
1446                      }
1447                    else
1448                      {
1449                        memset (buff, 0, 256);
1450                        snprintf (buff, 256, "%s.zcfg", corig);
1451                        memset (buff1, 0, 1024);
1452#ifdef DEBUG
1453                        printf ("\n#######%s\n########\n", buff);
1454#endif
1455                        while ((dp = readdir (dirp)) != NULL)
1456                          {
1457                            if (strcasecmp (dp->d_name, buff) == 0)
1458                              {
1459                                memset (buff1, 0, 1024);
1460                                snprintf (buff1, 1024, "%s/%s", conf_dir,
1461                                          dp->d_name);
1462                                s1 = (service *) malloc (SERVICE_SIZE);
1463                                if (s1 == NULL)
1464                                  {
1465                                    dup2 (saved_stdout, fileno (stdout));
1466                                    return errorException (m,
1467                                                           _
1468                                                           ("Unable to allocate memory."),
1469                                                           "InternalError",
1470                                                           NULL);
1471                                  }
1472#ifdef DEBUG
1473                                printf
1474                                  ("#################\n(%s) %s\n#################\n",
1475                                   r_inputs->value, buff1);
1476#endif
1477                                char *tmp0 = zStrdup (dp->d_name);
1478                                tmp0[strlen (tmp0) - 5] = 0;
1479                                t = readServiceFile (m, buff1, &s1, tmp0);
1480                                free (tmp0);
1481                                if (t < 0)
1482                                  {
1483                                    map *tmp00 =
1484                                      getMapFromMaps (m, "lenv", "message");
1485                                    char tmp01[1024];
1486                                    if (tmp00 != NULL)
1487                                      sprintf (tmp01,
1488                                               _
1489                                               ("Unable to parse the ZCFG file: %s (%s)"),
1490                                               dp->d_name, tmp00->value);
1491                                    else
1492                                      sprintf (tmp01,
1493                                               _
1494                                               ("Unable to parse the ZCFG file: %s."),
1495                                               dp->d_name);
1496                                    dup2 (saved_stdout, fileno (stdout));
1497                                    errorException (m, tmp01, "InternalError",
1498                                                    NULL);
1499                                    freeMaps (&m);
1500                                    free (m);
1501                                    if(zooRegistry!=NULL){
1502                                      freeRegistry(&zooRegistry);
1503                                      free(zooRegistry);
1504                                    }
1505                                    free (orig);
1506                                    free (REQUEST);
1507                                    closedir (dirp);
1508                                    xmlFreeDoc (doc);
1509                                    xmlCleanupParser ();
1510                                    zooXmlCleanupNs ();
1511                                    return 1;
1512                                  }
1513#ifdef DEBUG
1514                                dumpService (s1);
1515#endif
1516                                inheritance(zooRegistry,&s1);
1517                                printDescribeProcessForProcess (m, n, s1);
1518                                freeService (&s1);
1519                                free (s1);
1520                                s1 = NULL;
1521                                scount++;
1522                                hasVal = 1;
1523                              }
1524                          }
1525                      }
1526                    if (hasVal < 0)
1527                      {
1528                        map *tmp00 = getMapFromMaps (m, "lenv", "message");
1529                        char tmp01[1024];
1530                        if (tmp00 != NULL)
1531                          sprintf (tmp01,
1532                                   _("Unable to parse the ZCFG file: %s (%s)"),
1533                                   buff, tmp00->value);
1534                        else
1535                          sprintf (tmp01,
1536                                   _("Unable to parse the ZCFG file: %s."),
1537                                   buff);
1538                        dup2 (saved_stdout, fileno (stdout));
1539                        errorException (m, tmp01, "InvalidParameterValue",
1540                                        "Identifier");
1541                        freeMaps (&m);
1542                        free (m);
1543                        if(zooRegistry!=NULL){
1544                          freeRegistry(&zooRegistry);
1545                          free(zooRegistry);
1546                        }
1547                        free (orig);
1548                        free (REQUEST);
1549                        closedir (dirp);
1550                        xmlFreeDoc (doc);
1551                        xmlCleanupParser ();
1552                        zooXmlCleanupNs ();
1553                        return 1;
1554                      }
1555                    rewinddir (dirp);
1556                    tmps = strtok_r (NULL, ",", &saveptr);
1557                    if (corig != NULL)
1558                      free (corig);
1559                  }
1560              }
1561            closedir (dirp);
1562            fflush (stdout);
1563            dup2 (saved_stdout, fileno (stdout));
1564            free (orig);
1565            printDocument (m, doc, getpid ());
1566            freeMaps (&m);
1567            free (m);
1568            if(zooRegistry!=NULL){
1569              freeRegistry(&zooRegistry);
1570              free(zooRegistry);
1571            }
1572            free (REQUEST);
1573            free (SERVICE_URL);
1574            fflush (stdout);
1575            return 0;
1576          }
1577        else if (strncasecmp (REQUEST, "Execute", strlen (REQUEST)) != 0)
1578          {
1579            map* version=getMapFromMaps(m,"main","rversion");
1580            int vid=getVersionId(version->value);
1581            int len,j=0;
1582            for(j=0;j<nbSupportedRequests;j++){
1583              if(requests[vid][j]!=NULL)
1584                len+=strlen(requests[vid][j])+2;
1585              else{
1586                len+=4;
1587                break;
1588              }
1589            }
1590            char *tmpStr=(char*)malloc(len*sizeof(char));
1591            int it=0;
1592            for(j=0;j<nbSupportedRequests;j++){
1593              if(requests[vid][j]!=NULL){
1594                if(it==0){
1595                  sprintf(tmpStr,"%s",requests[vid][j]);
1596                  it++;
1597                }else{
1598                  char *tmpS=zStrdup(tmpStr);
1599                  if(j+1<nbSupportedRequests && requests[vid][j+1]==NULL){
1600                    sprintf(tmpStr,"%s and %s",tmpS,requests[vid][j]);
1601                  }else{
1602                    sprintf(tmpStr,"%s, %s",tmpS,requests[vid][j]);
1603                 
1604                  }
1605                  free(tmpS);
1606                }
1607              }
1608              else{
1609                len+=4;
1610                break;
1611              }
1612            }
1613            char* message=(char*)malloc((61+len)*sizeof(char));
1614            sprintf(message,"The <request> value was not recognized. Allowed values are %s.",tmpStr);
1615            errorException (m,_(message),"InvalidParameterValue", "request");
1616#ifdef DEBUG
1617            fprintf (stderr, "No request found %s", REQUEST);
1618#endif
1619            closedir (dirp);
1620            freeMaps (&m);
1621            free (m);
1622            if(zooRegistry!=NULL){
1623              freeRegistry(&zooRegistry);
1624              free(zooRegistry);
1625            }
1626            free (REQUEST);
1627            free (SERVICE_URL);
1628            fflush (stdout);
1629            return 0;
1630          }
1631        closedir (dirp);
1632      }
1633    }
1634
1635  map *postRequest = NULL;
1636  postRequest = getMap (request_inputs, "xrequest");
1637
1638  if(vid==1 && postRequest==NULL){
1639    errorException (m,_("Unable to run Execute request using the GET HTTP method"),"InvalidParameterValue", "request"); 
1640    freeMaps (&m);
1641    free (m);
1642    if(zooRegistry!=NULL){
1643      freeRegistry(&zooRegistry);
1644      free(zooRegistry);
1645    }
1646    free (REQUEST);
1647    free (SERVICE_URL);
1648    fflush (stdout);
1649    return 0;
1650  }
1651 
1652  s1 = NULL;
1653  s1 = (service *) malloc (SERVICE_SIZE);
1654  if (s1 == NULL)
1655    {
1656      freeMaps (&m);
1657      free (m);
1658      if(zooRegistry!=NULL){
1659        freeRegistry(&zooRegistry);
1660        free(zooRegistry);
1661      }
1662      free (REQUEST);
1663      free (SERVICE_URL);
1664      return errorException (m, _("Unable to allocate memory."),
1665                             "InternalError", NULL);
1666    }
1667
1668  r_inputs = getMap (request_inputs, "MetaPath");
1669  if (r_inputs != NULL)
1670    snprintf (tmps1, 1024, "%s/%s", ntmp, r_inputs->value);
1671  else
1672    snprintf (tmps1, 1024, "%s/", ntmp);
1673  r_inputs = getMap (request_inputs, "Identifier");
1674  char *ttmp = zStrdup (tmps1);
1675  snprintf (tmps1, 1024, "%s/%s.zcfg", ttmp, r_inputs->value);
1676  free (ttmp);
1677#ifdef DEBUG
1678  fprintf (stderr, "Trying to load %s\n", tmps1);
1679#endif
1680  if (strstr (r_inputs->value, ".") != NULL)
1681    {
1682      char *identifier = zStrdup (r_inputs->value);
1683      parseIdentifier (m, conf_dir, identifier, tmps1);
1684      map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
1685      if (tmpMap != NULL)
1686        addToMap (request_inputs, "metapath", tmpMap->value);
1687      free (identifier);
1688    }
1689  else
1690    {
1691      setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
1692      setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
1693    }
1694
1695  r_inputs = getMapFromMaps (m, "lenv", "Identifier");
1696  int saved_stdout = dup (fileno (stdout));
1697  dup2 (fileno (stderr), fileno (stdout));
1698  t = readServiceFile (m, tmps1, &s1, r_inputs->value);
1699  inheritance(zooRegistry,&s1);
1700  if(zooRegistry!=NULL){
1701    freeRegistry(&zooRegistry);
1702    free(zooRegistry);
1703  }
1704  fflush (stdout);
1705  dup2 (saved_stdout, fileno (stdout));
1706  if (t < 0)
1707    {
1708      char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
1709      sprintf (tmpMsg,
1710               _
1711               ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
1712               r_inputs->value);
1713      errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
1714      free (tmpMsg);
1715      free (s1);
1716      freeMaps (&m);
1717      free (m);
1718      free (REQUEST);
1719      free (SERVICE_URL);
1720      return 0;
1721    }
1722  close (saved_stdout);
1723
1724#ifdef DEBUG
1725  dumpService (s1);
1726#endif
1727  int j;
1728
1729
1730  /**
1731   * Create the input and output maps data structure
1732   */
1733  int i = 0;
1734  HINTERNET hInternet;
1735  HINTERNET res;
1736  hInternet = InternetOpen (
1737#ifndef WIN32
1738                            (LPCTSTR)
1739#endif
1740                            "ZooWPSClient\0",
1741                            INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1742
1743#ifndef WIN32
1744  if (!CHECK_INET_HANDLE (hInternet))
1745    fprintf (stderr, "WARNING : hInternet handle failed to initialize");
1746#endif
1747  maps *request_input_real_format = NULL;
1748  maps *tmpmaps = request_input_real_format;
1749
1750
1751  if(parseRequest(&m,&request_inputs,s1,&request_input_real_format,&request_output_real_format,&hInternet)<0){
1752    freeMaps (&m);
1753    free (m);
1754    free (REQUEST);
1755    free (SERVICE_URL);
1756    InternetCloseHandle (&hInternet);
1757    freeService (&s1);
1758    free (s1);
1759    return 0;
1760  }
1761
1762
1763  // Define each env variable in runing environment
1764  maps *curs = getMaps (m, "env");
1765  if (curs != NULL)
1766    {
1767      map *mapcs = curs->content;
1768      while (mapcs != NULLMAP)
1769        {
1770#ifndef WIN32
1771          setenv (mapcs->name, mapcs->value, 1);
1772#else
1773#ifdef DEBUG
1774          fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
1775                   mapcs->value);
1776#endif
1777          if (mapcs->value[strlen (mapcs->value) - 2] == '\r')
1778            {
1779#ifdef DEBUG
1780              fprintf (stderr, "[ZOO: Env var finish with \r]\n");
1781#endif
1782              mapcs->value[strlen (mapcs->value) - 1] = 0;
1783            }
1784#ifdef DEBUG
1785          if (SetEnvironmentVariable (mapcs->name, mapcs->value) == 0)
1786            {
1787              fflush (stderr);
1788              fprintf (stderr, "setting variable... %s\n", "OK");
1789            }
1790          else
1791            {
1792              fflush (stderr);
1793              fprintf (stderr, "setting variable... %s\n", "OK");
1794            }
1795#else
1796
1797
1798          SetEnvironmentVariable (mapcs->name, mapcs->value);
1799#endif
1800          char *toto =
1801            (char *)
1802            malloc ((strlen (mapcs->name) + strlen (mapcs->value) +
1803                     2) * sizeof (char));
1804          sprintf (toto, "%s=%s", mapcs->name, mapcs->value);
1805          putenv (toto);
1806#ifdef DEBUG
1807          fflush (stderr);
1808#endif
1809#endif
1810#ifdef DEBUG
1811          fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
1812                   mapcs->value);
1813          fflush (stderr);
1814#endif
1815          mapcs = mapcs->next;
1816        }
1817    }
1818
1819#ifdef DEBUG
1820  dumpMap (request_inputs);
1821#endif
1822
1823  map *status = getMap (request_inputs, "status");
1824  if(vid==0){
1825    // Need to check if we need to fork to load a status enabled
1826    r_inputs = NULL;
1827    map *store = getMap (request_inputs, "storeExecuteResponse");
1828    /**
1829     * 05-007r7 WPS 1.0.0 page 57 :
1830     * 'If status="true" and storeExecuteResponse is "false" then the service
1831     * shall raise an exception.'
1832     */
1833    if (status != NULL && strcmp (status->value, "true") == 0 &&
1834        store != NULL && strcmp (store->value, "false") == 0)
1835      {
1836        errorException (m,
1837                        _
1838                        ("The status parameter cannot be set to true if storeExecuteResponse is set to false. Please modify your request parameters."),
1839                        "InvalidParameterValue", "storeExecuteResponse");
1840        freeService (&s1);
1841        free (s1);
1842        freeMaps (&m);
1843        free (m);
1844       
1845        freeMaps (&request_input_real_format);
1846        free (request_input_real_format);
1847       
1848        freeMaps (&request_output_real_format);
1849        free (request_output_real_format);
1850
1851        free (REQUEST);
1852        free (SERVICE_URL);
1853        return 1;
1854      }
1855    r_inputs = getMap (request_inputs, "storeExecuteResponse");
1856  }else{
1857    // Define status depending on the WPS 2.0.0 mode attribute
1858    status = getMap (request_inputs, "mode");
1859    map* mode=getMap(s1->content,"mode");
1860    if(strcasecmp(status->value,"async")==0){
1861      if(mode!=NULL && strcasecmp(mode->value,"async")==0)
1862        addToMap(request_inputs,"status","true");
1863      else{
1864        if(mode!=NULL){
1865          // see ref. http://docs.opengeospatial.org/is/14-065/14-065.html#61
1866          errorException (m,_("The process does not permit the desired execution mode."),"NoSuchMode", mode->value); 
1867          fflush (stdout);
1868          freeMaps (&m);
1869          free (m);
1870          if(zooRegistry!=NULL){
1871            freeRegistry(&zooRegistry);
1872            free(zooRegistry);
1873          }
1874          freeMaps (&request_input_real_format);
1875          free (request_input_real_format);
1876          freeMaps (&request_output_real_format);
1877          free (request_output_real_format);
1878          free (REQUEST);
1879          free (SERVICE_URL);
1880          return 0;
1881        }else
1882          addToMap(request_inputs,"status","true");
1883      }
1884    }
1885    else{
1886      if(strcasecmp(status->value,"auto")==0){
1887        if(mode!=NULL){
1888          if(strcasecmp(mode->value,"async")==0)
1889            addToMap(request_inputs,"status","false");
1890          else
1891            addToMap(request_inputs,"status","true");
1892        }
1893        else
1894          addToMap(request_inputs,"status","false");
1895      }else
1896        addToMap(request_inputs,"status","false");
1897    }
1898    status = getMap (request_inputs, "status");
1899  }
1900
1901  int eres = SERVICE_STARTED;
1902  int cpid = getpid ();
1903
1904  /**
1905   * Initialize the specific [lenv] section which contains runtime variables:
1906   *
1907   *  - usid : it is an unique identification number
1908   *  - sid : it is the process idenfitication number (OS)
1909   *  - uusid : it is an universally unique identification number
1910   *  - status : value between 0 and 100 to express the  completude of
1911   * the operations of the running service
1912   *  - message : is a string where you can store error messages, in case
1913   * service is failing, or o provide details on the ongoing operation.
1914   *  - cwd : is the current working directory
1915   *  - soap : is a boolean value, true if the request was contained in a SOAP
1916   * Envelop
1917   *  - sessid : string storing the session identifier (only when cookie is
1918   * used)
1919   *  - cgiSid : only defined on Window platforms (for being able to identify
1920   * the created process)
1921   *
1922   */
1923  maps *_tmpMaps = (maps *) malloc (MAPS_SIZE);
1924  _tmpMaps->name = zStrdup ("lenv");
1925  char tmpBuff[100];
1926  struct ztimeval tp;
1927  if (zGettimeofday (&tp, NULL) == 0)
1928    sprintf (tmpBuff, "%i", (cpid + ((int) tp.tv_sec + (int) tp.tv_usec)));
1929  else
1930    sprintf (tmpBuff, "%i", (cpid + (int) time (NULL)));
1931  _tmpMaps->content = createMap ("osid", tmpBuff);
1932  _tmpMaps->next = NULL;
1933  sprintf (tmpBuff, "%i", cpid);
1934  addToMap (_tmpMaps->content, "sid", tmpBuff);
1935  char* tmpUuid=get_uuid();
1936  addToMap (_tmpMaps->content, "uusid", tmpUuid);
1937  addToMap (_tmpMaps->content, "usid", tmpUuid);
1938  free(tmpUuid);
1939  addToMap (_tmpMaps->content, "status", "0");
1940  addToMap (_tmpMaps->content, "cwd", ntmp);
1941  addToMap (_tmpMaps->content, "message", _("No message provided"));
1942  map *ltmp = getMap (request_inputs, "soap");
1943  if (ltmp != NULL)
1944    addToMap (_tmpMaps->content, "soap", ltmp->value);
1945  else
1946    addToMap (_tmpMaps->content, "soap", "false");
1947
1948  // Parse the session file and add it to the main maps
1949  if (cgiCookie != NULL && strlen (cgiCookie) > 0)
1950    {
1951      int hasValidCookie = -1;
1952      char *tcook = zStrdup (cgiCookie);
1953      char *tmp = NULL;
1954      map *testing = getMapFromMaps (m, "main", "cookiePrefix");
1955      if (testing == NULL)
1956        {
1957          tmp = zStrdup ("ID=");
1958        }
1959      else
1960        {
1961          tmp =
1962            (char *) malloc ((strlen (testing->value) + 2) * sizeof (char));
1963          sprintf (tmp, "%s=", testing->value);
1964        }
1965      if (strstr (cgiCookie, ";") != NULL)
1966        {
1967          char *token, *saveptr;
1968          token = strtok_r (cgiCookie, ";", &saveptr);
1969          while (token != NULL)
1970            {
1971              if (strcasestr (token, tmp) != NULL)
1972                {
1973                  if (tcook != NULL)
1974                    free (tcook);
1975                  tcook = zStrdup (token);
1976                  hasValidCookie = 1;
1977                }
1978              token = strtok_r (NULL, ";", &saveptr);
1979            }
1980        }
1981      else
1982        {
1983          if (strstr (cgiCookie, "=") != NULL
1984              && strcasestr (cgiCookie, tmp) != NULL)
1985            {
1986              tcook = zStrdup (cgiCookie);
1987              hasValidCookie = 1;
1988            }
1989          if (tmp != NULL)
1990            {
1991              free (tmp);
1992            }
1993        }
1994      if (hasValidCookie > 0)
1995        {
1996          addToMap (_tmpMaps->content, "sessid", strstr (tcook, "=") + 1);
1997          char session_file_path[1024];
1998          map *tmpPath = getMapFromMaps (m, "main", "sessPath");
1999          if (tmpPath == NULL)
2000            tmpPath = getMapFromMaps (m, "main", "tmpPath");
2001          char *tmp1 = strtok (tcook, ";");
2002          if (tmp1 != NULL)
2003            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
2004                     strstr (tmp1, "=") + 1);
2005          else
2006            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
2007                     strstr (cgiCookie, "=") + 1);
2008          free (tcook);
2009          maps *tmpSess = (maps *) malloc (MAPS_SIZE);
2010          struct stat file_status;
2011          int istat = stat (session_file_path, &file_status);
2012          if (istat == 0 && file_status.st_size > 0)
2013            {
2014              conf_read (session_file_path, tmpSess);
2015              addMapsToMaps (&m, tmpSess);
2016              freeMaps (&tmpSess);
2017              free (tmpSess);
2018            }
2019        }
2020    }
2021  addMapsToMaps (&m, _tmpMaps);
2022  freeMaps (&_tmpMaps);
2023  free (_tmpMaps);
2024  maps* bmap=NULL;
2025#ifdef DEBUG
2026  dumpMap (request_inputs);
2027#endif
2028#ifdef WIN32
2029  char *cgiSidL = NULL;
2030  if (getenv ("CGISID") != NULL)
2031    addToMap (request_inputs, "cgiSid", getenv ("CGISID"));
2032
2033  char* usidp;
2034  if ( (usidp = getenv("USID")) != NULL ) {
2035    setMapInMaps (m, "lenv", "usid", usidp);
2036  }
2037
2038  map *test1 = getMap (request_inputs, "cgiSid");
2039  if (test1 != NULL)
2040    {
2041      cgiSid = test1->value;
2042      addToMap (request_inputs, "storeExecuteResponse", "true");
2043      addToMap (request_inputs, "status", "true");
2044      setMapInMaps (m, "lenv", "sid", test1->value);
2045      status = getMap (request_inputs, "status");
2046    }
2047#endif
2048  char *fbkp, *fbkpid, *fbkpres, *fbkp1, *flog;
2049  FILE *f0, *f1;
2050  if (status != NULL)
2051    if (strcasecmp (status->value, "false") == 0)
2052      status = NULLMAP;
2053  if (status == NULLMAP)
2054    {
2055      if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
2056        freeService (&s1);
2057        free (s1);
2058        freeMaps (&m);
2059        free (m);
2060        free (REQUEST);
2061        free (SERVICE_URL);
2062        freeMaps (&request_input_real_format);
2063        free (request_input_real_format);
2064        freeMaps (&request_output_real_format);
2065        free (request_output_real_format);
2066        freeMaps (&tmpmaps);
2067        free (tmpmaps);
2068        return -1;
2069      }
2070
2071      loadServiceAndRun (&m, s1, request_inputs, &request_input_real_format,
2072                         &request_output_real_format, &eres);
2073    }
2074  else
2075    {
2076      int pid;
2077#ifdef DEBUG
2078      fprintf (stderr, "\nPID : %d\n", cpid);
2079#endif
2080
2081#ifndef WIN32
2082      pid = fork ();
2083#else
2084      if (cgiSid == NULL)
2085        {
2086          createProcess (m, request_inputs, s1, NULL, cpid,
2087                         request_input_real_format,
2088                         request_output_real_format);
2089          pid = cpid;
2090        }
2091      else
2092        {
2093          pid = 0;
2094          cpid = atoi (cgiSid);
2095        }
2096#endif
2097      if (pid > 0)
2098        {
2099          /**
2100           * dady :
2101           * set status to SERVICE_ACCEPTED
2102           */
2103#ifdef DEBUG
2104          fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
2105                   getpid ());
2106#endif
2107          eres = SERVICE_ACCEPTED;
2108        }
2109      else if (pid == 0)
2110        {
2111          /**
2112           * son : have to close the stdout, stdin and stderr to let the parent
2113           * process answer to http client.
2114           */
2115          map* usid = getMapFromMaps (m, "lenv", "uusid");
2116          map* tmpm = getMapFromMaps (m, "lenv", "osid");
2117          int cpid = atoi (tmpm->value);
2118          r_inputs = getMapFromMaps (m, "main", "tmpPath");
2119          map* r_inputs1 = createMap("ServiceName", s1->name);
2120
2121          // Create the filename for the result file (.res)
2122          fbkpres =
2123            (char *)
2124            malloc ((strlen (r_inputs->value) +
2125                     strlen (usid->value) + 7) * sizeof (char));
2126          sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
2127          bmap = (maps *) malloc (MAPS_SIZE);
2128          bmap->name=zStrdup("status");
2129          bmap->content=createMap("usid",usid->value);
2130          bmap->next=NULL;
2131          addToMap(bmap->content,"sid",tmpm->value);
2132          addIntToMap(bmap->content,"pid",getpid());
2133         
2134          // Create PID file referencing the OS process identifier
2135          fbkpid =
2136            (char *)
2137            malloc ((strlen (r_inputs->value) +
2138                     strlen (usid->value) + 7) * sizeof (char));
2139          sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
2140
2141          f0 = freopen (fbkpid, "w+", stdout);
2142          fprintf(stdout,"%d",getpid());
2143          fflush(stdout);
2144
2145          // Create SID file referencing the semaphore name
2146          fbkp =
2147            (char *)
2148            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2149                     strlen (usid->value) + 7) * sizeof (char));
2150          sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
2151
2152          FILE* f2 = fopen (fbkp, "w+");
2153          fprintf(f2,"%s",tmpm->value);
2154          fflush(f2);
2155          fclose(f2);
2156          free(fbkp);
2157
2158          fbkp =
2159            (char *)
2160            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2161                     strlen (usid->value) + 7) * sizeof (char));
2162          sprintf (fbkp, "%s/%s_%s.xml", r_inputs->value, r_inputs1->value,
2163                   usid->value);
2164          flog =
2165            (char *)
2166            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2167                     strlen (usid->value) + 13) * sizeof (char));
2168          sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
2169                   r_inputs1->value, usid->value);
2170#ifdef DEBUG
2171          fprintf (stderr, "RUN IN BACKGROUND MODE \n");
2172          fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
2173                   getpid ());
2174          fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
2175#endif
2176          freopen (flog, "w+", stderr);
2177          fflush (stderr);
2178          f0 = freopen (fbkp, "w+", stdout);
2179          rewind (stdout);
2180#ifndef WIN32
2181          fclose (stdin);
2182#endif
2183
2184#ifdef RELY_ON_DB
2185          init_sql(m);
2186          recordServiceStatus(m);
2187#endif
2188          if(vid==0){
2189            /**
2190             * set status to SERVICE_STARTED and flush stdout to ensure full
2191             * content was outputed (the file used to store the ResponseDocument).
2192             * The rewind stdout to restart writing from the bgining of the file,
2193             * this way the data will be updated at the end of the process run.
2194             */
2195            printProcessResponse (m, request_inputs, cpid, s1, r_inputs1->value,
2196                                  SERVICE_STARTED, request_input_real_format,
2197                                  request_output_real_format);
2198            fflush (stdout);
2199#ifdef RELY_ON_DB
2200            recordResponse(m,fbkp);
2201#endif
2202          }
2203
2204          fflush (stderr);
2205
2206          fbkp1 =
2207            (char *)
2208            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2209                     strlen (usid->value) + 13) * sizeof (char));
2210          sprintf (fbkp1, "%s/%s_final_%s.xml", r_inputs->value,
2211                   r_inputs1->value, usid->value);
2212
2213          f1 = freopen (fbkp1, "w+", stdout);
2214
2215          if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
2216            freeService (&s1);
2217            free (s1);
2218            freeMaps (&m);
2219            free (m);
2220            free (REQUEST);
2221            free (SERVICE_URL);
2222            freeMaps (&request_input_real_format);
2223            free (request_input_real_format);
2224            freeMaps (&request_output_real_format);
2225            free (request_output_real_format);
2226            freeMaps (&tmpmaps);
2227            free (tmpmaps);
2228            fflush (stdout);
2229            fflush (stderr);
2230            unhandleStatus (m);
2231            return -1;
2232          }
2233          loadServiceAndRun (&m, s1, request_inputs,
2234                             &request_input_real_format,
2235                             &request_output_real_format, &eres);
2236
2237        }
2238      else
2239        {
2240          /**
2241           * error server don't accept the process need to output a valid
2242           * error response here !!!
2243           */
2244          eres = -1;
2245          errorException (m, _("Unable to run the child process properly"),
2246                          "InternalError", NULL);
2247        }
2248    }
2249
2250#ifdef DEBUG
2251  dumpMaps (request_output_real_format);
2252#endif
2253  if (eres != -1)
2254    outputResponse (s1, request_input_real_format,
2255                    request_output_real_format, request_inputs,
2256                    cpid, m, eres);
2257  fflush (stdout);
2258 
2259  /**
2260   * Ensure that if error occurs when freeing memory, no signal will return
2261   * an ExceptionReport document as the result was already returned to the
2262   * client.
2263   */
2264#ifndef USE_GDB
2265  signal (SIGSEGV, donothing);
2266  signal (SIGTERM, donothing);
2267  signal (SIGINT, donothing);
2268  signal (SIGILL, donothing);
2269  signal (SIGFPE, donothing);
2270  signal (SIGABRT, donothing);
2271#endif
2272  if (((int) getpid ()) != cpid || cgiSid != NULL)
2273    {
2274      fclose (stdout);
2275      //fclose (stderr);
2276      /**
2277       * Dump back the final file fbkp1 to fbkp
2278       */
2279      fclose (f0);
2280      fclose (f1);
2281
2282      FILE *f2 = fopen (fbkp1, "rb");
2283#ifndef RELY_ON_DB
2284      semid lid = getShmLockId (m, 1);
2285      if (lid < 0)
2286        return -1;
2287      lockShm (lid);
2288#endif
2289      fclose(f0);
2290      FILE *f3 = fopen (fbkp, "wb+");
2291      free (fbkp);
2292      fseek (f2, 0, SEEK_END);
2293      long flen = ftell (f2);
2294      fseek (f2, 0, SEEK_SET);
2295      char *tmps1 = (char *) malloc ((flen + 1) * sizeof (char));
2296      fread (tmps1, flen, 1, f2);
2297      fwrite (tmps1, 1, flen, f3);
2298      fclose (f2);
2299      fclose (f3);
2300      unlink (fbkpid);
2301      switch(eres){
2302      default:
2303      case SERVICE_FAILED:
2304        setMapInMaps(bmap,"status","status",wpsStatus[1]);
2305        setMapInMaps(m,"lenv","fstate",wpsStatus[1]);
2306        break;
2307      case SERVICE_SUCCEEDED:
2308        setMapInMaps(bmap,"status","status",wpsStatus[0]);
2309        setMapInMaps(m,"lenv","fstate",wpsStatus[0]);
2310        break;
2311      }
2312#ifndef RELY_ON_DB
2313      dumpMapsToFile(bmap,fbkpres);
2314      removeShmLock (m, 1);
2315#else
2316      recordResponse(m,fbkp1);
2317#endif
2318      freeMaps(&bmap);
2319      free(bmap);
2320      unlink (fbkp1);
2321      unlink (flog);
2322      unhandleStatus (m);
2323      free(fbkpid);
2324      free(fbkpres);
2325      free (flog);
2326      free (fbkp1);
2327      free (tmps1);
2328    }
2329
2330  freeService (&s1);
2331  free (s1);
2332  freeMaps (&m);
2333  free (m);
2334
2335  freeMaps (&request_input_real_format);
2336  free (request_input_real_format);
2337
2338  freeMaps (&request_output_real_format);
2339  free (request_output_real_format);
2340
2341  free (REQUEST);
2342  free (SERVICE_URL);
2343#ifdef DEBUG
2344  fprintf (stderr, "Processed response \n");
2345  fflush (stdout);
2346  fflush (stderr);
2347#endif
2348
2349  if (((int) getpid ()) != cpid || cgiSid != NULL)
2350    {
2351      exit (0);
2352    }
2353
2354  return 0;
2355}
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