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

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

Remove uneeded debug messages

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 65.2 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* version1=getMap(request_inputs,"AcceptVersions");
1198    if(version1!=NULL){
1199      if(strstr(version1->value,schemas[1][0])!=NULL)
1200        addToMap(request_inputs,"version",schemas[1][0]);
1201      else
1202        addToMap(request_inputs,"version",version1->value);
1203      version=getMap(request_inputs,"version");
1204      setMapInMaps(m,"main","rversion",version->value);
1205      vid=getVersionId(version->value);
1206    }
1207  }
1208  if(err!=NULL){
1209    printExceptionReportResponse (m, err);
1210    freeMap(&err);
1211    free(err);
1212    if (count (request_inputs) == 1)
1213      {
1214        freeMap (&request_inputs);
1215        free (request_inputs);
1216      }
1217    free(REQUEST);
1218    freeMaps (&m);
1219    free (m);
1220    return 1;
1221  }
1222
1223  r_inputs = getMap (request_inputs, "serviceprovider");
1224  if (r_inputs == NULL)
1225    {
1226      addToMap (request_inputs, "serviceprovider", "");
1227    }
1228
1229  maps *request_output_real_format = NULL;
1230  map *tmpm = getMapFromMaps (m, "main", "serverAddress");
1231  if (tmpm != NULL)
1232    SERVICE_URL = zStrdup (tmpm->value);
1233  else
1234    SERVICE_URL = zStrdup (DEFAULT_SERVICE_URL);
1235
1236
1237
1238  service *s1;
1239  int scount = 0;
1240#ifdef DEBUG
1241  dumpMap (r_inputs);
1242#endif
1243  char conf_dir[1024];
1244  int t;
1245  char tmps1[1024];
1246
1247  r_inputs = NULL;
1248  r_inputs = getMap (request_inputs, "metapath");
1249 
1250  if (r_inputs != NULL)
1251    snprintf (conf_dir, 1024, "%s/%s", ntmp, r_inputs->value);
1252  else
1253    snprintf (conf_dir, 1024, "%s", ntmp);
1254
1255  map* reg = getMapFromMaps (m, "main", "registry");
1256  registry* zooRegistry=NULL;
1257  if(reg!=NULL){
1258    int saved_stdout = dup (fileno (stdout));
1259    dup2 (fileno (stderr), fileno (stdout));
1260    createRegistry (m,&zooRegistry,reg->value,saved_stdout);
1261    dup2 (saved_stdout, fileno (stdout));
1262  }
1263
1264  if (strncasecmp (REQUEST, "GetCapabilities", 15) == 0)
1265    {
1266#ifdef DEBUG
1267      dumpMap (r_inputs);
1268#endif
1269      xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
1270      xmlNodePtr n=printGetCapabilitiesHeader(doc,m,(version!=NULL?version->value:"1.0.0"));
1271      /**
1272       * Here we need to close stdout to ensure that unsupported chars
1273       * has been found in the zcfg and then printed on stdout
1274       */
1275      int saved_stdout = dup (fileno (stdout));
1276      dup2 (fileno (stderr), fileno (stdout));
1277      if (int res =               
1278          recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
1279                          printGetCapabilitiesForProcess) < 0)
1280        {
1281          freeMaps (&m);
1282          free (m);
1283          if(zooRegistry!=NULL){
1284            freeRegistry(&zooRegistry);
1285            free(zooRegistry);
1286          }
1287          free (REQUEST);
1288          free (SERVICE_URL);
1289          fflush (stdout);
1290          return res;
1291        }
1292      fflush (stdout);
1293      dup2 (saved_stdout, fileno (stdout));
1294      printDocument (m, doc, getpid ());
1295      freeMaps (&m);
1296      free (m);
1297      if(zooRegistry!=NULL){
1298        freeRegistry(&zooRegistry);
1299        free(zooRegistry);
1300      }
1301      free (REQUEST);
1302      free (SERVICE_URL);
1303      fflush (stdout);
1304      return 0;
1305    }
1306  else
1307    {
1308      r_inputs = getMap (request_inputs, "JobId");
1309      if(reqId>nbReqIdentifier){
1310        if (strncasecmp (REQUEST, "GetStatus", strlen(REQUEST)) == 0 ||
1311            strncasecmp (REQUEST, "GetResult", strlen(REQUEST)) == 0){
1312          runGetStatus(m,r_inputs->value,REQUEST);
1313          freeMaps (&m);
1314          free (m);
1315          if(zooRegistry!=NULL){
1316            freeRegistry(&zooRegistry);
1317            free(zooRegistry);
1318          }
1319          free (REQUEST);
1320          free (SERVICE_URL);
1321          return 0;
1322        }
1323        else
1324          if (strncasecmp (REQUEST, "Dismiss", strlen(REQUEST)) == 0){
1325            runDismiss(m,r_inputs->value);
1326            freeMaps (&m);
1327            free (m);
1328            if(zooRegistry!=NULL){
1329              freeRegistry(&zooRegistry);
1330              free(zooRegistry);
1331            }
1332            free (REQUEST);
1333            free (SERVICE_URL);
1334            return 0;
1335           
1336          }
1337        return 0;
1338      }
1339      if(reqId<=nbReqIdentifier){
1340        r_inputs = getMap (request_inputs, "Identifier");
1341
1342        struct dirent *dp;
1343        DIR *dirp = opendir (conf_dir);
1344        if (dirp == NULL)
1345          {
1346            errorException (m, _("The specified path path does not exist."),
1347                            "InvalidParameterValue", conf_dir);
1348            freeMaps (&m);
1349            free (m);
1350            if(zooRegistry!=NULL){
1351              freeRegistry(&zooRegistry);
1352              free(zooRegistry);
1353            }
1354            free (REQUEST);
1355            free (SERVICE_URL);
1356            return 0;
1357          }
1358        if (strncasecmp (REQUEST, "DescribeProcess", 15) == 0)
1359          {
1360            /**
1361             * Loop over Identifier list
1362             */
1363            xmlDocPtr doc = xmlNewDoc (BAD_CAST "1.0");
1364            r_inputs = NULL;
1365            r_inputs = getMap (request_inputs, "version");
1366            xmlNodePtr n = printWPSHeader(doc,m,"DescribeProcess",
1367                                          root_nodes[vid][1],(version!=NULL?version->value:"1.0.0"),1);
1368
1369            r_inputs = getMap (request_inputs, "Identifier");
1370
1371            char *orig = zStrdup (r_inputs->value);
1372
1373            int saved_stdout = dup (fileno (stdout));
1374            dup2 (fileno (stderr), fileno (stdout));
1375            if (strcasecmp ("all", orig) == 0)
1376              {
1377                if (int res =
1378                    recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
1379                                    printDescribeProcessForProcess) < 0)
1380                  return res;
1381              }
1382            else
1383              {
1384                char *saveptr;
1385                char *tmps = strtok_r (orig, ",", &saveptr);
1386
1387                char buff[256];
1388                char buff1[1024];
1389                while (tmps != NULL)
1390                  {
1391                    int hasVal = -1;
1392                    char *corig = zStrdup (tmps);
1393                    if (strstr (corig, ".") != NULL)
1394                      {
1395
1396                        parseIdentifier (m, conf_dir, corig, buff1);
1397                        map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
1398                        if (tmpMap != NULL)
1399                          addToMap (request_inputs, "metapath", tmpMap->value);
1400                        map *tmpMapI = getMapFromMaps (m, "lenv", "Identifier");
1401
1402                        s1 = (service *) malloc (SERVICE_SIZE);
1403                        t = readServiceFile (m, buff1, &s1, tmpMapI->value);
1404                        if (t < 0)
1405                          {
1406                            map *tmp00 = getMapFromMaps (m, "lenv", "message");
1407                            char tmp01[1024];
1408                            if (tmp00 != NULL)
1409                              sprintf (tmp01,
1410                                       _
1411                                       ("Unable to parse the ZCFG file for the following ZOO-Service: %s. Message: %s"),
1412                                       tmps, tmp00->value);
1413                            else
1414                              sprintf (tmp01,
1415                                       _
1416                                       ("Unable to parse the ZCFG file for the following ZOO-Service: %s."),
1417                                       tmps);
1418                            dup2 (saved_stdout, fileno (stdout));
1419                            errorException (m, tmp01, "InvalidParameterValue",
1420                                            "identifier");
1421                            freeMaps (&m);
1422                            free (m);
1423                            if(zooRegistry!=NULL){
1424                              freeRegistry(&zooRegistry);
1425                              free(zooRegistry);
1426                            }
1427                            free (REQUEST);
1428                            free (corig);
1429                            free (orig);
1430                            free (SERVICE_URL);
1431                            free (s1);
1432                            closedir (dirp);
1433                            xmlFreeDoc (doc);
1434                            xmlCleanupParser ();
1435                            zooXmlCleanupNs ();
1436                            return 1;
1437                          }
1438#ifdef DEBUG
1439                        dumpService (s1);
1440#endif
1441                        inheritance(zooRegistry,&s1);
1442                        printDescribeProcessForProcess (m, n, s1);
1443                        freeService (&s1);
1444                        free (s1);
1445                        s1 = NULL;
1446                        scount++;
1447                        hasVal = 1;
1448                        setMapInMaps (m, "lenv", "level", "0");
1449                      }
1450                    else
1451                      {
1452                        memset (buff, 0, 256);
1453                        snprintf (buff, 256, "%s.zcfg", corig);
1454                        memset (buff1, 0, 1024);
1455#ifdef DEBUG
1456                        printf ("\n#######%s\n########\n", buff);
1457#endif
1458                        while ((dp = readdir (dirp)) != NULL)
1459                          {
1460                            if (strcasecmp (dp->d_name, buff) == 0)
1461                              {
1462                                memset (buff1, 0, 1024);
1463                                snprintf (buff1, 1024, "%s/%s", conf_dir,
1464                                          dp->d_name);
1465                                s1 = (service *) malloc (SERVICE_SIZE);
1466                                if (s1 == NULL)
1467                                  {
1468                                    dup2 (saved_stdout, fileno (stdout));
1469                                    return errorException (m,
1470                                                           _
1471                                                           ("Unable to allocate memory."),
1472                                                           "InternalError",
1473                                                           NULL);
1474                                  }
1475#ifdef DEBUG
1476                                printf
1477                                  ("#################\n(%s) %s\n#################\n",
1478                                   r_inputs->value, buff1);
1479#endif
1480                                char *tmp0 = zStrdup (dp->d_name);
1481                                tmp0[strlen (tmp0) - 5] = 0;
1482                                t = readServiceFile (m, buff1, &s1, tmp0);
1483                                free (tmp0);
1484                                if (t < 0)
1485                                  {
1486                                    map *tmp00 =
1487                                      getMapFromMaps (m, "lenv", "message");
1488                                    char tmp01[1024];
1489                                    if (tmp00 != NULL)
1490                                      sprintf (tmp01,
1491                                               _
1492                                               ("Unable to parse the ZCFG file: %s (%s)"),
1493                                               dp->d_name, tmp00->value);
1494                                    else
1495                                      sprintf (tmp01,
1496                                               _
1497                                               ("Unable to parse the ZCFG file: %s."),
1498                                               dp->d_name);
1499                                    dup2 (saved_stdout, fileno (stdout));
1500                                    errorException (m, tmp01, "InternalError",
1501                                                    NULL);
1502                                    freeMaps (&m);
1503                                    free (m);
1504                                    if(zooRegistry!=NULL){
1505                                      freeRegistry(&zooRegistry);
1506                                      free(zooRegistry);
1507                                    }
1508                                    free (orig);
1509                                    free (REQUEST);
1510                                    closedir (dirp);
1511                                    xmlFreeDoc (doc);
1512                                    xmlCleanupParser ();
1513                                    zooXmlCleanupNs ();
1514                                    return 1;
1515                                  }
1516#ifdef DEBUG
1517                                dumpService (s1);
1518#endif
1519                                inheritance(zooRegistry,&s1);
1520                                printDescribeProcessForProcess (m, n, s1);
1521                                freeService (&s1);
1522                                free (s1);
1523                                s1 = NULL;
1524                                scount++;
1525                                hasVal = 1;
1526                              }
1527                          }
1528                      }
1529                    if (hasVal < 0)
1530                      {
1531                        map *tmp00 = getMapFromMaps (m, "lenv", "message");
1532                        char tmp01[1024];
1533                        if (tmp00 != NULL)
1534                          sprintf (tmp01,
1535                                   _("Unable to parse the ZCFG file: %s (%s)"),
1536                                   buff, tmp00->value);
1537                        else
1538                          sprintf (tmp01,
1539                                   _("Unable to parse the ZCFG file: %s."),
1540                                   buff);
1541                        dup2 (saved_stdout, fileno (stdout));
1542                        errorException (m, tmp01, "InvalidParameterValue",
1543                                        "Identifier");
1544                        freeMaps (&m);
1545                        free (m);
1546                        if(zooRegistry!=NULL){
1547                          freeRegistry(&zooRegistry);
1548                          free(zooRegistry);
1549                        }
1550                        free (orig);
1551                        free (REQUEST);
1552                        closedir (dirp);
1553                        xmlFreeDoc (doc);
1554                        xmlCleanupParser ();
1555                        zooXmlCleanupNs ();
1556                        return 1;
1557                      }
1558                    rewinddir (dirp);
1559                    tmps = strtok_r (NULL, ",", &saveptr);
1560                    if (corig != NULL)
1561                      free (corig);
1562                  }
1563              }
1564            closedir (dirp);
1565            fflush (stdout);
1566            dup2 (saved_stdout, fileno (stdout));
1567            free (orig);
1568            printDocument (m, doc, getpid ());
1569            freeMaps (&m);
1570            free (m);
1571            if(zooRegistry!=NULL){
1572              freeRegistry(&zooRegistry);
1573              free(zooRegistry);
1574            }
1575            free (REQUEST);
1576            free (SERVICE_URL);
1577            fflush (stdout);
1578            return 0;
1579          }
1580        else if (strncasecmp (REQUEST, "Execute", strlen (REQUEST)) != 0)
1581          {
1582            map* version=getMapFromMaps(m,"main","rversion");
1583            int vid=getVersionId(version->value);
1584            int len,j=0;
1585            for(j=0;j<nbSupportedRequests;j++){
1586              if(requests[vid][j]!=NULL)
1587                len+=strlen(requests[vid][j])+2;
1588              else{
1589                len+=4;
1590                break;
1591              }
1592            }
1593            char *tmpStr=(char*)malloc(len*sizeof(char));
1594            int it=0;
1595            for(j=0;j<nbSupportedRequests;j++){
1596              if(requests[vid][j]!=NULL){
1597                if(it==0){
1598                  sprintf(tmpStr,"%s",requests[vid][j]);
1599                  it++;
1600                }else{
1601                  char *tmpS=zStrdup(tmpStr);
1602                  if(j+1<nbSupportedRequests && requests[vid][j+1]==NULL){
1603                    sprintf(tmpStr,"%s and %s",tmpS,requests[vid][j]);
1604                  }else{
1605                    sprintf(tmpStr,"%s, %s",tmpS,requests[vid][j]);
1606                 
1607                  }
1608                  free(tmpS);
1609                }
1610              }
1611              else{
1612                len+=4;
1613                break;
1614              }
1615            }
1616            char* message=(char*)malloc((61+len)*sizeof(char));
1617            sprintf(message,"The <request> value was not recognized. Allowed values are %s.",tmpStr);
1618            errorException (m,_(message),"InvalidParameterValue", "request");
1619#ifdef DEBUG
1620            fprintf (stderr, "No request found %s", REQUEST);
1621#endif
1622            closedir (dirp);
1623            freeMaps (&m);
1624            free (m);
1625            if(zooRegistry!=NULL){
1626              freeRegistry(&zooRegistry);
1627              free(zooRegistry);
1628            }
1629            free (REQUEST);
1630            free (SERVICE_URL);
1631            fflush (stdout);
1632            return 0;
1633          }
1634        closedir (dirp);
1635      }
1636    }
1637
1638  map *postRequest = NULL;
1639  postRequest = getMap (request_inputs, "xrequest");
1640
1641  if(vid==1 && postRequest==NULL){
1642    errorException (m,_("Unable to run Execute request using the GET HTTP method"),"InvalidParameterValue", "request"); 
1643    freeMaps (&m);
1644    free (m);
1645    if(zooRegistry!=NULL){
1646      freeRegistry(&zooRegistry);
1647      free(zooRegistry);
1648    }
1649    free (REQUEST);
1650    free (SERVICE_URL);
1651    fflush (stdout);
1652    return 0;
1653  }
1654 
1655  s1 = NULL;
1656  s1 = (service *) malloc (SERVICE_SIZE);
1657  if (s1 == NULL)
1658    {
1659      freeMaps (&m);
1660      free (m);
1661      if(zooRegistry!=NULL){
1662        freeRegistry(&zooRegistry);
1663        free(zooRegistry);
1664      }
1665      free (REQUEST);
1666      free (SERVICE_URL);
1667      return errorException (m, _("Unable to allocate memory."),
1668                             "InternalError", NULL);
1669    }
1670
1671  r_inputs = getMap (request_inputs, "MetaPath");
1672  if (r_inputs != NULL)
1673    snprintf (tmps1, 1024, "%s/%s", ntmp, r_inputs->value);
1674  else
1675    snprintf (tmps1, 1024, "%s/", ntmp);
1676  r_inputs = getMap (request_inputs, "Identifier");
1677  char *ttmp = zStrdup (tmps1);
1678  snprintf (tmps1, 1024, "%s/%s.zcfg", ttmp, r_inputs->value);
1679  free (ttmp);
1680#ifdef DEBUG
1681  fprintf (stderr, "Trying to load %s\n", tmps1);
1682#endif
1683  if (strstr (r_inputs->value, ".") != NULL)
1684    {
1685      char *identifier = zStrdup (r_inputs->value);
1686      parseIdentifier (m, conf_dir, identifier, tmps1);
1687      map *tmpMap = getMapFromMaps (m, "lenv", "metapath");
1688      if (tmpMap != NULL)
1689        addToMap (request_inputs, "metapath", tmpMap->value);
1690      free (identifier);
1691    }
1692  else
1693    {
1694      setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
1695      setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
1696    }
1697
1698  r_inputs = getMapFromMaps (m, "lenv", "Identifier");
1699  int saved_stdout = dup (fileno (stdout));
1700  dup2 (fileno (stderr), fileno (stdout));
1701  t = readServiceFile (m, tmps1, &s1, r_inputs->value);
1702  inheritance(zooRegistry,&s1);
1703  if(zooRegistry!=NULL){
1704    freeRegistry(&zooRegistry);
1705    free(zooRegistry);
1706  }
1707  fflush (stdout);
1708  dup2 (saved_stdout, fileno (stdout));
1709  if (t < 0)
1710    {
1711      char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
1712      sprintf (tmpMsg,
1713               _
1714               ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
1715               r_inputs->value);
1716      errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
1717      free (tmpMsg);
1718      free (s1);
1719      freeMaps (&m);
1720      free (m);
1721      free (REQUEST);
1722      free (SERVICE_URL);
1723      return 0;
1724    }
1725  close (saved_stdout);
1726
1727#ifdef DEBUG
1728  dumpService (s1);
1729#endif
1730  int j;
1731
1732
1733  /**
1734   * Create the input and output maps data structure
1735   */
1736  int i = 0;
1737  HINTERNET hInternet;
1738  HINTERNET res;
1739  hInternet = InternetOpen (
1740#ifndef WIN32
1741                            (LPCTSTR)
1742#endif
1743                            "ZooWPSClient\0",
1744                            INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
1745
1746#ifndef WIN32
1747  if (!CHECK_INET_HANDLE (hInternet))
1748    fprintf (stderr, "WARNING : hInternet handle failed to initialize");
1749#endif
1750  maps *request_input_real_format = NULL;
1751  maps *tmpmaps = request_input_real_format;
1752
1753
1754  if(parseRequest(&m,&request_inputs,s1,&request_input_real_format,&request_output_real_format,&hInternet)<0){
1755    freeMaps (&m);
1756    free (m);
1757    free (REQUEST);
1758    free (SERVICE_URL);
1759    InternetCloseHandle (&hInternet);
1760    freeService (&s1);
1761    free (s1);
1762    return 0;
1763  }
1764
1765
1766  // Define each env variable in runing environment
1767  maps *curs = getMaps (m, "env");
1768  if (curs != NULL)
1769    {
1770      map *mapcs = curs->content;
1771      while (mapcs != NULLMAP)
1772        {
1773#ifndef WIN32
1774          setenv (mapcs->name, mapcs->value, 1);
1775#else
1776#ifdef DEBUG
1777          fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
1778                   mapcs->value);
1779#endif
1780          if (mapcs->value[strlen (mapcs->value) - 2] == '\r')
1781            {
1782#ifdef DEBUG
1783              fprintf (stderr, "[ZOO: Env var finish with \r]\n");
1784#endif
1785              mapcs->value[strlen (mapcs->value) - 1] = 0;
1786            }
1787#ifdef DEBUG
1788          if (SetEnvironmentVariable (mapcs->name, mapcs->value) == 0)
1789            {
1790              fflush (stderr);
1791              fprintf (stderr, "setting variable... %s\n", "OK");
1792            }
1793          else
1794            {
1795              fflush (stderr);
1796              fprintf (stderr, "setting variable... %s\n", "OK");
1797            }
1798#else
1799
1800
1801          SetEnvironmentVariable (mapcs->name, mapcs->value);
1802#endif
1803          char *toto =
1804            (char *)
1805            malloc ((strlen (mapcs->name) + strlen (mapcs->value) +
1806                     2) * sizeof (char));
1807          sprintf (toto, "%s=%s", mapcs->name, mapcs->value);
1808          putenv (toto);
1809#ifdef DEBUG
1810          fflush (stderr);
1811#endif
1812#endif
1813#ifdef DEBUG
1814          fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
1815                   mapcs->value);
1816          fflush (stderr);
1817#endif
1818          mapcs = mapcs->next;
1819        }
1820    }
1821
1822#ifdef DEBUG
1823  dumpMap (request_inputs);
1824#endif
1825
1826  map *status = getMap (request_inputs, "status");
1827  if(vid==0){
1828    // Need to check if we need to fork to load a status enabled
1829    r_inputs = NULL;
1830    map *store = getMap (request_inputs, "storeExecuteResponse");
1831    /**
1832     * 05-007r7 WPS 1.0.0 page 57 :
1833     * 'If status="true" and storeExecuteResponse is "false" then the service
1834     * shall raise an exception.'
1835     */
1836    if (status != NULL && strcmp (status->value, "true") == 0 &&
1837        store != NULL && strcmp (store->value, "false") == 0)
1838      {
1839        errorException (m,
1840                        _
1841                        ("The status parameter cannot be set to true if storeExecuteResponse is set to false. Please modify your request parameters."),
1842                        "InvalidParameterValue", "storeExecuteResponse");
1843        freeService (&s1);
1844        free (s1);
1845        freeMaps (&m);
1846        free (m);
1847       
1848        freeMaps (&request_input_real_format);
1849        free (request_input_real_format);
1850       
1851        freeMaps (&request_output_real_format);
1852        free (request_output_real_format);
1853
1854        free (REQUEST);
1855        free (SERVICE_URL);
1856        return 1;
1857      }
1858    r_inputs = getMap (request_inputs, "storeExecuteResponse");
1859  }else{
1860    // Define status depending on the WPS 2.0.0 mode attribute
1861    status = getMap (request_inputs, "mode");
1862    map* mode=getMap(s1->content,"mode");
1863    if(strcasecmp(status->value,"async")==0){
1864      if(mode!=NULL && strcasecmp(mode->value,"async")==0)
1865        addToMap(request_inputs,"status","true");
1866      else{
1867        if(mode!=NULL){
1868          // see ref. http://docs.opengeospatial.org/is/14-065/14-065.html#61
1869          errorException (m,_("The process does not permit the desired execution mode."),"NoSuchMode", mode->value); 
1870          fflush (stdout);
1871          freeMaps (&m);
1872          free (m);
1873          if(zooRegistry!=NULL){
1874            freeRegistry(&zooRegistry);
1875            free(zooRegistry);
1876          }
1877          freeMaps (&request_input_real_format);
1878          free (request_input_real_format);
1879          freeMaps (&request_output_real_format);
1880          free (request_output_real_format);
1881          free (REQUEST);
1882          free (SERVICE_URL);
1883          return 0;
1884        }else
1885          addToMap(request_inputs,"status","true");
1886      }
1887    }
1888    else{
1889      if(strcasecmp(status->value,"auto")==0){
1890        if(mode!=NULL){
1891          if(strcasecmp(mode->value,"async")==0)
1892            addToMap(request_inputs,"status","false");
1893          else
1894            addToMap(request_inputs,"status","true");
1895        }
1896        else
1897          addToMap(request_inputs,"status","false");
1898      }else
1899        addToMap(request_inputs,"status","false");
1900    }
1901    status = getMap (request_inputs, "status");
1902  }
1903
1904  int eres = SERVICE_STARTED;
1905  int cpid = getpid ();
1906
1907  /**
1908   * Initialize the specific [lenv] section which contains runtime variables:
1909   *
1910   *  - usid : it is an unique identification number
1911   *  - sid : it is the process idenfitication number (OS)
1912   *  - uusid : it is an universally unique identification number
1913   *  - status : value between 0 and 100 to express the  completude of
1914   * the operations of the running service
1915   *  - message : is a string where you can store error messages, in case
1916   * service is failing, or o provide details on the ongoing operation.
1917   *  - cwd : is the current working directory
1918   *  - soap : is a boolean value, true if the request was contained in a SOAP
1919   * Envelop
1920   *  - sessid : string storing the session identifier (only when cookie is
1921   * used)
1922   *  - cgiSid : only defined on Window platforms (for being able to identify
1923   * the created process)
1924   *
1925   */
1926  maps *_tmpMaps = (maps *) malloc (MAPS_SIZE);
1927  _tmpMaps->name = zStrdup ("lenv");
1928  char tmpBuff[100];
1929  struct ztimeval tp;
1930  if (zGettimeofday (&tp, NULL) == 0)
1931    sprintf (tmpBuff, "%i", (cpid + ((int) tp.tv_sec + (int) tp.tv_usec)));
1932  else
1933    sprintf (tmpBuff, "%i", (cpid + (int) time (NULL)));
1934  _tmpMaps->content = createMap ("osid", tmpBuff);
1935  _tmpMaps->next = NULL;
1936  sprintf (tmpBuff, "%i", cpid);
1937  addToMap (_tmpMaps->content, "sid", tmpBuff);
1938  char* tmpUuid=get_uuid();
1939  addToMap (_tmpMaps->content, "uusid", tmpUuid);
1940  addToMap (_tmpMaps->content, "usid", tmpUuid);
1941  free(tmpUuid);
1942  addToMap (_tmpMaps->content, "status", "0");
1943  addToMap (_tmpMaps->content, "cwd", ntmp);
1944  addToMap (_tmpMaps->content, "message", _("No message provided"));
1945  map *ltmp = getMap (request_inputs, "soap");
1946  if (ltmp != NULL)
1947    addToMap (_tmpMaps->content, "soap", ltmp->value);
1948  else
1949    addToMap (_tmpMaps->content, "soap", "false");
1950
1951  // Parse the session file and add it to the main maps
1952  if (cgiCookie != NULL && strlen (cgiCookie) > 0)
1953    {
1954      int hasValidCookie = -1;
1955      char *tcook = zStrdup (cgiCookie);
1956      char *tmp = NULL;
1957      map *testing = getMapFromMaps (m, "main", "cookiePrefix");
1958      if (testing == NULL)
1959        {
1960          tmp = zStrdup ("ID=");
1961        }
1962      else
1963        {
1964          tmp =
1965            (char *) malloc ((strlen (testing->value) + 2) * sizeof (char));
1966          sprintf (tmp, "%s=", testing->value);
1967        }
1968      if (strstr (cgiCookie, ";") != NULL)
1969        {
1970          char *token, *saveptr;
1971          token = strtok_r (cgiCookie, ";", &saveptr);
1972          while (token != NULL)
1973            {
1974              if (strcasestr (token, tmp) != NULL)
1975                {
1976                  if (tcook != NULL)
1977                    free (tcook);
1978                  tcook = zStrdup (token);
1979                  hasValidCookie = 1;
1980                }
1981              token = strtok_r (NULL, ";", &saveptr);
1982            }
1983        }
1984      else
1985        {
1986          if (strstr (cgiCookie, "=") != NULL
1987              && strcasestr (cgiCookie, tmp) != NULL)
1988            {
1989              tcook = zStrdup (cgiCookie);
1990              hasValidCookie = 1;
1991            }
1992          if (tmp != NULL)
1993            {
1994              free (tmp);
1995            }
1996        }
1997      if (hasValidCookie > 0)
1998        {
1999          addToMap (_tmpMaps->content, "sessid", strstr (tcook, "=") + 1);
2000          char session_file_path[1024];
2001          map *tmpPath = getMapFromMaps (m, "main", "sessPath");
2002          if (tmpPath == NULL)
2003            tmpPath = getMapFromMaps (m, "main", "tmpPath");
2004          char *tmp1 = strtok (tcook, ";");
2005          if (tmp1 != NULL)
2006            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
2007                     strstr (tmp1, "=") + 1);
2008          else
2009            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
2010                     strstr (cgiCookie, "=") + 1);
2011          free (tcook);
2012          maps *tmpSess = (maps *) malloc (MAPS_SIZE);
2013          struct stat file_status;
2014          int istat = stat (session_file_path, &file_status);
2015          if (istat == 0 && file_status.st_size > 0)
2016            {
2017              conf_read (session_file_path, tmpSess);
2018              addMapsToMaps (&m, tmpSess);
2019              freeMaps (&tmpSess);
2020              free (tmpSess);
2021            }
2022        }
2023    }
2024  addMapsToMaps (&m, _tmpMaps);
2025  freeMaps (&_tmpMaps);
2026  free (_tmpMaps);
2027  maps* bmap=NULL;
2028#ifdef DEBUG
2029  dumpMap (request_inputs);
2030#endif
2031#ifdef WIN32
2032  char *cgiSidL = NULL;
2033  if (getenv ("CGISID") != NULL)
2034    addToMap (request_inputs, "cgiSid", getenv ("CGISID"));
2035
2036  char* usidp;
2037  if ( (usidp = getenv("USID")) != NULL ) {
2038    setMapInMaps (m, "lenv", "usid", usidp);
2039  }
2040
2041  map *test1 = getMap (request_inputs, "cgiSid");
2042  if (test1 != NULL)
2043    {
2044      cgiSid = test1->value;
2045      addToMap (request_inputs, "storeExecuteResponse", "true");
2046      addToMap (request_inputs, "status", "true");
2047      setMapInMaps (m, "lenv", "sid", test1->value);
2048      status = getMap (request_inputs, "status");
2049    }
2050#endif
2051  char *fbkp, *fbkpid, *fbkpres, *fbkp1, *flog;
2052  FILE *f0, *f1;
2053  if (status != NULL)
2054    if (strcasecmp (status->value, "false") == 0)
2055      status = NULLMAP;
2056  if (status == NULLMAP)
2057    {
2058      if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
2059        freeService (&s1);
2060        free (s1);
2061        freeMaps (&m);
2062        free (m);
2063        free (REQUEST);
2064        free (SERVICE_URL);
2065        freeMaps (&request_input_real_format);
2066        free (request_input_real_format);
2067        freeMaps (&request_output_real_format);
2068        free (request_output_real_format);
2069        freeMaps (&tmpmaps);
2070        free (tmpmaps);
2071        return -1;
2072      }
2073
2074      loadServiceAndRun (&m, s1, request_inputs, &request_input_real_format,
2075                         &request_output_real_format, &eres);
2076    }
2077  else
2078    {
2079      int pid;
2080#ifdef DEBUG
2081      fprintf (stderr, "\nPID : %d\n", cpid);
2082#endif
2083
2084#ifndef WIN32
2085      pid = fork ();
2086#else
2087      if (cgiSid == NULL)
2088        {
2089          createProcess (m, request_inputs, s1, NULL, cpid,
2090                         request_input_real_format,
2091                         request_output_real_format);
2092          pid = cpid;
2093        }
2094      else
2095        {
2096          pid = 0;
2097          cpid = atoi (cgiSid);
2098        }
2099#endif
2100      if (pid > 0)
2101        {
2102          /**
2103           * dady :
2104           * set status to SERVICE_ACCEPTED
2105           */
2106#ifdef DEBUG
2107          fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
2108                   getpid ());
2109#endif
2110          eres = SERVICE_ACCEPTED;
2111        }
2112      else if (pid == 0)
2113        {
2114          /**
2115           * son : have to close the stdout, stdin and stderr to let the parent
2116           * process answer to http client.
2117           */
2118          map* usid = getMapFromMaps (m, "lenv", "uusid");
2119          map* tmpm = getMapFromMaps (m, "lenv", "osid");
2120          int cpid = atoi (tmpm->value);
2121          r_inputs = getMapFromMaps (m, "main", "tmpPath");
2122          map* r_inputs1 = createMap("ServiceName", s1->name);
2123
2124          // Create the filename for the result file (.res)
2125          fbkpres =
2126            (char *)
2127            malloc ((strlen (r_inputs->value) +
2128                     strlen (usid->value) + 7) * sizeof (char));
2129          sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
2130          bmap = (maps *) malloc (MAPS_SIZE);
2131          bmap->name=zStrdup("status");
2132          bmap->content=createMap("usid",usid->value);
2133          bmap->next=NULL;
2134          addToMap(bmap->content,"sid",tmpm->value);
2135          addIntToMap(bmap->content,"pid",getpid());
2136         
2137          // Create PID file referencing the OS process identifier
2138          fbkpid =
2139            (char *)
2140            malloc ((strlen (r_inputs->value) +
2141                     strlen (usid->value) + 7) * sizeof (char));
2142          sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
2143
2144          f0 = freopen (fbkpid, "w+", stdout);
2145          fprintf(stdout,"%d",getpid());
2146          fflush(stdout);
2147
2148          // Create SID file referencing the semaphore name
2149          fbkp =
2150            (char *)
2151            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2152                     strlen (usid->value) + 7) * sizeof (char));
2153          sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
2154
2155          FILE* f2 = fopen (fbkp, "w+");
2156          fprintf(f2,"%s",tmpm->value);
2157          fflush(f2);
2158          fclose(f2);
2159          free(fbkp);
2160
2161          fbkp =
2162            (char *)
2163            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2164                     strlen (usid->value) + 7) * sizeof (char));
2165          sprintf (fbkp, "%s/%s_%s.xml", r_inputs->value, r_inputs1->value,
2166                   usid->value);
2167          flog =
2168            (char *)
2169            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2170                     strlen (usid->value) + 13) * sizeof (char));
2171          sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
2172                   r_inputs1->value, usid->value);
2173#ifdef DEBUG
2174          fprintf (stderr, "RUN IN BACKGROUND MODE \n");
2175          fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
2176                   getpid ());
2177          fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
2178#endif
2179          freopen (flog, "w+", stderr);
2180          fflush (stderr);
2181          f0 = freopen (fbkp, "w+", stdout);
2182          rewind (stdout);
2183#ifndef WIN32
2184          fclose (stdin);
2185#endif
2186
2187#ifdef RELY_ON_DB
2188          init_sql(m);
2189          recordServiceStatus(m);
2190#endif
2191          if(vid==0){
2192            /**
2193             * set status to SERVICE_STARTED and flush stdout to ensure full
2194             * content was outputed (the file used to store the ResponseDocument).
2195             * The rewind stdout to restart writing from the bgining of the file,
2196             * this way the data will be updated at the end of the process run.
2197             */
2198            printProcessResponse (m, request_inputs, cpid, s1, r_inputs1->value,
2199                                  SERVICE_STARTED, request_input_real_format,
2200                                  request_output_real_format);
2201            fflush (stdout);
2202#ifdef RELY_ON_DB
2203            recordResponse(m,fbkp);
2204#endif
2205          }
2206
2207          fflush (stderr);
2208
2209          fbkp1 =
2210            (char *)
2211            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
2212                     strlen (usid->value) + 13) * sizeof (char));
2213          sprintf (fbkp1, "%s/%s_final_%s.xml", r_inputs->value,
2214                   r_inputs1->value, usid->value);
2215
2216          f1 = freopen (fbkp1, "w+", stdout);
2217
2218          if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
2219            freeService (&s1);
2220            free (s1);
2221            freeMaps (&m);
2222            free (m);
2223            free (REQUEST);
2224            free (SERVICE_URL);
2225            freeMaps (&request_input_real_format);
2226            free (request_input_real_format);
2227            freeMaps (&request_output_real_format);
2228            free (request_output_real_format);
2229            freeMaps (&tmpmaps);
2230            free (tmpmaps);
2231            fflush (stdout);
2232            fflush (stderr);
2233            unhandleStatus (m);
2234            return -1;
2235          }
2236          loadServiceAndRun (&m, s1, request_inputs,
2237                             &request_input_real_format,
2238                             &request_output_real_format, &eres);
2239
2240        }
2241      else
2242        {
2243          /**
2244           * error server don't accept the process need to output a valid
2245           * error response here !!!
2246           */
2247          eres = -1;
2248          errorException (m, _("Unable to run the child process properly"),
2249                          "InternalError", NULL);
2250        }
2251    }
2252
2253#ifdef DEBUG
2254  dumpMaps (request_output_real_format);
2255#endif
2256  if (eres != -1)
2257    outputResponse (s1, request_input_real_format,
2258                    request_output_real_format, request_inputs,
2259                    cpid, m, eres);
2260  fflush (stdout);
2261 
2262  /**
2263   * Ensure that if error occurs when freeing memory, no signal will return
2264   * an ExceptionReport document as the result was already returned to the
2265   * client.
2266   */
2267#ifndef USE_GDB
2268  signal (SIGSEGV, donothing);
2269  signal (SIGTERM, donothing);
2270  signal (SIGINT, donothing);
2271  signal (SIGILL, donothing);
2272  signal (SIGFPE, donothing);
2273  signal (SIGABRT, donothing);
2274#endif
2275  if (((int) getpid ()) != cpid || cgiSid != NULL)
2276    {
2277      fclose (stdout);
2278      //fclose (stderr);
2279      /**
2280       * Dump back the final file fbkp1 to fbkp
2281       */
2282      fclose (f0);
2283      fclose (f1);
2284
2285      FILE *f2 = fopen (fbkp1, "rb");
2286#ifndef RELY_ON_DB
2287      semid lid = getShmLockId (m, 1);
2288      if (lid < 0)
2289        return -1;
2290      lockShm (lid);
2291#endif
2292      fclose(f0);
2293      FILE *f3 = fopen (fbkp, "wb+");
2294      free (fbkp);
2295      fseek (f2, 0, SEEK_END);
2296      long flen = ftell (f2);
2297      fseek (f2, 0, SEEK_SET);
2298      char *tmps1 = (char *) malloc ((flen + 1) * sizeof (char));
2299      fread (tmps1, flen, 1, f2);
2300      fwrite (tmps1, 1, flen, f3);
2301      fclose (f2);
2302      fclose (f3);
2303      unlink (fbkpid);
2304      switch(eres){
2305      default:
2306      case SERVICE_FAILED:
2307        setMapInMaps(bmap,"status","status",wpsStatus[1]);
2308        setMapInMaps(m,"lenv","fstate",wpsStatus[1]);
2309        break;
2310      case SERVICE_SUCCEEDED:
2311        setMapInMaps(bmap,"status","status",wpsStatus[0]);
2312        setMapInMaps(m,"lenv","fstate",wpsStatus[0]);
2313        break;
2314      }
2315#ifndef RELY_ON_DB
2316      dumpMapsToFile(bmap,fbkpres);
2317      removeShmLock (m, 1);
2318#else
2319      recordResponse(m,fbkp1);
2320#endif
2321      freeMaps(&bmap);
2322      free(bmap);
2323      unlink (fbkp1);
2324      unlink (flog);
2325      unhandleStatus (m);
2326      free(fbkpid);
2327      free(fbkpres);
2328      free (flog);
2329      free (fbkp1);
2330      free (tmps1);
2331    }
2332
2333  freeService (&s1);
2334  free (s1);
2335  freeMaps (&m);
2336  free (m);
2337
2338  freeMaps (&request_input_real_format);
2339  free (request_input_real_format);
2340
2341  freeMaps (&request_output_real_format);
2342  free (request_output_real_format);
2343
2344  free (REQUEST);
2345  free (SERVICE_URL);
2346#ifdef DEBUG
2347  fprintf (stderr, "Processed response \n");
2348  fflush (stdout);
2349  fflush (stderr);
2350#endif
2351
2352  if (((int) getpid ()) != cpid || cgiSid != NULL)
2353    {
2354      exit (0);
2355    }
2356
2357  return 0;
2358}
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