Ignore:
Timestamp:
May 7, 2019, 2:17:08 PM (5 years ago)
Author:
djay
Message:

Merge prototype-v0 branch in trunk

Location:
trunk
Files:
40 edited
14 copied

Legend:

Unmodified
Added
Removed
  • trunk

  • trunk/zoo-project/zoo-kernel/Makefile.in

    r815 r917  
    99
    1010service.o: service.c service.h
    11         gcc ${YAML_CFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c service.c
     11        g++ ${YAML_CFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c service.c
    1212
    1313main_conf_read.tab.c: main_conf_read.y service.h
     
    3838        gcc -fPIC ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} -c ulinet.c
    3939
     40sshapi.o: sshapi.c
     41        g++ -fPIC ${CFLAGS} -c sshapi.c
     42
     43service_json.o: service_json.c
     44        g++ -fPIC ${JSON_CFLAGS} ${CFLAGS} -c service_json.c
     45
     46service_callback.o: service_callback.c
     47        g++ -fPIC ${XML2CFLAGS} ${GDAL_CFLAGS} ${JSON_CFLAGS} ${CFLAGS} -c service_callback.c
     48
    4049request_parser.o: request_parser.c request_parser.h
    4150        g++ -fPIC ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} -c request_parser.c
    4251
    4352sqlapi.o: sqlapi.c sqlapi.h
    44         g++ -fPIC ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} -c sqlapi.c
     53        g++ -fPIC ${METADB_ENABLED} ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} -c sqlapi.c
    4554
    4655caching.o: caching.c
     
    4857
    4958response_print.o: response_print.c response_print.h
    50         g++ -fPIC ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} -c response_print.c
     59        g++ -fPIC ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} ${JSCFLAGS} ${JS_ENABLED} ${HPC_ENABLED} -c response_print.c
    5160
    5261server_internal.o: server_internal.c server_internal.h service.h mimetypes.h
    53         g++ ${GDAL_CFLAGS} ${JS_ENABLED} ${JSCFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c server_internal.c
     62        g++ ${JSON_CFLAGS} ${GDAL_CFLAGS} ${JS_ENABLED} ${JSCFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c server_internal.c
    5463
    5564service_internal.o: service_internal.c service_internal.h service.h
    56         gcc ${GDAL_CFLAGS} ${JS_ENABLED} ${JSCFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c service_internal.c
     65        gcc ${JSON_CFLAGS} ${GDAL_CFLAGS} ${JS_ENABLED} ${JSCFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c service_internal.c
    5766
    5867service_yaml.o: service_yaml.c service.h
    5968        gcc ${YAML_CFLAGS} ${XML2CFLAGS} ${CFLAGS} -fPIC -c service_yaml.c
     69
     70meta_sql.o: meta_sql.c meta_sql.h service.h
     71        g++  ${METADB_ENABLED} ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} -c meta_sql.c
    6072
    6173service_internal_ms.o: service_internal_ms.c
     
    6678        g++ ${XML2CFLAGS} ${PYTHONCFLAGS} ${CFLAGS} -c service_internal_python.c
    6779
     80service_internal_r.o: service_internal_r.c service.h
     81        g++ ${XML2CFLAGS} ${RCFLAGS} ${CFLAGS} -c service_internal_r.c
     82
    6883service_internal_otb.o: service_internal_otb.c service_internal_otb.h service.h
    6984        g++ ${XML2CFLAGS} ${OTBCFLAGS} ${CFLAGS} -c service_internal_otb.c
     85
     86service_internal_hpc.o: service_internal_hpc.c service_internal_hpc.h service.h
     87        g++  ${JSON_CFLAGS} ${XML2CFLAGS} ${HPCCFLAGS} ${CFLAGS} -c service_internal_hpc.c
    7088
    7189service_internal_saga.o: service_internal_saga.c service_internal_saga.h service.h
     
    99117        g++ -c ${XML2CFLAGS} ${PYTHONCFLAGS} ${CFLAGS} service_loader.c
    100118
    101 zoo_service_loader.o: zoo_service_loader.c service.h version.h ${MS_FILE} ${PYTHON_FILE} ${PHP_FILE} ${JAVA_FILE} ${JS_FILE} ${PERL_FILE} ${RUBY_FILE} ${YAML_FILE} ${OTB_FILE} ${SAGA_FILE} ${MONO_FILE}
    102         g++ -g -O2 ${XML2CFLAGS} ${CFLAGS} ${MONO_CFLAGS} ${SAGA_CFLAGS} ${OTBCFLAGS} ${PYTHONCFLAGS} ${JAVACFLAGS} ${JSCFLAGS} ${PERLCFLAGS} ${PHPCFLAGS} ${SAGA_ENABLED} ${OTB_ENABLED} ${PYTHON_ENABLED} ${JS_ENABLED} ${PHP_ENABLED} ${PERL_ENABLED} ${JAVA_ENABLED} ${MONO_ENABLED} -c zoo_service_loader.c  -fno-common -DPIC -o zoo_service_loader.o
     119zoo_service_loader.o: zoo_service_loader.c service.h version.h ${MS_FILE} ${R_FILE} ${PYTHON_FILE} ${PHP_FILE} ${JAVA_FILE} ${JS_FILE} ${PERL_FILE} ${RUBY_FILE} ${YAML_FILE} ${OTB_FILE} ${SAGA_FILE} ${MONO_FILE} ${HPC_FILES} ${METADB_FILE}
     120        g++ -g -O2 ${JSON_CFLAGS} ${GDAL_CFLAGS} ${XML2CFLAGS} ${CFLAGS} ${MONO_CFLAGS} ${SAGA_CFLAGS} ${OTBCFLAGS} ${RCFLAGS} ${PYTHONCFLAGS} ${JAVACFLAGS} ${JSCFLAGS} ${PERLCFLAGS} ${PHPCFLAGS} ${SAGA_ENABLED} ${OTB_ENABLED} ${HPC_ENABLED} ${PYTHON_ENABLED} ${R_ENABLED} ${JS_ENABLED} ${PHP_ENABLED} ${PERL_ENABLED} ${JAVA_ENABLED} ${MONO_ENABLED} ${METADB_ENABLED} -c zoo_service_loader.c  -fno-common -DPIC -o zoo_service_loader.o
    103121
    104122libzoo_service.${EXT}: version.h service_internal.o service.o sqlapi.o
    105         gcc -shared  ${GDAL_CFLAGS} ${DEFAULT_OPTS} -fpic -o libzoo_service.${EXT} ${CFLAGS}  service_internal.o service.o sqlapi.o ${FCGI_LDFLAGS} ${GDAL_LIBS}
     123        g++ -shared  ${GDAL_CFLAGS} ${DEFAULT_OPTS} -fpic -o libzoo_service.${EXT} ${CFLAGS}  service_internal.o service.o sqlapi.o ${FCGI_LDFLAGS} ${GDAL_LIBS} ${ZOO_LDFLAGS} ${MACOS_LD_FLAGS}
    106124
    107 zoo_loader.cgi: version.h libzoo_service.${EXT} zoo_loader.c zoo_service_loader.o  ulinet.o service.h lex.sr.o service_conf.tab.o service_conf.y ulinet.o main_conf_read.tab.o lex.cr.o request_parser.o response_print.o server_internal.o caching.o ${MS_FILE} ${PYTHON_FILE} ${PHP_FILE} ${JAVA_FILE} ${JS_FILE} ${PERL_FILE} ${RUBY_FILE} ${YAML_FILE} ${OTB_FILE} ${SAGA_FILE}
    108         g++ -g -O2 ${JSCFLAGS} ${PHPCFLAGS}  ${PERLCFLAGS} ${RUBYCFLAGS}  ${JAVACFLAGS} ${XML2CFLAGS} ${PYTHONCFLAGS} ${CFLAGS} -c zoo_loader.c  -fno-common -DPIC -o zoo_loader.o
    109         g++  ${JSCFLAGS} ${SAGA_CFLAGS} ${OTBCFLAGS} ${GDAL_CFLAGS} ${XML2CFLAGS} ${PHPCFLAGS} ${PERLCFLAGS} ${JAVACFLAGS} ${PYTHONCFLAGS} ${CFLAGS} zoo_loader.o zoo_service_loader.o ${MS_FILE} ${PYTHON_FILE}  ${PERL_FILE} ${PHP_FILE}  ${JS_FILE} ${JAVA_FILE} ${YAML_FILE} ${OTB_FILE} ${SAGA_FILE} ${MONO_FILE} response_print.o server_internal.o caching.o request_parser.o ulinet.o lex.cr.o lex.sr.o service_conf.tab.o main_conf_read.tab.o -o zoo_loader.cgi -L. ${LDFLAGS}
     125zoo_loader.cgi: version.h libzoo_service.${EXT} zoo_loader.c zoo_service_loader.o  ulinet.o service.h lex.sr.o service_conf.tab.o service_conf.y ulinet.o main_conf_read.tab.o lex.cr.o request_parser.o response_print.o server_internal.o caching.o ${MS_FILE} ${PYTHON_FILE} ${PHP_FILE} ${JAVA_FILE} ${JS_FILE} ${PERL_FILE} ${RUBY_FILE} ${YAML_FILE} ${OTB_FILE} ${R_FILE} ${SAGA_FILE} ${HPC_FILES} ${METADB_FILE} ${JSON_FILE} ${CALLBACK_FILE}
     126        g++ -g -O2 ${JSON_CFLAGS} ${JSCFLAGS} ${PHPCFLAGS}  ${PERLCFLAGS} ${RUBYCFLAGS}  ${JAVACFLAGS} ${XML2CFLAGS} ${PYTHONCFLAGS} ${CFLAGS} -c zoo_loader.c  -fno-common -DPIC -o zoo_loader.o
     127        g++  ${JSON_CFLAGS} ${JSCFLAGS} ${SAGA_CFLAGS} ${OTBCFLAGS} ${GDAL_CFLAGS} ${XML2CFLAGS} ${PHPCFLAGS} ${PERLCFLAGS} ${JAVACFLAGS} ${PYTHONCFLAGS} ${CFLAGS} zoo_loader.o zoo_service_loader.o ${MS_FILE} ${PYTHON_FILE}  ${PERL_FILE} ${PHP_FILE}  ${JS_FILE} ${JAVA_FILE} ${YAML_FILE} ${OTB_FILE} ${SAGA_FILE} ${MONO_FILE} ${HPC_FILES} ${METADB_FILE} ${JSON_FILE} ${R_FILE} ${CALLBACK_FILE} response_print.o server_internal.o caching.o request_parser.o ulinet.o lex.cr.o lex.sr.o service_conf.tab.o main_conf_read.tab.o -o zoo_loader.cgi -L. ${LDFLAGS}
    110128
    111 zcfg2yaml: zcfg2yaml.c service.h lex.sr.o service_conf.tab.o service_conf.y main_conf_read.tab.o lex.cr.o response_print.o server_internal.o service_internal.o ${MS_FILE} ${YAML_FILE}
     129zcfg2yaml: zcfg2yaml.c service.h lex.sr.o service_conf.tab.o service_conf.y main_conf_read.tab.o lex.cr.o response_print.o server_internal.o service_internal.o ${MS_FILE} ${YAML_FILE} ${CALLBACK_FILE}
    112130        g++ -g -O2 ${JSCFLAGS} ${RUBYCFLAGS} ${XML2CFLAGS} ${CFLAGS} -c zcfg2yaml.c  -fno-common -DPIC -o zcfg2yaml.o
    113         g++  ${XML2CFLAGS} ${CFLAGS} zcfg2yaml.o server_internal.o service_internal.o ${MS_FILE} response_print.o lex.cr.o lex.sr.o service_conf.tab.o main_conf_read.tab.o  ${YAML_FILE} -o zcfg2yaml -L. ${LDFLAGS}
     131        g++  ${XML2CFLAGS} ${CFLAGS} zcfg2yaml.o caching.o ulinet.o ${CALLBACK_FILE} server_internal.o service_internal.o ${MS_FILE} response_print.o lex.cr.o lex.sr.o service_conf.tab.o main_conf_read.tab.o  ${YAML_FILE} -o zcfg2yaml -L. ${LDFLAGS}
    114132
    115133install: zoo_loader.cgi
  • trunk/zoo-project/zoo-kernel/ZOOMakefile.opts.in

    r866 r917  
    3030YAML_FILE1=@YAML_FILE1@
    3131
     32JSON_CFLAGS=@JSON_CPPFLAGS@
     33JSON_LDFLAGS=@JSON_LDFLAGS@
     34JSON_FILE=@JSON_FILE@
     35
     36METADB_ENABLED=@METADB@
     37METADB_FILE=@METADB_FILE@
     38
     39
    3240GDAL_CFLAGS=@GDAL_CFLAGS@
    3341GDAL_LIBS=@GDAL_LIBS@
     
    5058PYTHON_FILE=@PYTHON_FILE@
    5159
     60RCFLAGS=@R_CPPFLAGS@
     61RLDFLAGS=@R_LDFLAGS@
     62R_ENABLED=@R_ENABLED@
     63R_FILE=@R_FILE@
     64
    5265RUBYCFLAGS=@RUBY_CPPFLAGS@
    5366RUBYLDFLAGS=@RUBY_LDFLAGS@
     
    6881
    6982ZOO_CFLAGS=-I${ZRPATH}/../thirds/cgic206/ -I${ZRPATH}/zoo-kernel/
    70 ZOO_LDFLAGS=@OPENSSL_LDFLAGS@ -luuid
     83ZOO_LDFLAGS=@OPENSSL_LDFLAGS@ @UUID_LDFLAGS@
    7184
    7285JAVACFLAGS=@JAVA_CPPFLAGS@
     
    8093PHP_FILE=@PHP_FILE@
    8194
    82 
    8395PERLCFLAGS=@PERL_CPPFLAGS@
    8496PERLLDFLAGS=@PERL_LDFLAGS@
    8597PERL_ENABLED=@PERL_ENABLED@
    8698PERL_FILE=@PERL_FILE@
     99
     100HPCCFLAGS=@SSH2_CPPFLAGS@ @HPC_CPPFLAGS@
     101HPCLDFLAGS=@SSH2_LDFLAGS@ @HPC_LDFLAGS@
     102HPC_ENABLED=@HPC_ENABLED@
     103HPC_FILES=@HPC_FILES@
     104
     105CALLBACK_FILE=@CALLBACK_FILE@
     106CALLBACK_USE=@CALLBACK_USE@
    87107
    88108OTBCFLAGS=@OTB_CPPFLAGS@
     
    101121MONO_FILE=@MONO_FILE@
    102122
    103 CFLAGS=-Wdeclaration-after-statement @RELY_ON_DB@ @DEB_DEF@ -fpic @OPENSSL_CFLAGS@ ${FCGI_CFLAGS} ${YAML_CFLAGS} ${MACOS_CFLAGS} ${MS_CFLAGS} -I../../thirds/cgic206 -I. -DLINUX_FREE_ISSUE #-DDEBUG #-DDEBUG_SERVICE_CONF
    104 LDFLAGS=-lzoo_service @DEFAULT_LIBS@ -L../../thirds/cgic206 -lcgic ${GDAL_LIBS} ${XML2LDFLAGS} ${PYTHONLDFLAGS} ${PERLLDFLAGS}  ${PHPLDFLAGS} ${JAVALDFLAGS} ${JSLDFLAGS}  ${FCGI_LDFLAGS} @OPENSSL_LDFLAGS@ -luuid ${MS_LDFLAGS} ${MACOS_LD_FLAGS} ${MACOS_LD_NET_FLAGS} ${YAML_LDFLAGS} ${OTBLDFLAGS} ${SAGA_LDFLAGS} ${MONO_LDFLAGS}
     123CFLAGS=@CALLBACK_USE@ @SSH2_CPPFLAGS@ @PROJ_CPPFLAGS@ @RELY_ON_DB@ @DEB_DEF@ -fpic @OPENSSL_CFLAGS@ @UUID_CFLAGS@ ${FCGI_CFLAGS} ${YAML_CFLAGS} ${MACOS_CFLAGS} ${MS_CFLAGS} -I../../thirds/cgic206 -I. -DLINUX_FREE_ISSUE #-DDEBUG #-DDEBUG_SERVICE_CONF
     124LDFLAGS=-lzoo_service @SSH2_LDFLAGS@ @PROJ_LDFLAGS@ @DEFAULT_LIBS@ -L../../thirds/cgic206 -lcgic ${GDAL_LIBS} ${XML2LDFLAGS} ${PYTHONLDFLAGS} ${PERLLDFLAGS} ${PHPLDFLAGS} ${JAVALDFLAGS} ${JSLDFLAGS}  ${FCGI_LDFLAGS} @OPENSSL_LDFLAGS@ @UUID_LDFLAGS@ ${MS_LDFLAGS} ${MACOS_LD_FLAGS} ${MACOS_LD_NET_FLAGS} ${YAML_LDFLAGS} ${OTBLDFLAGS} ${SAGA_LDFLAGS} ${MONO_LDFLAGS} ${RLDFLAGS} @JSON_LDFLAGS@ @XSLT_LDFLAGS@
    105125
    106126DATAROOTDIR=@datarootdir@/zoo-project
  • trunk/zoo-project/zoo-kernel/caching.c

    r837 r917  
    2323 */
    2424
     25#include <openssl/md5.h>
     26#include <openssl/evp.h>
    2527#include "caching.h"
    2628#include "service.h"
    2729#include "service_internal.h"
    2830#include "response_print.h"
    29 #include <openssl/md5.h>
    30 #include <openssl/hmac.h>
    31 #include <openssl/evp.h>
    32 #include <openssl/bio.h>
    33 #include <openssl/buffer.h>
    34 
     31#ifdef MS_FORCE_LOCAL_FILE_USE
     32#include "ogr_api.h"
     33#include "mapserver.h"
     34#endif
    3535/**
    3636 * Compute md5
     
    4141 */
    4242char* getMd5(char* url){
    43   EVP_MD_CTX md5ctx;
     43  EVP_MD_CTX *md5ctx=EVP_MD_CTX_create();
    4444  char* fresult=(char*)malloc((EVP_MAX_MD_SIZE+1)*sizeof(char));
    4545  unsigned char result[EVP_MAX_MD_SIZE];
    4646  unsigned int len;
    47   EVP_DigestInit(&md5ctx, EVP_md5());
    48   EVP_DigestUpdate(&md5ctx, url, strlen(url));
    49   EVP_DigestFinal_ex(&md5ctx,result,&len);
    50   EVP_MD_CTX_cleanup(&md5ctx);
     47  EVP_DigestInit(md5ctx, EVP_md5());
     48  EVP_DigestUpdate(md5ctx, url, strlen(url));
     49  EVP_DigestFinal_ex(md5ctx,result,&len);
     50  EVP_MD_CTX_destroy(md5ctx);
    5151  int i;
    5252  for(i = 0; i < len; i++){
    5353    if(i>0){
    54       char *tmp=strdup(fresult);
     54      char *tmp=zStrdup(fresult);
    5555      sprintf(fresult,"%s%02x", tmp,result[i]);
    5656      free(tmp);
     
    6262}
    6363
     64/**
     65 * Compute md5 of a file
     66 *
     67 * @param file the char*
     68 * @return a char* representing the md5 of the url
     69 * @warning make sure to free resources returned by this function
     70 */
     71char* getMd5f(char* file){
     72  EVP_MD_CTX *md5ctx=EVP_MD_CTX_create();
     73  char* fresult=(char*)malloc((EVP_MAX_MD_SIZE+1)*sizeof(char));
     74  unsigned char result[EVP_MAX_MD_SIZE];
     75  unsigned int len;
     76  int bytes;
     77  int dlen=65536;
     78  unsigned char data[65537];
     79  FILE *inFile = fopen (file, "rb");
     80  EVP_DigestInit(md5ctx, EVP_md5());
     81  while ((bytes = fread (data, sizeof(unsigned char), dlen, inFile)) != 0)
     82    EVP_DigestUpdate(md5ctx, data, bytes);
     83  EVP_DigestFinal_ex(md5ctx,result,&len);
     84  EVP_MD_CTX_destroy(md5ctx);
     85  int i;
     86  for(i = 0; i < len; i++){
     87    if(i>0){
     88      char *tmp=zStrdup(fresult);
     89      sprintf(fresult,"%s%02x", tmp,result[i]);
     90      free(tmp);
     91    }
     92    else
     93      sprintf(fresult,"%02x",result[i]);
     94  }
     95  fclose (inFile);
     96  return fresult;
     97}
     98
     99
     100
     101/**
     102 * Create a URL by appending every request header listed in the security
     103 * section.This imply that the URL will contain any authentication
     104 * informations that should be fowarded to the server from which de input
     105 * was download.
     106 * @param conf the main configuration maps
     107 * @param request the URL to transform.
     108 * @return a char* that contain the original URL plus potential header (only for
     109 * hosts that are not shared).
     110 * @warning Be sure to free the memory returned by this function.
     111 */
     112char* getFilenameForRequest(maps* conf, const char* request){
     113  map* passThrough=getMapFromMaps(conf,"security","attributes");
     114  map* targetHosts=getMapFromMaps(conf,"security","hosts");
     115  char* passedHeader[10];
     116  int cnt=0;
     117  char *res=zStrdup(request);
     118  char *toAppend=NULL;
     119  if(passThrough!=NULL && targetHosts!=NULL){
     120    char *tmp=zStrdup(passThrough->value);
     121    char *token, *saveptr;
     122    token = strtok_r (tmp, ",", &saveptr);
     123    int i;
     124    if((strstr(targetHosts->value,"*")!=NULL || isProtectedHost(targetHosts->value,request)==1) && strncasecmp(getProvenance(conf,request),"SHARED",6)!=0){
     125      while (token != NULL){
     126        int length=strlen(token)+6;
     127        char* tmp1=(char*)malloc(length*sizeof(char));
     128        map* tmpMap;
     129        snprintf(tmp1,6,"HTTP_");
     130        int j;
     131        for(j=0;token[j]!='\0';j++){
     132          if(token[j]!='-')
     133            tmp1[5+j]=toupper(token[j]);
     134          else
     135            tmp1[5+j]='_';
     136          tmp1[5+j+1]='\0';
     137        }
     138        tmpMap = getMapFromMaps(conf,"renv",tmp1);
     139        if(tmpMap!=NULL){
     140          if(toAppend==NULL){
     141            toAppend=(char*)malloc((strlen(tmpMap->value)+1)*sizeof(char));
     142            sprintf(toAppend,"%s",tmpMap->value);
     143          }else{
     144            char *tmp3=zStrdup(toAppend);
     145            toAppend=(char*)realloc(toAppend,(strlen(tmpMap->value)+strlen(tmp3)+2)*sizeof(char));
     146            sprintf(toAppend,"%s,%s",tmp3,tmpMap->value);
     147            free(tmp3);
     148          }
     149        }
     150        free(tmp1);
     151        cnt+=1;
     152        token = strtok_r (NULL, ",", &saveptr);
     153      }
     154    }
     155    free(tmp);
     156  }
     157  if(toAppend!=NULL){
     158    char *tmp3=zStrdup(res);
     159    res=(char*)realloc(res,(strlen(tmp3)+strlen(toAppend)+1)*sizeof(char));
     160    sprintf(res,"%s%s",tmp3,toAppend);
     161    free(tmp3);
     162    free(toAppend);
     163  }
     164  return res;
     165}
     166
     167/**
     168 * Store MD5 of the content of a file
     169 * @file char* the full path of the file
     170 */
     171int storeMd5(char* file){
     172  char* storage=zStrdup(file);
     173  char* md5fstr=getMd5f(file);
     174  storage[strlen(storage)-2]='m';
     175  storage[strlen(storage)-1]='d';
     176  FILE* fo=fopen(storage,"w+");
     177  if(fo==NULL)
     178    return 1;
     179  fwrite(md5fstr,sizeof(char),strlen(md5fstr),fo);
     180  free(md5fstr);
     181  free(storage);
     182  fclose(fo);
     183  return 0;
     184}
    64185
    65186/**
     
    76197 * @param max_path the size of the allocated filepath buffer 
    77198 */
     199void cacheFile(maps* conf,char* request,char* mimeType,int length,char* filename){
     200  map* tmp=getMapFromMaps(conf,"main","cacheDir");
     201  char contentr[4096];
     202  int cred=0;
     203  if(tmp!=NULL){
     204    char* myRequest=getFilenameForRequest(conf,request);
     205    char* md5str=getMd5(myRequest);
     206    free(myRequest);
     207    char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
     208    // Store md5
     209    char* md5fstr=getMd5f(filename);
     210    sprintf(fname,"%s/%s.zmd",tmp->value,md5str);
     211    FILE* fo=fopen(fname,"w+");
     212#ifdef DEBUG
     213    fprintf(stderr,"filename: %s\n",filename);
     214    fprintf(stderr,"MD5: %s\n",md5fstr);
     215#endif
     216    fwrite(md5fstr,sizeof(char),strlen(md5fstr),fo);
     217    free(md5fstr);
     218    fclose(fo);
     219   
     220    sprintf(fname,"%s/%s.zca",tmp->value,md5str);
     221    zooLock* lck=lockFile(conf,fname,'w');
     222    if(lck!=NULL){
     223#ifdef DEBUG
     224      fprintf(stderr,"Cache list : %s\n",fname);
     225      fflush(stderr);
     226#endif
     227      FILE* fi=fopen(filename,"rb");
     228      sprintf(fname,"%s/%s.zca",tmp->value,md5str);
     229      fo=fopen(fname,"w+");
     230      if(fo==NULL){
     231#ifdef DEBUG
     232        fprintf (stderr, "Failed to open %s for writing: %s\n",fname, strerror(errno));
     233#endif
     234        unlockFile(conf,lck);
     235        return;
     236      }
     237      if(fi==NULL){
     238#ifdef DEBUG
     239        fprintf (stderr, "Failed to open %s for reading: %s\n",filename, strerror(errno));
     240#endif
     241        unlockFile(conf,lck);
     242        return;
     243      }
     244      memset(contentr,0,4096);
     245      while((cred=fread(contentr,sizeof(char),4096,fi))>0){
     246        fwrite(contentr,sizeof(char),cred,fo);
     247        fflush(fo);
     248        memset(contentr,0,4096);
     249      }
     250      unlockFile(conf,lck);
     251      fclose(fo);
     252      fclose(fi);
     253
     254      // Store mimeType
     255      sprintf(fname,"%s/%s.zcm",tmp->value,md5str);
     256      fo=fopen(fname,"w+");
     257#ifdef DEBUG
     258      fprintf(stderr,"MIMETYPE: %s\n",mimeType);
     259#endif
     260      fwrite(mimeType,sizeof(char),strlen(mimeType),fo);
     261      fclose(fo);
     262
     263      // Store provenance
     264      sprintf(fname,"%s/%s.zcp",tmp->value,md5str);
     265      fo=fopen(fname,"w+");
     266      char* origin=getProvenance(conf,request);
     267#ifdef DEBUG
     268      fprintf(stderr,"ORIGIN: %s\n",mimeType);
     269#endif
     270      fwrite(origin,sizeof(char),strlen(origin),fo);
     271      fclose(fo);
     272
     273      free(md5str);
     274
     275    }
     276    free(fname);
     277  }
     278}
     279
     280/**
     281 * Cache a file for a given request.
     282 * For each cached file, the are two files stored, a .zca and a .zcm containing
     283 * the downloaded content and the mimeType respectively.
     284 *
     285 * @param conf the maps containing the settings of the main.cfg file
     286 * @param request the url used too fetch the content
     287 * @param content the downloaded content
     288 * @param mimeType the content mimeType
     289 * @param length the content size
     290 * @param filepath a buffer for storing the path of the cached file; may be NULL
     291 * @param max_path the size of the allocated filepath buffer 
     292 */
    78293void addToCache(maps* conf,char* request,char* content,char* mimeType,int length,
    79294                char* filepath, size_t max_path){
    80295  map* tmp=getMapFromMaps(conf,"main","cacheDir");
    81296  if(tmp!=NULL){
    82     char* md5str=getMd5(request);
     297    char* myRequest=getFilenameForRequest(conf,request);
     298    char* md5str=getMd5(myRequest);
     299    free(myRequest);
    83300    char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
    84301    sprintf(fname,"%s/%s.zca",tmp->value,md5str);
    85 #ifdef DEBUG
    86     fprintf(stderr,"Cache list : %s\n",fname);
    87     fflush(stderr);
    88 #endif
    89     FILE* fo=fopen(fname,"w+");
    90     if(fo==NULL){
    91 #ifdef DEBUG
    92       fprintf (stderr, "Failed to open %s for writing: %s\n",fname, strerror(errno));
    93 #endif
    94       filepath = NULL; 
    95       return;
    96     }
    97     fwrite(content,sizeof(char),length,fo);
    98     fclose(fo);
     302    zooLock* lck=lockFile(conf,fname,'w');
     303    if(lck!=NULL){
     304#ifdef DEBUG
     305      fprintf(stderr,"Cache list : %s\n",fname);
     306      fflush(stderr);
     307#endif
     308      FILE* fo=fopen(fname,"w+");
     309      if(fo==NULL){
     310#ifdef DEBUG
     311        fprintf (stderr, "Failed to open %s for writing: %s\n",fname, strerror(errno));
     312#endif
     313        filepath = NULL;
     314        unlockFile(conf,lck);
     315        return;
     316      }
     317      fwrite(content,sizeof(char),length,fo);
     318      unlockFile(conf,lck);
     319      fclose(fo);
    99320       
    100         if (filepath != NULL) {
    101                 strncpy(filepath, fname, max_path);
    102         }       
    103 
    104     sprintf(fname,"%s/%s.zcm",tmp->value,md5str);
    105     fo=fopen(fname,"w+");
    106 #ifdef DEBUG
    107     fprintf(stderr,"MIMETYPE: %s\n",mimeType);
    108 #endif
    109     fwrite(mimeType,sizeof(char),strlen(mimeType),fo);
    110     fclose(fo);
    111 
    112     free(md5str);
    113     free(fname);
     321      if (filepath != NULL) {
     322        strncpy(filepath, fname, max_path);
     323      }
     324
     325      sprintf(fname,"%s/%s.zcm",tmp->value,md5str);
     326      fo=fopen(fname,"w+");
     327#ifdef DEBUG
     328      fprintf(stderr,"MIMETYPE: %s\n",mimeType);
     329#endif
     330      fwrite(mimeType,sizeof(char),strlen(mimeType),fo);
     331      fclose(fo);
     332
     333      sprintf(fname,"%s/%s.zcp",tmp->value,md5str);
     334      fo=fopen(fname,"w+");
     335      char* origin=getProvenance(conf,request);
     336#ifdef DEBUG
     337      fprintf(stderr,"ORIGIN: %s\n",mimeType);
     338#endif
     339      fwrite(origin,sizeof(char),strlen(origin),fo);
     340      fclose(fo);
     341
     342      free(md5str);
     343      free(fname);
     344    }
    114345  }
    115346  else {
    116           filepath = NULL;
     347    filepath = NULL;
    117348  }       
    118349}
     
    127358 */
    128359char* isInCache(maps* conf,char* request){
     360  map* tmpUrl=getMapFromMaps(conf,"main","tmpUrl");
    129361  map* tmpM=getMapFromMaps(conf,"main","cacheDir");
    130   if(tmpM!=NULL){
    131     char* md5str=getMd5(request);
     362  if(tmpM==NULL)
     363    tmpM=getMapFromMaps(conf,"main","tmpPath");
     364  if(strstr(request,tmpUrl->value)!=NULL){
     365    map* tmpPath=getMapFromMaps(conf,"main","tmpPath");
     366    char* tmpStr=strstr(request,tmpUrl->value);
     367    char* tmpStr1=zStrdup(tmpStr+strlen(tmpUrl->value));
     368    char* res=(char*) malloc((strlen(tmpPath->value)+strlen(tmpStr1)+2)*sizeof(char));
     369    sprintf(res,"%s/%s",tmpPath->value,tmpStr1);
     370    free(tmpStr1);
     371    return res;
     372  }
     373#ifdef MS_FORCE_LOCAL_FILE_USE
     374  map* msUrl=getMapFromMaps(conf,"main","mapserverAddress");
     375  if(msUrl!=NULL && strstr(request,msUrl->value)!=NULL){
     376    char *tmpStr=strstr(request,"?");
     377    char *cursor=zStrdup(tmpStr+1);
     378    char *token, *saveptr;
     379    token = strtok_r (cursor, "&", &saveptr);
     380    while(token!=NULL){
     381      char *token1, *saveptr1;
     382      token1 = strtok_r (token, "=", &saveptr1);
     383      char *name=NULL;
     384      while(token1!=NULL){
     385        if(name==NULL)
     386          name=zStrdup(token1);
     387        else
     388          if(strcasecmp(name,"map")==0){
     389            mapObj *myMap=msLoadMap(token1,NULL);
     390            char * res=zStrdup(myMap->layers[0]->data);
     391            free(name);
     392            free(cursor);
     393            msFreeMap(myMap);
     394            return res;
     395          }
     396        token1 = strtok_r (NULL, "=", &saveptr1);
     397      }
     398      token = strtok_r (NULL, "&", &saveptr);
     399    }
     400    free(cursor);
     401  }
     402#endif 
     403  if(strncasecmp(request,"file://",7)==0){
     404    char* tmpStr=zStrdup(request+7);
     405    fprintf(stderr,"**** %s %d %s \n",__FILE__,__LINE__,tmpStr);
     406    return tmpStr;
     407  }
     408  else{
     409    char* myRequest=getFilenameForRequest(conf,request);
     410    char* md5str=getMd5(myRequest);
     411    free(myRequest);
    132412#ifdef DEBUG
    133413    fprintf(stderr,"MD5STR : (%s)\n\n",md5str);
     
    135415    char* fname=(char*)malloc(sizeof(char)*(strlen(tmpM->value)+strlen(md5str)+6));
    136416    sprintf(fname,"%s/%s.zca",tmpM->value,md5str);
    137     struct stat f_status;
    138     int s=stat(fname, &f_status);
     417    zStatStruct f_status;
     418    int s=zStat(fname, &f_status);
    139419    if(s==0 && f_status.st_size>0){
    140420      free(md5str);
     
    158438 */
    159439int readCurrentInput(maps** m,maps** in,int* index,HINTERNET* hInternet,map** error){
     440 
     441  int shouldClean=-1;
    160442  map* tmp1;
    161443  char sindex[5];
    162444  maps* content=*in;
    163445  map* length=getMap(content->content,"length");
    164   int shouldClean=-1;
     446  map* memUse=getMapFromMaps(*m,"main","memory");
    165447  if(length==NULL){
    166448    length=createMap("length","1");
     
    171453    char *mimeType=NULL;
    172454    int fsize=0;
     455    char oriname[12];
    173456    char cname[15];
    174457    char vname[11];
     
    178461    char icname[14];
    179462    char xname[16];
     463    char bname[8];
     464    char hname[11];
    180465    char oname[12];
     466    char ufile[12];   
    181467    if(*index>0)
    182468      sprintf(vname1,"value_%d",*index);
     
    185471   
    186472    if(i>0){
     473      sprintf(cname,"cache_file_%d",i);
    187474      tmp1=getMap(content->content,cname);
    188       sprintf(cname,"cache_file_%d",i);
     475      sprintf(oriname,"origin_%d",i);
    189476      sprintf(vname,"value_%d",i);
    190477      sprintf(sname,"size_%d",i);
     
    192479      sprintf(icname,"isCached_%d",i);
    193480      sprintf(xname,"Reference_%d",i);
     481      sprintf(bname,"body_%d",i);
     482      sprintf(hname,"headers_%d",i);
    194483      sprintf(oname,"Order_%d",i);
     484      sprintf(ufile,"use_file_%d",i);
    195485    }else{
    196486      sprintf(cname,"cache_file");
     487      sprintf(oriname,"origin");
    197488      sprintf(vname,"value");
    198489      sprintf(sname,"size");
     
    200491      sprintf(icname,"isCached");
    201492      sprintf(xname,"Reference");
     493      sprintf(bname,"body");
     494      sprintf(hname,"headers");
    202495      sprintf(oname,"Order");
     496      sprintf(ufile,"use_file");
    203497    }
    204498   
     
    206500    sprintf(sindex,"%d",*index+1);
    207501    if((tmp1=getMap(content->content,xname))!=NULL && tmap!=NULL && strcasecmp(tmap->value,sindex)==0){
    208      
    209       if(getMap(content->content,icname)==NULL){
    210         fcontent=(char*)malloc((hInternet->ihandle[*index].nDataLen+1)*sizeof(char));
    211         if(fcontent == NULL){
    212           errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
    213           return -1;
     502
     503      if(getMap(content->content,icname)==NULL) {
     504        if(memUse==NULL || strcasecmp(memUse->value,"load")==0){
     505          fcontent=(char*)malloc((hInternet->ihandle[*index].nDataLen+1)*sizeof(char));
     506          if(fcontent == NULL){
     507            errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
     508            return -1;
     509          }
     510          size_t dwRead;
     511          InternetReadFile(hInternet->ihandle[*index],
     512                           (LPVOID)fcontent,
     513                           hInternet->ihandle[*index].nDataLen,
     514                           &dwRead);
     515          fcontent[hInternet->ihandle[*index].nDataLen]=0;
    214516        }
    215         size_t dwRead;
    216         InternetReadFile(hInternet->ihandle[*index],
    217                          (LPVOID)fcontent,
    218                          hInternet->ihandle[*index].nDataLen,
    219                          &dwRead);
    220         fcontent[hInternet->ihandle[*index].nDataLen]=0;
    221517        fsize=hInternet->ihandle[*index].nDataLen;
    222518        if(hInternet->ihandle[*index].mimeType==NULL)
     
    226522       
    227523        map* tmpMap=getMapOrFill(&(*in)->content,vname,"");
    228         free(tmpMap->value);
    229         tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
    230         if(tmpMap->value==NULL){
    231           return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
    232         }
    233         memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));
     524        if(memUse==NULL || strcasecmp(memUse->value,"load")==0){
     525          free(tmpMap->value);
     526          tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
     527          if(tmpMap->value==NULL){
     528            return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
     529          }
     530          memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));
     531        }else
     532          addToMap((*in)->content,ufile,"true");
    234533        if(hInternet->ihandle[*index].code!=200){
    235534          const char *error_rep_str=_("Unable to download the file for the input <%s>, response code was : %d.");
     
    255554        sprintf(ltmp1,"%d",fsize);
    256555        map* tmp=getMapFromMaps(*m,"main","cacheDir");
     556        char *request=NULL;
    257557        if(tmp!=NULL){
    258           char* md5str=getMd5(tmp1->value);
     558          map* tmp2;
     559          char* md5str=NULL;
     560          if((tmp2=getMap(content->content,bname))!=NULL){
     561            char *tmpStr=(char*)malloc((strlen(tmp1->value)+strlen(tmp2->value)+1)*sizeof(char));
     562            sprintf(tmpStr,"%s%s",tmp1->value,tmp2->value);
     563            if((tmp2=getMap(content->content,"headers"))!=NULL){
     564              char *tmpStr2=zStrdup(tmpStr);
     565              free(tmpStr);
     566              tmpStr=(char*)malloc((strlen(tmpStr2)+strlen(tmp2->value)+1)*sizeof(char));
     567              sprintf(tmpStr,"%s%s",tmpStr2,tmp2->value);
     568              free(tmpStr2);
     569            }
     570            md5str=getMd5(tmpStr);
     571            request=zStrdup(tmpStr);
     572            free(tmpStr);
     573          }else{
     574            char *myRequest=getFilenameForRequest(*m,tmp1->value);
     575            md5str=getMd5(myRequest);
     576            request=zStrdup(tmp1->value);
     577            free(myRequest);
     578          }
    259579          char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
    260580          sprintf(fname,"%s/%s.zca",tmp->value,md5str);
     
    264584        addToMap((*in)->content,sname,ltmp1);
    265585        addToMap((*in)->content,mname,mimeType);
    266         addToCache(*m,tmp1->value,fcontent,mimeType,fsize, NULL, 0);
    267         free(fcontent);
     586        char* origin=getProvenance(*m,request);
     587        addToMap((*in)->content,oriname,origin);
     588        if(memUse==NULL || strcasecmp(memUse->value,"load")==0){
     589          addToCache(*m,request,fcontent,mimeType,fsize, NULL, 0);
     590          free(fcontent);
     591        }else{
     592          addToMap((*in)->content,ufile,"true");
     593          cacheFile(*m,request,mimeType,fsize,hInternet->ihandle[*index].filename);
     594        }
    268595        free(mimeType);
    269         *index++;
    270        
     596        free(request);
     597        (*index)++;
    271598      }
    272599    }
     
    324651 */
    325652void addRequestToQueue(maps** m,HINTERNET* hInternet,const char* url,bool req){
    326   hInternet->waitingRequests[hInternet->nb]=strdup(url);
     653  hInternet->waitingRequests[hInternet->nb]=zStrdup(url);
    327654  if(req)
    328     InternetOpenUrl(hInternet,hInternet->waitingRequests[hInternet->nb],NULL,0,INTERNET_FLAG_NO_CACHE_WRITE,0);
     655    InternetOpenUrl(hInternet,hInternet->waitingRequests[hInternet->nb],NULL,0,INTERNET_FLAG_NO_CACHE_WRITE,0,*m);
    329656  maps *oreq=getMaps(*m,"orequests");
    330657  if(oreq==NULL){
     
    335662    free(oreq);
    336663  }else{
    337     setMapArray(oreq->content,"value",hInternet->nb-1,url);
     664    setMapArray(oreq->content,"value",hInternet->nb,url);
    338665  }
    339666}
     
    352679  char* cached=isInCache(*m,url);
    353680  char *mimeType=NULL;
    354   int fsize=0;
     681  char *origin=NULL;
     682  long long fsize=0;
     683  map* memUse=getMapFromMaps(*m,"main","memory");
    355684
    356685  map* t=getMap(*content,"xlink:href");
     
    361690
    362691  if(cached!=NULL){
    363 
    364     struct stat f_status;
    365     int s=stat(cached, &f_status);
     692    zStatStruct f_status;
     693    int s=zStat(cached, &f_status);
    366694    if(s==0){
    367       fcontent=(char*)malloc(sizeof(char)*(f_status.st_size+1));
    368       FILE* f=fopen(cached,"rb");
    369       fread(fcontent,f_status.st_size,1,f);
     695      zooLock* lck=lockFile(*m,cached,'r');
     696      if(lck==NULL)
     697        return -1;
    370698      fsize=f_status.st_size;
    371       fcontent[fsize]=0;
    372       fclose(f);
     699      if(memUse==NULL || strcasecmp(memUse->value,"load")==0){
     700        fcontent=(char*)malloc(sizeof(char)*(f_status.st_size+1));
     701        FILE* f=fopen(cached,"rb");
     702        if(f!=NULL){
     703          fread(fcontent,f_status.st_size,1,f);
     704          fcontent[fsize]=0;
     705          fclose(f);
     706        }
     707      }
    373708      addToMap(*content,"cache_file",cached);
     709      unlockFile(*m,lck);
    374710    }
    375711    cached[strlen(cached)-1]='m';
    376     s=stat(cached, &f_status);
     712    s=zStat(cached, &f_status);
    377713    if(s==0){
     714      zooLock* lck=lockFile(*m,cached,'r');
     715      if(lck==NULL)
     716        return -1;
    378717      mimeType=(char*)malloc(sizeof(char)*(f_status.st_size+1));
    379718      FILE* f=fopen(cached,"rb");
     
    381720      mimeType[f_status.st_size]=0;
    382721      fclose(f);
    383     }
    384 
     722      unlockFile(*m,lck);
     723    }
     724    cached[strlen(cached)-1]='p';
     725    s=zStat(cached, &f_status);
     726    if(s==0){
     727      zooLock* lck=lockFile(*m,cached,'r');
     728      if(lck==NULL)
     729        return -1;
     730      origin=(char*)malloc(sizeof(char)*(f_status.st_size+1));
     731      FILE* f=fopen(cached,"rb");
     732      fread(origin,f_status.st_size,1,f);
     733      mimeType[f_status.st_size]=0;
     734      fclose(f);
     735      unlockFile(*m,lck);
     736    }
    385737  }else{   
    386738    addRequestToQueue(m,hInternet,url,true);
     
    393745    addToMap(*content,"fmimeType",mimeType);
    394746  }
     747  if(origin!=NULL){
     748    addToMap(*content,"origin",origin);
     749  }
    395750
    396751  map* tmpMap=getMapOrFill(content,"value","");
    397    
    398   free(tmpMap->value);
    399   tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
    400   if(tmpMap->value==NULL || fcontent == NULL)
    401     return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
    402   memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));
    403 
     752  if(memUse==NULL || strcasecmp(memUse->value,"load")==0){
     753    free(tmpMap->value);
     754    tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
     755    if(tmpMap->value==NULL || fcontent == NULL)
     756      return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
     757    memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));
     758  }
     759 
    404760  char ltmp1[256];
    405   sprintf(ltmp1,"%d",fsize);
     761  sprintf(ltmp1,"%ld",fsize);
    406762  addToMap(*content,"size",ltmp1);
    407763  if(cached==NULL){
    408     addToCache(*m,url,fcontent,mimeType,fsize, NULL, 0);
     764    if(memUse==NULL || strcasecmp(memUse->value,"load")==0)
     765      addToCache(*m,url,fcontent,mimeType,fsize, NULL, 0);
     766    else
     767      cacheFile(*m,url,mimeType,fsize,hInternet->ihandle[hInternet->nb-1].filename);
    409768  }
    410769  else{
    411770    addToMap(*content,"isCached","true");
    412771    map* tmp=getMapFromMaps(*m,"main","cacheDir");
    413     if(tmp!=NULL){
     772    map* tmp1=getMap((*content),"cache_file");
     773    if(tmp!=NULL && tmp1==NULL){
    414774      map *c=getMap((*content),"xlink:href");
    415       char* md5str=getMd5(c->value);
    416       char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
    417       sprintf(fname,"%s/%s.zca",tmp->value,md5str);
    418       addToMap(*content,"cache_file",fname);
    419       free(fname);
    420     }
    421   }
    422   free(fcontent);
    423   free(mimeType);
    424   free(cached);
     775      if(strncasecmp(c->value,"file://",7)!=0){
     776        char *myRequest=getFilenameForRequest(*m,c->value);
     777        char* md5str=getMd5(myRequest);
     778        free(myRequest);
     779        char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
     780        sprintf(fname,"%s/%s.zca",tmp->value,md5str);
     781        addToMap(*content,"cache_file",fname);
     782        free(fname);
     783        free(md5str);
     784      }
     785    }
     786  }
     787  if(fcontent!=NULL)
     788    free(fcontent);
     789  if(mimeType!=NULL)
     790    free(mimeType);
     791  if(cached!=NULL)
     792    free(cached);
    425793  return 0;
    426794}
  • trunk/zoo-project/zoo-kernel/caching.h

    r797 r917  
    3535  void addRequestToQueue(maps**,HINTERNET*,const char*,bool);
    3636  int loadRemoteFile(maps**,map**,HINTERNET*,char*);
    37 
     37  char* getMd5f(char*);
     38  int storeMd5(char*);
     39 
    3840#ifdef __cplusplus
    3941}
  • trunk/zoo-project/zoo-kernel/configure.ac

    r817 r917  
    11AC_INIT([ZOO Kernel], [1.7.0], [bugs@zoo-project.org])
     2
     3AC_CONFIG_MACRO_DIR([macros])
    24
    35# Checks for programs.
     
    1214AC_CHECK_LIB([dl], [dlopen,dlsym,dlerror,dlclose])
    1315AC_CHECK_LIB([crypto], [EVP_DigestInit,EVP_md5,EVP_DigestUpdate,BIO_f_base64,BIO_new])
    14 AC_CHECK_LIB([uuid], [uuid_generate_time])
    1516
    1617DEFAULT_LIBS="$LIBS"
     
    2021# Checks for header files.
    2122AC_FUNC_ALLOCA
    22 AC_CHECK_HEADERS([fcntl.h inttypes.h libintl.h malloc.h stddef.h stdlib.h string.h unistd.h])
     23AC_CHECK_HEADERS([fcntl.h inttypes.h malloc.h stddef.h stdlib.h string.h unistd.h])
    2324
    2425# Checks for typedefs, structures, and compiler characteristics.
     
    3839AC_FUNC_REALLOC
    3940AC_CHECK_FUNCS([dup2 getcwd memset setenv strdup strstr])
     41
     42#============================================================================
     43# Detect if uuid is available
     44#============================================================================
     45
     46AC_ARG_WITH([uuid],
     47    [AS_HELP_STRING([--with-uuid=PATH], [Specifies an alternative location for the ossp-uuid library])],
     48    [UUID_DIR="$withval"], [UUID_DIR="/usr/"])
     49UUID_CFLAGS="-I$UUID_DIR/include"
     50UUID_LDFLAGS="-L$UUID_DIR/lib -luuid"
     51CPPFLAGS_SAVE="$CPPFLAGS"
     52CPPFLAGS="$UUID_CFLAGS"
     53LIBS_SAVE="$LIBS"
     54LIBS="$UUID_LDFLAGS"
     55AC_CHECK_HEADERS([uuid/uuid.h],
     56                        [], [AC_MSG_ERROR([could not find header file uuid.h])])
     57AC_CHECK_LIB([uuid], [uuid_generate_time],
     58                        [], [AC_MSG_ERROR([could not find function in uuid library])])
     59CPPFLAGS="$CPPFLAGS_SAVE"
     60AC_SUBST([UUID_CFLAGS])
     61AC_SUBST([UUID_LDFLAGS])
     62
     63#============================================================================
     64# Detect if json-c is available
     65#============================================================================
     66
     67AC_ARG_WITH([callback],
     68    [AS_HELP_STRING([--with-callback=yes], [Activate callback invocation during HPC execution])],
     69    [CALLBACK_ACTIVATED="$withval"], [CALLBACK_ACTIVATED="no"])
     70   
     71AC_ARG_WITH([json],
     72    [AS_HELP_STRING([--with-json=PATH], [Specifies an alternative location for the json-c library])],
     73    [JSON_DIR="$withval"], [JSON_DIR="/usr/"])
     74if test "x$JSON_DIR" != "x" && test "x$CALLBACK_ACTIVATED" == "xyes"
     75then
     76        JSON_CPPFLAGS="-I$JSON_DIR/include/json-c/"
     77        JSON_LDFLAGS="-L$JSON_DIR/lib -ljson-c"
     78        CPPFLAGS_SAVE="$CPPFLAGS"
     79        CPPFLAGS="$JSON_CPPFLAGS"
     80        LIBS_SAVE="$LIBS"
     81        LIBS="$JSON_LDFLAGS"
     82        AC_CHECK_HEADERS([json_object.h],
     83                [], [AC_MSG_ERROR([could not find header file json_object.h])])
     84        AC_CHECK_LIB([json-c], [json_object_new_object],
     85                [], [AC_MSG_ERROR([could not find function in json-c library])])
     86        CPPFLAGS="$CPPFLAGS_SAVE"
     87        JSON_FILE="service_json.o"
     88        JSON_ENABLED="-DJSON"
     89        CALLBACK_FILE="service_callback.o"
     90        CALLBACK_USE="-DUSE_CALLBACK"
     91fi
     92AC_SUBST([JSON_CPPFLAGS])
     93AC_SUBST([JSON_LDFLAGS])
     94AC_SUBST([JSON_FILE])
     95AC_SUBST([JSON_ENABLED])
     96AC_SUBST([CALLBACK_FILE])
     97AC_SUBST([CALLBACK_USE])
    4098
    4199#============================================================================
     
    56114AC_CHECK_LIB(crypto, BIO_f_base64,
    57115                        [], [AC_MSG_ERROR([could not find $i function in openssl library])])
     116CPPFLAGS="$CPPFLAGS_SAVE"
    58117AC_SUBST([OPENSSL_CFLAGS])
    59118AC_SUBST([OPENSSL_LDFLAGS])
     119
     120#============================================================================
     121# Detect if gettext is available
     122#============================================================================
     123
     124#AC_ARG_WITH([gettext],
     125#    [AS_HELP_STRING([--with-gettext=PATH], [Specifies an alternative location for the openssl library])],
     126#    [GETTEXT_DIR="$withval"], [GETTEXT_DIR="/usr/"])
     127
     128#GETTEXT_CFLAGS="-I$GETTEXT_DIR/include"
     129#GETTEXT_LDFLAGS="-L$GETTEXT_DIR/lib -lintl"
     130#CFLAGS_SAVE="$CFLAGS"
     131#CFLAGS="$GETTEXT_CFLAGS"
     132#LIBS_SAVE="$LIBS"
     133#LIBS="$GETTEXT_LDFLAGS"
     134#AM_GNU_GETTEXT([external], [], [])
     135#AC_CHECK_LIB(intl,
     136#                       [dgettext], [] , [AC_MSG_ERROR([could not find $i function in gettext library])])
     137#AC_SUBST([GETTEXT_CFLAGS])
     138#AC_SUBST([GETTEXT_LDFLAGS])
    60139
    61140#============================================================================
     
    145224AC_SUBST([FCGI_LDFLAGS])
    146225
     226AC_ARG_WITH([metadb],
     227        [AS_HELP_STRING([--with-metadb=yes], [Activates the metadata database support])],
     228        [WITHMETADB="$withval"], [WITHMETADB=""])
     229
     230if test "x$WITHMETADB" = "xyes"; then
     231        METADB="-DMETA_DB"
     232        METADB_FILE="meta_sql.o sqlapi.o"
     233else
     234        METADB=""
     235        METADB_FILE=""
     236fi
     237
     238AC_SUBST([METADB])
     239AC_SUBST([METADB_FILE])
     240
     241AC_ARG_WITH([hpc],
     242        [AS_HELP_STRING([--with-hpc=yes], [Specifies if you need to activate HPC support])],
     243        [HPCWITH="$withval"], [HPCWITH="no"])
     244
     245
     246AC_ARG_WITH([ssh2],
     247        [AS_HELP_STRING([--with-ssh2=PATH], [Specifies an alternative location for the ssh2 library])],
     248        [SSH2PATH="$withval"], [SSH2PATH="/usr"])
     249
     250if test "x$HPCWITH" = "xyes"; then
     251        HPC_FILES="service_internal_hpc.o sshapi.o"
     252        HPC_ENABLED="-DUSE_HPC"
     253        HPC_CPPFLAGS=""
     254        HPC_LDFLAGS=""
     255        # Extract the linker and include flags
     256        SSH2_LDFLAGS="-L$SSH2PATH/lib -lssh2"
     257        SSH2_CPPFLAGS="-I$SSH2PATH/include"
     258        # Check headers file
     259        CPPFLAGS_SAVE="$CPPFLAGS"
     260        CPPFLAGS="$SSH2_CPPFLAGS"
     261        LIBS_SAVE="$LIBS"
     262        LIBS="$SSH2_LDFLAGS"
     263       
     264        AC_CHECK_HEADERS([libssh2.h],
     265                 [], [AC_MSG_ERROR([could not find headers related to libssh2])])
     266        AC_CHECK_LIB([ssh2], [libssh2_session_init])
     267
     268        LIBS="$LIBS_SAVE"
     269fi
     270
     271AC_SUBST([HPC_CPPFLAGS])
     272AC_SUBST([HPC_LDFLAGS])
     273AC_SUBST([HPC_ENABLED])
     274AC_SUBST([HPC_FILES])
     275
     276AC_SUBST([SSH2_CPPFLAGS])
     277AC_SUBST([SSH2_LDFLAGS])
     278
    147279# ===========================================================================
    148280# Detect if libxml2 is installed
     
    400532AC_SUBST([MS_LIBS])
    401533AC_SUBST([MS_FILE])
     534AC_SUBST([MS_VERSION])
     535
     536# ===========================================================================
     537# Detect if R is installed
     538# ===========================================================================
     539
     540AC_ARG_WITH([r],
     541        [AS_HELP_STRING([--with-r=PATH], [To enable python support or Specifies an alternative directory for R installation,  disabled by default])],
     542        [R_PATH="$withval"; R_ENABLED="-DUSE_R"], [R_ENABLED=""])
     543
     544if test -z "$R_ENABLED"
     545then
     546        R_FILE=""
     547else
     548        R_FILE="service_internal_r.o"
     549        # Extract the linker and include flags
     550        R_LDFLAGS="-L$R_PATH/lib/ -lR"
     551        R_CPPFLAGS="-I$R_PATH/include/"
     552
     553        # Check headers file
     554        CPPFLAGS_SAVE="$CPPFLAGS"
     555        CPPFLAGS="$R_CPPFLAGS"
     556        AC_CHECK_HEADERS([RInternals.h],
     557                 [], [AC_MSG_ERROR([could not find headers include related to R])])
     558
     559        # Ensure we can link against libphp
     560        #LIBS_SAVE="$LIBS"
     561        #LIBS="$R_LDFLAGS"
     562        #AC_CHECK_LIB([$LIBS], [R_tryEval], [], [AC_MSG_ERROR([could not find libR])], [])
     563        #LIBS="$LIBS_SAVE"
     564fi
     565
     566AC_SUBST([R_CPPFLAGS])
     567AC_SUBST([R_LDFLAGS])
     568AC_SUBST([R_ENABLED])
     569AC_SUBST([R_FILE])
     570
    402571
    403572# ===========================================================================
     
    646815
    647816        AC_LANG([C++])
    648         echo $JAVA_CPPFLAGS
     817        #echo $JAVA_CPPFLAGS
    649818        # Check headers file (second time we check that in fact)
    650819        CPPFLAGS_SAVE="$CPPFLAGS"
     
    696865
    697866        AC_LANG([C++])
    698         echo $JAVA_CPPFLAGS
     867        #echo $JAVA_CPPFLAGS
    699868        # Check headers file (second time we check that in fact)
    700869        CPPFLAGS_SAVE="$CFLAGS"
     
    8881057        [SAGAPATH="$withval"], [SAGAPATH=""])
    8891058
     1059AC_ARG_WITH([saga-version],
     1060        [AS_HELP_STRING([--with-saga-version=VERSION], [Specifies the SAGA-GIS version number])],
     1061        [SAGAVERS="$withval"], [SAGAVERS="2"])
     1062
    8901063if test -z "$SAGAPATH"
    8911064then
     
    9031076        WX_ISSUE="-D_WX_WXCRTVARARG_H_"
    9041077        SAGA_DEFS="-D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD -DMODULE_LIBRARY_PATH=\\\"$SAGAPATH/lib/saga\\\""
    905         SAGA_CPPFLAGS=" -fPIC -I$SAGAPATH/include/saga/saga_core/saga_api/ `$WXCFG --unicode=yes --static=no --cxxflags` -D_SAGA_UNICODE $SAGA_DEFS $WX_ISSUE"
     1078        SAGA_CPPFLAGS="-DSAGA_VERSION=${SAGAVERS} -fPIC -I$SAGAPATH/include/saga/saga_core/saga_api/ `$WXCFG --unicode=yes --static=no --cxxflags` -D_SAGA_UNICODE $SAGA_DEFS $WX_ISSUE"
    9061079        SAGA_LDFLAGS="-fPIC `$WXCFG --unicode=yes --static=no --libs` -lsaga_api"
    9071080        SAGA_ENABLED="-DUSE_SAGA"
     
    9141087        LIBS_SAVE="$LIBS"
    9151088        LIBS="$SAGA_LDFLAGS"
    916         AC_CHECK_HEADERS([module_library.h],
    917                         [], [AC_MSG_ERROR([could not find header file $i related to SAGA-GIS])])
    918         AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include "module_library.h"],[SG_Get_Module_Library_Manager();]])],
    919                 [AC_MSG_RESULT([checking for SG_Get_Module_Library_Manager... yes])],[AC_MSG_ERROR([checking for SG_Get_Module_Library_Manager... failed])])
     1089        if test "$SAGAVERS" == "2"; then
     1090        AC_CHECK_HEADERS([module_library.h],
     1091                        [], [AC_MSG_ERROR([could not find header file $i related to SAGA-GIS])])
     1092        AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include "module_library.h"],[SG_Get_Module_Library_Manager();]])],
     1093                [AC_MSG_RESULT([checking for SG_Get_Module_Library_Manager... yes])],[AC_MSG_ERROR([checking for SG_Get_Module_Library_Manager... failed])])
     1094        else
     1095        AC_CHECK_HEADERS([tool_library.h],
     1096                        [], [AC_MSG_ERROR([could not find header file $i related to SAGA-GIS])])
     1097        AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include "tool_library.h"],[SG_Get_Tool_Library_Manager();]])],
     1098                [AC_MSG_RESULT([checking for SG_Get_Tool_Library_Manager... yes])],[AC_MSG_ERROR([checking for SG_Get_Tool_Library_Manager... failed])])
     1099        fi
     1100       
    9201101        LIBS="$LIBS_SAVE"
    9211102        AC_LANG_POP([C++])
  • trunk/zoo-project/zoo-kernel/main_conf_read.y

    r790 r917  
    8787 ;
    8888
    89 pair: PAIR {curr_key=zStrdup($1);}
     89pair: PAIR {if(curr_key!=NULL) free(curr_key);curr_key=zStrdup($1);}
    9090| EPAIR {
    9191  if(current_content==NULL)
     
    9999  }
    100100  free(curr_key);
     101  curr_key=NULL;
    101102  }
    102 | SPAIR  {curr_key=zStrdup($1);if(debug) printf("SPAIR FOUND !!\n"); }
     103| SPAIR  {if(curr_key!=NULL) free(curr_key);curr_key=zStrdup($1);if(debug) printf("SPAIR FOUND !!\n"); }
    103104 ;
    104105
     
    162163    free(current_content);
    163164  }
     165  if(curr_key!=NULL){
     166    free(curr_key);
     167  }
    164168
    165169  fclose(crin);
  • trunk/zoo-project/zoo-kernel/makefile.vc

    r788 r917  
    5050        $(CPP) $(CFLAGS) /c caching.c
    5151
     52service_json.obj: service_json.c service_json.h
     53        $(CPP) $(CFLAGS) /c service_json.c
     54
    5255request_parser.obj: request_parser.c request_parser.h
    5356        $(CPP) $(CFLAGS) /c request_parser.c
     
    7174        $(CPP) /c $(CFLAGS) service_internal_ruby.c
    7275
     76service_internal_mono.obj: service_internal_mono.c service_internal_mono.h service.h
     77        $(CPP) /c $(MONO_CLAGS) $(CFLAGS) service_internal_mono.c
     78
    7379service_internal_python.obj: service_internal_python.c service.h
    7480        $(CPP) /c $(CFLAGS) service_internal_python.c
     
    8995        $(CPP) /c $(CFLAGS) $(PHP_CFLAGS) service_internal_php.c
    9096   
     97service_callback.obj: service_callback.c service_callback.h service.h
     98        $(CPP) /c $(CFLAGS) service_callback.c
     99   
    91100service_internal_php7.obj: service_internal_php7.c service_internal_php.h service.h
    92101        $(CPP) /c $(CFLAGS) $(PHP_CFLAGS) service_internal_php7.c   
     
    95104        link /dll /out:$(LIBZOO_SERVICE) ./service.obj ./service_internal.obj ./sqlapi.obj $(LDFLAGS) /FORCE:MULTIPLE
    96105
    97 $(PROGRAMNAME): version.h $(LIBZOO_SERVICE) zoo_loader.obj zoo_service_loader.obj service_internal.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj lex.cr.obj lex.sr.obj service_conf.tab.obj main_conf_read.tab.obj request_parser.obj response_print.obj server_internal.obj caching.obj
    98         link zoo_loader.obj request_parser.obj response_print.obj server_internal.obj caching.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj main_conf_read.tab.obj lex.cr.obj service_conf.tab.obj lex.sr.obj  zoo_service_loader.obj ./libzoo_service.lib /out:$(PROGRAMNAME) $(LDFLAGS) $(LDFLAGSCGI)
     106$(PROGRAMNAME): version.h $(LIBZOO_SERVICE) zoo_loader.obj zoo_service_loader.obj service_internal.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(MONO_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj lex.cr.obj lex.sr.obj service_conf.tab.obj main_conf_read.tab.obj request_parser.obj response_print.obj server_internal.obj caching.obj service_json.obj service_callback.obj
     107        link zoo_loader.obj request_parser.obj response_print.obj server_internal.obj caching.obj service_json.obj service_callback.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(MONO_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj main_conf_read.tab.obj lex.cr.obj service_conf.tab.obj lex.sr.obj  zoo_service_loader.obj ./libzoo_service.lib /out:$(PROGRAMNAME) $(LDFLAGS) $(LDFLAGSCGI) $(JSONC_LIB) $(PTHREADS_LIB) $(XSLT_LIB)
    99108
    100 zcfg2yaml: version.h zcfg2yaml.obj zoo_service_loader.obj service_internal.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(RUBY_FILE) ulinet.obj lex.cr.obj lex.sr.obj service_conf.tab.obj main_conf_read.tab.obj
    101         link zcfg2yaml.obj server_internal.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj response_print.obj main_conf_read.tab.obj lex.cr.obj service_conf.tab.obj lex.sr.obj ./libzoo_service.lib /out:zcfg2yaml.exe $(LDFLAGS) $(LDFLAGSCGI)
     109zcfg2yaml: version.h zcfg2yaml.obj zoo_service_loader.obj service_internal.obj caching.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(MONO_FILE) $(RUBY_FILE) ulinet.obj lex.cr.obj lex.sr.obj service_conf.tab.obj main_conf_read.tab.obj
     110        link zcfg2yaml.obj server_internal.obj caching.obj $(PY_FILE) $(JAVA_FILE) $(MS_FILE) $(JS_FILE) $(MONO_FILE) $(RUBY_FILE) $(PHP_FILE) ulinet.obj response_print.obj main_conf_read.tab.obj lex.cr.obj service_conf.tab.obj lex.sr.obj ./libzoo_service.lib /out:zcfg2yaml.exe $(LDFLAGS) $(LDFLAGSCGI)
    102111
    103112clean:
     
    105114
    106115embed-manifest: zoo_loader.cgi
    107         mt.exe -manifest zoo_loader.cgi.manifest -outputresource:zoo_loader.cgi;1
     116        mt.exe -manifest zoo_loader.cgi.manifest -outputresource:zoo_loader.cgi;
  • trunk/zoo-project/zoo-kernel/mimetypes.h

    r601 r917  
    180180        { "application/vnd.dece.unspecified", "uvx" },
    181181        { "application/vnd.dece.zip", "uvz" },
    182         { "application/vnd.denovo.fcselayout-link", "fe_launch" },
     182        { "application/vnd.denovo.fcselayout-link", "fe_launch" },     
    183183        { "application/vnd.dna", "dna" },
    184184        { "application/vnd.dolby.mlp", "mlp" },
     
    818818*/
    819819static map* getFileExtensionMap(const char* mimeType, bool* hasExt) {
     820  map* ext = createMap("extension", "txt");
     821  *hasExt = false;
     822       
     823  if (mimeType != NULL) {       
     824    for (int i = 0; i < NUM_MIME_TYPES; i++) {                 
     825      if(strncmp(mimeType, MIME[i][M_Type], strlen(MIME[i][M_Type])) == 0) {
     826        free(ext->value);
     827        ext->value = zStrdup(MIME[i][M_Extension]);
     828        *hasExt = true;
     829        break;                         
     830      }
     831    }
     832    if (*hasExt == false && strncmp(mimeType, "image/", 6) == 0) {
     833      free(ext->value);
     834      ext->value = zStrdup(strstr(mimeType, "/") + 1);
     835    }
     836  }     
     837  return ext;
     838}
    820839
    821         map* ext = createMap("extension", "txt");
    822         *hasExt = false;
    823        
    824         if (mimeType != NULL) {         
    825                 for (int i = 0; i < NUM_MIME_TYPES; i++) {                     
    826                         if      (strncmp(mimeType, MIME[i][M_Type], strlen(MIME[i][M_Type])) == 0) {
    827                                 ext->value = zStrdup(MIME[i][M_Extension]);
    828                                 *hasExt = true;
    829                                 break;                         
    830                         }               
    831                 }
    832                 if (*hasExt == false && strncmp(mimeType, "image/", 6) == 0) {
    833                         ext->value = zStrdup(strstr(mimeType, "/") + 1);
    834                 }                       
    835         }       
    836         return ext;
     840static int isGeographic(const char* mimeType){
     841  char* imageMimeType[4]={
     842    "image/tiff",
     843    "image/png",
     844    "image/jpeg",
     845    "application/vnd.google-earth.kmz"
     846  };
     847  char* vectorMimeType[5]={
     848    "text/xml",
     849    "application/json",
     850    "application/gml+xml",
     851    "application/zip",
     852    "application/vnd.google-earth.kml+xml"
     853  };
     854  int i=0;
     855  for(;i<4;i++){
     856    if(strncmp(imageMimeType[i],mimeType,strlen(imageMimeType[i]))==0)
     857      return 1;
     858  }
     859  i=0;
     860  for(;i<5;i++){
     861    if(strncmp(vectorMimeType[i],mimeType,strlen(vectorMimeType[i]))==0)
     862      return 2;
     863  }
     864  return -1;
    837865}
  • trunk/zoo-project/zoo-kernel/nmake.opt

    r788 r917  
    8787!ENDIF
    8888
     89!IFDEF MONO_DIR
     90MONO_CFLAGS=-DUSE_MONO -I"$(MONO_DIR)"\msvc -I"$(MONO_DIR)"\msvc\include -I"$(MONO_DIR)"
     91MONO_LDFLAGS=/LIBPATH:"$(MONO_DIR)/msvc/build/sgen/x64/lib/Release" mono-2.0-sgen.lib
     92MONO_FILE=service_internal_mono.obj
     93!ENDIF
     94
    8995!IFNDEF ZOOK_DIR
    9096ZOOK_DIR=.
     
    100106!ENDIF
    101107
    102 CFLAGS= $(DB_FLAGS) $(MS_DEFS) $(INCLUDES) $(CFLAGS1) /nologo /MD /W3 /EHsc /Ox /D_CRT_SECURE_NO_WARNINGS /DWIN32 /DPROGRAMNAME=\"$(PROGRAMNAME)\" $(CJFLAGS) -I$(ZOOK_DIR) $(RUBY_CFLAGS) -I./ $(JAVA_CFLAGS) $(MS_CFLAGS) -I$(TROOT)\..\..\thirds\dirent-win32 -I$(INTL_DIR) -I$(CURL_DIR)\include -I$(XML2_DIR)\include -I$(GDAL_DIR)\port $(JS_CFLAGS) -I$(GDAL_DIR)\ogr -I$(GDAL_DIR)\gcore -I$(GD_DIR) -I$(ICONV_DIR) -I$(TROOT)\..\..\thirds\include -I$(TROOT)\..\..\thirds\cgic206 -I$(PYTHON_CPATH)\include -I$(SSL_DIR)/inc32 -I$(FCGI_DIR)\include $(PY_CFLAGS) $(PHP_CFLAGS) -DLINUX_FREE_ISSUE #-DDEBUG #-DDEBUG_SERVICE_CONF
     108!IFDEF WIN32_DEBUG
     109WIN32_DBG=-DWIN32_DEBUG
     110!ENDIF
     111
     112CFLAGS=$(MONO_CFLAGS) $(WIN32_DBG) $(DB_FLAGS) $(MS_DEFS) $(INCLUDES) $(CFLAGS1) /nologo /MD /W3 /EHsc /Ox /D_CRT_SECURE_NO_WARNINGS /DWIN32 /DPROGRAMNAME=\"$(PROGRAMNAME)\" $(CJFLAGS) -I$(ZOOK_DIR) $(RUBY_CFLAGS) -I./ $(JAVA_CFLAGS) $(MS_CFLAGS) -I$(TROOT)\..\..\thirds\dirent-win32 -I$(INTL_DIR) -I$(CURL_DIR)\include -I$(XML2_DIR)\include -I$(GDAL_DIR)\port $(JS_CFLAGS) -I$(GDAL_DIR)\ogr -I$(GDAL_DIR)\gcore -I$(GD_DIR) -I$(ICONV_DIR) -I$(TROOT)\..\..\thirds\include -I$(TROOT)\..\..\thirds\cgic206 -I$(PYTHON_CPATH)\include -I$(SSL_DIR)/inc32 -I$(FCGI_DIR)\include $(PY_CFLAGS) $(PHP_CFLAGS) -DLINUX_FREE_ISSUE #-DDEBUG #-DDEBUG_SERVICE_CONF
    103113
    104114LDFLAGSCGI=$(TROOT)/../../thirds/cgic206/libcgic.lib
    105 LDFLAGS=$(FCGI_DIR)/libfcgi/Release/libfcgi.lib $(CURL_LIBRARY) $(PY_LDFLAGS) $(XML2_LIBRARY) $(SSL_DIR)/out32dll/libeay32.lib $(JAVA_LDFLAGS) $(SSL_DIR)/out32dll/ssleay32.lib $(MS_LDFLAGS) $(INTL_DIR)/intl.lib $(XML2_DIR)/win32/bin.msvc/libxml2.lib $(GDAL_DIR)/gdal_i.lib $(CURL_DIR)/lib/libcurl.lib $(JS_LDFLAGS) $(RUBY_LDFLAGS) $(PHP_LDFLAGS) /machine:i386
     115LDFLAGS=$(MONO_LDFLAGS) $(FCGI_DIR)/libfcgi/Release/libfcgi.lib $(CURL_LIBRARY) $(PY_LDFLAGS) $(XML2_LIBRARY) $(SSL_DIR)/out32dll/libeay32.lib $(JAVA_LDFLAGS) $(SSL_DIR)/out32dll/ssleay32.lib $(MS_LDFLAGS) $(INTL_DIR)/intl.lib $(XML2_DIR)/win32/bin.msvc/libxml2.lib $(GDAL_DIR)/gdal_i.lib $(CURL_DIR)/lib/libcurl.lib $(JS_LDFLAGS) $(RUBY_LDFLAGS) $(PHP_LDFLAGS) /machine:i386
  • trunk/zoo-project/zoo-kernel/request_parser.c

    r889 r917  
    2828#include "response_print.h"
    2929#include "caching.h"
     30#include "cgic.h"
    3031
    3132/**
     
    154155      addToMap(cursor->content,"base64_value",tmp->value);
    155156      int size=0;
    156       char *s=strdup(tmp->value);
     157      char *s=zStrdup(tmp->value);
    157158      free(tmp->value);
    158159      tmp->value=base64d(s,strlen(s),&size);
     
    174175          addToMap(cursor->content,key,tmp->value);
    175176          int size=0;
    176           char *s=strdup(tmp->value);
     177          char *s=zStrdup(tmp->value);
    177178          free(tmp->value);
    178179          tmp->value=base64d(s,strlen(s),&size);
     
    521522  int l = 0;
    522523  map* version=getMapFromMaps(*main_conf,"main","rversion");
     524  map* memory=getMapFromMaps(*main_conf,"main","memory");
    523525  int vid=getVersionId(version->value);
    524526  for (k=0; k < nodes->nodeNr; k++)
     
    533535            xmlChar *val = xmlGetProp (cur, BAD_CAST "id");
    534536            tmpmaps = createMaps((char *) val);
     537            xmlFree(val);
    535538          }
    536539
     
    624627                            tmpmaps->content =
    625628                              createMap (refs[l], (char *) val);
    626 
    627629                          map *ltmp = getMap (tmpmaps->content, "method");
    628630                          if (l == 4 )
    629631                            {
    630                               if ((ltmp==NULL || strncasecmp (ltmp->value, "POST",4) != 0)) //
    631                               //if ((ltmp==NULL || strncmp (ltmp->value, "POST",4) != 0))
     632                              if ((ltmp==NULL || strncmp (ltmp->value, "POST",4) != 0))
    632633                                {
    633634                                  if (loadRemoteFile
     
    751752                                      map *btmp =
    752753                                        getMap (tmpmaps->content, "Reference");
     754                                      addToMap (tmpmaps->content, "Body", tmp);
    753755                                      if (btmp != NULL)
    754756                                        {
     
    759761                                                           xmlStrlen(btmps),
    760762                                                           INTERNET_FLAG_NO_CACHE_WRITE,
    761                                                            0);
     763                                                           0,
     764                                                           *main_conf);
    762765                                          addIntToMap (tmpmaps->content, "Order", hInternet->nb);
    763766                                        }
     
    778781                                  xmlGetProp (cur3, BAD_CAST "href");
    779782                                HINTERNET bInternet, res1, res;
     783                                maps *tmpConf=createMaps("main");
     784                                tmpConf->content=createMap("memory","load");
    780785                                bInternet = InternetOpen (
    781786#ifndef WIN32
     
    785790                                                          INTERNET_OPEN_TYPE_PRECONFIG,
    786791                                                          NULL, NULL, 0);
     792#ifndef WIN32
    787793                                if (!CHECK_INET_HANDLE (bInternet))
    788794                                  fprintf (stderr,
    789795                                           "WARNING : bInternet handle failed to initialize");
     796#endif
    790797                                bInternet.waitingRequests[0] =
    791                                   strdup ((char *) val);
     798                                  zStrdup ((char *) val);
    792799                                res1 =
    793800                                  InternetOpenUrl (&bInternet,
     
    795802                                                   [0], NULL, 0,
    796803                                                   INTERNET_FLAG_NO_CACHE_WRITE,
    797                                                    0);
     804                                                   0,
     805                                                   tmpConf);
    798806                                processDownloads (&bInternet);
     807                                freeMaps(&tmpConf);
     808                                free(tmpConf);
    799809                                char *tmp =
    800810                                  (char *)
     
    816826                                                  &bRead);
    817827                                tmp[bInternet.ihandle[0].nDataLen] = 0;
    818                                 InternetCloseHandle (&bInternet);
     828                                InternetCloseHandle(&bInternet);
     829                                addToMap (tmpmaps->content, "Body", tmp);
    819830                                map *btmp =
    820831                                  getMap (tmpmaps->content, "href");
     
    829840                                                       strlen(tmp),
    830841                                                       INTERNET_FLAG_NO_CACHE_WRITE,
    831                                                        0);
     842                                                       0,
     843                                                       *main_conf);
    832844                                    addIntToMap (tmpmaps->content, "Order", hInternet->nb);
    833845                                  }
    834846                                free (tmp);
     847                                xmlFree (val);
    835848                              }
    836849                        }
     
    895908                    }
    896909                  }
    897 
    898910
    899911                  while (cur4 != NULL)
     
    967979
    968980                      map *test = getMap (tmpmaps->content, "encoding");
    969 
    970981                      if (test == NULL)
    971                         { 
     982                        {
    972983                          if (tmpmaps->content != NULL)
    973984                            addToMap (tmpmaps->content, "encoding",
     
    979990                        }
    980991
    981                       if (getMap(tmpmaps->content,"dataType")==NULL && strcasecmp (test->value, "base64") != 0)
    982                         {
    983                           xmlChar *mv = xmlNodeListGetString (doc,
    984                                                               cur4->xmlChildrenNode,
    985                                                               1);
     992                      if (getMap(tmpmaps->content,"dataType")==NULL && test!=NULL && strcasecmp (test->value, "base64") != 0)
     993                        {
     994                          xmlChar *mv = NULL;
     995                          /*if(cur4!=NULL && cur4->xmlChildrenNode!=NULL)
     996                            xmlChar *mv = xmlNodeListGetString (doc,
     997                                                                cur4->xmlChildrenNode,
     998                                                                1);*/
    986999                          map *ltmp =
    9871000                            getMap (tmpmaps->content, "mimeType");
    988                           if (mv == NULL
    989                               ||
     1001                          if (/*mv == NULL
     1002                              ||*/
    9901003                              (xmlStrcasecmp
    9911004                               (cur4->name, BAD_CAST "ComplexData") == 0
     
    10251038                                           buffersize);
    10261039                            }else{
     1040
    10271041                            if(xmlStrcasecmp
    10281042                               (cur4->name, BAD_CAST "BoundingBoxData") == 0){
     
    10391053                              xmlNodePtr cur5 = cur4->children;
    10401054                              while (cur5 != NULL
     1055                                     && cur5->type != XML_ELEMENT_NODE
     1056                                     && cur5->type != XML_TEXT_NODE
    10411057                                     && cur5->type != XML_CDATA_SECTION_NODE)
    10421058                                cur5 = cur5->next;
    10431059                              if (cur5 != NULL
    1044                                   && cur5->type == XML_CDATA_SECTION_NODE){
    1045                                 if(mv!=NULL)
    1046                                   xmlFree(mv);
    1047                                 mv=xmlStrdup(cur5->content);
     1060                                  && cur5->type != XML_CDATA_SECTION_NODE
     1061                                  && cur5->type != XML_TEXT_NODE)
     1062                                {
     1063                                  xmlDocPtr doc1 = xmlNewDoc (BAD_CAST "1.0");
     1064                                  int buffersize;
     1065                                  xmlDocSetRootElement (doc1, cur5);
     1066                                  xmlDocDumpFormatMemoryEnc (doc1, &mv,
     1067                                                             &buffersize,
     1068                                                             "utf-8", 0);
     1069                                  addIntToMap (tmpmaps->content, "size",
     1070                                               buffersize);
     1071                                }
     1072                              else if (cur5 != NULL)/*
     1073                                     && cur5->type == XML_CDATA_SECTION_NODE)*/{
     1074                                xmlFree(mv);
     1075                                if(cur5->content!=NULL){
     1076                                  mv=xmlStrdup(cur5->content);
     1077                                }
    10481078                              }
    10491079                            }
     
    10881118                cur2 = cur2->next;
    10891119              }
     1120            }
     1121          if(memory!=NULL && strncasecmp(memory->value,"load",4)!=0)
     1122            if(getMap(tmpmaps->content,"to_load")==NULL){
     1123              addToMap(tmpmaps->content,"to_load","false");
    10901124            }
    10911125          {
     
    11231157                  }
    11241158              }
    1125             else
     1159            else{
    11261160              addMapsToMaps (request_output, tmpmaps);
     1161            }
    11271162          }
    11281163          freeMaps (&tmpmaps);
     
    11981233      const char ress[4][13] =
    11991234        { "mimeType", "encoding", "schema", "transmission" };
     1235      xmlFree (val);
    12001236      for (l = 0; l < 4; l++){
    12011237        val = xmlGetProp (cur, BAD_CAST ress[l]);
     
    12171253        while (ccur != NULL){
    12181254          if(ccur->type == XML_ELEMENT_NODE){
    1219             char *xpathExpr=(char*)malloc(65+strlen(tmpmaps->name));
    1220             sprintf(xpathExpr,"/*/*[local-name()='Output' and @id='%s']/*[local-name()='Output']",tmpmaps->name);
     1255            char *xpathExpr=(char*)malloc(66+strlen(tmpmaps->name));
     1256            sprintf(xpathExpr,"/*/*[local-name()='Output' and @id='%s']/*[local-name()='Output']",tmpmaps->name);           
    12211257            xmlXPathObjectPtr tmpsptr = extractFromDoc (doc, xpathExpr);
    12221258            xmlNodeSet* cnodes = tmpsptr->nodesetval;
    12231259            xmlParseOutputs2(main_conf,request_inputs,&tmpmaps->child,doc,cnodes);
     1260            xmlXPathFreeObject (tmpsptr);
     1261            free(xpathExpr);
    12241262            break;
    12251263          }
     
    14701508
    14711509  xmlInitParser ();
    1472   //xmlDocPtr doc = xmlReadMemory (post, cgiContentLength, "input_request.xml", NULL, XML_PARSE_RECOVER);
    1473   xmlDocPtr doc = xmlReadMemory (post, cgiContentLength, "input_request.xml", NULL, XML_PARSE_RECOVER | XML_PARSE_HUGE); //
     1510  xmlDocPtr doc = xmlReadMemory (post, cgiContentLength, "input_request.xml", NULL, XML_PARSE_RECOVER);
    14741511
    14751512  /**
     
    15031540          else
    15041541            addToMap(*request_inputs,"mode","auto");
     1542          xmlFree(val);
    15051543          val = xmlGetProp (cur, BAD_CAST "response");
    15061544          if(val!=NULL){
     
    15151553            addToMap(*request_inputs,"ResponseDocument","");
    15161554          }
     1555          xmlFree(val);
    15171556        }
    15181557      }
     
    17681807#endif
    17691808                  targetFile =
    1770                     open (storageNameOnServer, O_RDWR | O_CREAT | O_TRUNC,
     1809                    zOpen (storageNameOnServer, O_RDWR | O_CREAT | O_TRUNC,
    17711810                          S_IRWXU | S_IRGRP | S_IROTH);
    17721811                  if (targetFile < 0)
     
    17881827                  addToMap (tmpReqI->content, "lref", storageNameOnServer);
    17891828                  cgiFormFileClose (file);
    1790                   close (targetFile);
     1829                  zClose (targetFile);
    17911830                  free(fileNameOnServer);
    17921831                  free(storageNameOnServer);
     
    18201859  if (r_inputs == NULL){
    18211860    if(mandatory>0){
    1822       const char *replace=_("Mandatory parameter <%s> was not specified");
     1861      char *replace=_("Mandatory parameter <%s> was not specified");
    18231862      char *message=(char*)malloc((strlen(replace)+strlen(toCheck)+1)*sizeof(char));
    18241863      sprintf(message,replace,toCheck);
     
    18691908    }
    18701909    if(hasValidValue<0){
    1871       const char *replace=_("The value <%s> was not recognized, %s %s the only acceptable value.");
     1910      char *replace=_("The value <%s> was not recognized, %s %s the only acceptable value.");
    18721911      nb=0;
    18731912      char *vvalues=NULL;
    1874       const char* num=_("is");
     1913      char* num=_("is");
    18751914      while(avalues[nb]!=NULL){
    18761915        char *tvalues;
     
    19201959  }
    19211960}
     1961
     1962/**
     1963 * Parse cookie contained in request headers.
     1964 *
     1965 * @param conf the conf maps containinfg the main.cfg
     1966 * @param cookie the
     1967 */
     1968void parseCookie(maps** conf,const char* cookie){
     1969  char* tcook=zStrdup(cookie);
     1970  char *token, *saveptr;
     1971  token = strtok_r (tcook, "; ", &saveptr);
     1972  maps* res=createMaps("cookies");
     1973  while (token != NULL){
     1974    char *token1, *saveptr1, *name;
     1975    int i=0;
     1976    token1 = strtok_r (token, "=", &saveptr1);
     1977    while (token1 != NULL){
     1978      if(i==0){
     1979        name=zStrdup(token1);
     1980        i++;
     1981      }
     1982      else{
     1983        if(res->content==NULL)
     1984          res->content=createMap(name,token1);
     1985        else
     1986          addToMap(res->content,name,token1);
     1987        free(name);
     1988        name=NULL;
     1989        i=0;
     1990      }
     1991      token1 = strtok_r (NULL, "=", &saveptr1);
     1992    }
     1993    if(name!=NULL)
     1994      free(name);
     1995    token = strtok_r (NULL, "; ", &saveptr);
     1996  }
     1997  addMapsToMaps(conf,res);
     1998  freeMaps(&res);
     1999  free(res);
     2000  free(tcook);
     2001}
  • trunk/zoo-project/zoo-kernel/request_parser.h

    r866 r917  
    4545  int kvpParseOutputs(maps**,map *,maps**);
    4646  int xmlParseInputs(maps**,service*,maps**,xmlDocPtr,xmlNodeSet*,HINTERNET*);
     47  int xmlParseBoundingBox(maps** main_conf,map** current_input,xmlDocPtr doc);
    4748  int xmlParseOutputs(maps**,map**,maps**,xmlDocPtr,xmlNodePtr,bool);
    4849  int xmlParseRequest(maps**,const char*,map**,service*,maps**,maps**,HINTERNET*);
     
    5051  void checkValidValue(map*,map**,const char*,const char**,int);
    5152  int validateRequest(maps**,service*,map*,maps**,maps**,HINTERNET*);
    52 
     53  void parseCookie(maps**,const char*);
     54 
    5355#ifdef __cplusplus
    5456}
  • trunk/zoo-project/zoo-kernel/response_print.c

    r889 r917  
    2323 */
    2424
     25#include "service.h"
    2526#include "response_print.h"
    2627#include "request_parser.h"
     
    3132#else
    3233#include "cpl_vsi.h"
     34#endif
     35#ifdef USE_CALLBACK
     36#include "service_callback.h"
    3337#endif
    3438
     
    7579    }
    7680    if(prefix!=NULL){
    77       char* tmp0=strdup(serv->name);
     81      char* tmp0=zStrdup(serv->name);
    7882      free(serv->name);
    7983      serv->name=(char*)malloc((strlen(prefix)+strlen(tmp0)+1)*sizeof(char));
     
    179183    nbNs++;
    180184    currId=0;
    181     nsName[currId]=strdup(name);
     185    nsName[currId]=zStrdup(name);
    182186    usedNs[currId]=xmlNewNs(nr,BAD_CAST url,BAD_CAST name);
    183187  }else{
     
    186190      nbNs++;
    187191      currId=nbNs-1;
    188       nsName[currId]=strdup(name);
     192      nsName[currId]=zStrdup(name);
    189193      usedNs[currId]=xmlNewNs(nr,BAD_CAST url,BAD_CAST name);
    190194    }
     
    251255  if(soap!=NULL && strcasecmp(soap->value,"true")==0){
    252256    int lNbNs=nbNs;
    253     nsName[lNbNs]=strdup("soap");
     257    nsName[lNbNs]=zStrdup("soap");
    254258    usedNs[lNbNs]=xmlNewNs(NULL,BAD_CAST "http://www.w3.org/2003/05/soap-envelope",BAD_CAST "soap");
    255259    nbNs++;
    256260    xmlNodePtr nr = xmlNewNode(usedNs[lNbNs], BAD_CAST "Envelope");
    257     nsName[nbNs]=strdup("soap");
     261    nsName[nbNs]=zStrdup("soap");
    258262    usedNs[nbNs]=xmlNewNs(nr,BAD_CAST "http://www.w3.org/2003/05/soap-envelope",BAD_CAST "soap");
    259263    nbNs++;
    260     nsName[nbNs]=strdup("xsi");
     264    nsName[nbNs]=zStrdup("xsi");
    261265    usedNs[nbNs]=xmlNewNs(nr,BAD_CAST "http://www.w3.org/2001/XMLSchema-instance",BAD_CAST "xsi");
    262266    nbNs++;
     
    338342      }
    339343      else{
    340         nc4 = xmlNewNode(ns_ows, BAD_CAST "Language");
    341         xmlAddChild(nc4,xmlNewText(BAD_CAST buff));
    342344        if(dcount==0){
    343345          if(vid==0){
     346            nc4 = xmlNewNode(ns_ows, BAD_CAST "Language");
     347            xmlAddChild(nc4,xmlNewText(BAD_CAST buff));
    344348            xmlAddChild(nc2,nc4);
    345349            xmlAddChild(nc1,nc2);
     
    361365      nc4 = xmlNewNode(ns_ows, BAD_CAST "Language");
    362366      xmlAddChild(nc4,xmlNewText(BAD_CAST buff));             
    363         if(vid==0)
    364           xmlAddChild(nc3,nc4);
    365         else
    366           xmlAddChild(nc1,nc4);
     367      if(vid==0)
     368        xmlAddChild(nc3,nc4);
     369      else
     370        xmlAddChild(nc1,nc4);
    367371    }
    368372  }
     
    590594    map* tmp=getMap(toto1->content,"serverAddress");
    591595    if(tmp!=NULL){
    592       SERVICE_URL = strdup(tmp->value);
     596      SERVICE_URL = zStrdup(tmp->value);
    593597    }
    594598    else
    595       SERVICE_URL = strdup("not_defined");
     599      SERVICE_URL = zStrdup("not_defined");
    596600  }
    597601  else
    598     SERVICE_URL = strdup("not_defined");
     602    SERVICE_URL = zStrdup("not_defined");
    599603
    600604  for(j=0;j<nbSupportedRequests;j++){
     
    644648 * @return the generated wps:ProcessOfferings xmlNodePtr
    645649 */
    646 void printGetCapabilitiesForProcess(registry *reg, maps* m,xmlNodePtr nc,service* serv){
     650void printGetCapabilitiesForProcess(registry *reg, maps* m,xmlDocPtr doc,xmlNodePtr nc,service* serv){
    647651  xmlNsPtr ns,ns_ows,ns_xml,ns_xlink;
    648   xmlNodePtr n=NULL,nc1,nc2;
     652  xmlNodePtr n=NULL,nc1,nc2,nc3;
    649653  map* version=getMapFromMaps(m,"main","rversion");
    650654  int vid=getVersionId(version->value);
     
    667671      limit=7;
    668672    }
     673    nc3=NULL;
     674    map* sType=getMap(serv->content,"serviceType");
    669675    for(;i<limit;i+=2){
    670676      if(capabilities[vid][i]==NULL)
     
    682688            xmlNewNsProp(nc1,ns,BAD_CAST capabilities[vid][i],BAD_CAST tmp1->value);
    683689        }
    684         else
    685           xmlNewNsProp(nc1,ns,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
     690        else{
     691          if(i==3 && vid==1 && sType!=NULL && strstr(sType->value,"HPC")!=NULL)
     692            xmlNewNsProp(nc1,ns,BAD_CAST capabilities[vid][i],BAD_CAST "async-execute dismiss");
     693          else
     694            xmlNewNsProp(nc1,ns,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
     695        }
    686696      }
    687697    }
     
    690700    printDescription(nc1,ns_ows,serv->name,serv->content,vid);
    691701    tmp1=serv->metadata;
    692     while(tmp1!=NULL){
    693       nc2 = xmlNewNode(ns_ows, BAD_CAST "Metadata");
    694       xmlNewNsProp(nc2,ns_xlink,BAD_CAST tmp1->name,BAD_CAST tmp1->value);
    695       xmlAddChild(nc1,nc2);
    696       tmp1=tmp1->next;
    697     }
    698 
     702
     703    addMetadata(tmp1,doc,nc1,ns_ows,ns_xlink,vid);
     704    tmp1=serv->additional_parameters;
     705    int fromDb=-1;
     706    map* test=getMap(serv->content,"fromDb");
     707    if(test!=NULL && strncasecmp(test->value,"true",4)==0)
     708      fromDb=1;
     709    addAdditionalParameters(tmp1,doc,nc1,ns_ows,ns_xlink,fromDb);
     710
     711    if(nc3!=NULL)
     712      xmlAddChild(nc1,nc3);
    699713    xmlAddChild(nc,nc1);
    700714  }
     715
    701716}
    702717
     
    708723 * @param content the servive main content created from the zcfg file
    709724 * @param vid the version identifier (0 for 1.0.0 and 1 for 2.0.0)
    710  */
    711 void attachAttributes(xmlNodePtr n,xmlNsPtr ns,map* content,int vid){
     725 * @param serviceType string containing the current service type
     726 */
     727void attachAttributes(xmlNodePtr n,xmlNsPtr ns,map* content,int vid,map* serviceType){
    712728  int limit=7;
    713729  for(int i=1;i<limit;i+=2){
     
    728744    }
    729745    else{
    730       if(vid==0 && i>=2)
    731         xmlNewProp(n,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
     746      if(i==3 && vid==1 && serviceType!=NULL && strstr(serviceType->value,"HPC")!=NULL)
     747        xmlNewNsProp(n,ns,BAD_CAST capabilities[vid][i],BAD_CAST "async-execute dismiss");
    732748      else
    733         xmlNewNsProp(n,ns,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
    734     }
     749        if(vid==0 && i>=2)
     750          xmlNewProp(n,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
     751        else
     752          xmlNewNsProp(n,ns,BAD_CAST capabilities[vid][i],BAD_CAST capabilities[vid][i+1]);
     753    }
     754  }
     755}
     756
     757/**
     758 * Add a Metadata node to any existing node.
     759 * @param meta the map defining the additional parameters
     760 * @param doc the XML document used
     761 * @param nb the node to add the additional parameters
     762 * @param ns_ows the OWS namespace
     763 * @param ns_xlink the xlink namespace
     764 * @param vid the version of WPS to use (0 for 1.0.0 and 1 for 2.0)
     765 */
     766void addMetadata(map* meta,xmlDocPtr doc,xmlNodePtr nc,xmlNsPtr ns_ows,xmlNsPtr ns_xlink,int vid){
     767  int hasTitle=-1;
     768  int hasValue=-1;
     769  xmlNodePtr nc1;
     770  map* oMeta=meta;
     771  int isAdditionalParameters=-1;
     772  int level=0;
     773  map* test=getMap(meta,"title");
     774  if(test!=NULL)
     775    level+=1;
     776  test=getMap(meta,"href");
     777  if(test!=NULL)
     778    level+=1;
     779  test=getMap(meta,"role");
     780  if(test!=NULL)
     781    level+=1;
     782  if(count(oMeta)>level+1)
     783    isAdditionalParameters=1;
     784  char *ctitle=NULL;
     785  while(meta!=NULL){
     786    if(hasTitle<0)
     787      if(isAdditionalParameters<0)
     788        nc1 = xmlNewNode(ns_ows, BAD_CAST "Metadata");
     789      else
     790        if(hasValue<0)
     791          nc1 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameters");
     792    if(strncasecmp(meta->name,"title",5)==0 ||
     793       strcasecmp(meta->name,"href")==0 ||
     794       strcasecmp(meta->name,"role")==0 ){
     795      int index=5;
     796      if(strncasecmp(meta->name,"title",5)==0){
     797        index=6;
     798        hasTitle=1;
     799        if(ctitle!=NULL && strcasecmp(meta->value,ctitle)!=0){
     800          xmlAddChild(nc,nc1);
     801          nc1 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameters");
     802          free(ctitle);
     803          ctitle=NULL;
     804        }
     805        if(ctitle==NULL){
     806          char *tmp=(char*)malloc((strlen(meta->name)+1)*sizeof(char));
     807          snprintf(tmp,index,"%s",meta->name);
     808          xmlNewNsProp(nc1,ns_xlink,BAD_CAST tmp,BAD_CAST meta->value);
     809          free(tmp);
     810        }         
     811        if(ctitle!=NULL)
     812          free(ctitle);
     813        ctitle=zStrdup(meta->value);
     814      }
     815    }else{
     816      xmlNodePtr nc2 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameter");
     817      xmlNodePtr nc3 = xmlNewNode(ns_ows, BAD_CAST "Name");
     818      xmlAddChild(nc3,xmlNewText(BAD_CAST meta->name));
     819      xmlNodePtr nc4 = xmlNewNode(ns_ows, BAD_CAST "Value");
     820      xmlAddChild(nc4,xmlNewText(BAD_CAST meta->value));
     821      xmlAddChild(nc2,nc3);
     822      xmlAddChild(nc2,nc4);
     823      xmlAddChild(nc1,nc2);
     824      hasTitle=-1;
     825    }
     826    meta=meta->next;
     827    if(hasTitle<0){
     828      hasValue=1;
     829      if(isAdditionalParameters){
     830        if(vid==0){
     831          meta=NULL;
     832          break;
     833        }else
     834          xmlAddChild(nc,nc1);
     835      }
     836    }
     837  }
     838  if(oMeta!=NULL && hasValue<0 && nc1!=NULL){
     839    xmlAddChild(nc,nc1);
     840  }
     841}
     842
     843/**
     844 * Add AdditionalParameters nodes to any existing node.
     845 * @param meta the map defining the additional parameters
     846 * @param doc the XML document used
     847 * @param nb the node to add the additional parameters
     848 * @param ns_ows the OWS namespace
     849 * @param ns_xlink the xlink namespace
     850 * @param fromDb 1 if the metadata has been extracted from the metadb,
     851 * 0 otherwise
     852 */
     853void addAdditionalParameters(map* meta,xmlDocPtr doc,xmlNodePtr nc,xmlNsPtr ns_ows,xmlNsPtr ns_xlink,int fromDb){
     854  int hasTitle=-1;
     855  int hasValue=-1;
     856  int toAddAtEnd=-1;
     857  int cnt=0;
     858  xmlNodePtr* ncr=NULL;
     859  xmlNodePtr nc1;
     860  map* oMeta=meta;
     861  int isAdditionalParameters=-1;
     862  int level=0;
     863  map* test=getMap(meta,"title");
     864  map* otitle=getMap(meta,"title");
     865  map* length=getMap(meta,"length");
     866  int len=0;
     867  char *ctitle=NULL;
     868   
     869  if(test!=NULL)
     870    level+=1;
     871  test=getMap(meta,"href");
     872  if(test!=NULL)
     873    level+=1;
     874  test=getMap(meta,"role");
     875  if(test!=NULL)
     876    level+=1;
     877  if(count(oMeta)>level+1)
     878    isAdditionalParameters=1;
     879
     880  while(meta!=NULL){
     881    if(hasTitle<0 && hasValue<0){
     882      nc1 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameters");
     883    }
     884    if(strncasecmp(meta->name,"title",5)==0 ||
     885       strcasecmp(meta->name,"href")==0 ||
     886       strcasecmp(meta->name,"role")==0 ){
     887      int index=5;
     888      if(strncasecmp(meta->name,"title",5)==0){
     889        index=6;
     890        hasTitle=1;
     891        if(ctitle!=NULL && strcasecmp(meta->value,ctitle)!=0){
     892          xmlNodePtr ncTmp = xmlDocCopyNodeList(doc,nc1);
     893          xmlAddChild(nc,ncTmp);
     894          xmlFreeNode(nc1);
     895          toAddAtEnd=1;
     896          cnt++;
     897          nc1 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameters");
     898          free(ctitle);
     899          ctitle=NULL;
     900        }
     901        if(ctitle==NULL){
     902          char *tmp=(char*)malloc((strlen(meta->name)+1)*sizeof(char));
     903          snprintf(tmp,index,"%s",meta->name);
     904          xmlNewNsProp(nc1,ns_xlink,BAD_CAST tmp,BAD_CAST meta->value);
     905          free(tmp);
     906        }         
     907        if(ctitle!=NULL)
     908          free(ctitle);
     909        ctitle=zStrdup(meta->value);
     910      }else{
     911        xmlNewNsProp(nc1,ns_xlink,BAD_CAST meta->name,BAD_CAST meta->value);
     912      }
     913    }else{
     914      if(strncasecmp(meta->name,"length",6)!=0 && strncasecmp(meta->name,"fromDb",6)!=0){
     915        xmlNodePtr nc2 = xmlNewNode(ns_ows, BAD_CAST "AdditionalParameter");
     916        xmlNodePtr nc3 = xmlNewNode(ns_ows, BAD_CAST "Name");
     917        xmlAddChild(nc3,xmlNewText(BAD_CAST meta->name));
     918        xmlAddChild(nc2,nc3);
     919        if(fromDb<0){
     920          char *mptr;
     921          char* meta_values=strtok_r(meta->value,",",&mptr);
     922          while(meta_values!=NULL){
     923            xmlNodePtr nc4 = xmlNewNode(ns_ows, BAD_CAST "Value");
     924            xmlAddChild(nc4,xmlNewText(BAD_CAST meta_values));
     925            xmlAddChild(nc2,nc4);
     926            meta_values=strtok_r(NULL,",",&mptr);
     927          }
     928        }else{
     929          xmlNodePtr nc4 = xmlNewNode(ns_ows, BAD_CAST "Value");
     930          xmlAddChild(nc4,xmlNewCDataBlock(doc,BAD_CAST meta->value,strlen(meta->value)));
     931          xmlAddChild(nc2,nc4);
     932        }
     933        xmlAddChild(nc1,nc2);
     934      }
     935      hasTitle=-1;
     936    }
     937    meta=meta->next;
     938    if(hasTitle<0){
     939      //xmlAddChild(nc,nc1);
     940      hasValue=1;
     941    }/*else
     942       if(ctitle!=NULL)
     943       free(ctitle);*/
     944  }
     945  if(length!=NULL)
     946    len=atoi(length->value);
     947  if(otitle!=NULL)
     948    len=1;
     949  if(cnt<len){
     950    xmlAddChild(nc,nc1);
     951    free(ctitle);
    735952  }
    736953}
     
    7921009 * @return the generated wps:ProcessOfferings xmlNodePtr
    7931010 */
    794 void printDescribeProcessForProcess(registry *reg, maps* m,xmlNodePtr nc,service* serv){
     1011void printDescribeProcessForProcess(registry *reg, maps* m,xmlDocPtr doc,xmlNodePtr nc,service* serv){
    7951012  xmlNsPtr ns,ns_ows,ns_xlink;
    7961013  xmlNodePtr n,nc1;
     
    7981015  map* version=getMapFromMaps(m,"main","rversion");
    7991016  int vid=getVersionId(version->value);
     1017  int fromDb=-1;
     1018  map* serviceType=getMap(serv->content,"serviceType");
     1019  map* test=getMap(serv->content,"fromDb");
     1020  if(test!=NULL && strncasecmp(test->value,"true",4)==0)
     1021    fromDb=1;
    8001022
    8011023  n=nc;
     
    8111033  if(vid==0){
    8121034    nc = xmlNewNode(NULL, BAD_CAST "ProcessDescription");
    813     attachAttributes(nc,ns,serv->content,vid);
     1035    attachAttributes(nc,ns,serv->content,vid,NULL);
    8141036  }
    8151037  else{
     
    8281050      }
    8291051    }
    830     attachAttributes(nc2,NULL,serv->content,vid);
     1052    attachAttributes(nc2,NULL,serv->content,vid,serviceType);
    8311053    map* level=getMap(serv->content,"level");
    8321054    if(level!=NULL && strcasecmp(level->value,"generic")==0)
     
    8431065    tmp1=serv->metadata;
    8441066    while(tmp1!=NULL){
    845       nc1 = xmlNewNode(ns_ows, BAD_CAST "Metadata");
    846       xmlNewNsProp(nc1,ns_xlink,BAD_CAST tmp1->name,BAD_CAST tmp1->value);
    847       xmlAddChild(nc,nc1);
     1067      addMetadata(tmp1,doc,nc,ns_ows,ns_xlink,vid);
    8481068      tmp1=tmp1->next;
    8491069    }
     
    8551075    }
    8561076  }else{
     1077    tmp1=serv->metadata;
     1078    addMetadata(tmp1,doc,nc,ns_ows,ns_xlink,vid);
    8571079    addInheritedMetadata(nc,ns_ows,ns_xlink,reg,m,serv);
     1080    tmp1=serv->additional_parameters;
     1081    if(vid!=0)
     1082      addAdditionalParameters(tmp1,doc,nc,ns_ows,ns_xlink,fromDb);
    8581083  }
    8591084
     
    8621087    if(vid==0){
    8631088      nc1 = xmlNewNode(NULL, BAD_CAST "DataInputs");
    864       printFullDescription(1,e,"Input",ns,ns_ows,nc1,vid);
     1089      printFullDescription(doc,1,e,"Input",ns,ns_ows,nc1,vid,fromDb,NULL);
    8651090      xmlAddChild(nc,nc1);
    8661091    }
    8671092    else{
    868       printFullDescription(1,e,"wps:Input",ns,ns_ows,nc,vid);
     1093      printFullDescription(doc,1,e,"wps:Input",ns,ns_ows,nc,vid,fromDb,NULL);
    8691094    }
    8701095  }
     
    8731098  if(vid==0){
    8741099    nc1 = xmlNewNode(NULL, BAD_CAST "ProcessOutputs");
    875     printFullDescription(0,e,"Output",ns,ns_ows,nc1,vid);
     1100    printFullDescription(doc,0,e,"Output",ns,ns_ows,nc1,vid,fromDb,NULL);
    8761101    xmlAddChild(nc,nc1);
    8771102  }
    8781103  else{
    879     printFullDescription(0,e,"wps:Output",ns,ns_ows,nc,vid);
     1104    printFullDescription(doc,0,e,"wps:Output",ns,ns_ows,nc,vid,fromDb,serviceType);
    8801105  }
    8811106  if(vid==0)
     
    8991124 * @param nc1 the XML node to use to add the created tree
    9001125 * @param vid the WPS version id (0 for 1.0.0, 1 for 2.0.0)
    901  */
    902 void printFullDescription(int in,elements *elem,const char* type,xmlNsPtr ns,xmlNsPtr ns_ows,xmlNodePtr nc1,int vid){
     1126 * @param fromDb 1 in case the metadata comes from the DB, -1 in other cases
     1127 * @param serviceType the serviceType found in the ZCFG file or the DB
     1128 */
     1129void printFullDescription(xmlDocPtr doc,int in,elements *elem,const char* type,xmlNsPtr ns,xmlNsPtr ns_ows,xmlNodePtr nc1,int vid,int fromDb,const map* serviceType){
    9031130  xmlNsPtr ns1=NULL;
    9041131  if(vid==1)
     
    9131140    int isAnyValue=1;
    9141141    nc2 = xmlNewNode(NULL, BAD_CAST type);
     1142    // Extract min/max Occurence information
    9151143    if(strstr(type,"Input")!=NULL){
    9161144      tmp1=getMap(e->content,"minOccurs");
     
    9351163
    9361164    if(e->format!=NULL){
     1165#ifdef USE_HPC     
     1166    DEFAULT_OUT:
     1167#endif
    9371168      const char orderedFields[13][14]={
    9381169        "mimeType",
     
    9521183      //Build the (Literal/Complex/BoundingBox)Data node
    9531184      if(strncmp(type,"Output",6)==0){
    954         if(strncasecmp(e->format,"LITERALDATA",strlen(e->format))==0)
     1185        if(strncasecmp(e->format,"LITERAL",7)==0)
    9551186          nc3 = xmlNewNode(ns1, BAD_CAST "LiteralOutput");
    9561187        else if(strncasecmp(e->format,"COMPLEXDATA",strlen(e->format))==0)
     
    9981229                strcmp(e->format,"BoundingBoxData")==0){
    9991230          datatype=2;
    1000           nc5 = xmlNewNode(NULL, BAD_CAST "Default");
     1231          if(vid==0)
     1232            nc5 = xmlNewNode(NULL, BAD_CAST "Default");
     1233          else{
     1234            xmlNodePtr nc6 = xmlNewNode(ns1, BAD_CAST "Format");
     1235            xmlNewProp(nc6,BAD_CAST "mimeType",BAD_CAST "text/xml");
     1236            xmlNewProp(nc6,BAD_CAST "default",BAD_CAST "true");
     1237            xmlAddChild(nc3,nc6);
     1238            nc5 = xmlNewNode(NULL, BAD_CAST "SupportedCRS");
     1239          }
    10011240        }
    10021241        else{
     
    10391278            while(token!=NULL){
    10401279              nc7 = xmlNewNode(ns_ows, BAD_CAST "Value");
    1041               char *tmps=strdup(token);
     1280              char *tmps=zStrdup(token);
    10421281              tmps[strlen(tmps)]=0;
    1043               xmlAddChild(nc7,xmlNewText(BAD_CAST tmps));
     1282              nc8 = xmlNewText(BAD_CAST tmps);
     1283              xmlAddChild(nc7,nc8);
    10441284              free(tmps);
    10451285              xmlAddChild(nc6,nc7);
     
    12071447                 strncasecmp(tmp1->name,"range",5)!=0){
    12081448                if(datatype!=1){
    1209                   char *tmp2=zCapitalize1(tmp1->name);
    1210                   nc9 = xmlNewNode(NULL, BAD_CAST tmp2);
    1211                   free(tmp2);
     1449                  if(datatype==2 && vid==1){
     1450                    nc9 = xmlNewNode(ns, BAD_CAST "SupportedCRS");
     1451                    xmlNewProp(nc9,BAD_CAST "default",BAD_CAST "true");
     1452                  }
     1453                  else{
     1454                    char *tmp2=zCapitalize1(tmp1->name);
     1455                    nc9 = xmlNewNode(NULL, BAD_CAST tmp2);
     1456                    free(tmp2);
     1457                  }
    12121458                }
    12131459                else{
     
    12181464                xmlAddChild(nc9,xmlNewText(BAD_CAST tmp1->value));
    12191465                if(vid==0 || oI>=3){
    1220                   if(vid==0 || oI!=4)
    1221                     xmlAddChild(nc5,nc9);
     1466                  if(vid==0 || oI!=4){
     1467                    if(datatype==2 && vid==1)
     1468                      xmlAddChild(nc3,nc9);
     1469                    else
     1470                      xmlAddChild(nc5,nc9);
     1471                  }
    12221472                  if(oI==4 && vid==1){
    12231473                    xmlNewProp(nc9,BAD_CAST "default",BAD_CAST "true");
    12241474                  }
    12251475                }
    1226                 else
    1227                   xmlFree(nc9);
     1476                else{
     1477                  xmlFreeNode(nc9);
     1478                }
    12281479                if(strcasecmp(tmp1->name,"uom")==0)
    12291480                  hasUOM1=true;
    12301481                hasUOM=true;
    1231               }else       
    1232                 tmp1=tmp1->next;
     1482              }
    12331483            }
    12341484        }
     
    12451495          }else{
    12461496            if(hasUOM1==false && vid==0){
    1247               xmlFreeNode(nc5);
    1248               if(datatype==1)
     1497              if(nc5!=NULL)
     1498                xmlFreeNode(nc5);
     1499              if(datatype==1){
    12491500                xmlFreeNode(nc4);
     1501              }
    12501502            }
    1251             else
     1503            else{
    12521504              xmlAddChild(nc3,nc5);
     1505            }
    12531506          }
    12541507        }else{
    1255           xmlAddChild(nc3,nc5);
     1508          if(vid==0)
     1509            xmlAddChild(nc3,nc5);
     1510          else
     1511            xmlFreeNode(nc5);
    12561512        }
    12571513     
    1258         if(datatype!=1 && default1<0){
     1514        if(datatype==0 && default1<0){
    12591515          xmlFreeNode(nc5);
    1260           if(datatype!=2)
     1516          if(datatype!=2){
    12611517            xmlFreeNode(nc4);
     1518          }
    12621519        }
    12631520
     
    13101567              nc9 = xmlNewNode(ns_ows, BAD_CAST tmp2);
    13111568              free(tmp2);
    1312               //xmlNewProp(nc9, BAD_CAST "default", BAD_CAST "true");
    13131569              xmlAddChild(nc9,xmlNewText(BAD_CAST tmp1->value));
    13141570              xmlAddChild(nc5,nc9);
    1315               /*struct iotype * _ltmp=e->supported;
    1316                 while(_ltmp!=NULL){
    1317                 tmp1=getMap(_ltmp->content,"uom");
    1318                 if(tmp1!=NULL){
    1319                 char *tmp2=zCapitalize(tmp1->name);
    1320                 nc9 = xmlNewNode(ns_ows, BAD_CAST tmp2);
    1321                 free(tmp2);
    1322                 xmlAddChild(nc9,xmlNewText(BAD_CAST tmp1->value));
    1323                 xmlAddChild(nc5,nc9);
    1324                 }
    1325                 _ltmp=_ltmp->next;
    1326                 }*/
    1327            
    13281571            }
    13291572          }
     
    13401583        xmlNsPtr ns_xlink=usedNs[xlinkId];
    13411584
    1342         while(metadata!=NULL){
    1343           nc6=xmlNewNode(ns_ows, BAD_CAST "Metadata");
    1344           xmlNewNsProp(nc6,ns_xlink,BAD_CAST metadata->name,BAD_CAST metadata->value);
    1345           xmlAddChild(nc2,nc6);
    1346           metadata=metadata->next;
    1347         }
     1585        addMetadata(metadata,doc,nc2,ns_ows,ns_xlink,vid);
     1586        if(vid!=0)
     1587          addAdditionalParameters(e->additional_parameters,doc,nc2,ns_ows,ns_xlink,fromDb);
    13481588
    13491589      }
    13501590
    13511591      _tmp=e->supported;
    1352       if(_tmp==NULL && datatype!=1)
     1592      if(_tmp==NULL && datatype==0)
    13531593        _tmp=e->defaults;
    13541594
     
    13961636               strcasecmp(tmp1->name,"extension")!=0){
    13971637              if(datatype!=1){
    1398                 char *tmp2=zCapitalize1(tmp1->name);
    1399                 nc6 = xmlNewNode(NULL, BAD_CAST tmp2);
    1400                 free(tmp2);
     1638                if(datatype==2 && vid==1){
     1639                  nc6 = xmlNewNode(ns, BAD_CAST "SupportedCRS");
     1640                }
     1641                else{
     1642                  char *tmp2=zCapitalize1(tmp1->name);
     1643                  nc6 = xmlNewNode(NULL, BAD_CAST tmp2);
     1644                  free(tmp2);
     1645                }
    14011646              }
    14021647              else{
     
    14221667              }
    14231668              if(vid==0 || oI>=3){
    1424                 if(vid==0 || oI!=4)
    1425                   xmlAddChild(nc5,nc6);
    1426                 else
    1427                   xmlFree(nc6);
     1669                if(vid==0 || oI!=4){
     1670                  if(datatype==2 && vid==1)
     1671                    xmlAddChild(nc3,nc6);
     1672                  else
     1673                    xmlAddChild(nc5,nc6);
     1674                }
     1675                else{
     1676                  xmlFreeNode(nc6);
     1677                }
    14281678              }
    1429               else
    1430                 xmlFree(nc6);
     1679              else{
     1680                xmlFreeNode(nc6);
     1681              }
    14311682            }
    14321683            tmp1=tmp1->next;
     
    14391690            }
    14401691            else{
    1441               xmlAddChild(nc3,nc5);
     1692              if(datatype!=2)
     1693                xmlAddChild(nc3,nc5);
    14421694            }
    14431695
    14441696          }else{
    1445             if(datatype!=1)
     1697            if(datatype==2 && vid==0)
    14461698              xmlAddChild(nc3,nc5);
    14471699          }
     
    14591711          }
    14601712          else
    1461             if(datatype!=1)
     1713            if(datatype==0){
     1714              xmlFreeNode(nc4);
    14621715              xmlAddChild(nc3,nc5);
     1716            }
    14631717
    14641718        _tmp=_tmp->next;
     
    14661720
    14671721      if(hasSupported==0){
    1468         if(datatype==0 && vid!=0)
     1722        if(datatype==0 && vid!=0){
    14691723          xmlFreeNode(nc4);
     1724        }
    14701725        xmlFreeNode(nc5);
    14711726      }
     
    14781733        }
    14791734        else{
     1735          xmlFreeNode(nc4);
    14801736          xmlAddChild(nc3,nc5);
    14811737        }
     
    14911747    }else{
    14921748      if(e->child!=NULL && vid!=0){
    1493         printFullDescription(in,e->child,type,ns,ns_ows,nc2,vid);
    1494       }
    1495     }
    1496    
     1749        printFullDescription(doc,in,e->child,type,ns,ns_ows,nc2,vid,fromDb,NULL);
     1750      }
     1751    }
    14971752    if(e->child!=NULL && vid==0){
    14981753      elements* children=dupElements(e->child);
    14991754      elements* cursor=children;
    15001755      while(cursor!=NULL){
    1501         char* tmp=strdup(cursor->name);
    1502         free(cursor->name);
    1503         cursor->name=(char*)malloc((strlen(cursor->name)+strlen(e->name)+2)*sizeof(char));
    1504         sprintf(cursor->name,"%s.%s",e->name,tmp);
     1756        elements* ccursor=cursor;
     1757        char* tmp=zStrdup(ccursor->name);
     1758        free(ccursor->name);
     1759        ccursor->name=(char*)malloc((strlen(tmp)+strlen(e->name)+2)*sizeof(char));
     1760        sprintf(ccursor->name,"%s.%s",e->name,tmp);
    15051761        cursor=cursor->next;
    15061762      }
    1507       printFullDescription(in,children,type,ns,ns_ows,nc2,vid);
    1508       xmlAddChild(nc1,nc2);
     1763      printFullDescription(doc,in,children,type,ns,ns_ows,nc1,vid,fromDb,serviceType);
    15091764      freeElements(&children);
    15101765      free(children);
    1511     }else
    1512       xmlAddChild(nc1,nc2);
    1513    
     1766    }else{
     1767      if(nc2!=NULL){
     1768        xmlAddChild(nc1,nc2);
     1769      }
     1770    }
    15141771    e=e->next;
    15151772  }
     
    15281785 * @param outputs the outputs generated by the service
    15291786 */
    1530 void printProcessResponse(maps* m,map* request, int pid,service* serv,const char* service,int status,maps* inputs,maps* outputs){
     1787void printProcessResponse(maps* m,map* request, int pid,service* serv,const char* service,int status,maps* inputs,maps* outputs){       
    15311788  xmlNsPtr ns,ns_ows,ns_xlink;
    15321789  xmlNodePtr nr,n,nc,nc1=NULL,nc3;
     
    15491806  char stored_path[1024];
    15501807  memset(stored_path,0,1024);
    1551    
     1808 
    15521809  if(vid==0){
    15531810    char tmp[256];
     
    17341991    }
    17351992  }
    1736 
     1993 
    17371994  /**
    17381995   * Display the process output only when requested !
     
    17442001    maps* mcursor=outputs;
    17452002    elements* scursor=serv->outputs;
    1746     map* testResponse=getMap(request,"RawDataOutput");
     2003    map* testResponse=getMap(request,"RawDataOutput"); 
    17472004    if(testResponse==NULL)
    17482005      testResponse=getMap(request,"ResponseDocument");
    1749     while(mcursor!=NULL){
     2006    while(mcursor!=NULL){               
    17502007      map* tmp0=getMap(mcursor->content,"inRequest");
    1751       scursor=getElements(serv->outputs,mcursor->name);
    1752       if(scursor!=NULL){
    1753         if(testResponse==NULL || tmp0==NULL){
     2008      scursor=getElements(serv->outputs,mcursor->name);   
     2009      if(scursor!=NULL){                 
     2010        if(testResponse==NULL || tmp0==NULL){           
    17542011          if(vid==0)
    17552012            printIOType(doc,nc,ns,ns_ows,ns_xlink,scursor,mcursor,"Output",vid);
     
    17582015        }
    17592016        else
    1760 
    1761           if(tmp0!=NULL && strncmp(tmp0->value,"true",4)==0){
     2017          if(tmp0!=NULL && strncmp(tmp0->value,"true",4)==0){             
    17622018            if(vid==0)
    17632019              printIOType(doc,nc,ns,ns_ows,ns_xlink,scursor,mcursor,"Output",vid);
    17642020            else
    17652021              printIOType(doc,n,ns,ns_ows,ns_xlink,scursor,mcursor,"Output",vid);
    1766           }
     2022          }     
    17672023      }else
    17682024        /**
     
    17752031          printIOType(doc,n,ns,ns_ows,ns_xlink,scursor,mcursor,"Output",vid);
    17762032      mcursor=mcursor->next;
    1777     }
     2033    }   
    17782034    if(vid==0)
    17792035      xmlAddChild(n,nc);
    1780   }
    1781 
     2036  } 
    17822037  if(vid==0 &&
    17832038     hasStoredExecuteResponse==true
     
    18342089#endif
    18352090  }
     2091
    18362092  printDocument(m,doc,pid);
    18372093
     
    18912147  else{
    18922148    /*
    1893     dumpElements(e);
     2149      dumpElements(e);
    18942150    */
    18952151    return;
     
    19002156       || strncasecmp(tmp->name,"SCHEMA",strlen(tmp->name))==0
    19012157       || strncasecmp(tmp->name,"UOM",strlen(tmp->name))==0)
    1902     xmlNewProp(nc1,BAD_CAST tmp->name,BAD_CAST tmp->value);
     2158      xmlNewProp(nc1,BAD_CAST tmp->name,BAD_CAST tmp->value);
    19032159    tmp=tmp->next;
    19042160  }
     
    19272183 * @param type the type
    19282184 */
    1929 void printIOType(xmlDocPtr doc,xmlNodePtr nc,xmlNsPtr ns_wps,xmlNsPtr ns_ows,xmlNsPtr ns_xlink,elements* e,maps* m,const char* type,int vid){
    1930 
     2185void printIOType(xmlDocPtr doc,xmlNodePtr nc,xmlNsPtr ns_wps,xmlNsPtr ns_ows,xmlNsPtr ns_xlink,elements* e,maps* m,const char* type,int vid){   
    19312186  xmlNodePtr nc1,nc2,nc3;
    19322187  nc1=xmlNewNode(ns_wps, BAD_CAST type);
     
    19352190    tmp=e->content;
    19362191  else
    1937     tmp=m->content;
    1938 
     2192    tmp=m->content; 
    19392193  if(vid==0){
    19402194    nc2=xmlNewNode(ns_ows, BAD_CAST "Identifier");
     
    19762230    xmlNewProp(nc1,BAD_CAST "id",BAD_CAST (e!=NULL?e->name:m->name));
    19772231  }
    1978 
     2232 
    19792233  // IO type nested outputs
    1980   if(m->child!=NULL){
     2234  if(m->child!=NULL){     
    19812235    maps* curs=m->child;
    19822236    elements* ecurs=getElements(e,(e!=NULL?e->name:m->name));
    19832237    ecurs=ecurs->child;
    1984     while(curs!=NULL){
     2238    while(curs!=NULL/* && ecurs!=NULL*/){
    19852239      ecurs=getElements(ecurs,(curs->name));
    19862240      map* inRequest=getMap(curs->content,"inRequest");
     
    19922246    }
    19932247  }
    1994   else{
     2248  else{   
    19952249    map *tmpMap=getMap(m->content,"Reference");
    1996     if(tmpMap==NULL){
     2250    if(tmpMap==NULL){           
    19972251      nc2=xmlNewNode(ns_wps, BAD_CAST "Data");
    1998       if(e!=NULL && e->format!=NULL){
    1999         if(strncasecmp(e->format,"LiteralOutput",strlen(e->format))==0)
    2000           nc3=xmlNewNode(ns_wps, BAD_CAST "LiteralData");
     2252      if(e!=NULL && e->format!=NULL){             
     2253                  if (strncasecmp(e->format, "LiteralOutput", strlen(e->format)) == 0)                                   
     2254                          nc3 = xmlNewNode(ns_wps, BAD_CAST "LiteralData");               
    20012255        else
    20022256          if(strncasecmp(e->format,"ComplexOutput",strlen(e->format))==0)
     
    20052259            nc3=xmlNewNode(ns_wps, BAD_CAST "BoundingBoxData");
    20062260          else
    2007             nc3=xmlNewNode(ns_wps, BAD_CAST e->format);
    2008       }
    2009       else {
    2010         map* tmpV=getMapFromMaps(m,"format","value");
     2261            nc3=xmlNewNode(ns_wps, BAD_CAST e->format);           
     2262      }
     2263      else {             
     2264        map* tmpV=getMapFromMaps(m,"format","value");   
    20112265        if(tmpV!=NULL)
    20122266          nc3=xmlNewNode(ns_wps, BAD_CAST tmpV->value);
     
    20142268          nc3=xmlNewNode(ns_wps, BAD_CAST "LiteralData");
    20152269      }
    2016       tmp=m->content;
    2017      
     2270      tmp=m->content;     
     2271
    20182272      while(tmp!=NULL){
    20192273        if(strcasecmp(tmp->name,"mimeType")==0 ||
     
    20212275           strcasecmp(tmp->name,"schema")==0 ||
    20222276           strcasecmp(tmp->name,"datatype")==0 ||
    2023            strcasecmp(tmp->name,"uom")==0) {
    2024          
     2277           strcasecmp(tmp->name,"uom")==0) {   
    20252278          if(vid==0)
    20262279            xmlNewProp(nc3,BAD_CAST tmp->name,BAD_CAST tmp->value);
     
    20332286          }
    20342287        }
     2288
    20352289        if(vid==0)
    20362290          xmlAddChild(nc2,nc3);
    2037         tmp=tmp->next;
     2291        tmp=tmp->next; 
    20382292      }
    20392293      if(e!=NULL && e->format!=NULL && strcasecmp(e->format,"BoundingBoxData")==0) {
     
    20462300        }
    20472301      }
    2048       else {
    2049         if(e!=NULL)
    2050           tmp=getMap(e->defaults->content,"mimeType");
     2302      else {             
     2303                  //if (e != NULL) {
     2304                  if (e != NULL && e->defaults != NULL) { // knut: add extra NULL pointer check in case user omits <Default> block in config file                         
     2305                          tmp = getMap(e->defaults->content, "mimeType");
     2306                  }
    20512307        else
    2052           tmp=NULL;
    2053        
     2308          tmp=NULL;     
    20542309        map* tmp1=getMap(m->content,"encoding");
    20552310        map* tmp2=getMap(m->content,"mimeType");
     
    21062361             strstr(tmp2->value, "json") != NULL ||            //    (will not be parsed by XML reader)
    21072362             strstr(tmp2->value, "ecmascript") != NULL
    2108            ) {
     2363             ) {
    21092364            xmlAddChild((vid==0?nc3:nc2),xmlNewCDataBlock(doc,BAD_CAST tmp3->value,strlen(tmp3->value)));
    21102365          }   
     
    21122367            if (strstr(tmp2->value, "xml") != NULL ||                 // if XML-based format
    21132368                // include for backwards compatibility,
    2114               // although correct mime type is ...kml+xml:                 
     2369                // although correct mime type is ...kml+xml:               
    21152370                strstr(tmp2->value, "google-earth.kml") != NULL
    21162371                ) {
     
    22412496  else
    22422497    exceptionCode="501 Internal Server Error";
    2243 
     2498  tmp=getMapFromMaps(m,"lenv","status_code");
     2499  if(tmp!=NULL)
     2500    exceptionCode=tmp->value;
    22442501  if(m!=NULL){
    22452502    map *tmpSid=getMapFromMaps(m,"lenv","sid");
     
    23322589
    23332590    tmp=getMapArray(s,"text",cnt);
     2591    if(tmp==NULL)
     2592      tmp=getMapArray(s,"message",cnt);
    23342593    nc1 = xmlNewNode(ns, BAD_CAST "ExceptionText");
    23352594    if(tmp!=NULL){
    23362595      xmlNodePtr txt=xmlNewText(BAD_CAST tmp->value);
    23372596      xmlAddChild(nc1,txt);
     2597      if(cnt==0)
     2598        setMapInMaps(m,"lenv","message",tmp->value);
    23382599    }
    23392600    else{
     
    23812642void outputResponse(service* s,maps* request_inputs,maps* request_outputs,
    23822643                    map* request_inputs1,int cpid,maps* m,int res){
    2383                
    23842644#ifdef DEBUG
    23852645  dumpMaps(request_inputs);
    23862646  dumpMaps(request_outputs);
    23872647  fprintf(stderr,"printProcessResponse\n");
    2388 #endif
     2648#endif 
    23892649  map* toto=getMap(request_inputs1,"RawDataOutput");
    23902650  int asRaw=0;
     
    23962656  if(tmpSess!=NULL){
    23972657    map *_tmp=getMapFromMaps(m,"lenv","cookie");
     2658    maps *tmps=getMaps(m,"senv");
    23982659    char* sessId=NULL;
    23992660    if(_tmp!=NULL){
    24002661      printf("Set-Cookie: %s; HttpOnly\r\n",_tmp->value);
     2662      map *_tmp1=getMapFromMaps(m,"senv","ecookie_length");
     2663      if(_tmp1!=NULL){
     2664        int len=atoi(_tmp1->value);
     2665        int cnt=0;
     2666        for(cnt=0;cnt<len;cnt++){
     2667          map* _tmp2=getMapArray(tmps->content,"ecookie",cnt);
     2668          if(_tmp2!=NULL)
     2669            printf("Set-Cookie: %s; HttpOnly\r\n",_tmp2->value);
     2670        }
     2671      }
    24012672      printf("P3P: CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"\r\n");
    24022673      char session_file_path[100];
     
    24062677      else
    24072678        sprintf(session_file_path,"%s",strstr(_tmp->value,"=")+1);
    2408       sessId=strdup(session_file_path);
     2679      sessId=zStrdup(session_file_path);
    24092680    }else{
    24102681      maps* t=getMaps(m,"senv");
     
    24122683      while(p!=NULL){
    24132684        if(strstr(p->name,"ID")!=NULL){
    2414           sessId=strdup(p->value);
     2685          sessId=zStrdup(p->value);
    24152686          break;
    24162687        }
     
    24352706    }
    24362707  }
    2437                  
    24382708  if(res==SERVICE_FAILED){
    24392709    map *lenv;
     
    24622732    return;
    24632733  }
    2464        
     2734
     2735  if(res!=SERVICE_SUCCEEDED){     
     2736    printProcessResponse(m,request_inputs1,cpid,
     2737                         s, s->name,res,  // replace serviceProvider with serviceName in stored response file name
     2738                         request_inputs,
     2739                         request_outputs);
     2740    return;
     2741  }
     2742     
    24652743  map *tmp1=getMapFromMaps(m,"main","tmpPath");
    24662744  if(asRaw==0){
     
    24732751    map* usid=getMapFromMaps(m,"lenv","usid");
    24742752    int itn=0;
     2753    int error=-1;
    24752754  NESTED0:
    24762755    while(tmpI!=NULL){
     
    24832762#endif
    24842763      map *gfile=getMap(tmpI->content,"generated_file");
    2485       char *file_name;
     2764      char *file_name=NULL;       
    24862765      if(gfile!=NULL){
    24872766        gfile=getMap(tmpI->content,"expected_generated_file");
     
    24912770        readGeneratedFile(m,tmpI->content,gfile->value);
    24922771        file_name=zStrdup((gfile->value)+strlen(tmp1->value));
    2493       }
    2494 
     2772      }   
    24952773      toto=getMap(tmpI->content,"asReference");
    24962774#ifdef USE_MS
    2497       if(toto!=NULL && strcasecmp(toto->value,"true")==0 && testMap==NULL)
     2775      map* geodatatype=getMap(tmpI->content,"geodatatype");
     2776      if(toto!=NULL && strcasecmp(toto->value,"true")==0 &&
     2777         (testMap==NULL ||
     2778          strncasecmp(testMap->value,"true",4)!=0 ||
     2779          (geodatatype!=NULL && strcasecmp(geodatatype->value,"other")==0) ) )
    24982780#else
    2499       if(toto!=NULL && strcasecmp(toto->value,"true")==0)
     2781        if(toto!=NULL && strcasecmp(toto->value,"true")==0)
    25002782#endif
    2501         {
    2502           elements* in=getElements(s->outputs,tmpI->name);
    2503           if(in==NULL && s->outputs->child!=NULL){
    2504             in=getElements(s->outputs->child,tmpI->name);
     2783          {             
     2784            elements* in=getElements(s->outputs,tmpI->name);
     2785            if(in==NULL && s->outputs->child!=NULL){
     2786              in=getElements(s->outputs->child,tmpI->name);
     2787            }
     2788            char *format=NULL;
     2789            if(in!=NULL && in->format!=NULL){
     2790              format=in->format;
     2791            }else
     2792              format=(char*)"LiteralData";
     2793            if(format!=NULL && strcasecmp(format,"BoundingBoxData")==0){
     2794              addToMap(tmpI->content,"extension","xml");
     2795              addToMap(tmpI->content,"mimeType","text/xml");
     2796              addToMap(tmpI->content,"encoding","UTF-8");
     2797              addToMap(tmpI->content,"schema","http://schemas.opengis.net/ows/1.1.0/owsCommon.xsd");
     2798            }           
     2799            char *file_path=NULL;
     2800            if(gfile==NULL) {
     2801              map *ext=getMap(tmpI->content,"extension");
     2802              char file_ext[32];
     2803           
     2804              if( ext != NULL && ext->value != NULL) {
     2805                strncpy(file_ext, ext->value, 32);
     2806              }
     2807              else {
     2808                // Obtain default file extension (see mimetypes.h).           
     2809                // If the MIME type is not recognized, txt is used as the default extension
     2810                map* mtype=getMap(tmpI->content,"mimeType");
     2811                getFileExtension(mtype != NULL ? mtype->value : NULL, file_ext, 32);
     2812              }
     2813              if(file_name!=NULL)
     2814                free(file_name);
     2815              file_name=(char*)malloc((strlen(s->name)+strlen(usid->value)+strlen(file_ext)+strlen(tmpI->name)+45)*sizeof(char));
     2816              sprintf(file_name,"ZOO_DATA_%s_%s_%s_%d.%s",s->name,tmpI->name,usid->value,itn,file_ext);
     2817              itn++;
     2818              file_path=(char*)malloc((strlen(tmp1->value)+strlen(file_name)+2)*sizeof(char));
     2819              sprintf(file_path,"%s/%s",tmp1->value,file_name);
     2820
     2821              FILE *ofile=fopen(file_path,"wb");
     2822              if(ofile==NULL){
     2823                char tmpMsg[1024];
     2824                sprintf(tmpMsg,_("Unable to create the file \"%s\" for storing the %s final result."),file_name,tmpI->name);
     2825                errorException(m,tmpMsg,"InternalError",NULL);
     2826                free(file_name);
     2827                free(file_path);
     2828                return;
     2829              }
     2830
     2831              toto=getMap(tmpI->content,"value");
     2832              if(toto==NULL){
     2833                char tmpMsg[1024];
     2834                sprintf(tmpMsg,_("No value found for the requested output %s."),tmpI->name);
     2835                errorException(m,tmpMsg,"InternalError",NULL);
     2836                fclose(ofile);
     2837                free(file_name);
     2838                free(file_path);
     2839                return;
     2840              }
     2841              if(strcasecmp(format,"BoundingBoxData")!=0){
     2842                map* size=getMap(tmpI->content,"size");
     2843                if(size!=NULL && toto!=NULL)
     2844                  fwrite(toto->value,1,(atoi(size->value))*sizeof(char),ofile);
     2845                else
     2846                  if(toto!=NULL && toto->value!=NULL)
     2847                    fwrite(toto->value,1,strlen(toto->value)*sizeof(char),ofile);
     2848              }else{
     2849                printBoundingBoxDocument(m,tmpI,ofile);
     2850              }
     2851              fclose(ofile);
     2852            }
     2853
     2854            map *tmp2=getMapFromMaps(m,"main","tmpUrl");
     2855            map *tmp3=getMapFromMaps(m,"main","serverAddress");
     2856            char *file_url=NULL;
     2857            if(strncasecmp(tmp2->value,"http://",7)==0 ||
     2858               strncasecmp(tmp2->value,"https://",8)==0){
     2859              file_url=(char*)malloc((strlen(tmp2->value)+strlen(file_name)+2)*sizeof(char));
     2860              sprintf(file_url,"%s/%s",tmp2->value,file_name);
     2861            }else{
     2862              file_url=(char*)malloc((strlen(tmp3->value)+strlen(tmp2->value)+strlen(file_name)+3)*sizeof(char));
     2863              sprintf(file_url,"%s/%s/%s",tmp3->value,tmp2->value,file_name);
     2864            }
     2865            addToMap(tmpI->content,"Reference",file_url);
     2866            if(file_name!=NULL)
     2867              free(file_name);
     2868            if(file_url!=NULL)
     2869              free(file_url);
     2870            file_name=NULL;
    25052871          }
    2506           char *format=NULL;
    2507           if(in!=NULL && in->format!=NULL){
    2508             format=in->format;
    2509           }else
    2510             format=(char*)"LiteralData";
    2511           if(format!=NULL && strcasecmp(format,"BoundingBoxData")==0){
    2512             addToMap(tmpI->content,"extension","xml");
    2513             addToMap(tmpI->content,"mimeType","text/xml");
    2514             addToMap(tmpI->content,"encoding","UTF-8");
    2515             addToMap(tmpI->content,"schema","http://schemas.opengis.net/ows/1.1.0/owsCommon.xsd");
     2872#ifdef USE_MS
     2873        else{
     2874          if(testMap!=NULL){
     2875            map* nbFeatures;
     2876            setMapInMaps(m,"lenv","state","out");
     2877            setReferenceUrl(m,tmpI);
     2878            nbFeatures=getMap(tmpI->content,"nb_features");
     2879            geodatatype=getMap(tmpI->content,"geodatatype");
     2880            if((nbFeatures!=NULL && atoi(nbFeatures->value)==0) ||
     2881               (geodatatype!=NULL && strcasecmp(geodatatype->value,"other")==0)){
     2882              error=1;
     2883              res=SERVICE_FAILED;
     2884            }
    25162885          }
    2517 
    2518           if(gfile==NULL) {
    2519             map *ext=getMap(tmpI->content,"extension");
    2520             char *file_path;
    2521             char file_ext[32];
    2522 
    2523             if( ext != NULL && ext->value != NULL) {
    2524               strncpy(file_ext, ext->value, 32);
    2525             }
    2526             else {
    2527               // Obtain default file extension (see mimetypes.h).             
    2528               // If the MIME type is not recognized, txt is used as the default extension
    2529               map* mtype=getMap(tmpI->content,"mimeType");
    2530               getFileExtension(mtype != NULL ? mtype->value : NULL, file_ext, 32);
    2531             }
    2532 
    2533             file_name=(char*)malloc((strlen(s->name)+strlen(usid->value)+strlen(file_ext)+strlen(tmpI->name)+45)*sizeof(char));
    2534             sprintf(file_name,"%s_%s_%s_%d.%s",s->name,tmpI->name,usid->value,itn,file_ext);
    2535             itn++;
    2536             file_path=(char*)malloc((strlen(tmp1->value)+strlen(file_name)+2)*sizeof(char));
    2537             sprintf(file_path,"%s/%s",tmp1->value,file_name);
    2538 
    2539             FILE *ofile=fopen(file_path,"wb");
    2540             if(ofile==NULL){
    2541               char tmpMsg[1024];
    2542               sprintf(tmpMsg,_("Unable to create the file \"%s\" for storing the %s final result."),file_name,tmpI->name);
    2543               errorException(m,tmpMsg,"InternalError",NULL);
    2544               free(file_name);
    2545               free(file_path);
    2546               return;
    2547             }
    2548             free(file_path);
    2549 
    2550             toto=getMap(tmpI->content,"value");
    2551             if(strcasecmp(format,"BoundingBoxData")!=0){
    2552               map* size=getMap(tmpI->content,"size");
    2553               if(size!=NULL && toto!=NULL)
    2554                 fwrite(toto->value,1,(atoi(size->value))*sizeof(char),ofile);
    2555               else
    2556                 if(toto!=NULL && toto->value!=NULL)
    2557                   fwrite(toto->value,1,strlen(toto->value)*sizeof(char),ofile);
    2558             }else{
    2559               printBoundingBoxDocument(m,tmpI,ofile);
    2560             }
    2561             fclose(ofile);
    2562 
    2563           }
    2564 
    2565           map *tmp2=getMapFromMaps(m,"main","tmpUrl");
    2566           map *tmp3=getMapFromMaps(m,"main","serverAddress");
    2567           char *file_url;
    2568           if(strncasecmp(tmp2->value,"http://",7)==0 ||
    2569              strncasecmp(tmp2->value,"https://",8)==0){
    2570             file_url=(char*)malloc((strlen(tmp2->value)+strlen(file_name)+2)*sizeof(char));
    2571             sprintf(file_url,"%s/%s",tmp2->value,file_name);
    2572           }else{
    2573             file_url=(char*)malloc((strlen(tmp3->value)+strlen(tmp2->value)+strlen(file_name)+3)*sizeof(char));
    2574             sprintf(file_url,"%s/%s/%s",tmp3->value,tmp2->value,file_name);
    2575           }
    2576           addToMap(tmpI->content,"Reference",file_url);
    2577           free(file_name);
    2578           free(file_url);
    2579          
    2580         }
    2581 #ifdef USE_MS
    2582       else{
    2583         if(testMap!=NULL){
    2584           setReferenceUrl(m,tmpI);
    2585         }
    2586       }
    2587 #endif
     2886        }
     2887#endif 
     2888      if(file_name!=NULL){
     2889        free(file_name);
     2890        file_name=NULL;
     2891      }
    25882892      tmpI=tmpI->next;
    25892893    }
     
    25932897      if(tmpI!=NULL)
    25942898        goto NESTED0;
    2595     }
     2899    }   
    25962900#ifdef DEBUG
    25972901    fprintf(stderr,"SERVICE : %s\n",s->name);
    25982902    dumpMaps(m);
     2903#endif 
     2904    if(error<0)
     2905      printProcessResponse(m,request_inputs1,cpid,
     2906                           s, s->name,res,  // replace serviceProvider with serviceName in stored response file name
     2907                           request_inputs,
     2908                           request_outputs);
     2909    else{
     2910      maps* tmpMaps=getMaps(m,"lenv");
     2911#ifdef USE_CALLBACK
     2912      invokeCallback(m,NULL,NULL,7,0);
    25992913#endif
    2600     printProcessResponse(m,request_inputs1,cpid,
    2601                          s, s->name,res,  // replace serviceProvider with serviceName in stored response file name
    2602                          request_inputs,
    2603                          request_outputs);
     2914      printExceptionReportResponse(m,tmpMaps->content);
     2915    }
    26042916  }
    26052917  else{
  • trunk/zoo-project/zoo-kernel/response_print.h

    r785 r917  
    3939#include <libintl.h>
    4040#include <locale.h>
     41
    4142/**
    4243 * ZOO-Kernel internal messages translation function
     
    6364#include <sys/stat.h>
    6465#include <sys/types.h>
    65 #include "cgic.h"
    6666#ifndef WIN32
    6767#include <sys/ipc.h>
     
    8080#endif
    8181#ifndef WIN32
    82 #include <xlocale.h>
     82//#include <locale.h>
     83#include <locale.h> // knut: this appears to be a non-standard header file that has been removed in newer versions of glibc; it may be sufficient to include <locale.h> (see above)
    8384#endif
    8485#include "ulinet.h"
     
    9495#include <libxml/parser.h>
    9596#include <libxml/xpath.h>
     97
     98#include "cgic.h"
    9699
    97100#ifdef __cplusplus
     
    209212  xmlNodePtr printWPSHeader(xmlDocPtr,maps*,const char*,const char*,const char*,int);
    210213  xmlNodePtr printGetCapabilitiesHeader(xmlDocPtr,maps*,const char*);
    211   void printGetCapabilitiesForProcess(registry*,maps*,xmlNodePtr,service*);
    212   void printDescribeProcessForProcess(registry*,maps*,xmlNodePtr,service*);
    213   void printFullDescription(int,elements*,const char*,xmlNsPtr,xmlNsPtr,xmlNodePtr,int);
     214  void printGetCapabilitiesForProcess(registry*,maps*,xmlDocPtr,xmlNodePtr,service*);
     215  void printDescribeProcessForProcess(registry*,maps*,xmlDocPtr,xmlNodePtr,service*);
     216  void printFullDescription(xmlDocPtr,int,elements*,const char*,xmlNsPtr,xmlNsPtr,xmlNodePtr,int,int,const map*);
    214217  void printDocument(maps*,xmlDocPtr,int);
    215218  void printDescription(xmlNodePtr,xmlNsPtr,const char*,map*,int);
     
    220223  void printOutputDefinitions(xmlDocPtr,xmlNodePtr,xmlNsPtr,xmlNsPtr,elements*,maps*,const char*);
    221224  void printStatusInfo(maps*,map*,char*);
     225  void addAdditionalParameters(map*,xmlDocPtr,xmlNodePtr,xmlNsPtr,xmlNsPtr,int);
     226  void addMetadata(map*,xmlDocPtr,xmlNodePtr,xmlNsPtr,xmlNsPtr,int);
    222227
    223228  void outputResponse(service*,maps*,maps*,map*,int,maps*,int);
  • trunk/zoo-project/zoo-kernel/server_internal.c

    r889 r917  
    2626#include "service_internal.h"
    2727#include "response_print.h"
     28//#include "service_callback.h"
    2829#include "mimetypes.h"
    2930#ifndef WIN32
     
    366367 */
    367368void readGeneratedFile(maps* m,map* content,char* filename){
     369  char rsize[1024];
    368370  FILE * file=fopen(filename,"rb");
    369371  if(file==NULL){
    370     fprintf(stderr,"Failed to open file %s for reading purpose.\n",filename);
    371372    setMapInMaps(m,"lenv","message","Unable to read produced file. Please try again later");
    372373    return ;
    373374  }
    374375  fseek(file, 0, SEEK_END);
    375   long count = ftell(file);
     376  zStatStruct f_status;
     377  int s=zStat(filename, &f_status);
     378  sprintf(rsize,"%lld",f_status.st_size);
    376379  rewind(file);
    377   struct stat file_status;
    378   stat(filename, &file_status);
    379   map* tmpMap1=getMap(content,"value");
    380   if(tmpMap1==NULL){
    381     addToMap(content,"value","");
    382     tmpMap1=getMap(content,"value");
    383   }
    384   free(tmpMap1->value);
    385   tmpMap1->value=(char*) malloc((count+1)*sizeof(char)); 
    386   fread(tmpMap1->value,1,count,file);
    387   tmpMap1->value[count]=0;
    388   fclose(file);
    389   char rsize[1000];
    390   sprintf(rsize,"%ld",count);
     380  if(getMap(content,"storage")==NULL){
     381    map* memUse=getMapFromMaps(m,"main","memory");
     382    if(memUse==NULL || strncmp(memUse->value,"load",4)==0){
     383      map* tmpMap1=getMap(content,"value");
     384      if(tmpMap1==NULL){
     385        addToMap(content,"value","");
     386        tmpMap1=getMap(content,"value");
     387      }
     388      free(tmpMap1->value);
     389      tmpMap1->value=(char*) malloc((f_status.st_size+1)*sizeof(char));
     390      if(tmpMap1->value==NULL){
     391        setMapInMaps(m,"lenv","message","Unable to allocate the memory required to read the produced file.");
     392      }
     393      fread(&tmpMap1->value,1,f_status.st_size,file);
     394      tmpMap1->value[f_status.st_size]=0;
     395    }
     396  }
     397  fclose(file); 
    391398  addToMap(content,"size",rsize);
    392399}
     
    423430void dumpMapsValuesToFiles(maps** main_conf,maps** in){
    424431  map* tmpPath=getMapFromMaps(*main_conf,"main","tmpPath");
     432  map* tmpUrl=getMapFromMaps(*main_conf,"main","tmpUrl");
    425433  map* tmpSid=getMapFromMaps(*main_conf,"lenv","usid");
    426434  maps* inputs=*in;
     
    445453          if(cSize!=NULL){
    446454            length=atoi(cSize->value);
    447           }
     455          }else
     456            length=strlen(cValue->value);
    448457          writeFile(val,cValue->value,length);
    449458          setMapArray(cMap,"cache_file",k,val);
     459          free(val);
     460          val=(char*)malloc((strlen(tmpUrl->value)+strlen(inputs->name)+strlen(tmpSid->value)+strlen(file_ext)+16)*sizeof(char));
     461          sprintf(val,"%s/Input_%s_%s_%d.%s",tmpUrl->value,inputs->name,tmpSid->value,k,file_ext);
     462          setMapArray(cMap,"cache_url",k,val);
     463          setMapArray(cMap,"byValue",k,"true");
    450464          free(val);
    451465        }
     
    461475        if(cSize!=NULL){
    462476          length=atoi(cSize->value);
    463         }
     477        }else
     478          length=strlen(cValue->value);
    464479        writeFile(val,cValue->value,length);
    465480        addToMap(cMap,"cache_file",val);
     481        free(val);
     482        val=(char*)malloc((strlen(tmpUrl->value)+strlen(inputs->name)+strlen(tmpSid->value)+strlen(file_ext)+16)*sizeof(char));
     483        sprintf(val,"%s/Input_%s_%s_%d.%s",tmpUrl->value,inputs->name,tmpSid->value,0,file_ext);
     484        addToMap(cMap,"cache_url",val);
     485        addToMap(cMap,"byValue",val);
    466486        free(val);
    467487      }
     
    638658        }
    639659        if(res==NULL){
     660          map* tmpMaxO0=getMap(tmpInputs->content,"useMapserver");
     661          if(tmpMaxO0!=NULL){
     662            if(tmpMaps2->content==NULL)
     663              tmpMaps2->content=createMap("useMapserver",tmpMaxO0->value);
     664            else
     665              addToMap(tmpMaps2->content,"useMapserver",tmpMaxO0->value);
     666          }
    640667          map* tmpMaxO=getMap(tmpInputs->content,"maxOccurs");
    641668          if(tmpMaxO!=NULL){
     
    701728      }
    702729    }
    703     else {
     730    else /*toto*/{
    704731      iotype* tmpIoType=NULL;
    705732      if(tmpMaps->content!=NULL){
     
    711738           * content map.
    712739           */
    713           map* tmpMap1=getMap(tmpInputs->content,"minOccurs");
    714           if(tmpMap1!=NULL){
    715             if(tmpMaps->content==NULL)
    716               tmpMaps->content=createMap("minOccurs",tmpMap1->value);
    717             else
    718               addToMap(tmpMaps->content,"minOccurs",tmpMap1->value);
    719           }
    720           map* tmpMaxO=getMap(tmpInputs->content,"maxOccurs");
    721           if(tmpMaxO!=NULL){
    722             if(tmpMaps->content==NULL)
    723               tmpMaps->content=createMap("maxOccurs",tmpMaxO->value);
    724             else
    725               addToMap(tmpMaps->content,"maxOccurs",tmpMaxO->value);
    726           }
    727           map* tmpMaxMB=getMap(tmpInputs->content,"maximumMegabytes");
    728           if(tmpMaxMB!=NULL){
    729             if(tmpMaps->content==NULL)
    730               tmpMaps->content=createMap("maximumMegabytes",tmpMaxMB->value);
    731             else
    732               addToMap(tmpMaps->content,"maximumMegabytes",tmpMaxMB->value);
     740          char* keys[4]={
     741            "minOccurs",
     742            "maxOccurs",
     743            "maximumMegabytes",
     744            "useMapserver"
     745          };
     746          int i=0;
     747          for(i=0;i<4;i++){
     748            map* tmpMap1=getMap(tmpInputs->content,keys[i]);
     749            if(tmpMap1!=NULL){
     750              addToMap(tmpMaps->content,keys[i],tmpMap1->value);
     751            }
    733752          }
    734753          /**
     
    743762              map* tmpV=getMap(tmpI->content,"value");
    744763              if(tmpV!=NULL){
    745                 char *tmpVS=strdup(tmpV->value);
     764                char *tmpVS=zStrdup(tmpV->value);
    746765                map* tmp=parseBoundingBox(tmpVS);
    747766                free(tmpVS);
     
    780799              map* length=getMap(tmpMaps->content,"length");
    781800              int i;
    782               char *tcn=strdup(tmpContent->name);
     801              char *tcn=zStrdup(tmpContent->name);
    783802              for(i=1;i<atoi(length->value);i++){
    784803#ifdef DEBUG
     
    806825         */
    807826        if(tmpIoType!=NULL){
    808           map* tmpCheck=getMap(tmpIoType->content,"useMapServer");
    809           if(tmpCheck!=NULL){
     827          map* tmpCheck=getMap(tmpIoType->content,"useMapserver");
     828          if(tmpCheck!=NULL && strncasecmp(tmpCheck->value,"true",4)==0){
    810829            // Get the default value
     830            addToMap(tmpMaps->content,"useMapserver","true");
    811831            tmpIoType=getIoTypeFromElement(tmpInputs,tmpInputs->name,NULL);
    812832            tmpCheck=getMap(tmpMaps->content,"mimeType");
     
    834854        addToMap(tmpMaps->content,"inRequest","true");
    835855      elements* tmpElements=getElements(in,tmpMaps->name);
    836       if(tmpElements!=NULL && tmpElements->child!=NULL){
     856      if(/*tmpMaps->child!=NULL && */tmpElements!=NULL && tmpElements->child!=NULL){
    837857        char *res=addDefaultValues(&tmpMaps->child,tmpElements->child,m,type,err);
    838858        if(strlen(res)>0){
    839859          return res;
    840860        }
     861      }
     862    }
     863    if(tmpInputs->child!=NULL){
     864      tmpInputss=tmpInputs->next;
     865      tmpInputs=tmpInputs->child;
     866      if(tmpMaps!=NULL){
     867        out1=tmpMaps->child;
     868        out1s=tmpMaps;
    841869      }
    842870    }
     
    9721000    if(isRunning(conf,pid)>0){         
    9731001      if(strncasecmp(req,"GetResult",strlen(req))==0){
    974         errorException (conf, _("The result for the requested JobID has not yet been generated. "),
     1002        errorException (conf, _("The result for the requested JobID has not yet been generated. The service is currently running."),
    9751003                        "ResultNotReady", pid);
    9761004        return;
     
    9811009          char* tmpStr=_getStatus(conf,pid);
    9821010          if(tmpStr!=NULL && strncmp(tmpStr,"-1",2)!=0){
    983             char *tmpStr1=strdup(tmpStr);
    984             char *tmpStr0=strdup(strstr(tmpStr,"|")+1);
     1011            char *tmpStr1=zStrdup(tmpStr);
     1012            char *tmpStr0=zStrdup(strstr(tmpStr,"|")+1);
    9851013            free(tmpStr);
    9861014            tmpStr1[strlen(tmpStr1)-strlen(tmpStr0)-1]='\0';
     
    10001028          printf("%s",result);
    10011029          fflush(stdout);
     1030          free(sid);
    10021031          freeMap(&statusInfo);
    10031032          free(statusInfo);
     1033          free(result);
    10041034          return;
    10051035        }else{
    1006           errorException (conf, _("The result for the requested JobID has not yet been generated. "),
     1036          errorException (conf, _("The result for the requested JobID has not yet been generated. The service ends but it still needs to produce the outputs."),
    10071037                          "ResultNotReady", pid);
    10081038          freeMap(&statusInfo);
     
    10151045          char* tmpStr=_getStatus(conf,pid);
    10161046          if(tmpStr!=NULL && strncmp(tmpStr,"-1",2)!=0){
    1017             char *tmpStr1=strdup(tmpStr);
    1018             char *tmpStr0=strdup(strstr(tmpStr,"|")+1);
     1047            char *tmpStr1=zStrdup(tmpStr);
     1048            char *tmpStr0=zStrdup(strstr(tmpStr,"|")+1);
    10191049            free(tmpStr);
    10201050            tmpStr1[strlen(tmpStr1)-strlen(tmpStr0)-1]='\0';
     
    10261056        }
    10271057    }
     1058    free(sid);
    10281059    printStatusInfo(conf,statusInfo,req);
    10291060    freeMap(&statusInfo);
     
    10831114        if(strstr(dp->d_name,pid)!=0){
    10841115          sprintf(fileName,"%s/%s",r_inputs->value,dp->d_name);
    1085           if(unlink(fileName)!=0){
     1116          if(zUnlink(fileName)!=0){
    10861117            errorException (conf,
    10871118                            _("The job cannot be removed, a file cannot be removed"),
     
    10951126    removeService(conf,pid);
    10961127#endif
     1128    /* No need to call 7_1 when an execution is dismissed.
     1129      fprintf(stderr,"************************* %s %d \n\n",__FILE__,__LINE__);
     1130      invokeCallback(conf,NULL,NULL,7,1);
     1131      fprintf(stderr,"************************* %s %d \n\n",__FILE__,__LINE__);
     1132    */
    10971133    map* statusInfo=createMap("JobID",pid);
    10981134    addToMap(statusInfo,"Status","Dismissed");
  • trunk/zoo-project/zoo-kernel/service.c

    r889 r917  
    22 * Author : Gérald FENOY
    33 *
    4  * Copyright (c) 2015 GeoLabs SARL
     4 * Copyright (c) 2015-2019 GeoLabs SARL
    55 *
    66 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    2828#include <ctime>
    2929#include <chrono>
     30#ifdef WIN32
    3031#include <process.h>
     32#endif
    3133
    3234#if defined(_MSC_VER) && _MSC_VER < 1800
     
    102104    fprintf(stderr," * CONTENT [%s] \n",tmp->name);
    103105    dumpMap(tmp->content);
    104     fprintf(stderr," * CHILD [%s] \n",tmp->name);
    105     dumpMaps(tmp->child);
     106    if(tmp->child!=NULL){
     107      fprintf(stderr," * CHILD [%s] \n",tmp->name);
     108      dumpMaps(tmp->child);
     109      fprintf(stderr," * /CHILD [%s] \n",tmp->name);
     110    }
    106111    tmp=tmp->next;
    107112  }
     
    125130    fflush(file);
    126131    tmp=tmp->next;
    127     cnt++;
    128132    if(limit>=0 && cnt==limit)
    129133      tmp=NULL;
     134    cnt++;
    130135  }
    131136  fflush(file);
     
    144149  fflush(file);
    145150  fclose(file);
     151}
     152
     153/**
     154 * Create a new iotype*
     155 *
     156 * @return a pointer to the allocated iotype
     157 */
     158iotype* createIoType(){
     159  iotype* io=(iotype*)malloc(IOTYPE_SIZE);
     160  io->content=NULL;
     161  io->next=NULL;
     162  return io;
    146163}
    147164
     
    179196 * Count number of map in a map
    180197 *
    181  * @param m the maps to count
     198 * @param m the map to count
    182199 * @return number of map in a map
    183200 */
    184201int count(map* m){
    185202  map* tmp=m;
     203  int c=0;
     204  while(tmp!=NULL){
     205    c++;
     206    tmp=tmp->next;
     207  }
     208  return c;
     209}
     210
     211/**
     212 * Count number of maps in a maps
     213 *
     214 * @param m the maps to count
     215 * @return number of maps in a maps
     216 */
     217int maps_length(maps* m){
     218  maps* tmp=m;
    186219  int c=0;
    187220  while(tmp!=NULL){
     
    401434    if(tmp->metadata!=NULL)
    402435      free(tmp->metadata);
     436    freeMap(&tmp->additional_parameters);
     437    if(tmp->additional_parameters!=NULL)
     438      free(tmp->additional_parameters);
    403439    if(tmp->format!=NULL)
    404440      free(tmp->format);
     441    freeElements(&tmp->child);
    405442    if(tmp->child!=NULL){
    406       freeElements(&tmp->child);
    407443      free(tmp->child);
    408444    }
    409     freeIOType(&tmp->defaults);
    410     if(tmp->defaults!=NULL)
     445    if(tmp->defaults!=NULL){
     446      freeIOType(&tmp->defaults);
    411447      free(tmp->defaults);
    412     freeIOType(&tmp->supported);
     448    }
    413449    if(tmp->supported!=NULL){
     450      freeIOType(&tmp->supported);
    414451      free(tmp->supported);
    415452    }
    416     freeElements(&tmp->next);
    417     if(tmp->next!=NULL)
     453    if(tmp->next!=NULL){
     454      freeElements(&tmp->next);
    418455      free(tmp->next);
    419   }
     456    }
     457  }
     458}
     459
     460
     461/**
     462 * Allocate memory for a service.
     463 * Require to call free after calling this function.
     464 *
     465 * @return the service
     466 */
     467service* createService(){
     468  service *s1 = (service *) malloc (SERVICE_SIZE);
     469  s1->name=NULL;
     470  s1->content=NULL;
     471  s1->metadata=NULL;
     472  s1->additional_parameters=NULL;
     473  s1->inputs=NULL;
     474  s1->outputs=NULL;
     475  return s1;
    420476}
    421477
    422478/**
    423479 * Free allocated memory of a service.
    424  * Require to call free on e after calling this function.
     480 * Require to be invoked for every createService call.
    425481 *
    426482 * @param s the service to free
     
    437493    if(tmp->metadata!=NULL)
    438494      free(tmp->metadata);
     495    freeMap(&tmp->additional_parameters);
     496    if(tmp->additional_parameters!=NULL)
     497      free(tmp->additional_parameters);
    439498    freeElements(&tmp->inputs);
    440499    if(tmp->inputs!=NULL)
     
    454513 */
    455514void addToMap(map* m,const char* n,const char* v){
    456   if (m != NULL) { // knut: add NULL-pointer check
    457     if(hasKey(m,n)==false){
    458       map* _cursor=m;
    459       while(_cursor->next!=NULL){
    460         _cursor=_cursor->next;
    461       }
    462       _cursor->next=createMap(n,v);
    463     }
    464     else{
    465       map *tmp=getMap(m,n);
    466       if(tmp->value!=NULL)
    467         free(tmp->value);
    468       tmp->value=zStrdup(v);
    469     }
    470   }
     515    if (m != NULL) { // knut: add NULL-pointer check
     516        if (hasKey(m, n) == false) {
     517            map* _cursor = m;
     518            while (_cursor->next != NULL) {
     519                _cursor = _cursor->next;
     520            }
     521            _cursor->next = createMap(n, v);
     522        }
     523        else {
     524            map *tmp = getMap(m, n);
     525            if (tmp->value != NULL)
     526                free(tmp->value);
     527            tmp->value = zStrdup(v);
     528        }
     529    }
    471530}
    472531
     
    506565 */
    507566map* addToMapWithSize(map* m,const char* n,const char* v,int size){
     567  char sin[128];
     568  char sname[10]="size";
     569  map *tmp;
    508570  if(hasKey(m,n)==false){
    509571    map* _cursor=m;
     
    514576    }
    515577  }
    516   char sname[10]="size";
    517578  if(strlen(n)>5)
    518579    sprintf(sname,"size_%s",n+6);
    519   map *tmp=getMap(m,n);
     580  tmp=getMap(m,n);
    520581  if(tmp->value!=NULL)
    521582    free(tmp->value);
     
    524585    memmove(tmp->value,v,size*sizeof(char));
    525586  tmp->value[size]=0;
    526   char sin[128];
    527587  sprintf(sin,"%d",size);
    528588  addToMap(m,sname,sin);
     
    545605    }
    546606    else{
    547 #ifdef DEBUG
    548       fprintf(stderr,"_CURSOR\n");
    549       dumpMap(_cursor);
    550 #endif
    551       while(_cursor->next!=NULL)
    552         _cursor=_cursor->next;
    553607      map* tmp1=getMap(*mo,tmp->name);
    554608      if(tmp1==NULL){
     609        while(_cursor->next!=NULL)
     610          _cursor=_cursor->next;
    555611        _cursor->next=createMap(tmp->name,tmp->value);
    556612      }
     
    561617    _cursor=*mo;
    562618    tmp=tmp->next;
    563 #ifdef DEBUG
    564     fprintf(stderr,"MO\n");
    565     dumpMap(*mo);
    566 #endif
    567619  }
    568620}
     
    678730  map* size=getMap(in,"size");
    679731  map *lout=*out;
     732  map *tmpVin,*tmpVout;
    680733  if(size!=NULL && pos>0){
    681734    char tmp[11];
     
    683736    size=getMap(in,tmp);
    684737    sprintf(tmp,"value_%d",pos);
    685     map* tmpVin=getMap(in,tmp);
    686     map* tmpVout=getMap(lout,tmp);
     738    tmpVin=getMap(in,tmp);
     739    tmpVout=getMap(lout,tmp);
    687740    free(tmpVout->value);
    688741    tmpVout->value=(char*)malloc((atoi(size->value)+1)*sizeof(char));
     
    691744  }else{
    692745    if(size!=NULL){
    693       map* tmpVin=getMap(in,"value");
    694       map* tmpVout=getMap(lout,"value");
     746      tmpVin=getMap(in,"value");
     747      tmpVout=getMap(lout,"value");
    695748      free(tmpVout->value);
    696749      tmpVout->value=(char*)malloc((atoi(size->value)+1)*sizeof(char));
     
    712765  map* size=getMap(in,"size");
    713766  map* length=getMap(in,"length");
     767  map* toload=getMap(in,"to_load");
     768  if(toload!=NULL && strcasecmp(toload->value,"false")==0){
     769#ifdef DEBUG
     770    fprintf(stderr,"NO LOAD %s %d \n",__FILE__,__LINE__);
     771#endif
     772    return ;
     773  }
    714774  if(length!=NULL){
    715775    int len=atoi(length->value);
     
    734794  maps* res=NULL;
    735795  if(_cursor!=NULL){
     796    map* mc=_cursor->content;
     797    maps* mcs=_cursor->child;
    736798    res=createMaps(_cursor->name);
    737     map* mc=_cursor->content;
    738799    if(mc!=NULL){
    739800      addMapToMap(&res->content,mc);
    740801      loadMapBinaries(&res->content,mc);
    741802    }
    742     maps* mcs=_cursor->child;
    743803    if(mcs!=NULL){
    744804      res->child=dupMaps(&mcs);
     
    764824    }
    765825    else{
     826      maps* tmp1=getMaps(*mo,tmp->name);
    766827      while(_cursor->next!=NULL)
    767828        _cursor=_cursor->next;
    768       maps* tmp1=getMaps(*mo,tmp->name);
    769829      if(tmp1==NULL){
    770830        _cursor->next=dupMaps(&tmp);
     
    797857map* getMapArray(map* m,const char* key,int index){
    798858  char tmp[1024];
     859  map* tmpMap;
    799860  if(index>0)
    800861    sprintf(tmp,"%s_%d",key,index);
     
    804865  fprintf(stderr,"** KEY %s\n",tmp);
    805866#endif
    806   map* tmpMap=getMap(m,tmp);
     867  tmpMap=getMap(m,tmp);
    807868#ifdef DEBUG
    808869  if(tmpMap!=NULL)
     
    823884void setMapArray(map* m,const char* key,int index,const char* value){
    824885  char tmp[1024];
     886  map* tmpSize;
    825887  if(index>0){
     888    map* len=getMap(m,"length");
    826889    sprintf(tmp,"%s_%d",key,index);
    827     map* len=getMap(m,"length");
    828890    if((len!=NULL && atoi(len->value)<index+1) || len==NULL){
    829891      char tmp0[5];
     
    832894    }
    833895  }
    834   else
     896  else{
    835897    sprintf(tmp,"%s",key);
    836   map* tmpSize=getMapArray(m,"size",index);
     898    addToMap(m,"length","1");
     899  }
     900  tmpSize=getMapArray(m,"size",index);
    837901  if(tmpSize!=NULL && strncasecmp(key,"value",5)==0){
     902    map* ptr=getMapOrFill(&m,tmp,(char *)"");
    838903#ifdef DEBUG
    839904    fprintf(stderr,"%s\n",tmpSize->value);
    840905#endif
    841     map* ptr=getMapOrFill(&m,tmp,(char *)"");
    842906    free(ptr->value);
    843907    ptr->value=(char*)malloc((atoi(tmpSize->value)+1)*sizeof(char));
     
    846910  else
    847911    addToMap(m,tmp,value);
     912}
     913
     914/**
     915 * Add a key and an integer value to an existing map array.
     916 *
     917 * @param m the map to add the KVP
     918 * @param n the key to add
     919 * @param index the index of the MapArray
     920 * @param v the corresponding value to add
     921 */
     922void addIntToMapArray(map* m,const char* n,int index,const int v){
     923  char svalue[10];
     924  sprintf(svalue,"%d",v);
     925  setMapArray(m,n,index,svalue);
    848926}
    849927
     
    881959  maps* tmp=mi;   
    882960  maps* _cursor=getMaps(*mo,tmp->name);
    883 
    884   if(_cursor==NULL)
    885     return -1;
    886 
    887   map* tmpLength=getMap(_cursor->content,"length");
    888961  char tmpLen[10];
    889962  int len=1;
    890   if(tmpLength!=NULL){
    891     len=atoi(tmpLength->value);
    892   }
    893 
    894963  char *tmpV[14]={
    895964    (char*)"size",
     
    906975    (char*)"isCached",
    907976    (char*)"LowerCorner",
    908     (char*)"UpperCorner"   
     977    (char*)"UpperCorner"
    909978  };
     979  int i=0;
     980  map* tmpLength;
     981 
     982  if(_cursor==NULL)
     983    return -1;
     984
     985  tmpLength=getMap(_cursor->content,"length");
     986  if(tmpLength!=NULL){
     987    len=atoi(tmpLength->value);
     988  }
     989
    910990  sprintf(tmpLen,"%d",len+1);
    911991  addToMap(_cursor->content,"length",tmpLen);
    912   int i=0;
    913992  for(i=0;i<14;i++){
    914993    map* tmpVI=getMap(tmp->content,tmpV[i]);
     
    9671046  res->content=NULL;
    9681047  res->metadata=NULL;
     1048  res->additional_parameters=NULL; 
    9691049  res->format=NULL;
    9701050  res->defaults=NULL;
     
    9811061 * @return a pointer to the allocated elements
    9821062 */
    983 elements* createElements(char* name){
     1063elements* createElements(const char* name){
    9841064  elements* res=(elements*)malloc(ELEMENTS_SIZE);
    9851065  res->name=zStrdup(name);
    9861066  res->content=NULL;
    9871067  res->metadata=NULL;
     1068  res->additional_parameters=NULL;
    9881069  res->format=NULL;
    9891070  res->defaults=NULL;
     
    10201101  elements* tmp=e;
    10211102  while(tmp!=NULL){
     1103    iotype* tmpio=tmp->defaults;
     1104    int ioc=0;
    10221105    fprintf(stderr,"ELEMENT [%s]\n",tmp->name);
    10231106    fprintf(stderr," > CONTENT [%s]\n",tmp->name);
     
    10251108    fprintf(stderr," > METADATA [%s]\n",tmp->name);
    10261109    dumpMap(tmp->metadata);
     1110    fprintf(stderr," > ADDITIONAL PARAMETERS [%s]\n",tmp->name);
     1111    dumpMap(tmp->additional_parameters);
    10271112    fprintf(stderr," > FORMAT [%s]\n",tmp->format);
    1028     iotype* tmpio=tmp->defaults;
    1029     int ioc=0;
    10301113    while(tmpio!=NULL){
    10311114      fprintf(stderr," > DEFAULTS [%s] (%i)\n",tmp->name,ioc);
     
    10601143  int i;
    10611144  while(tmp!=NULL){
     1145    map* mcurs=tmp->content;
     1146    int ioc=0;
     1147    iotype* tmpio;
    10621148    for(i=0;i<2+(4*level);i++)
    10631149      fprintf(stderr," ");
    10641150    fprintf(stderr,"%s:\n",tmp->name);
    1065     map* mcurs=tmp->content;
    10661151    while(mcurs!=NULL){
    10671152      for(i=0;i<4+(4*level);i++)
     
    10911176        dumpElementsAsYAML(tmp->child,level+1);
    10921177    }
    1093     iotype* tmpio=tmp->defaults;
    1094     int ioc=0;
     1178    tmpio=tmp->defaults;
    10951179    while(tmpio!=NULL){
    10961180      for(i=0;i<6+(4*level);i++)
     
    11421226  elements* cursor=e;
    11431227  elements* tmp=NULL;
    1144   if(cursor!=NULL){
     1228  if(cursor!=NULL && cursor->name!=NULL){
    11451229#ifdef DEBUG
    11461230    fprintf(stderr,">> %s %i\n",__FILE__,__LINE__);
     
    11491233#endif
    11501234    tmp=(elements*)malloc(ELEMENTS_SIZE);
    1151     tmp->name=zStrdup(e->name);
     1235    tmp->name=zStrdup(cursor->name);
    11521236    tmp->content=NULL;
    1153     addMapToMap(&tmp->content,e->content);
     1237    addMapToMap(&tmp->content,cursor->content);
    11541238    tmp->metadata=NULL;
    1155     addMapToMap(&tmp->metadata,e->metadata);
    1156     if(e->format!=NULL)
    1157       tmp->format=zStrdup(e->format);
     1239    addMapToMap(&tmp->metadata,cursor->metadata);
     1240    tmp->additional_parameters=NULL;
     1241    addMapToMap(&tmp->additional_parameters,cursor->additional_parameters);
     1242    if(cursor->format!=NULL)
     1243      tmp->format=zStrdup(cursor->format);
    11581244    else
    11591245      tmp->format=NULL;
    1160     if(e->defaults!=NULL){
     1246    if(cursor->defaults!=NULL){
    11611247      tmp->defaults=(iotype*)malloc(IOTYPE_SIZE);
    11621248      tmp->defaults->content=NULL;
    1163       addMapToMap(&tmp->defaults->content,e->defaults->content);
     1249      addMapToMap(&tmp->defaults->content,cursor->defaults->content);
    11641250      tmp->defaults->next=NULL;
    11651251#ifdef DEBUG
     
    11691255    }else
    11701256      tmp->defaults=NULL;
    1171     if(e->supported!=NULL){
     1257    if(cursor->supported!=NULL && cursor->supported->content!=NULL){
     1258      iotype *tmp2=cursor->supported->next;
    11721259      tmp->supported=(iotype*)malloc(IOTYPE_SIZE);
    11731260      tmp->supported->content=NULL;
    1174       addMapToMap(&tmp->supported->content,e->supported->content);
     1261      addMapToMap(&tmp->supported->content,cursor->supported->content);
    11751262      tmp->supported->next=NULL;
    1176       iotype *tmp2=e->supported->next;
    1177       while(tmp2!=NULL){
     1263            while(tmp2!=NULL){
    11781264        addMapToIoType(&tmp->supported,tmp2->content);
    11791265#ifdef DEBUG
     
    11901276    else
    11911277      tmp->child=NULL;
    1192     tmp->next=dupElements(cursor->next);
     1278    if(cursor->next!=NULL)
     1279      tmp->next=dupElements(cursor->next);
     1280    else
     1281      tmp->next=NULL;
    11931282  }
    11941283  return tmp;
     
    12051294  elements* tmp=e;
    12061295  if(*m==NULL){
    1207     *m=dupElements(tmp);
     1296    (*m)=dupElements(tmp);
    12081297  }else{
    12091298    addToElements(&(*m)->next,tmp);
     
    12371326    fprintf(stderr,"CONTENT MAP\n");
    12381327    dumpMap(s->content);
    1239     fprintf(stderr,"CONTENT METADATA\n");
     1328    if(s->metadata!=NULL)
     1329      fprintf(stderr,"CONTENT METADATA\n");
    12401330    dumpMap(s->metadata);
     1331    if(s->additional_parameters!=NULL)
     1332      fprintf(stderr,"CONTENT AdditionalParameters\n");
     1333    dumpMap(s->additional_parameters);
    12411334  }
    12421335  if(s->inputs!=NULL){
     
    12961389  res->metadata=NULL;
    12971390  addMapToMap(&res->metadata,s->metadata);
     1391  res->additional_parameters=NULL;
     1392  addMapToMap(&res->additional_parameters,s->additional_parameters);
    12981393  res->inputs=dupElements(s->inputs);
    12991394  res->outputs=dupElements(s->outputs);
     
    13091404  registry* p=r;
    13101405  while(p!=NULL){
     1406    services* s=p->content;
    13111407    fprintf(stderr,"%s \n",p->name);
    1312     services* s=p->content;
    13131408    s=p->content;
    13141409    while(s!=NULL){
     
    15091604 */
    15101605void inheritance(registry *r,service** s){
     1606  service* ls=*s;
     1607  map *profile,*level;
    15111608  if(r==NULL)
    15121609    return;
    1513   service* ls=*s;
    1514   if(ls->content==NULL)
     1610  if(ls==NULL || ls->content==NULL)
    15151611    return;
    1516   map* profile=getMap(ls->content,"extend");
    1517   map* level=getMap(ls->content,"level");
     1612  profile=getMap(ls->content,"extend");
     1613  level=getMap(ls->content,"level");
    15181614  if(profile!=NULL&&level!=NULL){
    15191615    service* s1;
     
    15501646  memset(tmp,0,1024*10*10);
    15511647  while(tm!=NULL){
     1648    map* tc=tm->content;
    15521649    if(i>=10)
    15531650      break;
     
    15561653    strcpy(tmp[i][j],tm->name);
    15571654    j++;
    1558     map* tc=tm->content;
    15591655    while(tc!=NULL){
    15601656      if(j>=30)
     
    16091705 * @return true if map has a value or false if value is missing/empty/NULL
    16101706 */
    1611 bool nonempty( map* map ) {
    1612     return ( map != NULL && map->value != NULL && strlen(map->value) > 0 && strcmp(map->value, "NULL") != 0 );
    1613 }
    1614 
    1615 /**
    1616  * Verify that a particular map value exists in a maps 
     1707bool nonempty(map* map) {
     1708        return (map != NULL && map->value != NULL && strlen(map->value) > 0 && strcmp(map->value, "NULL") != 0);
     1709}
     1710
     1711/**
     1712 * Verify that a particular map value exists in a maps
    16171713 * data structure, and obtain that value
    16181714 *
     
    16201716 * @param node name of maps node to search
    16211717 * @param key name of map node to find
    1622  * @param address to the map* if it exists, otherwise NULL
     1718 * @param kvp address to the map* if it exists, otherwise NULL
    16231719 * @return true if map has a value or false if value is missing/NULL
    1624  */
    1625 bool hasvalue( maps* source, const char* node, const char* key, map** kvp ) {
    1626     *kvp = getMapFromMaps(source, node, key);
    1627     return ( *kvp != NULL && (*kvp)->value != NULL &&
    1628              strlen((*kvp)->value) > 0 && strcmp((*kvp)->value, "NULL") != 0 );
     1720 *
     1721 * @note The map assigned to kvp is owned by the source maps
     1722 */
     1723bool hasvalue(maps* source, const char* node, const char* key, map** kvp) {
     1724        *kvp = getMapFromMaps(source, node, key);
     1725        return (*kvp != NULL && (*kvp)->value != NULL &&
     1726                strlen((*kvp)->value) > 0 && strcmp((*kvp)->value, "NULL") != 0);
    16291727}
    16301728
     
    16331731 *
    16341732 * @param conf reference to configuration maps
    1635  * @param service name of service 
     1733 * @param service name of service
    16361734 * @param exc WPSException code
    16371735 * @param message exception text (default: exception text in WPS specification)
    16381736 */
    1639 void setErrorMessage( maps*& conf, const char* service, WPSException exc, const char* message ) {
    1640  
    1641   if (message == NULL) {
    1642     message = WPSExceptionText[exc];
    1643   }
    1644 
    1645         size_t len = strlen( service ) + strlen(": ") + strlen( message ) + strlen(": ") + strlen(WPSExceptionCode[exc]) + 16;
    1646         char* msg = (char*) malloc( len * sizeof(char) );
     1737void setErrorMessage(maps*& conf, const char* service, WPSException exc, const char* message) {
     1738
     1739        if (message == NULL) {
     1740                message = WPSExceptionText[exc];
     1741        }
     1742
     1743        size_t len = strlen(service) + strlen(": ") + strlen(message) + strlen(": ") + strlen(WPSExceptionCode[exc]) + 16;
     1744        char* msg = (char*)malloc(len * sizeof(char));
    16471745
    16481746        if (msg != NULL) {
    1649                 snprintf( msg, len*sizeof(char), "\n%s: %s: %s\n", service, message, WPSExceptionCode[exc] );
    1650                 setMapInMaps( conf, "lenv", "message", msg );
    1651                 free( msg );
    1652         }       
     1747                snprintf(msg, len * sizeof(char), "\n%s: %s: %s\n", service, message, WPSExceptionCode[exc]);
     1748                setMapInMaps(conf, "lenv", "message", msg);
     1749                free(msg);
     1750        }
    16531751}
    16541752
    16551753void logMessage(const char* source, const char* function, int line, const char* file, const char* message) { //, const char* source, const char* function, int line) {
    1656  
    1657   size_t msglen = 512;
    1658   const char empty[] = "";
    1659  
    1660   FILE* log;
    1661  
    1662   // system time, process time [nanoseconds]   
    1663   unsigned long long sys_t, proc_t;
    1664  
    1665   // processor time consumed by the program:
    1666   clock_t t = clock();
    1667    
    1668   // system time:
    1669   std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    1670  
    1671   std::time_t now_t = std::chrono::system_clock::to_time_t( now );
    1672   std::tm* tm = localtime( &now_t );
     1754
     1755        size_t msglen = 512;
     1756        const char empty[] = "";
     1757
     1758        FILE* log;
     1759
     1760        // system time, process time [nanoseconds]   
     1761        unsigned long long sys_t, proc_t;
     1762
     1763        // processor time consumed by the program:
     1764        clock_t t = clock();
     1765
     1766        // system time:
     1767        std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
     1768
     1769        std::time_t now_t = std::chrono::system_clock::to_time_t(now);
     1770        std::tm* tm = localtime(&now_t);
    16731771        char* str = asctime(tm);
    1674   str[strlen(str)-1] = '\0'; // remove newline
    1675  
    1676   sys_t = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
    1677   //proc_t = (unsigned long long)(1.0e9*t/CLOCKS_PER_SEC);
    1678   proc_t = t;
    1679  
    1680   if ( message != NULL ) {
    1681      msglen += strlen(message);
    1682   } 
    1683   else {
    1684     message = empty;
    1685   }
    1686   //getLastErrorMessage(); // cgiScriptName 
    1687   char* text = (char*) malloc( sizeof(char)*msglen );
    1688  
    1689   snprintf( text, msglen, "pid: %d %s line %d %s() %s systime: %lld ns ticks: %lld %s\n",
    1690     _getpid(), source, line, function, str, sys_t, proc_t, message ); // __FILE__ __LINE__ __func__ //
    1691  
    1692   if ( file != NULL && (log = fopen( file, "a+" )) != NULL ) {
    1693     fputs( text, log );
    1694     fclose( log );
    1695   }
    1696   else {
    1697     #ifdef MSG_LOG_FILE
    1698     if ( (log = fopen( MSG_LOG_FILE, "a+" )) != NULL ) {
    1699       fputs( text, log );
    1700       fclose( log );
    1701     }     
    1702     #endif
    1703   }
    1704  
    1705   if ( text != NULL ) free( text );
     1772        str[strlen(str) - 1] = '\0'; // remove newline
     1773
     1774        sys_t = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();
     1775        //proc_t = (unsigned long long)(1.0e9*t/CLOCKS_PER_SEC);
     1776        proc_t = t;
     1777
     1778        if (message != NULL) {
     1779                msglen += strlen(message);
     1780        }
     1781        else {
     1782                message = empty;
     1783        }
     1784        //getLastErrorMessage(); // cgiScriptName 
     1785        char* text = (char*)malloc(sizeof(char)*msglen);
     1786
     1787        snprintf(text, msglen, "pid: %d %s line %d %s() %s systime: %lld ns ticks: %lld %s\n",
     1788                zGetpid(), source, line, function, str, sys_t, proc_t, message); // __FILE__ __LINE__ __func__ //
     1789
     1790        if (file != NULL && (log = fopen(file, "a+")) != NULL) {
     1791                fputs(text, log);
     1792                fclose(log);
     1793        }
     1794        else {
     1795#ifdef MSG_LOG_FILE
     1796                if ((log = fopen(MSG_LOG_FILE, "a+")) != NULL) {
     1797                        fputs(text, log);
     1798                        fclose(log);
     1799                }
     1800#endif
     1801        }
     1802
     1803        if (text != NULL) free(text);
    17061804}
    17071805
     
    17101808// zooLog;
    17111809// zooLogMsg(NULL, getLastErrorMessage());
    1712 // zooLogMsg(log.txt, getLastErrorMessage());
    1713 
    1714 #ifdef WIN32
    1715 #ifndef USE_MS
    1716 char *strcasestr (char const *a, char const *b)
    1717   {
    1718     char *x = zStrdup (a);
    1719     char *y = zStrdup (b);
    1720  
    1721       x = _strlwr (x);
    1722       y = _strlwr (y);
    1723     char *pos = strstr (x, y);
    1724     char *ret = pos == NULL ? NULL : (char *) (a + (pos - x));
    1725       free (x);
    1726       free (y);
    1727       return ret;
    1728   };
    1729 #else
    1730    ;
    1731 #endif
    1732 #endif
     1810// zooLogMsg("log.txt", getLastErrorMessage());
  • trunk/zoo-project/zoo-kernel/service.h

    r889 r917  
    22 * Author : Gérald FENOY
    33 *
    4  * Copyright (c) 2009-2015 GeoLabs SARL
     4 * Copyright (c) 2009-2019 GeoLabs SARL
    55 *
    66 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    3434#endif
    3535
     36 // knut: add bool if necessary
     37#ifndef __cplusplus
     38#ifndef WIN32
     39#include <stdbool.h>
     40#else
     41typedef int bool;
     42#define false 0
     43#define true 1 
     44#endif
     45#endif
     46#ifndef __bool_true_false_are_defined
     47#define __bool_true_false_are_defined 1
     48#endif
     49
    3650#ifdef WIN32
    37 #ifndef USE_MS
    38 ZOO_DLL_EXPORT char *strcasestr (char const *,char const *);
    39 #endif
    40 #endif
    41 
    42 // knut: add bool if necessary
    43 #ifndef __cplusplus
    44   #ifndef WIN32
    45     #include <stdbool.h>
    46   #else
    47     typedef int bool;
    48     #define false 0
    49     #define true 1     
    50   #endif
    51 #endif
    52 #ifndef __bool_true_false_are_defined
    53   #define __bool_true_false_are_defined 1
    54 #endif
    55 
    56 #ifdef WIN32
     51#define strtok_r strtok_s
    5752#define strncasecmp _strnicmp
    5853#define strcasecmp _stricmp
    59 #define strtok_r strtok_s
    6054#if defined(_MSC_VER) && _MSC_VER < 1900
    6155#define snprintf _snprintf
    6256#endif
    63 /* knut: see new definition of bool above
    64 #if defined(_MSC_VER) && _MSC_VER < 1800
    65 #define false 0
    66 #define true 1
    67 #define bool int
    68 #endif
    69 */
    7057#define zStrdup _strdup
    7158#define zMkdir _mkdir
     59#define zGetpid _getpid
    7260#define zOpen _open
     61#define zClose _close
     62#define zUnlink _unlink
     63#define zDup _dup
     64#define zDup2 _dup2
    7365#define zWrite _write
    7466#define zSleep Sleep
     
    8072static int zGettimeofday(struct ztimeval* tp, void* tzp)
    8173{
    82   struct _timeb theTime;       
    8374  if (tp == 0) {
    8475    return -1;
    8576  }
    8677 
     78  struct _timeb theTime;
    8779  _ftime(&theTime);
    8880  tp->tv_sec = theTime.time;
     
    9284}
    9385
     86#define zStatStruct struct _stati64
     87#define zStat _stati64
     88
    9489#else
    9590/**
     
    106101#define zOpen open
    107102/**
     103 * The crossplatform close alias
     104 */
     105#define zClose close
     106/**
     107 * The crossplatform unlink alias
     108 */
     109#define zUnlink unlink
     110/**
     111 * The crossplatform dup alias
     112 */
     113#define zDup dup
     114/**
     115 * The crossplatform dup2 alias
     116 */
     117#define zDup2 dup2
     118/**
    108119 * The crossplatform write alias
    109120 */
    110121#define zWrite write
     122#include "unistd.h"
    111123/**
    112124 * The crossplatform sleep alias
    113125 */
    114 #define zSleep sleep
     126static int zSleep(const long millisecond){
     127  return usleep(millisecond*1000);
     128}
    115129/**
    116130 * The crossplatform gettimeofday alias
     
    121135 */
    122136#define ztimeval timeval
     137/**
     138 * The crossplatform getpid alias
     139 */
     140#define zGetpid getpid
     141
     142#define zStatStruct struct stat64
     143#define zStat stat64
     144
    123145#endif
    124146
     
    140162#ifndef WIN32
    141163#include <ctype.h>
    142 //#include <stdbool.h> // knut: see new definition of bool above
     164#include <stdbool.h>
    143165#endif
    144166
     
    167189 * The memory size to create an elements
    168190 */
    169 #define ELEMENTS_SIZE (sizeof(char*)+(((2*sizeof(char*))+sizeof(maps*))*2)+sizeof(char*)+(((2*sizeof(char*))+sizeof(iotype*))*2)+(2*sizeof(elements*)))
     191#define ELEMENTS_SIZE (sizeof(char*)+(((2*sizeof(char*))+sizeof(maps*))*3)+sizeof(char*)+((sizeof(map*) + sizeof(iotype*))*2)+(2*sizeof(elements*)))
    170192/**
    171193 * The memory size to create a map
     
    187209 */
    188210//#define SERVICE_SIZE (ELEMENTS_SIZE*2)+(MAP_SIZE*2)+sizeof(char*)
    189 #define SERVICE_SIZE sizeof(char*) + 2*sizeof(map*) + 2*sizeof(elements*)
     211#define SERVICE_SIZE sizeof(char*) + 3*sizeof(map*) + 2*sizeof(elements*)
    190212/**
    191213 * The memory size to create a services
     
    221243#ifdef WIN32
    222244#define NULLMAP ((map*) 0)
     245// knut: see new definition above
     246//#define bool int
     247//#define true 1
     248//#define false 0
    223249#else
    224250#define NULLMAP NULL
     
    256282    struct map* content; //!< the content map
    257283    struct map* metadata; //!< the metadata map
     284    struct map* additional_parameters; //!< the additional parameters map
    258285    char* format; //!< the format: LiteralData or ComplexData or BoundingBoxData
    259286    struct iotype* defaults; //!< the default iotype
     
    270297    struct map* content; //!< the content map
    271298    struct map* metadata; //!< the metadata map
     299    struct map* additional_parameters; //!< the additional parameters map
    272300    struct elements* inputs; //!< the inputs elements
    273301    struct elements* outputs; //!< the outputs elements
     
    290318    struct registry* next; //!< the next registry pointer
    291319  } registry;
    292  
     320
    293321  // knut
    294322  enum WPSException {
    295     /*
    296     * StatusOK is not a WPS exception, it is added
    297     * here for convenience.
    298     */     
    299     StatusOK,                 
    300     /*
    301     * See WPS 1.0 specification, Table 38 and Table 62.
    302     */
    303     MissingParameterValue,   
    304     InvalidParameterValue,
    305     NoApplicableCode,
    306     NotEnoughStorage,
    307     ServerBusy,
    308     FileSizeExceeded,
    309     StorageNotSupported,
    310     VersionNegotiationFailed,
    311     /*
    312     * See WPS 2.0 specification, Tables 41, 46, 48, and 50.
    313     */
    314     NoSuchProcess,
    315     NoSuchMode,
    316     NoSuchInput,
    317     NoSuchOutput,
    318     DataNotAccessible,
    319     SizeExceeded,
    320     TooManyInputs,
    321     TooManyOutputs,
    322     NoSuchFormat,
    323     WrongInputData,
    324     InternalServerError,
    325     NoSuchJob,
    326     ResultNotReady
    327   }; 
    328  
     323          /*
     324          * StatusOK is not a WPS exception, it is added
     325          * here for convenience.
     326          */
     327          StatusOK,
     328          /*
     329          * See WPS 1.0 specification, Table 38 and Table 62.
     330          */
     331          MissingParameterValue,
     332          InvalidParameterValue,
     333          NoApplicableCode,
     334          NotEnoughStorage,
     335          ServerBusy,
     336          FileSizeExceeded,
     337          StorageNotSupported,
     338          VersionNegotiationFailed,
     339          /*
     340          * See WPS 2.0 specification, Tables 41, 46, 48, and 50.
     341          */
     342          NoSuchProcess,
     343          NoSuchMode,
     344          NoSuchInput,
     345          NoSuchOutput,
     346          DataNotAccessible,
     347          SizeExceeded,
     348          TooManyInputs,
     349          TooManyOutputs,
     350          NoSuchFormat,
     351          WrongInputData,
     352          InternalServerError,
     353          NoSuchJob,
     354          ResultNotReady
     355  };
     356
    329357  static const char* const WPSExceptionCode[] = {
    330     "StatusOK",
    331     "MissingParameterValue",
    332     "InvalidParameterValue",
    333     "NoApplicableCode",
    334     "NotEnoughStorage",
    335     "ServerBusy",
    336     "FileSizeExceeded",
    337     "StorageNotSupported",
    338     "VersionNegotiationFailed",
    339     "NoSuchProcess",
    340     "NoSuchMode",
    341     "NoSuchInput",
    342     "NoSuchOutput",
    343     "DataNotAccessible",
    344     "SizeExceeded",
    345     "TooManyInputs",
    346     "TooManyOutputs",
    347     "NoSuchFormat",
    348     "WrongInputData",
    349     "InternalServerError",
    350     "NoSuchJob",
    351     "ResultNotReady"   
    352   };     
     358        "StatusOK",
     359        "MissingParameterValue",
     360        "InvalidParameterValue",
     361        "NoApplicableCode",
     362        "NotEnoughStorage",
     363        "ServerBusy",
     364        "FileSizeExceeded",
     365        "StorageNotSupported",
     366        "VersionNegotiationFailed",
     367        "NoSuchProcess",
     368        "NoSuchMode",
     369        "NoSuchInput",
     370        "NoSuchOutput",
     371        "DataNotAccessible",
     372        "SizeExceeded",
     373        "TooManyInputs",
     374        "TooManyOutputs",
     375        "NoSuchFormat",
     376        "WrongInputData",
     377        "InternalServerError",
     378        "NoSuchJob",
     379        "ResultNotReady"
     380  };
    353381
    354382  static const char* const WPSExceptionText[] = {
    355     "No problem detected",
    356     "Operation request does not include a parameter value, and this server did not declare a default value for that parameter.",
    357     "Operation request contains an invalid parameter value.",
    358     "No other exceptionCode specified by this service and server applies to this exception.",
    359     "The server does not have enough space available to store the inputs and outputs associated with the request.",
    360     "The server is too busy to accept and queue the request at this time.",
    361     "The file size of one of the input parameters was too large for this process to handle.",
    362     "Execute operation request included transmission=”reference” for one of the outputs, but storage is not offered by this server.",
    363     "Service version for a ComplexData xlink:href input was not supported by the referenced server, and version negotiation failed.",
    364     "One of the identifiers passed does not match with any of the processes offered by this server.",
    365     "The process does not permit the desired execution mode.",
    366     "One or more of the input identifiers passed does not match with any of the input identifiers of this process.",
    367     "One or more of the output identifiers passed does not match with any of the input identifiers of this process.",
    368     "One of the referenced input data sets was inaccessible.",
    369     "The size of one of the input parameters was too large for this process to handle.",
    370     "Too many input items have been specified.",
    371     "Too many output items have been specified.",
    372     "One or more of the input or output formats specified in the request did not match with any of the formats defined for that particular input or output.",
    373     "One or more of inputs for which the service was able to retrieve the data but could not read it.",
    374     "",
    375     "The JobID from the request does not match any of the Jobs running on this server.",
    376     "The result for the requested JobID has not yet been generated."
     383        "No problem detected",
     384        "Operation request does not include a parameter value, and this server did not declare a default value for that parameter.",
     385        "Operation request contains an invalid parameter value.",
     386        "No other exceptionCode specified by this service and server applies to this exception.",
     387        "The server does not have enough space available to store the inputs and outputs associated with the request.",
     388        "The server is too busy to accept and queue the request at this time.",
     389        "The file size of one of the input parameters was too large for this process to handle.",
     390        "Execute operation request included transmission=”reference” for one of the outputs, but storage is not offered by this server.",
     391        "Service version for a ComplexData xlink:href input was not supported by the referenced server, and version negotiation failed.",
     392        "One of the identifiers passed does not match with any of the processes offered by this server.",
     393        "The process does not permit the desired execution mode.",
     394        "One or more of the input identifiers passed does not match with any of the input identifiers of this process.",
     395        "One or more of the output identifiers passed does not match with any of the input identifiers of this process.",
     396        "One of the referenced input data sets was inaccessible.",
     397        "The size of one of the input parameters was too large for this process to handle.",
     398        "Too many input items have been specified.",
     399        "Too many output items have been specified.",
     400        "One or more of the input or output formats specified in the request did not match with any of the formats defined for that particular input or output.",
     401        "One or more of inputs for which the service was able to retrieve the data but could not read it.",
     402        "",
     403        "The JobID from the request does not match any of the Jobs running on this server.",
     404        "The result for the requested JobID has not yet been generated."
    377405  };
    378406
     
    392420  ZOO_DLL_EXPORT void freeMap(map**);
    393421  ZOO_DLL_EXPORT void freeMaps(maps** mo);
    394  
    395 
     422  ZOO_DLL_EXPORT iotype* createIoType();
    396423  ZOO_DLL_EXPORT elements* createEmptyElements();
    397   ZOO_DLL_EXPORT elements* createElements(char*);
     424  ZOO_DLL_EXPORT elements* createElements(const char*);
    398425  ZOO_DLL_EXPORT void setElementsName(elements**,char*);
    399426  ZOO_DLL_EXPORT bool hasElement(elements*,const char*);
     
    402429  ZOO_DLL_EXPORT void freeElements(elements**);
    403430  ZOO_DLL_EXPORT void setServiceName(service**,char*);
     431  ZOO_DLL_EXPORT service* createService();
    404432  ZOO_DLL_EXPORT void freeService(service**);
    405433  ZOO_DLL_EXPORT void addToMap(map*,const char*,const char*);
    406434  ZOO_DLL_EXPORT void addIntToMap(map*,const char*,const int);
     435  ZOO_DLL_EXPORT void addIntToMapArray(map*,const char*,int,const int);
    407436  ZOO_DLL_EXPORT map* addToMapWithSize(map*,const char*,const char*,int);
    408437  ZOO_DLL_EXPORT void addMapToMap(map**,map*);
     
    446475  ZOO_DLL_EXPORT bool nonempty(map* map);
    447476  ZOO_DLL_EXPORT bool hasvalue(maps* source, const char* node, const char* key, map** kvp);
     477#ifdef __cplusplus
    448478  ZOO_DLL_EXPORT void setErrorMessage(maps*& conf, const char* service, WPSException exc, const char* message = NULL);
    449   ZOO_DLL_EXPORT void logMessage(const char* source, const char* function, int line, const char* file = NULL, const char* message = NULL); 
     479  ZOO_DLL_EXPORT void logMessage(const char* source, const char* function, int line, const char* file = NULL, const char* message = NULL);
     480#endif
    450481  #define zooLogMsg(file,message) logMessage(__FILE__, __func__, __LINE__, (file), (message))
    451482  #define zooLog logMessage(__FILE__, __func__, __LINE__) 
    452  
     483
    453484#ifdef __cplusplus
    454485}
  • trunk/zoo-project/zoo-kernel/service_conf.y

    r790 r917  
    3333static bool wait_maincontent=true;
    3434static bool wait_mainmetadata=false;
     35static bool wait_mainap=false;
    3536static bool wait_metadata=false;
     37static bool wait_ap=false;
    3638static bool wait_nested=false;
    3739static bool wait_inputs=false;
     
    156158    current_content=NULL;
    157159    my_service->metadata=NULL;
     160    my_service->additional_parameters=NULL;
    158161    wait_maincontent=false;
    159162  }
    160163  if(strncasecmp($2,"EndNested",9)==0){
    161164#ifdef DEBUG_SERVICE_CONF
    162       fprintf(stderr,"(ENDNESTED - %d) \n",__LINE__);
    163       fflush(stderr);
    164 #endif
    165       nested_level-=1;
    166       if(nested_level==0){
    167         wait_nested=false;
    168       }
     165    fprintf(stderr,"(ENDNESTED - %d) \n",__LINE__);
     166    fflush(stderr);
     167#endif
     168    nested_level-=1;
     169    if(nested_level==0){
     170      wait_nested=false;
     171    }
    169172  }
    170173
     
    229232    }
    230233    else
    231       if(strncasecmp($2,"MetaData",8)==0){
    232         previous_data=current_data;
    233         current_data=3;
    234         if(current_element!=NULL){
    235 #ifdef DEBUG_SERVICE_CONF
    236           fprintf(stderr,"add current_content to current_element->content\n");
    237           fprintf(stderr,"LINE %d",__LINE__);
    238 #endif
    239           addMapToMap(&current_element->content,current_content);
    240           freeMap(&current_content);
    241           free(current_content);
    242           if(previous_data==1 || previous_data==2)
    243             wait_metadata=true;
    244           else
    245             wait_mainmetadata=true;
    246         }
    247         else{
    248           if(previous_data==1 || previous_data==2)
    249             wait_metadata=true;
    250           else
    251             wait_mainmetadata=true;
     234      if(strncasecmp($2,"MetaData",8)==0 ||
     235         strncasecmp($2,"AdditionalParameters",8)==0){
     236        if(strncasecmp($2,"AdditionalParameters",8)==0){
     237          previous_data=current_data;
     238          current_data=4;
     239          if(current_element!=NULL){
     240#ifdef DEBUG_SERVICE_CONF
     241            fprintf(stderr,"add current_content to current_element->content\n");
     242            fprintf(stderr,"LINE %d",__LINE__);
     243#endif
     244            if(wait_mainmetadata)
     245              addMapToMap(&my_service->metadata,current_content);
     246            else
     247              if(wait_metadata)
     248                addMapToMap(&current_element->metadata,current_content);
     249              else
     250                addMapToMap(&current_element->content,current_content);         
     251            freeMap(&current_content);
     252            free(current_content);
     253            if(previous_data==1 || previous_data==2)
     254              wait_ap=true;
     255            else
     256              wait_mainap=true;
     257          }
     258          else{
     259            if(previous_data==1 || previous_data==2)
     260              wait_ap=true;
     261            else
     262              wait_mainap=true;
     263          }
     264        }else{
     265          previous_data=current_data;
     266          current_data=3;
     267          if(current_element!=NULL){
     268#ifdef DEBUG_SERVICE_CONF
     269            fprintf(stderr,"add current_content to current_element->content\n");
     270            fprintf(stderr,"LINE %d",__LINE__);
     271#endif
     272            addMapToMap(&current_element->content,current_content);
     273            freeMap(&current_content);
     274            free(current_content);
     275            if(previous_data==1 || previous_data==2)
     276              wait_metadata=true;
     277            else
     278              wait_mainmetadata=true;
     279          }
     280          else{
     281            if(previous_data==1 || previous_data==2)
     282              wait_metadata=true;
     283            else
     284              wait_mainmetadata=true;
     285          }
    252286        }
    253287        current_content=NULL;
     
    425459  if(strcmp($3,"DataOutputs")==0){
    426460    current_data=2;
     461  } 
     462  if(strcmp($3,"AdditionalParameters")==0){
     463    if(current_content!=NULL){
     464#ifdef DEBUG_SERVICE_CONF
     465      fprintf(stderr,"add current_content to current_element->content\n");
     466      fprintf(stderr,"LINE %d",__LINE__);
     467#endif
     468      if(wait_ap){
     469        current_element->additional_parameters=NULL;
     470        addMapToMap(&current_element->additional_parameters,current_content);
     471        current_element->next=NULL;
     472        current_element->defaults=NULL;
     473        current_element->supported=NULL;
     474        current_element->child=NULL;
     475      }else{
     476        if(wait_mainap){
     477          addMapToMap(&my_service->additional_parameters,current_content);
     478        }
     479      }
     480
     481      freeMap(&current_content);
     482      free(current_content);
     483      current_content=NULL;
     484    }
     485    current_data=previous_data;
     486    wait_mainap=false;
     487    wait_ap=false;
    427488  }
    428489  if(strcmp($3,"MetaData")==0){
     
    866927  wait_mainmetadata=false;
    867928  wait_metadata=false;
     929  wait_mainap=false;
     930  wait_ap=false;
    868931  wait_inputs=false;
    869932  wait_defaults=false;
  • trunk/zoo-project/zoo-kernel/service_internal.c

    r889 r917  
    22 * Author : Gérald FENOY
    33 *
    4  * Copyright (c) 2009-2015 GeoLabs SARL
     4 * Copyright (c) 2009-2018 GeoLabs SARL
    55 *
    66 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    3131#include "service_internal.h"
    3232
    33 #ifndef TRUE
    34 #define TRUE 1
    35 #endif
    36 #ifndef FALSE
    37 #define FALSE -1
    38 #endif
    39 
     33#ifdef WIN32
     34// ref. https://docs.microsoft.com/en-us/windows/desktop/fileio/locking-and-unlocking-byte-ranges-in-files
     35__inline int fcntl(int fd, int cmd, ...)
     36{
     37  va_list a;
     38  va_start(a, cmd);
     39  switch(cmd)
     40    {
     41    case F_SETLK:
     42      {
     43        HANDLE h = (HANDLE)_get_osfhandle(fd);
     44        struct flock* l= va_arg(a, struct flock*);
     45        OVERLAPPED sOverlapped;
     46        sOverlapped.Offset = 0;
     47        sOverlapped.OffsetHigh = 0;
     48        switch(l->l_type)
     49          {
     50          case F_RDLCK:
     51            {
     52              if (!LockFileEx(h, LOCKFILE_FAIL_IMMEDIATELY, 0, l->l_len, 0, &sOverlapped))
     53                {
     54                  _set_errno(GetLastError() == ERROR_LOCK_VIOLATION ? EAGAIN : EBADF);
     55                  return -1;
     56                }
     57            }
     58            break;
     59          case F_WRLCK:
     60            {
     61              if (!LockFileEx(h, LOCKFILE_FAIL_IMMEDIATELY|LOCKFILE_EXCLUSIVE_LOCK, 0, l->l_len, 0, &sOverlapped))
     62                {
     63                  _set_errno(GetLastError() == ERROR_LOCK_VIOLATION ? EAGAIN : EBADF);
     64                  return -1;
     65                }
     66            }
     67            break;
     68          case F_UNLCK:
     69            {
     70              UnlockFileEx(h, 0, l->l_len, 0, &sOverlapped);
     71            }
     72            break;
     73          default:
     74            _set_errno(ENOTSUP);
     75            return -1;
     76          }
     77      }
     78      break;
     79    default:
     80      _set_errno(ENOTSUP);
     81      return -1;
     82    }
     83  return 0;
     84}
     85#endif
    4086#define ERROR_MSG_MAX_LENGTH 1024
     87
     88/**
     89 * Lock a file for read, write and upload.
     90 * @param conf the main configuration maps
     91 * @param filename the file to lock
     92 * @param mode define access: 'r' for read, 'w' for write
     93 * @return a new zooLock structure on sucess, NULL on failure
     94 */
     95struct zooLock* lockFile(maps* conf,const char* filename,const char mode){
     96  struct stat f_status;
     97  int itn=0;
     98  int s;
     99  struct zooLock* myLock=(struct zooLock*)malloc(sizeof(struct flock)+sizeof(FILE*)+sizeof(char*));
     100  int len=6;
     101  char *myTemplate="%s.lock";
     102  int res=-1;
     103 retryLockFile:
     104  myLock->filename=(char*)malloc((strlen(filename)+len)*sizeof(char));
     105  sprintf(myLock->filename,myTemplate,filename);
     106  s=stat(myLock->filename, &f_status);
     107  if(s==0 && mode!='r'){
     108    if(itn<ZOO_LOCK_MAX_RETRY){
     109      itn++;
     110#ifdef DEBUG
     111      fprintf(stderr,"(%d) Wait for write lock on %s, tried %d times (sleep) ... \n",zGetpid(),myLock->filename,itn);
     112      fflush(stderr);
     113#endif
     114      zSleep(5);
     115      free(myLock->filename);
     116      goto retryLockFile;
     117    }else{
     118      free(myLock->filename);
     119      free(myLock);
     120      return NULL;
     121    }
     122  }else{
     123    char local_mode[3];
     124    memset(local_mode,0,3);
     125    if(mode=='w')
     126      sprintf(local_mode,"%c+",mode);
     127    else
     128      sprintf(local_mode,"%c",mode);
     129    myLock->lockfile=fopen(myLock->filename,local_mode);
     130    char tmp[512];
     131    sprintf(tmp,"%d",zGetpid());
     132    if(myLock->lockfile==NULL){
     133      myLock->lockfile=fopen(myLock->filename,"w+");
     134      fwrite(tmp,sizeof(char),strlen(tmp),myLock->lockfile);
     135      fflush(myLock->lockfile);
     136      fclose(myLock->lockfile);
     137      myLock->lockfile=fopen(myLock->filename,local_mode);
     138    }/*else
     139       fprintf(stderr,"%s %d %d\n",__FILE__,__LINE__,(myLock->lockfile==NULL));*/
     140    if(mode!='r'){
     141      fwrite(tmp,sizeof(char),strlen(tmp),myLock->lockfile);
     142      fflush(myLock->lockfile);
     143    }
     144    int cnt=0;
     145    if(mode=='r'){
     146      myLock->lock.l_type = F_RDLCK;
     147    }else
     148      myLock->lock.l_type = F_WRLCK;
     149    myLock->lock.l_whence = 0;
     150    myLock->lock.l_start = 0;
     151    myLock->lock.l_len = strlen(tmp)*sizeof(char);
     152    while (true) {
     153      if((res=fcntl(fileno(myLock->lockfile), F_SETLK, &(myLock->lock)))==-1 &&
     154         (errno==EAGAIN || errno==EACCES)){
     155          if(cnt >= ZOO_LOCK_MAX_RETRY){
     156            char message[51];     
     157            sprintf(message,"Unable to get the lock after %d attempts.\n",cnt);
     158            setMapInMaps(conf,"lenv","message",message);
     159            fclose(myLock->lockfile);
     160            free(myLock->filename);
     161            free(myLock);
     162            return NULL;
     163          }
     164#ifdef DEBUG
     165          fprintf(stderr,"(%d) Wait for lock on  %s, tried %d times ... \n",zGetpid(),myLock->filename,cnt);
     166          fflush(stderr);
     167#endif
     168          zSleep(1);
     169          cnt++;
     170        }else
     171           break;
     172    }
     173    if(res<0){
     174      char *tmp;
     175      if(errno==EBADF)
     176        tmp="Either: the filedes argument is invalid; you requested a read lock but the filedes is not open for read access; or, you requested a write lock but the filedes is not open for write access.";
     177      else
     178        if(errno==EINVAL)
     179          tmp="Either the lockp argument doesn’t specify valid lock information, or the file associated with filedes doesn’t support locks.";
     180        else
     181          tmp="The system has run out of file lock resources; there are already too many file locks in place.";
     182#ifdef DEBUG
     183      fprintf(stderr,"Unable to get the lock on %s due to the following error: %s\n",myLock->filename,tmp);
     184#endif
     185      return NULL;
     186    }
     187    return myLock;
     188  }
     189}
     190
     191/**
     192 * Remove a lock.
     193 * @param conf the main configuration maps
     194 * @param s the zooLock structure
     195 * @return 0 on success, -1 on failure.
     196 */
     197int unlockFile(maps* conf,struct zooLock* s){
     198  int res=-1;
     199  if(s!=NULL){
     200    s->lock.l_type = F_UNLCK;
     201    res=fcntl(fileno(s->lockfile), F_SETLK, &s->lock);
     202    if(res==-1)
     203      return res;
     204    fclose(s->lockfile);
     205#ifndef WIN32
     206    // Check if there is any process locking a file and delete the lock if not.
     207    s->lock.l_type = F_WRLCK;
     208    if(fcntl(fileno(s->lockfile), F_GETLK, &s->lock)!=-1 && s->lock.l_type == F_UNLCK){
     209#endif
     210      zUnlink(s->filename);
     211#ifndef WIN32
     212    }
     213#endif
     214    free(s->filename);
     215    free(s);
     216  }
     217  return res;
     218}
     219
    41220#ifndef RELY_ON_DB
    42 #include <dirent.h>
     221#include "dirent.h"
    43222
    44223/**
     
    148327
    149328    //FILE* f0 = fopen (fileName, "r");
    150         // knut: open file in binary mode to avoid conversion of line endings (yielding extra bytes) on Windows platforms
    151         FILE* f0 = fopen(fileName, "rb");
     329    // knut: open file in binary mode to avoid conversion of line endings (yielding extra bytes) on Windows platforms
     330    FILE* f0 = fopen(fileName, "rb");
    152331    if(f0!=NULL){
    153332      fseek (f0, 0, SEEK_END);
     
    162341        free(stat);
    163342      }
    164 
    165343      return tmps1;
    166344    }
     
    250428                     * sizeof (char));
    251429  sprintf (fbkpid, "%s/%s.status", r_inputs->value, usid->value);
    252   unlink(fbkpid);
     430  zUnlink(fbkpid);
    253431  free(fbkpid);
    254432}
     
    510688            }
    511689        }
     690        setMapInMaps(conf,"lenv","semaphore","Created");
    512691    } else if (errno == EEXIST) { /* someone else got it first */
    513692        int ready = 0;
     
    529708              fprintf(stderr,"Retry to access the semaphore later ...\n");
    530709#endif
    531               zSleep(1);
     710              zSleep(1000);
    532711            }
    533712        }
     
    540719          return -1;
    541720        }
     721        setMapInMaps(conf,"lenv","semaphore","Acquired");
    542722    } else {
    543723        return sem_id; /* error, check errno */
     
    739919}
    740920
     921/**
     922 * Check if file exists in specified folder
     923 *
     924 * @param dir the folder in which to search for file
     925 * @param name the name of the file (not full path)
     926 * @return a character string with the full path [dir/name], or NULL if the file does not exist
     927 *
     928 * @attention Caller is responsible for applying free() to the returned pointer
     929 */
     930char* file_exists(const char* dir, const char* name) {
     931        const char* d = (dir != NULL ? dir : ".");
     932        if (name != NULL) {
     933                size_t length = strlen(d) + strlen(name) + 2; // including file separator and \0 character
     934                char* path = (char*)calloc(length, sizeof(char));
     935                snprintf(path, length, "%s/%s", d, name);
     936
     937                struct stat buffer;
     938                if (stat(path, &buffer) != 0) {
     939                        free(path);
     940                        path = NULL;
     941                }
     942                return path;
     943        }
     944        else {
     945                return NULL;
     946        }
     947}
  • trunk/zoo-project/zoo-kernel/service_internal.h

    r680 r917  
    6363 * Number of time the ZOO-Kernel will try to acquire lock
    6464 */
    65 #define ZOO_LOCK_MAX_RETRY 10
     65#define ZOO_LOCK_MAX_RETRY 180
    6666
    6767#include <sys/stat.h>
    6868#include <sys/types.h>
    69 #include "cgic.h"
    7069#ifndef WIN32
    7170#include <sys/ipc.h>
     
    8281#endif
    8382#ifndef WIN32
    84 #include <xlocale.h>
     83#include <locale.h>
    8584#endif
    8685
     86#include <fcntl.h>
     87 
    8788#include "service.h"
    8889
     
    9495#endif
    9596
     97#ifdef WIN32
     98// fcntl flock definitions
     99#define F_SETLK  8   // Non-Blocking set or clear a lock
     100#define F_SETLKW 9   // Blocking set or clear a lock
     101#define F_GETLK 10
     102#define F_RDLCK  1   // read lock
     103#define F_WRLCK  2   // write lock
     104#define F_UNLCK  3   // remove lock
     105struct flock {
     106    short l_type;   // F_RDLCK, F_WRLCK, or F_UNLCK
     107    short l_whence; // flag to choose starting offset, must be SEEK_SET
     108    long  l_start;  // relative offset, in bytes, must be 0
     109    long  l_len;    // length, in bytes; 0 means lock to EOF, must be 0
     110    short l_pid;    // unused (returned with the unsupported F_GETLK)
     111    short l_xxx;    // reserved for future use
     112};
     113#endif
     114
     115/**
     116 * The lock structure used by the ZOO-Kernel to ensure atomicity of operations
     117 *
     118 */
     119typedef struct zooLock{
     120  struct flock lock; //!< The lock
     121  FILE* lockfile;    //!< The pointer to the lock file
     122  char* filename;    //!< The filename to lock
     123} zooLock;
     124
     125static zooLock** zoo_file_locks=NULL;
     126static int zoo_file_locks_cnt=0;
     127
    96128#ifdef __cplusplus
    97129extern "C" {
    98130#endif
    99131
     132 
    100133  ZOO_DLL_EXPORT char *readVSIFile(maps*,const char*);
    101134  ZOO_DLL_EXPORT int  setOutputValue( maps*, const char*, char*, size_t);
    102135  ZOO_DLL_EXPORT char* getInputValue( maps*,const char*,size_t*);
     136
     137  ZOO_DLL_EXPORT struct zooLock* lockFile(maps*,const char*,const char);
     138  ZOO_DLL_EXPORT int unlockFile(maps*,struct zooLock*);
    103139
    104140  ZOO_DLL_EXPORT void unhandleStatus(maps*);
     
    125161  ZOO_DLL_EXPORT int unlockShm(semid);
    126162
     163  ZOO_DLL_EXPORT char* file_exists(const char* dir, const char* name);
     164
    127165#ifdef __cplusplus
    128166}
  • trunk/zoo-project/zoo-kernel/service_internal_java.c

    r790 r917  
    208208#endif
    209209#ifdef JAVA7
    210   cls_gr = (*env)NewGlobalRef(cls);
     210  cls_gr = (*env).NewGlobalRef(cls);
    211211#else
    212212  cls_gr = (*env)->NewGlobalRef(env, cls);
     
    215215  if (cls != NULL) {
    216216#ifdef JAVA7
    217 @    (*env).ExceptionClear();
     217    (*env).ExceptionClear();
    218218    pmid=(*env).GetStaticMethodID(cls, s->name, "(Ljava/util/HashMap;Ljava/util/HashMap;Ljava/util/HashMap;)I");
    219219#else
     
    284284  }
    285285#ifdef JAVA7
    286       (*jvm).DestroyJavaVM();
     286  (*jvm).DestroyJavaVM();
    287287#else
    288288  (*jvm)->DestroyJavaVM(jvm);
     
    427427#endif
    428428      map* sizeV=getMap(tmp1,"size");
     429      map* useFile=getMap(tmp1,"use_file");
     430      map* cacheFile=getMap(tmp1,"cache_file");
    429431      map* isArray=getMap(tmp1,"isArray");
    430432      map* alen=getMap(tmp1,"length");
     
    432434        if(strcmp(tmp1->name,"value")==0){
    433435          if(isArray==NULL){
    434             if(sizeV!=NULL && strcmp(tmp1->name,"value")==0){
     436            if(sizeV!=NULL && strcmp(tmp1->name,"value")==0 && useFile==NULL){
    435437#ifdef JAVA7
    436438              jbyteArray tmpData=(*env).NewByteArray(atoi(sizeV->value));
    437439              (*env).SetByteArrayRegion(tmpData,0,atoi(sizeV->value),(const jbyte *)tmp1->value);
    438               (*env).CallObjectMethod(env,scObject1, put_mid, (*env).NewStringUTF(env,tmp1->name), tmpData);
     440              (*env).CallObjectMethod(scObject1, put_mid, (*env).NewStringUTF(tmp1->name), tmpData);
    439441#else
    440442              jbyteArray tmpData=(*env)->NewByteArray(env,atoi(sizeV->value));
     
    448450              (*env)->CallObjectMethod(env,scObject1, put_mid, (*env)->NewStringUTF(env,tmp1->name), (*env)->NewStringUTF(env,tmp1->value));
    449451#endif
     452              if(useFile!=NULL)
     453#ifdef JAVA7
     454                (*env).CallObjectMethod(scObject1, put_mid, (*env).NewStringUTF("cache_file"), (*env).NewStringUTF(cacheFile->value));
     455#else
     456                (*env)->CallObjectMethod(env,scObject1, put_mid, (*env)->NewStringUTF(env,"cache_file"), (*env)->NewStringUTF(env,cacheFile->value));
     457#endif
     458             
    450459          }
    451460          else{
     
    455464            jclass scArrayListClass,scArrayList_class;
    456465            jmethodID scArrayList_constructor;
    457             jobject scObject2;
     466            jobject scObject2,scObject3;
    458467#ifdef JAVA7
    459468            scArrayListClass = (*env).FindClass("java/util/ArrayList");
     
    462471            jmethodID add_mid = 0;
    463472            scObject2 = (*env).NewObject(scArrayList_class, scArrayList_constructor);
     473            scObject3 = (*env).NewObject(scArrayList_class, scArrayList_constructor);
    464474
    465475            add_mid = (*env).GetMethodID(scArrayListClass,
     
    471481            jmethodID add_mid = 0;
    472482            scObject2 = (*env)->NewObject(env, scArrayList_class, scArrayList_constructor);
     483            scObject3 = (*env)->NewObject(env, scArrayList_class, scArrayList_constructor);
    473484
    474485            add_mid = (*env)->GetMethodID(env,scArrayListClass,
     
    478489           
    479490            for(i=0;i<alen1;i++){
     491              map* cMap=getMapArray(tmp->content,"cache_file",i);
     492              map* uMap=getMapArray(tmp->content,"use_file",i);
    480493              map* vMap=getMapArray(tmp->content,"value",i);
    481494              map* sMap=getMapArray(tmp->content,"size",i);
    482495              map* mMap=getMapArray(tmp->content,tmap->value,i);
    483496             
    484               if(sMap!=NULL && vMap!=NULL && strncmp(vMap->name,"value",5)==0){
     497              if(sMap!=NULL && vMap!=NULL && strncmp(vMap->name,"value",5)==0 && uMap==NULL){
    485498#ifdef JAVA7
    486499                jbyteArray tmpData=(*env).NewByteArray(atoi(sMap->value));
     
    501514#endif
    502515              }
    503              
     516
     517              if(cMap!=NULL){
     518#ifdef JAVA7
     519                jobject tmpData=(*env).NewStringUTF(cMap->value);
     520                (*env).CallObjectMethod(scObject3, add_mid, tmpData);
     521#else
     522                jobject tmpData=(*env)->NewStringUTF(env,cMap->value);
     523                (*env)->CallObjectMethod(env,scObject3, add_mid, tmpData);
     524#endif
     525
     526              }
    504527            }
    505528
    506529#ifdef JAVA7
    507530            (*env).CallObjectMethod(scObject1, put_mid, (*env).NewStringUTF(tmp1->name), scObject2);
     531            (*env).CallObjectMethod(scObject1, put_mid, (*env).NewStringUTF("cache_file"), scObject3);
    508532#else       
    509533            (*env)->CallObjectMethod(env,scObject1, put_mid, (*env)->NewStringUTF(env,tmp1->name), scObject2);
     534            (*env)->CallObjectMethod(env,scObject1, put_mid, (*env)->NewStringUTF(env,"cache_file"), scObject3);
    510535#endif
    511536
  • trunk/zoo-project/zoo-kernel/service_internal_js.c

    r828 r917  
    157157    return 1;
    158158  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
     159    return 1; 
     160  if (!JS_DefineFunction(cx, global, "sleep", JSSleep, 1, 0))
    159161    return 1; 
    160162  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
     
    901903  char* tmpValue;
    902904  size_t dwRead;
     905  maps *tmpConf=createMaps("main");
     906  tmpConf->content=createMap("memory","load");
    903907  JS_MaybeGC(cx);
    904908  hInternet=InternetOpen("ZooWPSClient\0",
     
    929933#endif
    930934    InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
    931                     INTERNET_FLAG_NO_CACHE_WRITE,0);   
     935                    INTERNET_FLAG_NO_CACHE_WRITE,0,tmpConf);   
    932936    processDownloads(&hInternet);
    933937    free(body);
     
    940944        }
    941945        InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
    942                         INTERNET_FLAG_NO_CACHE_WRITE,0);
     946                        INTERNET_FLAG_NO_CACHE_WRITE,0,tmpConf);
    943947        processDownloads(&hInternet);
    944948      }else{
    945949        char *body=JSValToChar(cx,&argv[2]);
    946950        InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
    947                         INTERNET_FLAG_NO_CACHE_WRITE,0);
     951                        INTERNET_FLAG_NO_CACHE_WRITE,0,tmpConf);
    948952        processDownloads(&hInternet);
    949953        free(body);
     
    951955    }else{
    952956      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
    953                       INTERNET_FLAG_NO_CACHE_WRITE,0);
     957                      INTERNET_FLAG_NO_CACHE_WRITE,0,tmpConf);
    954958      processDownloads(&hInternet);
    955959    }
     
    972976  if(argc>=2)
    973977    free(method);
     978  freeMaps(&tmpConf);
     979  free(tmpConf);
    974980  InternetCloseHandle(&hInternet);
    975981  JS_MaybeGC(cx);
     
    10231029}
    10241030
     1031/**
     1032 * The function used as sleep from the JavaScript environment
     1033 * (ZOO-API).
     1034 *
     1035 * @param cx the JavaScript context
     1036 * @param argc the number of parameters
     1037 * @param argv1 the parameter values
     1038 * @return true
     1039 */
     1040JSBool
     1041JSSleep(JSContext *cx, uintN argc, jsval *argv1)
     1042{
     1043  jsval *argv = JS_ARGV(cx,argv1);
     1044  JS_MaybeGC(cx);
     1045  int isleep=0;
     1046  if(JS_ValueToInt32(cx,argv[0],&isleep)==JS_TRUE){
     1047    zSleep(isleep);
     1048  }
     1049  JS_MaybeGC(cx);
     1050  return JS_TRUE;
     1051}
     1052
  • trunk/zoo-project/zoo-kernel/service_internal_js.h

    r580 r917  
    4949  JSBool JSRequest(JSContext*, uintN, jsval*);
    5050  JSBool JSUpdateStatus(JSContext*,uintN,jsval *);
     51  JSBool JSSleep(JSContext*,uintN,jsval *);
    5152
    5253  void reportError(JSContext *cx, const char *message, JSErrorReport *report);
  • trunk/zoo-project/zoo-kernel/service_internal_mono.c

    r794 r917  
    3030#include "response_print.h"
    3131
     32MonoClass *iclasses[4];
     33MonoMethod *imethods[10];
     34
    3235/**
    3336 * Load a Mono dll then run the static public method corresponding to the
     
    6972    mono_config_parse(NULL);
    7073
    71   MonoDomain* monoDomain = mono_jit_init_version("ZOO_Embedded_Domain",
    72                                                  "v4.0.30319");
    73 
    74   map* cwdMap=getMapFromMaps(*main_conf,"main","servicePath");
    75   if(cwdMap==NULL)
    76     cwdMap=getMapFromMaps(*main_conf,"lenv","cwd");
    77  
    78   char *zooAssembly=(char*)malloc((strlen(cwdMap->value)+11)*sizeof(char));
    79   sprintf(zooAssembly,"%s/ZMaps.dll",cwdMap->value);
    80   assembly = mono_domain_assembly_open(monoDomain,zooAssembly);
    81   if(assembly==NULL){
    82     setMapInMaps(*main_conf,"lenv","message",_("The ZMaps.dll assembly cannot be found!"));
    83     return 4;
    84   }
    85   mono_add_internal_call ("ZOO_API::Translate", MonoTranslate);
    86   mono_add_internal_call ("ZOO_API::UpdateStatus", MonoUpdateStatus);
    87 
     74  MonoDomain* monoDomain;
     75  map* mono;
     76  if (hasvalue(*main_conf, "mono", "version", &mono)) {   
     77          monoDomain = mono_jit_init_version("ZOO_Embedded_Domain", mono->value);
     78  }
     79  else {         
     80          monoDomain = mono_jit_init("ZOO_Embedded_Domain"); // use default framework version
     81  }
     82
     83  //MonoDomain* monoDomain = mono_jit_init_version("ZOO_Embedded_Domain", "v4.0.30319");
     84  //MonoDomain* monoDomain = mono_jit_init("ZOO_Embedded_Domain"); 
     85
     86  char* ZMapsLib = "ZMaps.dll";
     87  char *zooAssembly = NULL;
     88 
     89  map* config = NULL, *basedir = NULL;
     90  if (hasvalue(*main_conf, "mono", "configdir", &basedir) && // knut: rename to e.g. "base_dir"?
     91          hasvalue(*main_conf, "mono", "configfile", &config)) {         
     92          mono_domain_set_config(monoDomain, basedir->value, config->value);
     93          zooAssembly = file_exists(basedir->value, ZMapsLib);
     94  }
     95  else {         
     96          mono_domain_set_config(monoDomain, "./", "");
     97  }   
     98
     99  map* cwdMap;
     100  if (! hasvalue(*main_conf, "main", "servicePath", &cwdMap) &&
     101          ! hasvalue(*main_conf, "main", "libPath", &cwdMap) ) {
     102          cwdMap = getMapFromMaps(*main_conf, "lenv", "cwd");
     103  } 
     104
     105  if (zooAssembly != NULL || (zooAssembly = file_exists(cwdMap->value, ZMapsLib)) != NULL) {
     106          assembly = mono_domain_assembly_open(monoDomain, zooAssembly);
     107  }
     108  else {
     109          // try to load from default locations (GAC?)
     110          assembly = mono_domain_assembly_open(monoDomain, ZMapsLib);
     111  } 
     112  free(zooAssembly);
     113
     114  if (assembly == NULL) {
     115          setMapInMaps(*main_conf, "lenv", "message", _("The ZMaps.dll assembly cannot be found!"));
     116          return 4;
     117  }
     118
     119  mono_add_internal_call ("ZOO_API::Translate", MonoTranslate);   
     120  mono_add_internal_call("ZOO_API::UpdateStatus", MonoUpdateStatus);
     121 
    88122  monoImage = mono_assembly_get_image(assembly);
    89123  MonoClass *KeysList = mono_class_from_name(monoImage, "ZooGenerics", "KeysList");
     
    104138  MonoClass *classes[3]={_ZMapsClass,ZMapsClass,ZMapClass};
    105139  MonoMethod *methods[5]={ZMapsAdd,_ZMapsSetContent,_ZMapsSetChild,ZMapAdd,ZMapDisplay};
    106 
     140 
    107141  MonoMethod *ZMapsGetKeys = mono_class_get_method_from_name(ZMapsClass, "getKeys", 0);
     142 
    108143  MonoMethod *ZMapsGetKeysCount = mono_class_get_method_from_name(ZMapsClass, "getKeysCount", 0);
    109144  MonoMethod *ZMapsGetKey = mono_class_get_method_from_name(ZMapsClass, "getKey", 1);
     
    116151  MonoClass *oclasses[4]={_ZMapsClass,ZMapsClass,ZMapClass,KeysList};
    117152  MonoMethod *omethods[10]={ZMapsGetMaps,ZMapsGetKeysCount,ZMapsGetKey,ZMapGetMap,ZMapGetKeysCount,ZMapGetKey,_ZMapsGetContent,_ZMapsGetChild,ZMapGetSize,ZMapGetMapAsBytes};
    118 
     153 
    119154  for(int i=0;i<4;i++){
    120155    iclasses[i]=oclasses[i];
     
    131166
    132167  MonoObject * out=ZMapsFromMaps(monoDomain,classes,methods,&exc,outputs);
    133 
     168 
    134169  args [0] = main;
    135170  args [1] = in;
    136171  args [2] = out;
    137172
    138   tmp=getMap(s->content,"serviceProvider");
    139   char *sName=(char*)malloc((strlen(tmp->value)+strlen(cwdMap->value)+2)*sizeof(char));
    140   sprintf(sName,"%s/%s",cwdMap->value,tmp->value);
    141   MonoAssembly* serviceAssembly = mono_domain_assembly_open(monoDomain,sName);
     173  char* sName = NULL;
     174  MonoAssembly* serviceAssembly = NULL;
     175 
     176  tmp = getMap(s->content, "serviceProvider"); 
     177  char* test = file_exists(NULL, "log.txt");
     178  if ( (sName = file_exists(cwdMap->value, tmp->value)) != NULL ||
     179           (sName = file_exists(".", tmp->value)) != NULL ||  // in case servicePath is defined but serviceProvider is in working directory
     180           (basedir != NULL && (sName = file_exists(basedir->value, tmp->value)) != NULL) ) {
     181
     182           serviceAssembly = mono_domain_assembly_open(monoDomain, sName);
     183  }
     184  else {
     185          // try to open from default locations   
     186          serviceAssembly = mono_domain_assembly_open(monoDomain, tmp->value);
     187  }
     188  free(sName);
     189
     190  //char *sName=(char*)malloc((strlen(tmp->value)+strlen(cwdMap->value)+2)*sizeof(char));
     191  //sprintf(sName,"%s/%s",cwdMap->value,tmp->value);
     192  //MonoAssembly* serviceAssembly = mono_domain_assembly_open(monoDomain,sName);
     193 
    142194  if(serviceAssembly==NULL){
    143195    char *msg=(char*)malloc((strlen(_("Your service assembly: %s cannot be found!"))+strlen(tmp->value)+1)*sizeof(char));
     
    147199    return 4;
    148200  }
    149 
     201 
    150202  MonoImage* serviceImage = mono_assembly_get_image(serviceAssembly);
    151203
    152204  map* tmp1=getMap(s->content,"serviceNameSpace");
     205 
    153206  tmp=getMap(s->content,"serviceClass");
    154207  MonoClass *serviceClass = mono_class_from_name(serviceImage, tmp1->value, tmp->value);
     
    160213    return 4;
    161214  }
     215 
    162216  MonoMethod *serviceFunction = mono_class_get_method_from_name(serviceClass, s->name, 3);
    163217  if(serviceFunction==NULL){
     
    168222    return 4;
    169223  }
     224 
    170225  MonoObject *exception=NULL;
    171226  MonoObject *result = mono_runtime_invoke(serviceFunction,NULL,args,&exception);
     227 
     228  if (exception != NULL) { // knut: add exception handling
     229          MonoString* pMsg = mono_object_to_string(exception, NULL);     
     230          setErrorMessage(*main_conf, s->name, NoApplicableCode, mono_string_to_utf8(pMsg));
     231          return 4;
     232  }
     233
    172234  res=*(int*)mono_object_unbox (result);
     235 
    173236  if(res==3){
    174237    freeMaps(&outputs);
    175238    free(outputs);
    176     outputs=mapsFromZMaps(monoDomain,oclasses,omethods,args[2]);
     239    outputs=mapsFromZMaps(monoDomain,oclasses,omethods,(MonoObject*)args[2]);
    177240    *real_outputs=outputs;
    178241  }
     242 
    179243  freeMaps(&m);
    180244  free(m);
    181   m=mapsFromZMaps(monoDomain,oclasses,omethods,args[0]);
     245  m=mapsFromZMaps(monoDomain,oclasses,omethods,(MonoObject*)args[0]);
    182246  *main_conf=m;
    183   mono_jit_cleanup (monoDomain);
     247  mono_jit_cleanup (monoDomain); 
    184248  return res;
    185249}
     
    288352      values[0]=&i;
    289353      exc=NULL;
    290       MonoObject *okey = (MonoString*) mono_runtime_invoke(methods[2],m,values,&exc);
     354      MonoString *okey = (MonoString*) mono_runtime_invoke(methods[2],m,values,&exc);
    291355      char* key = mono_string_to_utf8(okey);
    292356      maps* tmp=createMaps(key);
    293357      values[0]=mono_string_new (domain, key);
    294       MonoObject *content_ZMaps = (MonoString*) mono_runtime_invoke(methods[0],m,values,&exc);
    295       MonoObject *content = mono_runtime_invoke(methods[6],content_ZMaps,NULL,&exc);
     358      MonoString *content_ZMaps = (MonoString*) mono_runtime_invoke(methods[0],m,values,&exc);
     359      MonoObject *content = mono_runtime_invoke(methods[6],(MonoObject*)content_ZMaps,NULL,&exc);
    296360      tmp->content=mapFromZMap(domain,classes,methods,content);
    297361      MonoObject *childs = mono_runtime_invoke(methods[7],content_ZMaps,NULL,&exc);
     
    329393      values[0]=&i;
    330394      exc=NULL;
    331       MonoObject *okey = (MonoString*) mono_runtime_invoke(methods[5],m,values,&exc);
     395      MonoString *okey = (MonoString*) mono_runtime_invoke(methods[5],m,values,&exc);
    332396      char* key = mono_string_to_utf8(okey);
    333397      values[0]=mono_string_new (domain, key);
    334398      exc=NULL;
    335       MonoObject *ovalue = (MonoString*) mono_runtime_invoke(methods[3],m,values,&exc);
     399      MonoString *ovalue = (MonoString*) mono_runtime_invoke(methods[3],m,values,&exc);
    336400      char* value = mono_string_to_utf8(ovalue);
    337401      if(res==NULL)
     
    350414 */
    351415static MonoString* MonoTranslate(MonoString *str){
    352   return mono_string_new (mono_domain_get(), mono_string_to_utf8(_(str)));
     416  return mono_string_new (mono_domain_get(), _(mono_string_to_utf8(str)));
    353417}
    354418
     
    360424 * @return the translated string
    361425 */
    362 static void MonoUpdateStatus(MonoObject* obj,MonoString *str,int* p){
    363   MonoDomain* domain = mono_object_get_domain (obj);
    364   maps *confMaps=mapsFromZMaps(domain,iclasses,imethods,obj);
    365   setMapInMaps(confMaps,"lenv","message",mono_string_to_utf8(str));
    366   int tmp=p;
    367   if (p < 0 || p > 100){
    368     tmp=-1;
    369   }
    370   char tmpStatus[5];
    371   snprintf(tmpStatus, 4, "%d", tmp);
    372   setMapInMaps(confMaps,"lenv","status",(char*)tmpStatus);
    373   _updateStatus(confMaps);
    374   freeMaps(&confMaps);
    375   free(confMaps);
    376   return;
    377 }
     426static void MonoUpdateStatus(MonoObject* obj, MonoString *str, int p) {
     427        MonoDomain* domain = mono_object_get_domain(obj);       
     428        maps *confMaps = mapsFromZMaps(domain, iclasses, imethods, obj);       
     429        setMapInMaps(confMaps, "lenv", "message", mono_string_to_utf8(str));   
     430        int tmp = p > 100 || p < 0 ? -1 : p;   
     431        char tmpStatus[5];
     432        snprintf(tmpStatus, 4, "%d", tmp);     
     433        setMapInMaps(confMaps, "lenv", "status", (char*)tmpStatus);     
     434        _updateStatus(confMaps);       
     435        freeMaps(&confMaps);   
     436        free(confMaps);
     437        return;
     438}
  • trunk/zoo-project/zoo-kernel/service_internal_mono.h

    r794 r917  
    4545  map* mapFromZMap(MonoDomain*,MonoClass**,MonoMethod**,MonoObject*);
    4646  static MonoString* MonoTranslate(MonoString*);
    47   static void MonoUpdateStatus(MonoObject*,MonoString*,int*);
    48   MonoClass *iclasses[4];
    49   MonoMethod *imethods[10];
     47  //static void MonoUpdateStatus(MonoObject*,MonoString*,int*);
     48  static void MonoUpdateStatus(MonoObject*, MonoString*, int);
     49  //MonoClass *iclasses[4]; // knut: move declarations to service_internal_mono.c
     50  //MonoMethod *imethods[10];
    5051
    5152#ifdef __cplusplus
  • trunk/zoo-project/zoo-kernel/service_internal_ms.c

    r781 r917  
    3434#include "server_internal.h"
    3535#include "response_print.h"
     36#include "caching.h"
    3637
    3738/**
     
    7677
    7778/**
     79 * Return the current publish_id value
     80 * @param elem and maps pointer on which the search occur
     81 * @return the integer value of the publish_id field, if any, 0 otherwise
     82 */
     83int getPublishedId(maps* elem){
     84  if(elem!=NULL && elem->content!=NULL){
     85    map* myIndex=getMap(elem->content,"published_id");
     86    if(myIndex!=NULL){
     87      return atoi(myIndex->value);
     88    }
     89  }
     90  return 0;
     91}
     92
     93/**
    7894 * Add width and height keys to an output maps containing the maximum width
    7995 * and height for displaying the full data extent.
     
    87103 */
    88104void setMapSize(maps* output,double minx,double miny,double maxx,double maxy){
     105  int imyIndex=getPublishedId(output);
    89106  double maxWidth=640;
    90107  double maxHeight=480;
     
    118135#endif
    119136  if(output!=NULL){
    120     addToMap(output->content,"width",sWidth);
    121     addToMap(output->content,"height",sHeight);
     137    setMapArray(output->content,"width",imyIndex,sWidth);
     138    setMapArray(output->content,"height",imyIndex,sHeight);
    122139  }
    123140}
     
    131148 */
    132149void setReferenceUrl(maps* m,maps* tmpI){
     150  int imyIndex=getPublishedId(tmpI);
     151  if(getMapArray(tmpI->content,"ref_wms_link",imyIndex)!=NULL)
     152    return;
    133153  outputMapfile(m,tmpI);
    134154  map *msUrl=getMapFromMaps(m,"main","mapserverAddress");
     
    138158    exit(-1);
    139159  }
     160  if(getMapArray(tmpI->content,"ref_wms_link",imyIndex)!=NULL)
     161    return;
     162  int finalProto=-1;
    140163  map *msOgcVersion=getMapFromMaps(m,"main","msOgcVersion");
    141164  map *dataPath=getMapFromMaps(m,"main","dataPath");
    142165  map *sid=getMapFromMaps(m,"lenv","usid");
    143   map* format=getMap(tmpI->content,"mimeType");
    144   map* rformat=getMap(tmpI->content,"requestedMimeType");
    145   map* width=getMap(tmpI->content,"width");
    146   map* height=getMap(tmpI->content,"height");
    147   map* protoMap=getMap(tmpI->content,"msOgc");
    148   map* versionMap=getMap(tmpI->content,"msOgcVersion");
    149   char options[3][5][25]={
     166  map* format=getMapArray(tmpI->content,"mimeType",imyIndex);
     167  map* rformat=getMapArray(tmpI->content,"requestedMimeType",imyIndex);
     168  map* width=getMapArray(tmpI->content,"width",imyIndex);
     169  map* height=getMapArray(tmpI->content,"height",imyIndex);
     170  map* protoMap=getMapArray(tmpI->content,"msOgc",imyIndex);
     171  map* versionMap=getMapArray(tmpI->content,"msOgcVersion",imyIndex);
     172  map* datatype=getMapArray(tmpI->content,"geodatatype",imyIndex);
     173  map* layerName=getMapArray(tmpI->content,"msLayer",imyIndex);
     174  char options[4][5][25]={
    150175    {"WMS","1.3.0","GetMap","layers=%s","wms_extent"},
    151     {"WFS","1.1.0","GetFeature","typename=%s","wcs_extent"},
    152     {"WCS","1.1.0","GetCoverage","coverage=%s","wcs_extent"}
     176    {"WFS","1.0.0","GetFeature","typename=%s","wcs_extent"},
     177    {"WCS","2.0.0","GetCoverage","coverageid=%s","wcs_extent"},
     178    {"WCS","1.0.0","GetCoverage","coverage=%s","wcs_extent"}
    153179  };
     180  map *nbElements=getMapArray(tmpI->content,"nb_features",imyIndex);
     181  if(nbElements==NULL)
     182    nbElements=getMapArray(tmpI->content,"nb_pixels",imyIndex);
     183  if(datatype==NULL || strncmp(datatype->value,"other",5)==0 || (nbElements!=NULL && atoi(nbElements->value)==0)){
     184    map* minNb=getMap(tmpI->content,"minoccurs");
     185    map* useMs=getMap(tmpI->content,"useMapserver");
     186    if((minNb==NULL || atoi(minNb->value)>=1) && useMs!=NULL && strncasecmp(useMs->value,"true",4)==0){
     187      int lIndex=0;
     188      maps* lenv=getMaps(m,"lenv");
     189      if(getMapFromMaps(m,"lenv","mapErrorNb")==NULL)
     190        setMapInMaps(m,"lenv","mapErrorNb","0");
     191      else{
     192        map* tmpV=getMapFromMaps(m,"lenv","mapErrorNb");
     193        lIndex=atoi(tmpV->value)+1;
     194        addIntToMap(lenv->content,"mapErrorNb",lIndex);
     195      }
     196      setMapInMaps(m,"lenv","mapError","true");
     197      setMapArray(lenv->content,"locator",lIndex,tmpI->name);
     198      if(nbElements==NULL)
     199        setMapArray(lenv->content,"message",lIndex,_("The ZOO-Kernel was able to retrieve the data but could not read it as geographic data."));
     200      else
     201        setMapArray(lenv->content,"message",lIndex,_("The ZOO-Kernel was able to retrieve the data but could not access any feature or pixel in te resulting file."));
     202      if(getMapFromMaps(m,"lenv","state")==NULL)
     203        errorException (m, _("Unable to find any geographic data"), "WrongInputData", tmpI->name);
     204    }
     205    return;
     206  }
    154207  int proto=0;
    155208  if(rformat==NULL){
    156     rformat=getMap(tmpI->content,"mimeType");
     209    rformat=getMapArray(tmpI->content,"mimeType",imyIndex);
    157210  }
    158211  if(strncasecmp(rformat->value,"text/xml",8)==0)
    159212    proto=1;
    160   if(strncasecmp(rformat->value,"image/tiff",10)==0)
     213  if(strncasecmp(rformat->value,"image/tiff",10)==0 ||
     214     strncasecmp(rformat->value,"image/geotiff",10)==0)
    161215    proto=2;
     216  int hasFormat=-1;
    162217  if(protoMap!=NULL){
    163     if(strncasecmp(protoMap->value,"WMS",3)==0)
     218    hasFormat=1;
     219    if(strncasecmp(protoMap->value,"WMS",3)==0){
    164220      proto=0;
     221      rformat=createMap("value","image/png");
     222    }
    165223    else{
    166       if(strncasecmp(protoMap->value,"WFS",3)==0)
     224      if(strncasecmp(protoMap->value,"WFS",3)==0){
    167225        proto=1;
    168       else
     226        rformat=createMap("value","text/xml");
     227      }
     228      else {
    169229        proto=2;
     230        rformat=createMap("value","image/tiff");
     231      }
    170232    }
    171233  }
     
    178240  }
    179241
    180   map* extent=getMap(tmpI->content,options[proto][4]);
    181   map* crs=getMap(tmpI->content,"crs");
     242
     243  map* extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
     244  map* crs=getMapArray(tmpI->content,"crs",imyIndex);
    182245  int hasCRS=1;
    183246  if(crs==NULL){
     
    189252  }
    190253  char layers[128];
    191   sprintf(layers,options[proto][3],tmpI->name);
    192 
    193   char* webService_url=(char*)malloc((strlen(msUrl->value)+strlen(format->value)+strlen(tmpI->name)+strlen(width->value)+strlen(height->value)+strlen(extent->value)+256)*sizeof(char));
     254  if(layerName==NULL)
     255    sprintf(layers,options[proto][3],tmpI->name);
     256  else
     257    sprintf(layers,options[proto][3],layerName->value);
     258
     259  if(format==NULL || width==NULL || height==NULL || extent==NULL){
     260    char tmpStr[1024];
     261    sprintf(tmpStr,_("Unable to create the mapfile for %s because of missing values."),tmpI->name);
     262    errorException (m, tmpStr,
     263                    "InternalError", NULL);
     264    exit(-1);
     265    return;
     266  }
     267
     268  if(proto==0){
     269    hasFormat=1;
     270    rformat=createMap("mimeType","image/png");
     271  }else{
     272    if(proto==1){
     273      rformat=createMap("mimeType","text/xml");
     274      hasFormat=1;
     275    }
     276    else
     277      if(proto==2){
     278        rformat=createMap("mimeType","image/tiff");
     279        hasFormat=1;
     280        finalProto=1;
     281      }
     282  }
     283 
     284  char* webService_url=(char*)malloc((strlen(msUrl->value)+strlen(rformat->value)+strlen(tmpI->name)+strlen(width->value)+strlen(height->value)+strlen(extent->value)+256)*sizeof(char));
     285
    194286
    195287  if(proto>0){
     288    if(proto==2)
     289      finalProto=1;
    196290    sprintf(webService_url,
    197             "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
     291            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
    198292            msUrl->value,
    199293            dataPath->value,
    200294            tmpI->name,
     295            imyIndex,
    201296            sid->value,
    202297            options[proto][2],
     
    208303            crs->value
    209304            );
     305    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
     306      setMapArray(tmpI->content,"ref_wcs_link",imyIndex,webService_url);
     307    }
     308    else{
     309      setMapArray(tmpI->content,"ref_wfs_link",imyIndex,webService_url);
     310    }
     311    proto=0;
     312    freeMap(&rformat);
     313    free(rformat);
     314    rformat=createMap("mimeType","image/png");
    210315  }
    211316  else{
    212317    sprintf(webService_url,
    213             "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
     318            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
    214319            msUrl->value,
    215320            dataPath->value,
    216321            tmpI->name,
     322            imyIndex,
    217323            sid->value,
    218324            options[proto][2],
     
    226332            crs->value
    227333            );
     334    setMapArray(tmpI->content,"ref_wms_link",imyIndex,webService_url);
     335    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
     336      proto=2;
     337      freeMap(&rformat);
     338      free(rformat);
     339      rformat=createMap("mimeType","image/tiff");
     340    }
     341    else{
     342      proto=1;
     343      freeMap(&rformat);
     344      free(rformat);
     345      rformat=createMap("mimeType","text/xml");
     346    }
     347  }
     348  setMapArray(tmpI->content,"Reference",imyIndex,webService_url);
     349  memset(layers,0,128);
     350  sprintf(layers,options[proto][3],tmpI->name);
     351  protoVersion=options[proto][1];
     352  extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
     353  memset(webService_url,0,strlen(webService_url));
     354  if(proto>0){
     355    if(proto==2)
     356      finalProto=1;
     357    sprintf(webService_url,
     358            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
     359            msUrl->value,
     360            dataPath->value,
     361            tmpI->name,
     362            imyIndex,
     363            sid->value,
     364            options[proto][2],
     365            options[proto][0],
     366            protoVersion,
     367            layers,
     368            rformat->value,
     369            extent->value,
     370            crs->value
     371            );
     372    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
     373      setMapArray(tmpI->content,"ref_wcs_link",imyIndex,webService_url);
     374    }
     375    else{
     376      setMapArray(tmpI->content,"ref_wfs_link",imyIndex,webService_url);
     377    }
     378  }else{
     379    sprintf(webService_url,
     380            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
     381            msUrl->value,
     382            dataPath->value,
     383            tmpI->name,
     384            imyIndex,
     385            sid->value,
     386            options[proto][2],
     387            options[proto][0],
     388            protoVersion,
     389            layers,
     390            width->value,
     391            height->value,
     392            rformat->value,
     393            extent->value,
     394            crs->value
     395            );
     396    setMapArray(tmpI->content,"ref_wms_link",imyIndex,webService_url);
     397  }
     398  if(finalProto>0){
     399    proto=3;
     400    memset(layers,0,128);
     401    sprintf(layers,options[proto][3],tmpI->name);
     402    protoVersion=options[proto][1];
     403    extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
     404    memset(webService_url,0,strlen(webService_url));
     405     freeMap(&rformat);
     406    free(rformat);
     407    rformat=createMap("value","image/tiff");
     408    sprintf(webService_url,
     409            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
     410            msUrl->value,
     411            dataPath->value,
     412            tmpI->name,
     413            imyIndex,
     414            sid->value,
     415            options[proto][2],
     416            options[proto][0],
     417            protoVersion,
     418            layers,
     419            rformat->value,
     420            extent->value,
     421            crs->value
     422            );
     423    setMapArray(tmpI->content,"ref_wcs_preview_link",imyIndex,webService_url);
    228424  }
    229425  if(hasCRS==0){
     
    231427    free(crs);
    232428  }
    233   addToMap(tmpI->content,"Reference",webService_url);
     429  freeMap(&rformat);
     430  free(rformat);
    234431  free(webService_url);
    235432}
     
    249446  OGRSpatialReferenceH  hSRS;
    250447  map* msSrs=NULL;
     448  int imyIndex=getPublishedId(output);
    251449  hSRS = OSRNewSpatialReference(NULL);
    252450  if( pszProjection!=NULL && strlen(pszProjection)>1){
     
    272470        if(output!=NULL){
    273471          if(OSRIsGeographic(hSRS)==TRUE)
    274             addToMap(output->content,"crs_isGeographic","true");
     472            setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
    275473          else
    276             addToMap(output->content,"crs_isGeographic","false");
    277           addToMap(output->content,"crs",tmpSrs);
     474            setMapArray(output->content,"crs_isGeographic",imyIndex,"false");
     475          setMapArray(output->content,"crs",imyIndex,tmpSrs);
    278476        }
    279477      }
     
    288486          if(output!=NULL){
    289487            if(OSRIsGeographic(hSRS)==TRUE)
    290               addToMap(output->content,"crs_isGeographic","true");
     488              setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
    291489            else
    292               addToMap(output->content,"crs_isGeographic","false");
     490              setMapArray(output->content,"crs_isGeographic",imyIndex,"false");
    293491          }
    294492          free(proj4Str);
     
    298496          msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
    299497          if(output!=NULL){
    300             addToMap(output->content,"crs_isGeographic","true");
     498            setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
    301499          }
    302500        }
    303501        if(output!=NULL){
    304           addToMap(output->content,"crs","EPSG:4326");
    305           addToMap(output->content,"real_extent","true");
     502          setMapArray(output->content,"crs",imyIndex,"EPSG:4326");
     503          setMapArray(output->content,"real_extent",imyIndex,"true");
    306504        }
    307505        msInsertHashTable(&(m->web.metadata),"ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
     
    312510  else{
    313511    if(output!=NULL){
    314       msSrs=getMap(output->content,"msSrs");
     512      msSrs=getMapArray(output->content,"msSrs",imyIndex);
    315513    }
    316514    if(msSrs!=NULL){
     
    328526    }
    329527    if(output!=NULL){
    330       addToMap(output->content,"crs",msSrs->value);
    331       addToMap(output->content,"crs_isGeographic","true");
     528      setMapArray(output->content,"crs",imyIndex,msSrs->value);
     529      setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
    332530    }
    333531  }
     
    351549void setMsExtent(maps* output,mapObj* m,layerObj* myLayer,
    352550                 double minX,double minY,double maxX,double maxY){
     551  int imyIndex=getPublishedId(output);
    353552  msMapSetExtent(m,minX,minY,maxX,maxY);
     553  //m->maxsize=4096;
    354554#ifdef DEBUGMS
    355555  fprintf(stderr,"Extent %.15f %.15f %.15f %.15f\n",minX,minY,maxX,maxY);
     
    363563 
    364564  if(output!=NULL){
    365     map* test=getMap(output->content,"real_extent");
     565    map* test=getMapArray(output->content,"real_extent",imyIndex);
     566    pointObj min, max;
     567    projectionObj tempSrs;
     568    min.x = m->extent.minx;
     569    min.y = m->extent.miny;
     570    max.x = m->extent.maxx;
     571    max.y = m->extent.maxy;
     572    char tmpSrsStr[1024];
     573    msInitProjection(&tempSrs);
     574    msLoadProjectionStringEPSG(&tempSrs,"EPSG:4326");
     575
     576    msProjectPoint(&(myLayer->projection),&tempSrs,&min);
     577    msProjectPoint(&myLayer->projection,&tempSrs,&max);
     578 
    366579    if(test!=NULL){
    367       pointObj min, max;
    368       projectionObj tempSrs;
    369       min.x = m->extent.minx;
    370       min.y = m->extent.miny;
    371       max.x = m->extent.maxx;
    372       max.y = m->extent.maxy;
    373       char tmpSrsStr[1024];
    374       msInitProjection(&tempSrs);
    375       msLoadProjectionStringEPSG(&tempSrs,"EPSG:4326");
    376 
    377       msProjectPoint(&(m->projection),&tempSrs,&min);
    378       msProjectPoint(&m->projection,&tempSrs,&max);
    379      
    380       sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.y,min.x,max.y,max.x);
    381       map* isGeo=getMap(output->content,"crs_isGeographic");
     580      sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",min.y,min.x,max.y,max.x);
     581      map* isGeo=getMapArray(output->content,"crs_isGeographic",imyIndex);
    382582#ifdef DEBUGMS
    383583      fprintf(stderr,"isGeo = %s\n",isGeo->value);
    384584#endif
    385       if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
    386         sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
    387       addToMap(output->content,"wms_extent",tmpExtent);
    388       sprintf(tmpSrsStr,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
    389       addToMap(output->content,"wcs_extent",tmpExtent);
     585      if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0){
     586        sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",min.y,min.x,max.y,max.x);
     587        setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
     588        sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f", minY,minX, maxY, maxX);
     589      }else{
     590        sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",min.x,min.y,max.x,max.y);
     591        setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
     592      }
     593      setMapArray(output->content,"wms_extent",imyIndex,tmpExtent);
     594      sprintf(tmpSrsStr,"%.15f,%.15f,%.15f,%.15f",min.x,min.y,max.x,max.y);
     595      setMapArray(output->content,"wcs_extent",imyIndex,tmpExtent);
    390596    }else{
    391       sprintf(tmpExtent,"%f,%f,%f,%f",minX, minY, maxX, maxY);
    392       map* isGeo=getMap(output->content,"crs_isGeographic");
     597      sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",min.x,min.y,max.x,max.y);
     598      setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
     599      sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",minX, minY, maxX, maxY);
     600      map* isGeo=getMapArray(output->content,"crs_isGeographic",imyIndex);
    393601      if(isGeo!=NULL){
    394602#ifdef DEBUGMS
     
    396604#endif
    397605        if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
    398           sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
    399       }
    400       addToMap(output->content,"wms_extent",tmpExtent);
    401       sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",minX,minY,maxX,maxY);
    402       addToMap(output->content,"wcs_extent",tmpExtent);
     606          sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f", minY,minX, maxY, maxX);
     607      }
     608      setMapArray(output->content,"wms_extent",imyIndex,tmpExtent);
     609      sprintf(tmpExtent,"%.15f,%.15f,%.15f,%.15f",minX,minY,maxX,maxY);
     610      setMapArray(output->content,"wcs_extent",imyIndex,tmpExtent);
    403611    }
    404612  }
     
    415623 */
    416624int tryOgr(maps* conf,maps* output,mapObj* m){
    417 
    418   map* tmpMap=getMap(output->content,"storage");
     625  int imyIndex=getPublishedId(output);
     626  map* tmpMap=getMapArray(output->content,"storage",imyIndex);
    419627  char *pszDataSource=tmpMap->value;
    420628
     
    425633  /**
    426634   * Try to load the file as ZIP
    427    */
    428 
     635   *
    429636  OGRDataSourceH poDS1 = NULL;
    430637  OGRSFDriverH *poDriver1 = NULL;
     
    467674    fprintf(stderr,"Unable to access the DataSource as ZIP File\n");
    468675    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
    469     OGR_DS_Destroy(poDS1);
     676    fprintf(stderr,"Remove ZIP File!\n");
     677    unlink(odsName);
     678    //OGR_DS_Destroy(poDS1);
    470679  }else{
    471680#ifdef DEBUGMS
     
    526735      i++;
    527736    }
    528   }
     737    OGR_DS_Destroy(poDS1);
     738    }
    529739  free(sdsName);
    530   free(dsName);
    531 
     740  free(dsName);*/
     741 
    532742  OGRDataSourceH poDS = NULL;
    533743  OGRSFDriverH *poDriver = NULL;
     
    538748#endif
    539749    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
    540     OGR_DS_Destroy(poDS);
    541     OGRCleanupAll();
    542750#ifdef DEBUGMS
    543751    fprintf(stderr,"Unable to access the DataSource, exit! \n");
     
    546754  }
    547755
     756  setMapArray(output->content,"gdalType",imyIndex,OGR_Dr_GetName(OGR_DS_GetDriver(poDS))); 
     757  setMapArray(output->content,"geodatatype",imyIndex,"vector");
    548758  int iLayer = 0;
    549759  for( iLayer=0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++ ){
     
    561771     * Add a new layer set name, data
    562772     */
    563     if(msGrowMapLayers(m)==NULL){
    564       return -1;
    565     }
    566     if(initLayer((m->layers[m->numlayers]), m) == -1){
    567       return -1;
    568     }
    569 
    570     layerObj* myLayer=m->layers[m->numlayers];
     773    layerObj* myLayer=NULL;
     774    if(getMapArray(output->content,"msInclude",imyIndex)==NULL){
     775      if(msGrowMapLayers(m)==NULL){
     776        return -1;
     777      }
     778      if(initLayer((m->layers[m->numlayers]), m) == -1){
     779        return -1;
     780      }
     781      myLayer=m->layers[m->numlayers];
     782    }else{
     783      myLayer=m->layers[m->numlayers-1];
     784    }
     785   
    571786#ifdef DEBUGMS
    572787    dumpMaps(output);
     
    580795    myLayer->status = MS_ON;
    581796    msConnectLayer(myLayer,MS_OGR,pszDataSource);
     797
     798    addIntToMapArray(output->content,"nb_features",imyIndex,OGR_L_GetFeatureCount(poLayer,1));
    582799
    583800    /**
     
    631848    }
    632849    else{
    633       addToMap(output->content,"crs","EPSG:4326");
    634       addToMap(output->content,"crs_isGeographic","true");
     850      setMapArray(output->content,"crs",imyIndex,"EPSG:4326");
     851      setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
    635852      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
    636853      msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
     
    641858    if (OGR_L_GetExtent(poLayer,&oExt, TRUE) == OGRERR_NONE){
    642859      setMsExtent(output,m,myLayer,oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
     860      char extent[1024];
     861      memset(&extent,0,1024);
     862      sprintf(extent,"%d,%d,%d,%d",oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
     863      setMapArray(output->content,"boundingbox",imyIndex,extent);
    643864    }
    644865 
     
    659880    msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
    660881    msInsertHashTable(&(myLayer->metadata), "ows_name", output->name);
    661     map* tmpMap=getMap(output->content,"title");
     882    map* tmpMap=getMapArray(output->content,"title",imyIndex);
    662883    if(tmpMap!=NULL)
    663884      msInsertHashTable(&(myLayer->metadata), "ows_title", tmpMap->value);
    664885    else
    665886      msInsertHashTable(&(myLayer->metadata), "ows_title", "Default Title");
     887
     888    if(getMapArray(output->content,"msInclude",imyIndex)==NULL){
     889      if(msGrowLayerClasses(myLayer) == NULL)
     890        return -1;
     891      if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
     892        return -1;
     893      if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
     894        return -1;
     895      if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
     896        return -1;
     897      /**
     898       * Apply msStyle else fallback to the default style
     899       */
     900      tmpMap=getMap(output->content,"msStyle");
     901      if(tmpMap==NULL){
     902        switch(myLayer->type){
     903        case MS_LAYER_POLYGON:
     904          tmpMap=getMapFromMaps(conf,"main","msStylePoly");
     905          break;
     906        case MS_LAYER_LINE:
     907          tmpMap=getMapFromMaps(conf,"main","msStyleLine");
     908          break;
     909        default:
     910          tmpMap=getMapFromMaps(conf,"main","msStylePoint");
     911          break;
     912        }
     913      }
     914      if(tmpMap!=NULL)
     915        msUpdateStyleFromString(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles],tmpMap->value,0);
     916      else{
     917        /**
     918         * Set style
     919         */
     920        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=125;
     921        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=125;
     922        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=255;
     923        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
     924        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
     925        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
     926       
     927        /**
     928         * Set specific style depending on type
     929         */
     930        if(myLayer->type == MS_LAYER_POLYGON)
     931          myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
     932        if(myLayer->type == MS_LAYER_LINE){
     933          myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
     934          myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
     935        }
     936        if(myLayer->type == MS_LAYER_POINT){
     937          myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->symbol=1;
     938          myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->size=15;
     939        }
     940       
     941      }
     942      myLayer->CLASS[myLayer->numclasses]->numstyles++;
     943      myLayer->numclasses++;
    666944   
    667     if(msGrowLayerClasses(myLayer) == NULL)
    668       return -1;
    669     if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
    670       return -1;
    671     if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
    672       return -1;
    673     if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
    674       return -1;
    675     /**
    676      * Apply msStyle else fallback to the default style
    677      */
    678     tmpMap=getMap(output->content,"msStyle");
    679     if(tmpMap!=NULL)
    680       msUpdateStyleFromString(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles],tmpMap->value,0);
    681     else{
    682       /**
    683        * Set style
    684        */
    685       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=125;
    686       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=125;
    687       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=255;
    688       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
    689       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
    690       myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
    691      
    692       /**
    693        * Set specific style depending on type
    694        */
    695       if(myLayer->type == MS_LAYER_POLYGON)
    696         myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
    697       if(myLayer->type == MS_LAYER_LINE){
    698         myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
    699         myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
    700       }
    701       if(myLayer->type == MS_LAYER_POINT){
    702         myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->symbol=1;
    703         myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->size=15;
    704       }
    705      
    706     }
    707     myLayer->CLASS[myLayer->numclasses]->numstyles++;
    708     myLayer->numclasses++;
    709    
    710     m->layerorder[m->numlayers] = m->numlayers;
    711     m->numlayers++;
    712 
    713   }
    714 
     945      m->layerorder[m->numlayers] = m->numlayers;
     946      m->numlayers++;
     947
     948    }
     949  }
    715950  OGR_DS_Destroy(poDS);
    716   OGRCleanupAll();
     951  //OGRCleanupAll();
    717952
    718953  return 1;
     
    727962 */
    728963int tryGdal(maps* conf,maps* output,mapObj* m){
    729   map* tmpMap=getMap(output->content,"storage");
     964  int imyIndex=getPublishedId(output);
     965  map* tmpMap=getMapArray(output->content,"storage",imyIndex);
     966  map* styleMap=getMap(output->content,"msStyle");
    730967  char *pszFilename=tmpMap->value;
    731968  GDALDatasetH hDataset;
     
    738975   */
    739976  GDALAllRegister();
    740   hDataset = GDALOpen( pszFilename, GA_ReadOnly );
     977  hDataset = GDALOpen( pszFilename, GA_Update ); /*GA_ReadOnly*/
    741978  if( hDataset == NULL ){
    742979#ifdef DEBUGMS
    743980    fprintf(stderr,"Unable to access the DataSource %s \n",pszFilename);
    744981#endif
     982    setMapArray(output->content,"geodatatype",imyIndex,"other");
    745983    setMapInMaps(conf,"lenv","message","gdalinfo failed - unable to open");
    746984    GDALDestroyDriverManager();
     
    751989#endif
    752990
     991  setMapArray(output->content,"geodatatype",imyIndex,"raster");
    753992  /**
    754993   * Add a new layer set name, data
     
    7721011
    7731012  char *title=output->name;
    774   tmpMap=getMap(output->content,"title");
     1013  tmpMap=getMapArray(output->content,"title",imyIndex);
    7751014  if(tmpMap!=NULL)
    7761015    title=tmpMap->value;
    7771016  char *abstract=output->name;
    778   tmpMap=getMap(output->content,"abstract");
     1017  tmpMap=getMapArray(output->content,"abstract",imyIndex);
    7791018  if(tmpMap!=NULL)
    7801019    abstract=tmpMap->value;
     
    7911030  m->width=GDALGetRasterXSize( hDataset );
    7921031  m->height=GDALGetRasterYSize( hDataset );
    793  
     1032  if(m->width>4096 || m->height>4096){
     1033    if(m->width>m->height)
     1034      m->maxsize=m->width;
     1035    else 
     1036      m->maxsize=m->height;
     1037  }else
     1038    m->maxsize=4096;
     1039  addIntToMapArray(output->content,"nb_pixels",imyIndex,GDALGetRasterXSize( hDataset )*GDALGetRasterYSize( hDataset ));
     1040  int pixel_type=GDALGetRasterDataType( hDataset );
     1041  addIntToMapArray(output->content,"pixel_data_type",imyIndex,pixel_type);
     1042
     1043  int outputIndex=msGetOutputFormatIndex(m,"tiff");
     1044  if(outputIndex>=0){
     1045    m->outputformatlist[outputIndex]->imagemode=((pixel_type==GDT_Byte)?MS_IMAGEMODE_BYTE:((pixel_type==GDT_Int16 || pixel_type==GDT_UInt16)?MS_IMAGEMODE_INT16:((pixel_type!=GDT_Float32)?MS_IMAGEMODE_FLOAT32:MS_IMAGEMODE_BYTE)));
     1046    outputIndex=msGetOutputFormatIndex(m,"geotiff");
     1047    if(outputIndex>=0)
     1048      m->outputformatlist[outputIndex]->imagemode=((pixel_type==GDT_Byte)?MS_IMAGEMODE_BYTE:((pixel_type==GDT_Int16 || pixel_type==GDT_UInt16)?MS_IMAGEMODE_INT16:((pixel_type!=GDT_Float32)?MS_IMAGEMODE_FLOAT32:MS_IMAGEMODE_BYTE)));
     1049  }
     1050  //
     1051   
    7941052  /**
    7951053   * Set projection using Authority Code and Name if available or fallback to
     
    8051063    setSrsInformations(output,m,myLayer,pszProjection);
    8061064  }else{
    807     fprintf(stderr,"NO SRS FOUND ! %s\n",GDALGetProjectionRef( hDataset ));   
    808   }
    809 
     1065    fprintf(stderr,"NO SRS FOUND %s %d ! %s\n",__FILE__,__LINE__,GDALGetProjectionRef( hDataset ));
     1066    fflush(stderr);
     1067    CPLErr sp=GDALSetProjection( hDataset , "+init=epsg:4326" );
     1068    if(sp!=CE_None){
     1069      fprintf(stderr,"NO SRS SET ! %s\n",CPLGetLastErrorMsg());
     1070    }
     1071  }
    8101072
    8111073  /**
     
    8251087        + adfGeoTransform[4] * GDALGetRasterXSize(hDataset);
    8261088
    827        setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
    828 
    829     }
     1089      setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
     1090      char extent[1024];
     1091      memset(&extent,0,1024);
     1092      sprintf(extent,"%d,%d,%d,%d",minX,minY,maxX,maxY);
     1093      setMapArray(output->content,"boundingbox",imyIndex,extent);
     1094    }
     1095  }else{
     1096    int scale=1;
     1097    if(m->width>2048){
     1098      addIntToMapArray(output->content,"width",imyIndex,2048);
     1099      scale=2048/m->width;
     1100    }else
     1101      addIntToMapArray(output->content,"width",imyIndex,m->width);
     1102    addIntToMapArray(output->content,"height",imyIndex,m->height*scale);
    8301103  }
    8311104
     
    8351108   */
    8361109  char nBands[3];
     1110  memset(&nBands,0,3);
    8371111  int nBandsI=GDALGetRasterCount( hDataset );
    838   sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
    839   msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
    840   if(nBandsI>=3)
    841     msLayerAddProcessing(myLayer,"BANDS=1,2,3");
    842   else if(nBandsI>=2)
    843     msLayerAddProcessing(myLayer,"BANDS=1,2");
    844   else
    845     msLayerAddProcessing(myLayer,"BANDS=1");
     1112  if(nBandsI<100){
     1113    sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
     1114    msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
     1115  }
     1116  if(styleMap==NULL || strstr(styleMap->value,"BANDS=")==NULL){
     1117    if(nBandsI>=3)
     1118      if(nBandsI==4)
     1119        msLayerAddProcessing(myLayer,"BANDS=1,2,3,4");
     1120      else
     1121        msLayerAddProcessing(myLayer,"BANDS=1,2,3");
     1122    else if(nBandsI>=2)
     1123      msLayerAddProcessing(myLayer,"BANDS=1,2");
     1124    else
     1125      msLayerAddProcessing(myLayer,"BANDS=1");
     1126  }
    8461127
    8471128  /**
     
    8511132  char *nameBands=NULL;
    8521133  for( iBand = 0; iBand < nBandsI; iBand++ ){
    853     sprintf(lBands,"Band%d",iBand+1);
     1134    memset(&lBands,0,7);
     1135    sprintf(lBands,"Band%d",iBand+1);   
    8541136    if(nameBands==NULL){
    8551137      nameBands=(char*)malloc((strlen(lBands)+1)*sizeof(char));
    8561138      sprintf(nameBands,"%s",lBands);
    8571139    }else{
    858       if(iBand<4){
     1140      /*if(iBand<4)*/{
    8591141        char *tmpS=zStrdup(nameBands);
    860         nameBands=(char*)realloc(nameBands,(strlen(nameBands)+strlen(lBands)+1)*sizeof(char));
     1142        nameBands=(char*)realloc(nameBands,(strlen(tmpS)+strlen(lBands)+2)*sizeof(char));
    8611143        sprintf(nameBands,"%s %s",tmpS,lBands);
    8621144        free(tmpS);
     
    8641146    }
    8651147  }
    866   msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
    867  
     1148  if(nameBands!=NULL){
     1149    msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
     1150    free(nameBands);
     1151  }
     1152
    8681153  /**
    8691154   * Loops over metadata information to setup specific information
    8701155   */
    8711156  for( iBand = 0; iBand < nBandsI; iBand++ ){
    872     //int         bGotNodata;//, bSuccess;
    873     double      adfCMinMax[2]/*, dfNoData*/;
    874     //int         nBlockXSize, nBlockYSize, nMaskFlags;
    875     //double      /*dfMean, dfStdDev*/;
     1157    double      pdfMin, pdfMax, pdfMean, pdfStdDev;
    8761158    hBand = GDALGetRasterBand( hDataset, iBand+1 );
    8771159
    8781160    CPLErrorReset();
    879     GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
     1161    GDALGetRasterStatistics( hBand, TRUE, TRUE, &pdfMin, &pdfMax, &pdfMean, &pdfStdDev);
    8801162    char tmpN[21];
    8811163    sprintf(tmpN,"Band%d",iBand+1);
    8821164    if (CPLGetLastErrorType() == CE_None){
    883       char tmpMm[100];
    884       sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
    885       char tmpI[21];
     1165      char tmpMm[100],tmpMp[100],tmpNb[3];
     1166      sprintf(tmpMm,"%.3f %.3f",pdfMin,pdfMax);
     1167      if(pdfMin!=pdfMax && (styleMap==NULL || strstr(styleMap->value,"SCALE_")==NULL)){
     1168        sprintf(tmpNb,"%d",iBand+1);
     1169        if(styleMap==NULL || strstr(styleMap->value,"BANDS=")==NULL || strstr(strstr(styleMap->value,"BANDS="),tmpNb)!=NULL){
     1170          if(pdfMean-(2*pdfStdDev)<0)
     1171            sprintf(tmpMp,"SCALE_%d=%.3f,%.3f",iBand+1,0.0,pdfMean+(2*pdfStdDev));
     1172          else
     1173            sprintf(tmpMp,"SCALE_%d=%.3f,%.3f",iBand+1,pdfMean-(2*pdfStdDev),pdfMean+(2*pdfStdDev));
     1174          msLayerAddProcessing(myLayer,tmpMp);
     1175        }
     1176      }
     1177      char tmpI[31];     
    8861178      sprintf(tmpI,"%s_interval",tmpN);
    8871179      msInsertHashTable(&(myLayer->metadata), tmpI, tmpMm);
    888 
    8891180      map* test=getMap(output->content,"msClassify");
    8901181      if(test!=NULL && strncasecmp(test->value,"true",4)==0){
     
    9061197         
    9071198        if(nBandsI==1){
    908           double delta=adfCMinMax[1]-adfCMinMax[0];
     1199          double delta=pdfMax-pdfMin;
    9091200          double interval=delta/10;
    910           double cstep=adfCMinMax[0];
     1201          double cstep=pdfMin;
    9111202          for(i=0;i<10;i++){
    9121203            /**
     
    9521243         
    9531244          char tmpMm[100];
    954           sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
     1245          sprintf(tmpMm,"%.3f %.3f",pdfMin,pdfMax);
    9551246         
    9561247        }
     
    9621253          myLayer->offsite.blue=0;
    9631254        }
    964         msLayerAddProcessing(myLayer,"RESAMPLE=BILINEAR");
    9651255      }
    9661256    }
    9671257    if( strlen(GDALGetRasterUnitType(hBand)) > 0 ){
    968       char tmpU[21];
     1258      char tmpU[31];
    9691259      sprintf(tmpU,"%s_band_uom",tmpN);
    9701260      msInsertHashTable(&(myLayer->metadata), tmpU, GDALGetRasterUnitType(hBand));
     
    9721262
    9731263  }
    974 
     1264  if(styleMap==NULL || strstr(styleMap->value,"RESAMPLE")==NULL)
     1265    msLayerAddProcessing(myLayer,"RESAMPLE=BILINEAR");
     1266 
     1267  if(styleMap!=NULL && strlen(styleMap->value)>9){
     1268    msUpdateLayerFromString(myLayer,styleMap->value,MS_FALSE);
     1269  }
     1270 
    9751271  m->layerorder[m->numlayers] = m->numlayers;
    9761272  m->numlayers++;
     
    9781274  GDALDestroyDriverManager();
    9791275  CPLCleanupTLS();
     1276  storeMd5(pszFilename);
    9801277  return 1;
    9811278}
     
    9881285 */
    9891286void outputMapfile(maps* conf,maps* outputs){
    990 
    9911287  /**
    9921288   * First store the value on disk
    9931289   */
    994   map* mime=getMap(outputs->content,"mimeType");
     1290  int imyIndex=getPublishedId(outputs);
     1291  map* mime=getMapArray(outputs->content,"mimeType",imyIndex);
     1292  map* msUrl=getMapFromMaps(conf,"main","mapserverAddress");
     1293  map* dataPath=getMapFromMaps(conf,"main","dataPath");
    9951294  char *ext="data";
    9961295  if(mime!=NULL)
     
    9981297      ext="json";
    9991298
    1000   map* tmpMap=getMapFromMaps(conf,"main","dataPath");
    1001   map* sidMap=getMapFromMaps(conf,"lenv","usid");
    1002   char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
    1003   sprintf(pszDataSource,"%s/ZOO_DATA_%s_%s.%s",tmpMap->value,outputs->name,sidMap->value,ext);
    1004   int f=zOpen(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
    1005   map *gfile=getMap(outputs->content,"generated_file");
    1006   if(gfile!=NULL){
    1007     readGeneratedFile(conf,outputs->content,gfile->value);         
    1008   }
    1009   map* sizeMap=getMap(outputs->content,"size");
    1010   map* vData=getMap(outputs->content,"value");
    1011   if(sizeMap!=NULL){
    1012     zWrite(f,vData->value,atoi(sizeMap->value)*sizeof(char));
    1013   }
    1014   else{
    1015     zWrite(f,vData->value,(strlen(vData->value)+1)*sizeof(char));
    1016   }
    1017   close(f);
    1018   addToMap(outputs->content,"storage",pszDataSource);
    1019   free(pszDataSource);
     1299  map* storage=getMapArray(outputs->content,"storage",imyIndex);
     1300  if(storage==NULL){
     1301    map* tmpMap=getMapFromMaps(conf,"main","dataPath");
     1302    map* sidMap=getMapFromMaps(conf,"lenv","usid");
     1303    char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
     1304    sprintf(pszDataSource,"%s/ZOO_DATA_%d_%s_%s.%s",tmpMap->value,imyIndex,outputs->name,sidMap->value,ext);
     1305    int f=zOpen(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
     1306    map *gfile=getMapArray(outputs->content,"generated_file",imyIndex);
     1307    if(gfile!=NULL){
     1308      readGeneratedFile(conf,outputs->content,gfile->value);       
     1309    }
     1310    map* sizeMap=getMapArray(outputs->content,"size",imyIndex);
     1311    map* vData=getMapArray(outputs->content,"value",imyIndex);
     1312    if(sizeMap!=NULL){
     1313      zWrite(f,vData->value,atoi(sizeMap->value)*sizeof(char));
     1314    }
     1315    else{
     1316      zWrite(f,vData->value,(strlen(vData->value)+1)*sizeof(char));
     1317    }
     1318    close(f);
     1319    setMapArray(outputs->content,"storage",imyIndex,pszDataSource);
     1320    free(pszDataSource);
     1321  }
    10201322
    10211323  /*
    10221324   * Create an empty map, set name, default size and extent
    10231325   */
    1024   mapObj *myMap=msNewMapObj();
     1326  map* mapfileTemplate=getMapArray(outputs->content,"msInclude",imyIndex);
     1327  mapObj *myMap=NULL;
     1328  if(mapfileTemplate==NULL){
     1329    myMap=msNewMapObj();
     1330  }
     1331  else{
     1332    map* dataPath=getMapFromMaps(conf,"main","dataPath");
     1333    map* sid=getMapFromMaps(conf,"lenv","sid");
     1334    char *mapfileTemplatePath=(char*)malloc(((strlen(dataPath->value)+strlen(sid->value)+strlen(outputs->name)+10)*sizeof(char)));
     1335    sprintf(mapfileTemplatePath,"%s/%s_%s.map",dataPath->value,outputs->name,sid->value);
     1336    myMap=msLoadMap(mapfileTemplate->value,mapfileTemplatePath);
     1337    if(myMap==NULL){
     1338      setMapInMaps(conf,"lenv","message",_("Unable to open your template mapfile!"));
     1339      return ;
     1340    }
     1341  }
    10251342  free(myMap->name);
    10261343  myMap->name=zStrdup("ZOO-Project_WXS_Server");
     
    10481365#ifdef USE_KML
    10491366  outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
    1050   o2->inmapfile=MS_TRUE; 
    1051   msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
    1052   msFreeOutputFormat(o2);
     1367  if(!o2){
     1368    perror("Unable to initialize KML driver");
     1369    fprintf(stderr,"Unable to initialize KML driver !\n");
     1370  }else{
     1371    o2->inmapfile=MS_TRUE; 
     1372    msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
     1373    msFreeOutputFormat(o2);
     1374  }
    10531375#endif
    10541376
     
    10571379    fprintf(stderr,"Unable to initialize GDAL driver !\n");
    10581380  else{
    1059     o3->imagemode=MS_IMAGEMODE_BYTE;
     1381    o3->imagemode=MS_IMAGEMODE_INT16;
    10601382    o3->inmapfile=MS_TRUE; 
    10611383    msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
     
    10671389    fprintf(stderr,"Unable to initialize GDAL driver !\n");
    10681390  else{
    1069     o4->imagemode=MS_IMAGEMODE_INT16;
     1391    o4->imagemode=MS_IMAGEMODE_BYTE;
    10701392    o4->inmapfile=MS_TRUE; 
    10711393    msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
     
    10861408#endif
    10871409
     1410 
     1411  outputFormatObj *o6=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","geotiff");
     1412  if(!o6)
     1413    fprintf(stderr,"Unable to initialize GDAL driver !\n");
     1414  else{
     1415    o6->imagemode=MS_IMAGEMODE_BYTE;
     1416    o6->mimetype=strdup("image/geotiff");
     1417    o6->inmapfile=MS_TRUE;
     1418    msAppendOutputFormat(myMap,msCloneOutputFormat(o6));
     1419    msFreeOutputFormat(o6);
     1420  }
     1421
     1422 
    10881423  /*
    10891424   * Set default projection to EPSG:4326
     
    10911426  msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
    10921427  myMap->transparent=1;
    1093 
    1094   /**
    1095    * Set metadata extracted from main.cfg file maps
    1096    */
    1097   maps* cursor=conf;
    1098   map* correspondance=getCorrespondance();
    1099   while(cursor!=NULL){
    1100     map* _cursor=cursor->content;
    1101     map* vMap;
    1102     while(_cursor!=NULL){
    1103       if((vMap=getMap(correspondance,_cursor->name))!=NULL){
    1104         if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
    1105 #ifdef DEBUGMS
    1106           fprintf(stderr,"Unable to add metadata");
    1107 #endif
    1108           return;
    1109         }
    1110       }
    1111       _cursor=_cursor->next;
    1112     }
    1113     cursor=cursor->next;
    1114   }
    1115   freeMap(&correspondance);
    1116   free(correspondance);
    11171428
    11181429  /*
     
    11571468  msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
    11581469
     1470  /**
     1471   * Set metadata extracted from main.cfg file maps
     1472   */
     1473  maps* cursor=conf;
     1474  map* correspondance=getCorrespondance();
     1475  while(cursor!=NULL){
     1476    if(strstr(cursor->name,"_help")==NULL){
     1477      map* _cursor=cursor->content;
     1478      map* vMap;
     1479      while(_cursor!=NULL){
     1480        if((vMap=getMap(correspondance,_cursor->name))!=NULL){
     1481          if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
     1482#ifdef DEBUGMS
     1483            fprintf(stderr,"Unable to add metadata");
     1484#endif
     1485            freeMap(&correspondance);
     1486            free(correspondance);
     1487            return;
     1488          }
     1489        }
     1490        _cursor=_cursor->next;
     1491      }
     1492    }
     1493    cursor=cursor->next;
     1494  }
     1495  freeMap(&correspondance);
     1496  free(correspondance);
     1497
     1498  map* sid=getMapFromMaps(conf,"lenv","usid");
     1499  char *mapPath=
     1500    (char*)malloc((14+strlen(sid->value)+strlen(outputs->name)+strlen(dataPath->value))*sizeof(char));
     1501  sprintf(mapPath,"%s/%s_%d_%s.map",dataPath->value,outputs->name,imyIndex,sid->value);
     1502  char *mapUrl=
     1503    (char*)malloc((6+strlen(mapPath)+strlen(msUrl->value))*sizeof(char));
     1504  sprintf(mapUrl,"%s?map=%s",msUrl->value,mapPath);
     1505
     1506  if (msInsertHashTable(&(myMap->web.metadata), "ows_onlineresource", mapUrl) == NULL){
     1507#ifdef DEBUGMS
     1508    fprintf(stderr,"Unable to add metadata");
     1509#endif
     1510    return;
     1511  }
     1512
    11591513  if(tryOgr(conf,outputs,myMap)<0)
    11601514    if(tryGdal(conf,outputs,myMap)<0)
    11611515      return ;
    11621516
    1163   tmp1=getMapFromMaps(conf,"main","dataPath");
    1164   char *tmpPath=(char*)malloc((13+strlen(tmp1->value))*sizeof(char));
    1165   sprintf(tmpPath,"%s/symbols.sym",tmp1->value);
     1517  char *tmpPath=(char*)malloc((13+strlen(dataPath->value))*sizeof(char));
     1518  sprintf(tmpPath,"%s/symbols.sym",dataPath->value);
    11661519  msInitSymbolSet(&myMap->symbolset);
    11671520  myMap->symbolset.filename=zStrdup(tmpPath);
    11681521  free(tmpPath);
    11691522
    1170   map* sid=getMapFromMaps(conf,"lenv","usid");
    1171   char *mapPath=
    1172     (char*)malloc((7+strlen(sid->value)+strlen(outputs->name)+strlen(tmp1->value))*sizeof(char));
    1173   sprintf(mapPath,"%s/%s_%s.map",tmp1->value,outputs->name,sid->value);
    11741523  msSaveMap(myMap,mapPath);
     1524  saveMapNames(conf,outputs,mapPath);
    11751525  free(mapPath);
     1526  //free(myMap->symbolset.filename);
     1527  //msFreeSymbolSet(&myMap->symbolset);
     1528  msFreeMap(myMap);
     1529  //msFree(myMap);
    11761530  msGDALCleanup();
    1177   msFreeMap(myMap);
    11781531}
    11791532
     1533/**
     1534 * Save the map fullpath in a text file (.maps)
     1535 * @param conf the main configuration map pointer
     1536 * @param output the current output for which a mapfile has been generated
     1537 * @param mapfile the mapfile saved to store in the text file
     1538 */
     1539void saveMapNames(maps* conf,maps* output,char* mapfile){
     1540  map* storage=getMap(output->content,"storage");
     1541  char *tmp=zStrdup(storage->value);
     1542  tmp[strlen(tmp)-strlen(strrchr(tmp,'.'))]=0;
     1543  char* mapName=(char*)malloc((strlen(tmp)+6)*sizeof(char*));
     1544  sprintf(mapName,"%s.maps",tmp);
     1545  FILE* myMaps=fopen(mapName,"a");
     1546  if(myMaps!=NULL){
     1547    fprintf(myMaps,"%s\n",mapfile);
     1548    fclose(myMaps);
     1549  }
     1550  free(mapName);
     1551  free(tmp);
     1552}
  • trunk/zoo-project/zoo-kernel/service_internal_ms.h

    r889 r917  
    5656  int tryGdal(maps* conf,maps* output,mapObj* m);
    5757  void outputMapfile(maps* conf,maps* outputs);
     58  void saveMapNames(maps*,maps*,char*);
     59
    5860#ifdef __cplusplus
    5961}
  • trunk/zoo-project/zoo-kernel/service_internal_php7.c

    r796 r917  
    2525#ifdef WIN32
    2626  #define NO_FCGI_DEFINES
     27  #define ZEND_WIN32_KEEP_INLINE
    2728#endif
    2829
  • trunk/zoo-project/zoo-kernel/service_internal_python.c

    r790 r917  
    5757 * from the ZOO-Kernel Python environment:
    5858 *  - "_" corresponding to the PythonTranslate function
    59  *  - "updte_status" corresponding to the PythonUpdateStatus function
     59 *  - "update_status" corresponding to the PythonUpdateStatus function
    6060 * @see PythonTranslate, PythonUpdateStatus
    6161 */
     
    146146 */
    147147int zoo_python_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
     148
    148149  char *pythonpath;
    149150  char *python_path;
     151
     152#ifdef WIN32
     153  char* os_pathsep = ";";
     154#else
     155  char* os_pathsep = ":";
     156#endif
     157
    150158  maps* m=*main_conf;
    151159  maps* inputs=*real_inputs;
    152160  maps* outputs=*real_outputs;
    153161  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
    154   char *ntmp=tmp0->value;
     162  char *ntmp=tmp0->value; 
    155163  map* tmp=NULL;
    156164  int hasToClean=0;
    157   tmp=getMapFromMaps(*main_conf,"env","PYTHONPATH");
     165  tmp=getMapFromMaps(*main_conf,"env","PYTHONPATH");
     166
     167  map* kvp = NULL;
     168  char* libPath = NULL;
     169  if (hasvalue(*main_conf, "main", "libPath", &kvp)) {
     170          libPath = kvp->value;
     171  }
     172  else {
     173          libPath = "";
     174  }
     175
    158176#ifdef DEBUG
    159177  fprintf(stderr,"PYTHON SUPPORT \n");
     
    163181    fprintf(stderr,"PYTHON SUPPORT (%i)\n",strlen(tmp->value));
    164182#endif
    165     python_path=(char*)malloc((strlen(tmp->value))*sizeof(char));
     183    python_path=(char*)malloc((strlen(tmp->value)+1)*sizeof(char));
    166184    sprintf(python_path,"%s",tmp->value);
    167185    hasToClean=1;
     
    172190      python_path=cwdMap->value;
    173191    else
    174       python_path=(char*)".";
     192      python_path=(char*)".";   
    175193  }
    176194  tmp=NULL;
    177195  tmp=getMap(request,"metapath");
    178196  if(tmp!=NULL && strcmp(tmp->value,"")!=0){
    179     pythonpath=(char*)malloc((4+strlen(python_path)+strlen(ntmp)+strlen(tmp->value))*sizeof(char));
     197    //pythonpath=(char*)malloc((4+strlen(python_path)+strlen(ntmp)+strlen(tmp->value))*sizeof(char));
     198          pythonpath = (char*)malloc((5 + strlen(python_path) + strlen(ntmp) + strlen(tmp->value) + strlen(libPath)) * sizeof(char));
    180199#ifdef WIN32
    181   sprintf(pythonpath,"%s/%s/;%s",ntmp,tmp->value,python_path);
     200  //sprintf(pythonpath,"%s/%s/;%s",ntmp,tmp->value,python_path);
     201        sprintf(pythonpath, "%s/%s/;%s;%s", ntmp, tmp->value, python_path, libPath);
    182202#else
    183   sprintf(pythonpath,"%s/%s/:%s",ntmp,tmp->value,python_path);
     203  //sprintf(pythonpath,"%s/%s/:%s",ntmp,tmp->value,python_path);
     204  sprintf(pythonpath, "%s/%s/:%s:%s", ntmp, tmp->value, python_path, libPath); 
    184205#endif
    185206  }
    186207  else{
    187     pythonpath=(char*)malloc((2+strlen(python_path)+strlen(ntmp))*sizeof(char));
     208    //pythonpath=(char*)malloc((2+strlen(python_path)+strlen(ntmp))*sizeof(char));
     209          pythonpath = (char*)malloc((3 + strlen(python_path) + strlen(ntmp) + strlen(libPath)) * sizeof(char));
    188210#ifdef WIN32
    189     sprintf(pythonpath,"%s;%s",ntmp,python_path);
     211    //sprintf(pythonpath,"%s;%s",ntmp,python_path);
     212        sprintf(pythonpath, "%s;%s;%s", ntmp, python_path, libPath);
    190213#else
    191     sprintf(pythonpath,"%s:%s",ntmp,python_path);
    192 #endif
     214    //sprintf(pythonpath,"%s:%s",ntmp,python_path);
     215        sprintf(pythonpath, "%s:%s:%s", ntmp, python_path, libPath);
     216#endif 
    193217  }
    194218#ifdef DEBUG
    195219    fprintf(stderr,"PYTHONPATH=%s\n",pythonpath);
    196220#endif
    197 #ifndef WIN32
    198   setenv("PYTHONPATH",pythonpath,1);
    199 #else
     221        map* home = NULL;
     222// knut: also set PYTHONHOME environment variable so that Python can load standard modules
     223#ifndef WIN32   
     224  setenv("PYTHONPATH",pythonpath,1); 
     225  //= getMapFromMaps(*main_conf, "env", "PYTHONHOME");
     226  if (hasvalue(*main_conf, "env", "PYTHONHOME", &home)) {
     227          setenv("PYTHONHOME", home->value, 1); // overwrite
     228  }
     229#else   
    200230  SetEnvironmentVariable("PYTHONPATH",pythonpath);
    201231  char* toto=(char*)malloc((strlen(pythonpath)+12)*sizeof(char));
    202232  sprintf(toto,"PYTHONPATH=%s",pythonpath);
    203   putenv(toto);
     233  _putenv(toto);
    204234  free(toto);
    205 #endif
     235  if (hasvalue(*main_conf, "env", "PYTHONHOME", &home)) {
     236          SetEnvironmentVariable("PYTHONHOME", home->value);
     237  }
     238  char buffer[128];       
     239#endif 
    206240  if(hasToClean>0)
    207241    free(python_path);
     
    209243
    210244  PyThreadState *mainstate;
    211 #if PY_MAJOR_VERSION >= 3
    212   PyImport_AppendInittab("zoo", init_zoo);
     245#if PY_MAJOR_VERSION >= 3 
     246  PyImport_AppendInittab("zoo", init_zoo); 
    213247#else
    214248  PyEval_InitThreads();
    215 #endif
    216   Py_Initialize();
    217 #if PY_MAJOR_VERSION >= 3
     249#endif 
     250  Py_Initialize(); 
     251#if PY_MAJOR_VERSION >= 3 
    218252  PyEval_InitThreads();
    219   PyImport_ImportModule("zoo");
     253  PyImport_ImportModule("zoo"); 
    220254#else
    221255  init_zoo();
    222 #endif
     256#endif 
    223257  mainstate = PyThreadState_Swap(NULL);
    224258  PyEval_ReleaseLock();
     
    240274      char *mn=(char*)malloc((strlen(mps)+strlen(tmp->value)+2)*sizeof(char));
    241275      sprintf(mn,"%s.%s",mps,tmp->value);
    242       pName = PyString_FromString(mn);
     276      pName = PyString_FromString(mn);   
    243277      free(mn);
    244278      free(mps);
     
    251285    errorException (m, "Unable to parse serviceProvider please check your zcfg file.", "NoApplicableCode", NULL);
    252286    exit(-1);
    253   }
    254   pModule = PyImport_Import(pName);
     287  } 
     288  pModule = PyImport_Import(pName);   
    255289  int res=SERVICE_FAILED;
    256290  if (pModule != NULL) {
     
    267301      PyTuple_SetItem(pArgs, 1, (PyObject *)arg2);
    268302      PyTuple_SetItem(pArgs, 2, (PyObject *)arg3);
    269       pValue = PyObject_CallObject(pFunc, pArgs);
     303      pValue = PyObject_CallObject(pFunc, pArgs);         
    270304      if (pValue != NULL) {
    271305        res=PyInt_AsLong(pValue);
     
    275309        free(*main_conf);
    276310        *main_conf=mapsFromPyDict(arg1);
    277         *real_outputs=mapsFromPyDict(arg3);
     311        *real_outputs=mapsFromPyDict(arg3);     
    278312#ifdef DEBUG
    279313        fprintf(stderr,"Result of call: %i\n", PyInt_AsLong(pValue));
     
    281315        dumpMaps(*real_outputs);
    282316#endif
    283       }else{     
     317      }else{
    284318        PythonZooReport(m,tmp->value,0);
    285319        res=-1;
     
    301335#endif
    302336  PyThreadState_Swap(mainstate);
    303   Py_Finalize();
     337  Py_Finalize(); 
    304338  return res;
    305339}
     
    323357  char *pbt=NULL;
    324358  if(PyString_Check(trace)){
    325     pbt=(char*)malloc((7+strlen(PyString_AsString(trace))+1)*sizeof(char));
     359    pbt=(char*)malloc((8+strlen(PyString_AsString(trace)))*sizeof(char));
    326360    sprintf(pbt,"TRACE: %s",PyString_AsString(trace));
    327361  }
    328362  else
    329363    fprintf(stderr,"EMPTY TRACE ?");
    330  
     364
    331365  trace=NULL;
    332366 
     
    425459  map* isArray=getMap(tmp,"isArray");
    426460  map* size=getMap(tmp,"size");
     461  map* useFile=getMap(tmp,"use_file");
     462  map* cacheFile=getMap(tmp,"cache_file");
    427463  map* tmap=getMapType(tmp);
    428464  while(tmp!=NULL){
     
    435471        PyObject* mvalue=PyList_New(cnt);
    436472        PyObject* svalue=PyList_New(cnt);
     473        PyObject* cvalue=PyList_New(cnt);
    437474
    438475        for(int i=0;i<cnt;i++){
    439476         
    440           map* vMap=getMapArray(tmp,"value",i);     
    441           map* sMap=getMapArray(tmp,"size",i);
     477          map* vMap=getMapArray(t,"value",i);
     478          map* uMap=getMapArray(t,"use_file",i);
     479          map* sMap=getMapArray(t,"size",i);
     480          map* cMap=getMapArray(t,"cache_file",i);
    442481
    443482          if(vMap!=NULL){
     
    445484            PyObject* lvalue;
    446485            PyObject* lsvalue;
    447             if(sMap==NULL){
     486            PyObject* lcvalue;
     487            if(sMap==NULL || uMap!=NULL){
    448488              lvalue=PyString_FromString(vMap->value);
    449               lsvalue=Py_None;
    450489            }
    451490            else{   
    452491              lvalue=PyString_FromStringAndSize(vMap->value,atoi(sMap->value));
     492            }
     493            if(sMap!=NULL){
    453494              lsvalue=PyString_FromString(sMap->value);
    454495              hasSize=1;
    455496            }
     497            else
     498              lsvalue=Py_None;
     499            if(uMap!=NULL){
     500              lcvalue=PyString_FromString(cMap->value);;
     501            }else
     502              lcvalue=Py_None;
    456503
    457504            if(PyList_SetItem(value,i,lvalue)<0){
     
    463510              return NULL;
    464511            }
     512            if(PyList_SetItem(cvalue,i,lcvalue)<0){
     513              fprintf(stderr,"Unable to set key value pair...");
     514              return NULL;
     515            }
    465516          }
    466517         
     518          PyObject* lmvalue;
    467519          map* mMap=getMapArray(tmp,tmap->name,i);
    468           PyObject* lmvalue;
    469520          if(mMap!=NULL){
    470521            lmvalue=PyString_FromString(mMap->value);
     
    487538          return NULL;
    488539        }
     540        if(PyDict_SetItem(res,PyString_FromString("cache_file"),cvalue)<0){
     541          fprintf(stderr,"Unable to set key value pair...");
     542          return NULL;
     543        }
    489544        if(hasSize>0)
    490545          if(PyDict_SetItem(res,PyString_FromString("size"),svalue)<0){
     
    493548          }
    494549      }
    495       else if(size!=NULL){
     550      else if(size!=NULL && useFile==NULL){
    496551        PyObject* value=PyString_FromStringAndSize(tmp->value,atoi(size->value));
    497552        if(PyDict_SetItem(res,name,value)<0){
  • trunk/zoo-project/zoo-kernel/service_internal_python.h

    r640 r917  
    22 * Author : Gérald FENOY
    33 *
    4  * Copyright (c) 2009-2010 GeoLabs SARL
     4 * Copyright (c) 2009-2019 GeoLabs SARL
    55 *
    66 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    2828#pragma once
    2929
     30#include <Python.h>
    3031#include "service_internal.h"
    3132#include "response_print.h"
    32 #include <Python.h>
    33 #include "cgic.h"
    3433#ifdef WIN32
    3534#include <windows.h>
  • trunk/zoo-project/zoo-kernel/service_internal_ruby.c

    r790 r917  
    260260  int hasSize=0;
    261261  map* isArray=getMap(tmp,"isArray");
     262  map* useFile=getMap(tmp,"use_file");
    262263  map* size=getMap(tmp,"size");
    263264  map* tmap=getMapType(tmp);
     
    271272        VALUE mvalue=rb_ary_new2(cnt);
    272273        VALUE svalue=rb_ary_new2(cnt);
     274        VALUE cvalue=rb_ary_new2(cnt);
    273275
    274276        for(int i=0;i<cnt;i++){
     
    276278          map* vMap=getMapArray(tmp,"value",i);     
    277279          map* sMap=getMapArray(tmp,"size",i);
     280          map* uMap=getMapArray(tmp,"use_file",i);
     281          map* cMap=getMapArray(tmp,"cache_file",i);
    278282
    279283          if(vMap!=NULL){
     
    281285            VALUE lvalue;
    282286            VALUE lsvalue;
    283             if(sMap==NULL){
     287            VALUE lcvalue;
     288            if(sMap==NULL || uMap==NULL){
    284289              lvalue=rb_str_new2(vMap->value);
    285               lsvalue=Qnil;
     290              if(sMap==NULL)
     291                lsvalue=Qnil;
     292              else
     293                lsvalue=rb_str_new2(sMap->value);
    286294            }
    287295            else{
     
    290298              hasSize=1;
    291299            }
     300            if(uMap!=NULL)
     301              lcvalue=rb_str_new2(cMap->value);
     302            else
     303              lcvalue=Qnil;
    292304
    293305            rb_ary_push(value,lvalue);
    294306            rb_ary_push(svalue,lsvalue);
     307            rb_ary_push(cvalue,lcvalue);
    295308          }
    296309         
     
    308321        rb_hash_aset(res, name, mvalue);
    309322        rb_hash_aset(res, rb_str_new2(tmap->name), mvalue);
     323        VALUE lname0=rb_str_new2("cache_size");
     324        rb_hash_aset(res, lname0, value);
    310325     
    311326        if(hasSize>0){
  • trunk/zoo-project/zoo-kernel/service_internal_saga.c

    r790 r917  
    3030#include <api_core.h>
    3131#include <data_manager.h>
    32 #include <module_library.h>
     32#include <saga_api.h>
    3333#define _ZOO_SAGA
    3434#include "service_internal_saga.h"
     
    237237        return false;
    238238      }
    239       return( param->Set_Value(SG_Get_Data_Manager().Find(&fileName)) );
     239      fprintf(stderr,"%s %s\n",carg->name,carg->value);
     240      fflush(stderr);
     241      return( param->Set_Value(SG_Get_Data_Manager().Find(&fileName,false)) );
    240242    }
    241243    else
     
    250252            SG_Get_Data_Manager().Add(&fileName);
    251253          }
    252           param->asList()->Add_Item(SG_Get_Data_Manager().Find(&fileName));
     254          param->asList()->Add_Item(SG_Get_Data_Manager().Find(&fileName,false));
    253255        }
    254256      }
     
    327329            inmap=getMap(argument,(CSG_String(param->Get_Identifier())+"_MIN").b_str());
    328330            if(inmap!=NULL)
     331#if SAGA_MAJOR_VERSION == 2           
    329332              param->asRange()->Set_LoVal(strtod(inmap->value,NULL));
     333#else
     334              param->asRange()->Set_Min(strtod(inmap->value,NULL));
     335#endif     
    330336            inmap=getMap(argument,(CSG_String(param->Get_Identifier())+"_MAX").b_str());
    331337            if(inmap!=NULL)
     338#if SAGA_MAJOR_VERSION == 2           
    332339              param->asRange()->Set_HiVal(strtod(inmap->value,NULL));       
     340#else
     341              param->asRange()->Set_Max(strtod(inmap->value,NULL));
     342#endif     
    333343          }
    334344          if(inmap==NULL){
     
    386396            else if( param->is_DataObject_List() )
    387397              {
    388                 for(int i=0; i<param->asList()->Get_Count(); i++)
     398                for(int i=0; i<
     399#if SAGA_MAJOR_VERSION == 2
     400                      param->asList()->Get_Count()
     401#else
     402                      param->asList()->Get_Data_Count()
     403#endif               
     404                      ; i++)
    389405                  {
    390                     CSG_Data_Object *pObject = param->asList()->asDataObject(i);
     406                    CSG_Data_Object *pObject =
     407#if SAGA_MAJOR_VERSION == 2                   
     408                      param->asList()->asDataObject(i)
     409#else
     410                      param->asList()->Get_Data(i)
     411#endif               
     412                      ;
    391413                   
    392414                    if( pObject->is_Modified() && SG_File_Exists(pObject->Get_File_Name()) )
     
    439461                        }
    440462                    }
    441                  
     463#if SAGA_MAJOR_VERSION == 2               
    442464                  int nFileNames = param->asList()->Get_Count() <= fileNames.Get_Count() ? fileNames.Get_Count() : fileNames.Get_Count() - 1;
    443465                  for(int i=0; i<param->asList()->Get_Count(); i++)
     
    458480                                  CSG_String(param->asList()->asDataObject(i)->Get_File_Name()).b_str());
    459481                    }
     482#else
     483                  int nFileNames = param->asList()->Get_Data_Count() <= fileNames.Get_Count() ? fileNames.Get_Count() : fileNames.Get_Count() - 1;
     484                  for(int i=0; i<param->asList()->Get_Data_Count(); i++)
     485                    {
     486                      if( i < nFileNames )
     487                        {
     488                          param->asList()->Get_Data(i)->Save(fileNames[i]);
     489                        }
     490                      else
     491                        {
     492                          param->asList()->Get_Data(i)->Save(CSG_String::Format(SG_T("%s_%0*d"),
     493                                                                                    fileNames[fileNames.Get_Count() - 1].c_str(),
     494                                                                                    SG_Get_Digit_Count(param->asList()->Get_Data_Count()),
     495                                                                                    1 + i - nFileNames
     496                                                                                    ));
     497                        }
     498                      setMapArray(cMaps->content,"generated_file",i,
     499                                  CSG_String(param->asList()->Get_Data(i)->Get_File_Name()).b_str());
     500                    }
     501                 
     502#endif           
    460503                }
    461504            }
     
    477520  int res=SERVICE_FAILED;
    478521
     522#if SAGA_MAJOR_VERSION == 2 
    479523  CSG_Module_Library * library=SG_Get_Module_Library_Manager().Get_Library(CSG_String(lib_name),true);
     524#else
     525  CSG_Tool_Library * library=SG_Get_Tool_Library_Manager().Get_Library(CSG_String(lib_name),true);
     526#endif 
    480527  if( library == NULL){
    481528    char tmp[255];
     
    486533  }
    487534
     535#if SAGA_MAJOR_VERSION == 2 
    488536  CSG_Module * module=library->Get_Module(atoi(module_name));
     537#else
     538  CSG_Tool * module=library->Get_Tool(atoi(module_name));
     539#endif 
    489540  if(module == NULL){
    490541    char tmp[255];
     
    9851036  SG_Set_UI_Callback(Get_Callback(watcher));
    9861037
     1038#if SAGA_MAJOR_VERSION == 2 
    9871039  int n = SG_Get_Module_Library_Manager().Add_Directory(wxT(MODULE_LIBRARY_PATH),false);
    988   if( SG_Get_Module_Library_Manager().Get_Count() <= 0 ){
     1040  if( SG_Get_Module_Library_Manager().Get_Count() <= 0 )
     1041#else
     1042  int n = SG_Get_Tool_Library_Manager().Add_Directory(wxT(MODULE_LIBRARY_PATH),false);
     1043  if( SG_Get_Tool_Library_Manager().Get_Count() <= 0 )
     1044#endif
     1045  {
    9891046    setMapInMaps(*main_conf,"lenv","message","Could not load any SAGA tool library");
    9901047    res=SERVICE_FAILED;
     
    9951052
    9961053  // Load the SAGA-GIS library corresponding to the serviceProvider
     1054#if SAGA_MAJOR_VERSION == 2 
    9971055  CSG_Module_Library * library=SG_Get_Module_Library_Manager().Get_Library(CSG_String(serviceProvider->value),true);
     1056#else
     1057  CSG_Tool_Library * library=SG_Get_Tool_Library_Manager().Get_Library(CSG_String(serviceProvider->value),true);
     1058#endif
    9981059  if( library == NULL){
    9991060    char tmp[255];
     
    10051066 
    10061067  // Load the SAGA-GIS module corresponding to the service name from the library
     1068#if SAGA_MAJOR_VERSION == 2 
    10071069  CSG_Module * module=library->Get_Module(atoi(s->name));
     1070#else
     1071  CSG_Tool * module=library->Get_Tool(atoi(s->name));
     1072#endif
    10081073  if(module == NULL){
    10091074    char tmp[255];
     
    10171082  // Load all the parameters defined for the module
    10181083  CSG_Parameters * params=module->Get_Parameters();
    1019   int pc=params->Get_Count();
    10201084  if(!params){
    10211085    char tmp[255];
     
    10261090    return res;
    10271091  }
     1092  int pc=params->Get_Count();
    10281093
    10291094  // Loop over each inputs to transform raster files to grid when needed,
  • trunk/zoo-project/zoo-kernel/service_yaml.c

    r790 r917  
    487487              addMapToIoType(&current_element->supported,current_content);
    488488          }
    489           freeMaps(&current_content);
     489          freeMap(&current_content);
    490490          free(current_content);
    491491          current_content=NULL;
  • trunk/zoo-project/zoo-kernel/sql/schema.sql

    r781 r917  
    3131-- Create a dedicated schema to store all tables
    3232-- Uncomment the following 2 lines to activate the schema use
    33 -- CREATE SCHEMA zoo;
    34 -- SET search_path TO zoo;
     33-- CREATE SCHEMA processdb;
     34-- SET search_path TO processdb;
    3535--------------------------------------------------------------------------------
    3636-- Services table
  • trunk/zoo-project/zoo-kernel/sqlapi.c

    r786 r917  
    11/*
    2  * Author : David Saggiorato
    3  *          Gérald Fenoy
     2 * Authors : David Saggiorato
     3 *           Gérald Fenoy
    44 *  Copyright 2015 GeoLabs SARL. All rights reserved.
    55 *
     
    2323 */
    2424
    25 #ifdef RELY_ON_DB
    2625#include "ogr_api.h"
    2726#include "ogrsf_frmts.h"
     
    4443OGRDataSource
    4544#endif
    46  *zoo_DS = NULL;
     45 **zoo_DS = NULL;
    4746
    4847/**
     
    5251
    5352/**
    54  * Create a GDAL / OGR string for connecting to the db backend
    55  * (do not support active_schema)
    56  *
    57  * @param conf the maps containing the setting of the main.cfg file
    58  */
    59 char* createInitString(maps* conf){
     53 * Create a GDAL / OGR string for connecting to a db backend defined in the
     54 * key section.
     55 *
     56 * @param conf the maps containing the setting of the main.cfg file
     57 * @param key the name of the section containing the connection setting
     58 * @return the OGR connection string
     59 */
     60char* _createInitString(maps* conf,const char* key){
    6061  char* res=NULL;
    61   char keywords[5][9]={
     62  char keywords[6][14]={
    6263    "dbname",
    6364    "host",
    6465    "port",
    6566    "user",
    66     "password"
     67    "password",
     68    "active_schema"   
    6769  };
    6870  int i=0;
    69   maps* cconf=getMaps(conf,"database");
     71  maps* cconf=getMaps(conf,key);
     72  if(cconf==NULL){
     73    fprintf(stderr,"%s %d\n",__FILE__,__LINE__);
     74    return "-1";
     75  }
    7076  int len=0;
    71   for(i=0;i<5;i++){
     77  for(i=0;i<6;i++){
    7278    map* tmp=getMap(cconf->content,keywords[i]);
    7379    if(tmp!=NULL){
     
    98104
    99105/**
    100  * Connect to the db backend.
     106 * Create a GDAL / OGR string for connecting to the db backend
     107 *
     108 * @param conf the maps containing the setting of the main.cfg file
     109 * @return the OGR connection string
     110 */
     111char* createInitString(maps* conf){
     112  return _createInitString(conf,"database");
     113}
     114
     115/**
     116 * Connect to a db backend.
    101117 *
    102118 * @param conf the maps containing the setting of the main.cfg file
    103119 * @see createInitString
    104120 */
    105 void init_sql(maps* conf){
    106   char* sqlInitString=createInitString(conf);
     121int _init_sql(maps* conf,const char* key){
     122  char* sqlInitString=_createInitString(conf,key);
     123#ifdef SQL_DEBUG
     124  fprintf(stderr,"Try to connect to: %s %s !\n",key,sqlInitString);
     125  fflush(stderr); 
     126#endif
     127  if(strncmp(sqlInitString,"-1",2)==0)
     128    return -1;
    107129  OGRSFDriver *poDriver = NULL;
    108130  OGRRegisterAll();
    109 
     131  int zoo_ds_nb=0;
     132  map* dsNb=getMapFromMaps(conf,"lenv","ds_nb");
     133  if(dsNb==NULL){
     134    setMapInMaps(conf,"lenv","ds_nb","1");
     135  }else{
     136    zoo_ds_nb=atoi(dsNb->value);
     137    char* tmp=(char*)malloc(11*sizeof(char));
     138    sprintf(tmp,"%d",zoo_ds_nb+1);
     139    setMapInMaps(conf,"lenv","ds_nb",(const char*)tmp);
     140    free(tmp);
     141  }
     142  if(zoo_DS==NULL)
     143    zoo_DS=
    110144#if GDAL_VERSION_MAJOR >= 2
    111   zoo_DS = (GDALDataset*) GDALOpenEx( sqlInitString,
     145      (GDALDataset**) malloc(sizeof(GDALDataset*))
     146#else
     147      (OGRDataSource**) malloc(sizeof(OGRDataSource*))
     148#endif
     149      ;
     150  else
     151    zoo_DS=     
     152#if GDAL_VERSION_MAJOR >= 2
     153      (GDALDataset**)realloc(zoo_DS,(zoo_ds_nb+1)*sizeof(GDALDataset*))
     154#else
     155      (OGRDataSource**)realloc(zoo_DS,(zoo_ds_nb+1)*sizeof(OGRDataSource*))
     156#endif
     157      ;
     158 
     159#if GDAL_VERSION_MAJOR >= 2
     160  zoo_DS[zoo_ds_nb] = (GDALDataset*) GDALOpenEx( sqlInitString,
    112161                                      GDAL_OF_UPDATE | GDAL_OF_VECTOR,
    113162                                      NULL, NULL, NULL );
    114163#else
    115   zoo_DS = OGRSFDriverRegistrar::Open(sqlInitString,false,&poDriver);
    116 #endif
    117   if( zoo_DS == NULL ){
    118 #ifdef DEBUG
     164  zoo_DS[zoo_ds_nb] = OGRSFDriverRegistrar::Open(sqlInitString,false,&poDriver);
     165#endif
     166  if( zoo_DS[zoo_ds_nb] == NULL ){
     167#ifdef SQL_DEBUG
    119168    fprintf(stderr,"sqlInitString: %s FAILED !\n",sqlInitString);
    120169    fflush(stderr);
    121170#endif
    122171    free(sqlInitString);
    123     setMapInMaps(conf,"lenv","message","Failed to connect to the database backend");
    124     return;
    125   }
    126 #ifdef DEBUG
     172    setMapInMaps(conf,"lenv","dbIssue","1");
     173    setMapInMaps(conf,"lenv","message",_("Failed to connect to the database backend"));
     174    return -2;
     175  }
     176#ifdef SQL_DEBUG
    127177  fprintf(stderr,"sqlInitString: %s SUCEED !\n",sqlInitString);
    128178  fflush(stderr);
    129179#endif
    130180  free(sqlInitString);
     181  zoo_ds_nb++;
     182  return zoo_ds_nb;
     183}
     184
     185/**
     186 * Connect to the db backend.
     187 *
     188 * @param conf the maps containing the setting of the main.cfg file
     189 * @see createInitString
     190 */
     191int init_sql(maps* conf){
     192  return _init_sql(conf,"database");
    131193}
    132194
     
    136198 * @param conf the maps containing the setting of the main.cfg file
    137199 */
    138 void close_sql(maps* conf){
    139   if( zoo_ResultSet != NULL )
    140     zoo_DS->ReleaseResultSet( zoo_ResultSet );
    141   if(zoo_DS!=NULL){
     200void close_sql(maps* conf,int cid){
     201  if( zoo_ResultSet != NULL ){
     202    zoo_DS[cid]->ReleaseResultSet( zoo_ResultSet );
     203    zoo_ResultSet=NULL;
     204  }
     205  if(zoo_DS!=NULL && zoo_DS[cid]!=NULL){
    142206#if GDAL_VERSION_MAJOR >= 2
    143     GDALClose(zoo_DS);
    144 #else
    145     OGRDataSource::DestroyDataSource( zoo_DS );
    146 #endif
    147     zoo_DS=NULL;
     207    GDALClose(zoo_DS[cid]);
     208#else
     209    OGRDataSource::DestroyDataSource( zoo_DS[cid] );
     210#endif
     211    zoo_DS[cid]=NULL;
    148212  }
    149213}
     
    158222
    159223/**
     224 * Fetch a tuple set by executing a SQL query to the Database Backend.
     225 *
     226 * @param conf the maps containing the setting of the main.cfg file
     227 * @param sqlQuery the SQL query to run
     228 * @return NULL in case of failure or an OGRLayer pointer if the query succeed.
     229 */
     230OGRLayer *fetchSql(maps* conf,int cid,const char* sqlQuery){
     231  if(zoo_DS==NULL || zoo_DS[cid]==NULL)
     232    return NULL;
     233  OGRLayer *res=NULL;
     234#ifdef SQL_DEBUG
     235  fprintf(stderr,"************************* %s %s %d\n\n",sqlQuery,__FILE__,__LINE__);
     236  fflush(stderr);
     237#endif
     238  res = zoo_DS[cid]->ExecuteSQL( sqlQuery, NULL, NULL);
     239  return res;
     240}
     241
     242void cleanFetchSql(maps* conf,int cid,OGRLayer *objects){
     243  if( objects != NULL ){
     244    zoo_DS[cid]->ReleaseResultSet( objects );
     245    objects=NULL;
     246  }
     247}
     248
     249/**
    160250 * Execute a SQL query to the SQL Database Backend.
    161251 *
     
    164254 * @return -1 in case of failure and 1 if the query succeed.
    165255 */
    166 int execSql(maps* conf,const char* sqlQuery){
    167   zoo_ResultSet = zoo_DS->ExecuteSQL( sqlQuery, NULL, NULL);
     256int execSql(maps* conf,int cid,const char* sqlQuery){
     257  int res=-1;
     258  if(zoo_DS == NULL || zoo_DS[cid]==NULL)
     259    return -1;
     260  zoo_ResultSet = zoo_DS[cid]->ExecuteSQL( sqlQuery, NULL, NULL);
    168261  if( zoo_ResultSet != NULL ){
    169     return 1;
    170   }
    171   return -1;
     262    res=1;
     263  }
     264  return res;
    172265}
    173266
     
    179272 * @return -1 in case of failure and 1 if the query succeed.
    180273 */
    181 void cleanUpResultSet(const maps* conf){
     274void cleanUpResultSet(const maps* conf,int cid){
    182275  if( zoo_ResultSet != NULL ){
    183     zoo_DS->ReleaseResultSet( zoo_ResultSet );
     276    zoo_DS[cid]->ReleaseResultSet( zoo_ResultSet );
    184277    zoo_ResultSet=NULL;
    185278  }
     279}
     280
     281#ifdef RELY_ON_DB
     282int getCurrentId(maps* conf){
     283  int res=0;
     284  map* dsNb=getMapFromMaps(conf,"lenv","ds_nb");
     285  if(dsNb!=NULL)
     286    res=atoi(dsNb->value);
     287  return res;
    186288}
    187289
     
    195297 */
    196298void recordStoredFile(maps* conf,const char* filename,const char* type,const char* name){
     299  int zoo_ds_nb=getCurrentId(conf);
    197300  map *uusid=getMapFromMaps(conf,"lenv","usid");
    198301  map *schema=getMapFromMaps(conf,"database","schema");
     
    202305  else
    203306    sprintf(sqlQuery,"INSERT INTO %s.files (uuid,filename,nature,name) VALUES ('%s','%s','%s',NULL);",schema->value,uusid->value,filename,type);
    204   execSql(conf,sqlQuery);
    205   free(sqlQuery);
    206   cleanUpResultSet(conf);
     307  execSql(conf,zoo_ds_nb-1,sqlQuery);
     308  free(sqlQuery);
     309  cleanUpResultSet(conf,zoo_ds_nb-1);
    207310}
    208311
     
    213316 */
    214317void recordServiceStatus(maps* conf){
     318  int zoo_ds_nb=getCurrentId(conf);
    215319  map *sid=getMapFromMaps(conf,"lenv","sid");
    216320  map *osid=getMapFromMaps(conf,"lenv","osid");
     
    230334          osid->value,
    231335          wpsStatus[2]);
    232   execSql(conf,sqlQuery);
    233   free(sqlQuery);
    234   cleanUpResultSet(conf);
     336  execSql(conf,zoo_ds_nb-1,sqlQuery);
     337  free(sqlQuery);
     338  cleanUpResultSet(conf,zoo_ds_nb-1);
    235339}
    236340
     
    242346 */
    243347void recordResponse(maps* conf,char* filename){
     348  int zoo_ds_nb=getCurrentId(conf);
    244349  FILE *file = fopen (filename, "rb");
    245350  fseek (file, 0, SEEK_END);
     
    254359  char *sqlQuery=(char*)malloc((strlen(schema->value)+flen+strlen(sid->value)+57+1)*sizeof(char));
    255360  sprintf(sqlQuery,"INSERT INTO %s.responses (content,uuid) VALUES ($$%s$$,$$%s$$);",schema->value,tmps,sid->value);
    256   execSql(conf,sqlQuery);
     361  execSql(conf,zoo_ds_nb-1,sqlQuery);
    257362  free(sqlQuery);
    258363  free(tmps);
    259   cleanUpResultSet(conf);
     364  cleanUpResultSet(conf,zoo_ds_nb-1);
    260365}
    261366
     
    267372 */
    268373int _updateStatus(maps* conf){
     374  int zoo_ds_nb=getCurrentId(conf);
    269375  map *sid=getMapFromMaps(conf,"lenv","usid");
    270376  map *p=getMapFromMaps(conf,"lenv","status");
     
    273379  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(msg->value)+strlen(p->value)+strlen(sid->value)+64+1)*sizeof(char));
    274380  sprintf(sqlQuery,"UPDATE %s.services set status=$$%s$$,message=$$%s$$ where uuid=$$%s$$;",schema->value,p->value,msg->value,sid->value);
    275   fflush(stderr);
    276   if( zoo_DS == NULL )
     381  if( zoo_DS == NULL || zoo_DS[zoo_ds_nb-1]==NULL ){
    277382    init_sql(conf);
    278   execSql(conf,sqlQuery);
    279   cleanUpResultSet(conf);
     383    zoo_ds_nb++;
     384  }
     385  execSql(conf,zoo_ds_nb-1,sqlQuery);
     386  cleanUpResultSet(conf,zoo_ds_nb-1);
    280387  free(sqlQuery);
    281388  return 0;
     
    290397 */
    291398char* _getStatus(maps* conf,char* pid){
     399  int zoo_ds_nb=getCurrentId(conf);
     400  int created=-1;
    292401  map *schema=getMapFromMaps(conf,"database","schema");
    293402  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(pid)+58+1)*sizeof(char));
    294403  sprintf(sqlQuery,"select status||'|'||message from %s.services where uuid=$$%s$$;",schema->value,pid);
    295   if( zoo_DS == NULL )
     404  if( zoo_ds_nb==
     405#ifdef META_DB
     406      1
     407#else
     408      0
     409#endif
     410      ){
    296411    init_sql(conf);
    297   execSql(conf,sqlQuery);
     412    zoo_ds_nb++;
     413    created=1;
     414  }
     415  execSql(conf,zoo_ds_nb-1,sqlQuery);
    298416  OGRFeature  *poFeature = NULL;
    299417  const char *tmp1;
     
    301419    for( int iField = 0; iField < poFeature->GetFieldCount(); iField++ ){
    302420      if( poFeature->IsFieldSet( iField ) ){
    303         tmp1=strdup(poFeature->GetFieldAsString( iField ));
     421        tmp1=zStrdup(poFeature->GetFieldAsString( iField ));
    304422      }
    305423      else
     
    308426    OGRFeature::DestroyFeature( poFeature );
    309427  }
    310   cleanUpResultSet(conf);
     428  cleanUpResultSet(conf,zoo_ds_nb-1);
    311429  free(sqlQuery);
    312430  return (char*)tmp1;
     
    321439 */
    322440char* _getStatusFile(maps* conf,char* pid){
    323   map *schema=getMapFromMaps(conf,"database","schema");
     441  int zoo_ds_nb=getCurrentId(conf);
     442  map *schema=getMapFromMaps(conf,"database","schema");
     443  OGRFeature  *poFeature = NULL;
     444  const char *tmp1=NULL;
     445  int hasRes=-1;
    324446  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(pid)+82+1)*sizeof(char));
    325447  sprintf(sqlQuery,
    326448          "select content from %s.responses where uuid=$$%s$$"
    327449          " order by creation_time desc limit 1",schema->value,pid);
    328   if( zoo_DS == NULL )
     450  if( zoo_ds_nb==
     451#ifdef META_DB
     452      1
     453#else
     454      0
     455#endif
     456      ){
    329457    init_sql(conf);
    330   execSql(conf,sqlQuery);
    331   OGRFeature  *poFeature = NULL;
    332   const char *tmp1;
    333   int hasRes=-1;
    334   while( (poFeature = zoo_ResultSet->GetNextFeature()) != NULL ){
    335     for( int iField = 0; iField < poFeature->GetFieldCount(); iField++ ){
    336       if( poFeature->IsFieldSet( iField ) ){
    337         tmp1=strdup(poFeature->GetFieldAsString( iField ));
    338         hasRes=1;
     458    zoo_ds_nb++;
     459  }
     460  execSql(conf,zoo_ds_nb-1,sqlQuery);
     461  if(zoo_ResultSet!=NULL){
     462      while( (poFeature = zoo_ResultSet->GetNextFeature()) != NULL ){
     463        for( int iField = 0; iField < poFeature->GetFieldCount(); iField++ ){
     464          if( poFeature->IsFieldSet( iField ) ){
     465            tmp1=zStrdup(poFeature->GetFieldAsString( iField ));
     466            hasRes=1;
     467          }
     468          else
     469            tmp1=NULL;
     470        }
     471        OGRFeature::DestroyFeature( poFeature );
    339472      }
    340       else
    341         tmp1=NULL;
    342     }
    343     OGRFeature::DestroyFeature( poFeature );
    344473  }
    345474  if(hasRes<0)
    346475    tmp1=NULL;
    347   cleanUpResultSet(conf);
     476  cleanUpResultSet(conf,zoo_ds_nb-1);
    348477  free(sqlQuery);
    349478  return (char*)tmp1;
     
    357486 */
    358487void removeService(maps* conf,char* pid){
     488  int zoo_ds_nb=getCurrentId(conf);
    359489  map *schema=getMapFromMaps(conf,"database","schema");
    360490  char *sqlQuery=(char*)
    361491    malloc((strlen(pid)+strlen(schema->value)+38+1)
    362492           *sizeof(char));
    363   if( zoo_DS == NULL )
     493  if( zoo_ds_nb==
     494#ifdef META_DB
     495      1
     496#else
     497      0
     498#endif
     499      ){
    364500    init_sql(conf);
     501    zoo_ds_nb++;
     502  }
    365503  sprintf(sqlQuery,
    366504          "DELETE FROM %s.services where uuid=$$%s$$;",
    367505          schema->value,pid);
    368   execSql(conf,sqlQuery);
    369   cleanUpResultSet(conf);
    370   close_sql(conf);
     506  execSql(conf,zoo_ds_nb-1,sqlQuery);
     507  cleanUpResultSet(conf,zoo_ds_nb-1);
     508  close_sql(conf,zoo_ds_nb-1);
    371509  free(sqlQuery);
    372510  end_sql();
     
    379517 */
    380518void unhandleStatus(maps* conf){
     519  int zoo_ds_nb=getCurrentId(conf);
    381520  map *schema=getMapFromMaps(conf,"database","schema");
    382521  map *sid=getMapFromMaps(conf,"lenv","usid");
     
    392531          " where uuid=$$%s$$;",
    393532          schema->value,(fstate!=NULL?fstate->value:"Failed"),sid->value);
    394   execSql(conf,sqlQuery);
    395   cleanUpResultSet(conf);
    396   close_sql(conf);
    397   free(sqlQuery);
    398   end_sql();
     533  execSql(conf,zoo_ds_nb-1,sqlQuery);
     534  cleanUpResultSet(conf,zoo_ds_nb-1);
     535  //close_sql(conf,zoo_ds_nb-1);
     536  free(sqlQuery);
     537  //end_sql();
    399538}
    400539
     
    407546 */
    408547char* getStatusId(maps* conf,char* pid){
     548  int zoo_ds_nb=getCurrentId(conf);
    409549  map *schema=getMapFromMaps(conf,"database","schema");
    410550  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(pid)+58+1)*sizeof(char));
     
    412552          "select osid from %s.services where uuid=$$%s$$",
    413553          schema->value,pid);
    414   if( zoo_DS == NULL )
     554  if( zoo_ds_nb==0 ){
    415555    init_sql(conf);
    416   execSql(conf,sqlQuery);
     556    zoo_ds_nb++;
     557  }
     558  if(execSql(conf,zoo_ds_nb-1,sqlQuery)<0)
     559    return NULL;
    417560  OGRFeature  *poFeature = NULL;
    418561  const char *tmp1;
     
    431574    tmp1=NULL;
    432575  free(sqlQuery);
     576  cleanUpResultSet(conf,zoo_ds_nb-1);
    433577  return (char*)tmp1;
    434578}
     
    441585 */
    442586void readFinalRes(maps* conf,char* pid,map* statusInfo){
     587  int zoo_ds_nb=getCurrentId(conf);
    443588  map *schema=getMapFromMaps(conf,"database","schema");
    444589  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(pid)+58+1)*sizeof(char));
     
    448593  if( zoo_DS == NULL )
    449594    init_sql(conf);
    450   execSql(conf,sqlQuery);
     595  execSql(conf,zoo_ds_nb-1,sqlQuery);
    451596  OGRFeature  *poFeature = NULL;
    452597  int hasRes=-1;
     
    461606    OGRFeature::DestroyFeature( poFeature );
    462607  }
     608  cleanUpResultSet(conf,zoo_ds_nb-1);
    463609  if(hasRes<0)
    464610    addToMap(statusInfo,"Status","Failed");
     
    476622int isRunning(maps* conf,char* pid){
    477623  int res=0;
     624  int zoo_ds_nb=getCurrentId(conf);
    478625  map *schema=getMapFromMaps(conf,"database","schema");
    479626  char *sqlQuery=(char*)malloc((strlen(schema->value)+strlen(pid)+73+1)*sizeof(char));
    480627  sprintf(sqlQuery,"select count(*) as t from %s.services where uuid=$$%s$$ and end_time is null;",schema->value,pid);
    481   if( zoo_DS == NULL )
     628  if( zoo_ds_nb == 0 ){
    482629    init_sql(conf);
    483   execSql(conf,sqlQuery);
     630    zoo_ds_nb++;
     631  }
     632  execSql(conf,zoo_ds_nb-1,sqlQuery);
    484633  OGRFeature  *poFeature = NULL;
    485634  const char *tmp1;
     
    494643    OGRFeature::DestroyFeature( poFeature );
    495644  }
    496   cleanUpResultSet(conf);
     645  cleanUpResultSet(conf,zoo_ds_nb-1);
    497646  free(sqlQuery);
    498647  return res;
  • trunk/zoo-project/zoo-kernel/sqlapi.h

    r784 r917  
    2525#ifndef ZOO_SQLAPI_H
    2626#define ZOO_SQLAPI_H 1
    27 #ifdef RELY_ON_DB
     27
     28#ifdef META_DB
     29#include "ogrsf_frmts.h"
     30#include "ogr_p.h"
     31#if GDAL_VERSION_MAJOR >= 2
     32#include <gdal_priv.h>
     33#endif
     34#endif
     35
    2836#include "service.h"
    2937#include "service_internal.h"
     38
     39#ifdef META_DB
     40extern "C"
     41#if GDAL_VERSION_MAJOR >=2
     42  GDALDataset
     43#else
     44  OGRDataSource
     45#endif
     46  **zoo_DS;
     47#endif
    3048
    3149#ifdef __cplusplus
    3250extern "C" {
    3351#endif
    34   ZOO_DLL_EXPORT void init_sql(maps*);
    35   ZOO_DLL_EXPORT void close_sql(maps*);
    36   ZOO_DLL_EXPORT int execSql(maps*,const char*);
     52
     53 
     54#ifdef META_DB
     55  ZOO_DLL_EXPORT char* _createInitString(maps*,const char*);
     56  ZOO_DLL_EXPORT int _init_sql(maps*,const char*);
     57  ZOO_DLL_EXPORT OGRLayer *fetchSql(maps*,int,const char*);
     58  ZOO_DLL_EXPORT void cleanFetchSql(maps*,int,OGRLayer*);
     59#endif
     60#ifdef RELY_ON_DB
     61  ZOO_DLL_EXPORT int init_sql(maps*);
     62  ZOO_DLL_EXPORT void close_sql(maps*,int);
     63  ZOO_DLL_EXPORT int execSql(maps*,int,const char*);
    3764  ZOO_DLL_EXPORT void recordStoredFile(maps*,const char*,const char*,const char*);
    3865  ZOO_DLL_EXPORT void recordServiceStatus(maps*);
     
    4269  ZOO_DLL_EXPORT char* getStatusId(maps*,char*);
    4370  ZOO_DLL_EXPORT void removeService(maps*,char*);
     71  ZOO_DLL_EXPORT void end_sql();
     72#endif
    4473
    4574#ifdef __cplusplus
     
    4877
    4978#endif
    50 #endif
  • trunk/zoo-project/zoo-kernel/ulinet.c

    r889 r917  
    44 * Author : Gérald FENOY
    55 *
    6  * Copyright (c) 2008-2015 GeoLabs SARL
     6 * Copyright (c) 2008-2019 GeoLabs SARL
    77 *
    88 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    2929#define MAX_WAIT_MSECS 180*1000 /* Wait max. 180 seconds */
    3030#include "ulinet.h"
     31#include "server_internal.h"
    3132#include <assert.h>
    3233#include <ctype.h>
     34#include "fcgi_stdio.h"
    3335
    3436/**
     
    6971
    7072/**
     73 * Write the downloaded content in the file pouted by the _HINTERNET structure
     74 *
     75 * @param buffer the buffer to read
     76 * @param size size of each member
     77 * @param nmemb number of element to read
     78 * @param data the _HINTERNET structure to write in
     79 * @return the size red, -1 if buffer is NULL
     80 */
     81size_t write_data_into_file(void *buffer, size_t size, size_t nmemb, void *data)
     82{
     83   size_t realsize = size * nmemb;
     84   int writen=0;
     85   _HINTERNET *psInternet;
     86   if(buffer==NULL){
     87     buffer=NULL;
     88     return -1;
     89   }
     90   psInternet=(_HINTERNET *)data;
     91   writen+=fwrite(buffer, size, nmemb, psInternet->file);
     92   fflush(psInternet->file);
     93   psInternet->nDataLen += realsize;
     94
     95   buffer=NULL;
     96   return realsize;
     97}
     98
     99
     100/**
    71101 * In case of presence of "Set-Cookie" in the headers red, store the cookie
    72102 * identifier in cookie
     
    83113    int i;
    84114    char* tmp;
    85     int cnt;
    86     _HINTERNET *psInternet;
    87115    for(i=0;i<12;i++)
    88116#ifndef WIN32
     
    92120#endif
    93121    tmp=strtok((char*) buffer,";"); // knut: added cast to char*
    94     cnt=0;
    95     psInternet=(_HINTERNET *)data;
     122    int cnt=0;
     123    _HINTERNET *psInternet=(_HINTERNET *)data;
    96124    if(tmp!=NULL && psInternet!=NULL){
    97125      psInternet->cookie=(char*)malloc(sizeof(char)*(strlen(tmp)+1));
     
    211239  HINTERNET ret;
    212240  ret.handle=curl_multi_init();
    213   ret.agent=strdup(lpszAgent);
     241  ret.agent=zStrdup(lpszAgent);
    214242  ret.nb=0;
     243  ret.waitingRequests[ret.nb] = NULL;
    215244  ret.ihandle[ret.nb].header=NULL;
     245  ret.ihandle[ret.nb].handle=NULL;
     246  ret.ihandle[ret.nb].hasCacheFile=0;
     247  ret.ihandle[ret.nb].nDataAlloc = 0;
     248  ret.ihandle[ret.nb].url = NULL;
     249  ret.ihandle[ret.nb].mimeType = NULL;
     250  ret.ihandle[ret.nb].cookie = NULL;
     251  ret.ihandle[ret.nb].nDataLen = 0;
     252  ret.ihandle[ret.nb].nDataAlloc = 0;
     253  ret.ihandle[ret.nb].pabyData = NULL;
     254  ret.ihandle[ret.nb].post = NULL;
    216255  return ret;
     256}
     257
     258/**
     259 * Verify if the URL should use a shared cache or not.
     260 *
     261 * In case the security section contains a key named "shared", then if the
     262 * domain listed in the shared key are contained in the url given as parameter
     263 * then it return "SHARED" in other cases, it returns "OTHER".
     264 *
     265 * @param conf the main configuration file maps
     266 * @param url the URL to evaluate
     267 * @return a string "SHARED" in case the host is in a domain listed in the
     268 * shared key, "OTHER" in other cases.
     269 */
     270char* getProvenance(maps* conf,const char* url){
     271  map* sharedCache=getMapFromMaps(conf,"security","shared");
     272  char *res="OTHER";
     273  char *paths[2]={
     274    "mapserverAddress",
     275    "tmpUrl"
     276  };
     277  if(sharedCache!=NULL){
     278    char *hosts=sharedCache->value;
     279    char *curs=strtok(hosts,",");
     280    while(curs!=NULL){
     281      if(strstr(url,curs)==NULL){
     282        return "SHARED";
     283      }
     284      curs=strtok(NULL,",");
     285    }
     286  }
     287  for(int i=0;i<2;i++){
     288    sharedCache=getMapFromMaps(conf,"main",paths[i]);
     289    if(sharedCache!=NULL){
     290      if(strstr(url,sharedCache->value)!=NULL){
     291        return "LOCAL";
     292      }
     293    }
     294  }
     295  return res;
    217296}
    218297
     
    244323 * @return 1 if the host is listed as protected, 0 in other case
    245324 */
    246 int isProtectedHost(const char* protectedHosts,const char* url){
    247   char *token, *saveptr;
    248   int cnt;
    249   char* host;
    250  
    251   // knut: make a copy of url since strtok family modifies first argument and cannot be used on constant strings 
    252   char* urlcpy = (char*) malloc(sizeof(char)*(strlen(url)+1));
    253   urlcpy = strncpy(urlcpy, url, strlen(url)+1); // since count > strlen(url), a null character is properly appended
    254  
    255   //token = strtok_r (url, "//", &saveptr);
    256   token = strtok_r (urlcpy, "//", &saveptr);   // knut
    257   cnt=0;
    258   while(token!=NULL && cnt<=1){
    259     fprintf(stderr,"%s %d %s \n",__FILE__,__LINE__,token);
    260     if(cnt==1)
    261       fprintf(stderr,"%s %d %s \n",__FILE__,__LINE__,strstr(protectedHosts,token));
    262     fflush(stderr);
    263     if(cnt==1 && strstr(protectedHosts,token)!=NULL){
    264       fprintf(stderr,"%s %d %s \n",__FILE__,__LINE__,strstr(protectedHosts,token));
    265       free(urlcpy);
    266       return 1;
    267     }
    268     token = strtok_r (NULL, "/", &saveptr);
    269     cnt+=1;
    270   }
    271   free(urlcpy);
    272   return 0;
     325int isProtectedHost(const char* protectedHosts, const char* url) {
     326        char *token, *saveptr;
     327        int cnt;
     328        char* host;
     329
     330        // knut: make a copy of url since strtok family modifies first argument and cannot be used on constant strings 
     331        char* urlcpy = (char*)malloc(sizeof(char)*(strlen(url) + 1));
     332        urlcpy = strncpy(urlcpy, url, strlen(url) + 1); // since count > strlen(url), a null character is properly appended
     333
     334        //token = strtok_r (url, "//", &saveptr);
     335        token = strtok_r(urlcpy, "//", &saveptr);   // knut
     336        cnt = 0;
     337        while (token != NULL && cnt <= 1) {
     338                fprintf(stderr, "%s %d %s \n", __FILE__, __LINE__, token);
     339                if (cnt == 1)
     340                        fprintf(stderr, "%s %d %s \n", __FILE__, __LINE__, strstr(protectedHosts, token));
     341                fflush(stderr);
     342                if (cnt == 1 && strstr(protectedHosts, token) != NULL) {
     343                        fprintf(stderr, "%s %d %s \n", __FILE__, __LINE__, strstr(protectedHosts, token));
     344                        free(urlcpy);
     345                        return 1;
     346                }
     347                token = strtok_r(NULL, "/", &saveptr);
     348                cnt += 1;
     349        }
     350        free(urlcpy);
     351        return 0;
    273352}
    274353
     
    289368  if(passThrough!=NULL && targetHosts!=NULL){
    290369    char *tmp=zStrdup(passThrough->value);
    291     char *token, *saveptr;
    292     int i;   
    293     token = strtok_r (tmp, ",", &saveptr);
     370    int i;
    294371    for(i=0;i<handle->nb;i++){
    295       if(targetHosts->value[0]=='*' || isProtectedHost(targetHosts->value,handle->ihandle[i].url)==1){
     372      if(strstr(targetHosts->value,"*")!=NULL || isProtectedHost(targetHosts->value,handle->ihandle[i].url)==1){
     373        char *token, *saveptr;
     374        token = strtok_r (tmp, ",", &saveptr);
    296375        while (token != NULL){
    297           int j;
    298       map* tmpMap;       
    299376          int length=strlen(token)+6;
    300377          char* tmp1=(char*)malloc(length*sizeof(char));
     378          map* tmpMap;
    301379          snprintf(tmp1,6,"HTTP_");
     380          int j;
    302381          for(j=0;token[j]!='\0';j++){
    303382            if(token[j]!='-')
    304               tmp1[5+j]=toupper(token[i]);
     383              tmp1[5+j]=toupper(token[j]);
    305384            else
    306385              tmp1[5+j]='_';
    307386            tmp1[5+j+1]='\0';
    308387          }
    309           fprintf(stderr,"%s %d %s \n",__FILE__,__LINE__,tmp1);
    310388          tmpMap = getMapFromMaps(conf,"renv",tmp1);
    311           if(tmpMap!=NULL)         
     389          if(tmpMap!=NULL){
    312390            AddMissingHeaderEntry(&handle->ihandle[i],token,tmpMap->value);
    313           free(tmp1);
     391          }
    314392          if(handle->ihandle[i].header!=NULL)
    315393            curl_easy_setopt(handle->ihandle[i].handle,CURLOPT_HTTPHEADER,handle->ihandle[i].header);
     394          free(tmp1);
    316395          cnt+=1;
    317396          token = strtok_r (NULL, ",", &saveptr);
     
    330409void InternetCloseHandle(HINTERNET* handle0){
    331410  int i=0;
    332   for(i=0;i<handle0->nb;i++){
    333     _HINTERNET handle=handle0->ihandle[i];
    334     if(handle.hasCacheFile>0){
    335       fclose(handle.file);
    336       unlink(handle.filename);
    337     }
    338     else{
    339       handle.pabyData = NULL;
    340       handle.nDataAlloc = handle.nDataLen = 0;
    341     }
    342     if(handle0->ihandle[i].header!=NULL){
    343       curl_slist_free_all(handle0->ihandle[i].header);
    344       handle0->ihandle[i].header=NULL;
    345     }
    346     if(handle.post!=NULL)
    347       free(handle.post);
    348     if(handle.url!=NULL)
    349       free(handle.url);
    350     if(handle.mimeType!=NULL)
    351       free(handle.mimeType);
    352     if(handle.cookie!=NULL)
    353       free(handle.cookie);
    354   }
    355   if(handle0->handle)
    356     curl_multi_cleanup(handle0->handle);
    357   free(handle0->agent);
    358   for(i=handle0->nb-1;i>=0;i--){
    359     free(handle0->waitingRequests[i]);
     411  if(handle0!=NULL){
     412    for(i=0;i<handle0->nb;i++){
     413      _HINTERNET handle=handle0->ihandle[i];
     414      if(handle.hasCacheFile>0){
     415        fclose(handle.file);
     416        unlink(handle.filename);
     417        free(handle.filename);
     418      }
     419      else{
     420        handle.pabyData = NULL;
     421        handle.nDataAlloc = handle.nDataLen = 0;
     422      }
     423      if(handle.header!=NULL){
     424        curl_slist_free_all(handle.header);
     425        handle.header=NULL;
     426      }
     427      if(handle.post!=NULL){
     428        free(handle.post);
     429        handle.post=NULL;
     430      }
     431      if(handle.url!=NULL){
     432        free(handle.url);
     433        handle.url=NULL;
     434      }
     435      if(handle.mimeType!=NULL){
     436        free(handle.mimeType);
     437        handle.mimeType=NULL;
     438      }
     439      if(handle.cookie!=NULL){
     440        free(handle.cookie);
     441        handle.cookie=NULL;
     442      }
     443      if(handle0->waitingRequests[i]!=NULL){
     444        free(handle0->waitingRequests[i]);
     445        handle0->waitingRequests[i]=NULL;
     446      }
     447    }
     448    if(handle0->handle)
     449      curl_multi_cleanup(handle0->handle);
     450    if(handle0->agent!=NULL){
     451      free(handle0->agent);
     452      handle0->agent=NULL;
     453    }
    360454  }
    361455}
     
    370464 * @param dwFlags desired download mode (INTERNET_FLAG_NO_CACHE_WRITE for not using cache file)
    371465 * @param dwContext not used
    372  */
    373 HINTERNET InternetOpenUrl(HINTERNET* hInternet,LPCTSTR lpszUrl,LPCTSTR lpszHeaders,size_t dwHeadersLength,size_t dwFlags,size_t dwContext){
     466 * @param conf the main configuration file maps pointer
     467 * @return the updated HINTERNET
     468 */
     469HINTERNET InternetOpenUrl(HINTERNET* hInternet,LPCTSTR lpszUrl,LPCTSTR lpszHeaders,size_t dwHeadersLength,size_t dwFlags,size_t dwContext,const maps* conf){
    374470
    375471  char filename[255];
     472  int ldwFlags=INTERNET_FLAG_NEED_FILE;
    376473  struct MemoryStruct header;
     474  map* memUse=getMapFromMaps((maps*) conf,"main","memory"); // knut: addad cast to maps*
    377475
    378476  hInternet->ihandle[hInternet->nb].handle=curl_easy_init( );
     
    407505#endif
    408506
    409      
    410   switch(dwFlags)
     507  if(memUse!=NULL && strcasecmp(memUse->value,"load")==0)
     508    ldwFlags=INTERNET_FLAG_NO_CACHE_WRITE;
     509 
     510  switch(ldwFlags)
    411511    {
    412512    case INTERNET_FLAG_NO_CACHE_WRITE:
    413       hInternet->ihandle[hInternet->nb].hasCacheFile=-1;
    414513      curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEFUNCTION, write_data_into);
    415514      curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEDATA, (void*)&hInternet->ihandle[hInternet->nb]);
     515      hInternet->ihandle[hInternet->nb].hasCacheFile=-1;
    416516      break;
    417517    default:
    418       sprintf(hInternet->ihandle[hInternet->nb].filename,"/tmp/ZOO_Cache%d",(int)time(NULL));
    419       hInternet->ihandle[hInternet->nb].filename[24]=0;
    420 #ifdef MSG_LAF_VERBOSE
    421       fprintf(stderr,"file=%s",hInternet->ihandle[hInternet->nb].filename);
    422 #endif
    423       hInternet->ihandle[hInternet->nb].filename=filename;
     518      memset(filename,0,255);
     519      char* tmpUuid=get_uuid();
     520      map* tmpPath=NULL;
     521      if(conf!=NULL){
     522        tmpPath=getMapFromMaps((maps*) conf,"main","tmpPath"); // knut added cast to maps*
     523      }
     524      if(tmpPath==NULL)
     525        sprintf(filename,"/tmp/ZOO_Cache%s", tmpUuid);
     526      else
     527        sprintf(filename,"%s/ZOO_Cache%s", tmpPath->value,tmpUuid);
     528      free(tmpUuid);
     529      hInternet->ihandle[hInternet->nb].filename=zStrdup(filename);
    424530      hInternet->ihandle[hInternet->nb].file=fopen(hInternet->ihandle[hInternet->nb].filename,"w+");
    425    
    426531      hInternet->ihandle[hInternet->nb].hasCacheFile=1;
    427       curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEFUNCTION, NULL);
    428       curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEDATA, hInternet->ihandle[hInternet->nb].file);
    429       hInternet->ihandle[hInternet->nb].nDataLen=0;
     532      curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEFUNCTION, write_data_into_file);
     533      curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle, CURLOPT_WRITEDATA, (void*)&hInternet->ihandle[hInternet->nb]);
    430534      break;
    431535    }
     
    443547    curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle,CURLOPT_VERBOSE,1);
    444548#endif
    445     hInternet->ihandle[hInternet->nb].post=strdup(lpszHeaders);
     549    hInternet->ihandle[hInternet->nb].post=zStrdup(lpszHeaders);
    446550    curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle,CURLOPT_POSTFIELDS,hInternet->ihandle[hInternet->nb].post);
    447551    curl_easy_setopt(hInternet->ihandle[hInternet->nb].handle,CURLOPT_POSTFIELDSIZE,(long)dwHeadersLength);
     
    457561  hInternet->ihandle[hInternet->nb].header=NULL;
    458562  ++hInternet->nb;
     563  hInternet->ihandle[hInternet->nb].header=NULL;
    459564
    460565#ifdef ULINET_DEBUG
     
    472577 */
    473578int processDownloads(HINTERNET* hInternet){
    474   int still_running=0;
     579  int still_running=0,numfds;
    475580  int msgs_left=0;
    476581  int i=0;
    477582  do{
    478     curl_multi_perform(hInternet->handle, &still_running);
     583    CURLMcode mc;
     584    mc = curl_multi_perform(hInternet->handle, &still_running);
     585    if(mc==CURLM_OK){
     586#if LIBCURL_VERSION_MINOR >= 28
     587      mc = curl_multi_wait(hInternet->handle, NULL, 0, 1000, &numfds);
     588#else
     589      struct timeval timeout;
     590      fd_set fdread;
     591      fd_set fdwrite;
     592      fd_set fdexcep;
     593      int maxfd = -1;
     594
     595      long curl_timeo = -1;
     596
     597      FD_ZERO(&fdread);
     598      FD_ZERO(&fdwrite);
     599      FD_ZERO(&fdexcep);
     600
     601      /* set a suitable timeout to play around with */
     602      timeout.tv_sec = 1;
     603      timeout.tv_usec = 0;
     604
     605      curl_multi_timeout(hInternet->handle, &curl_timeo);
     606      if(curl_timeo >= 0) {
     607        timeout.tv_sec = curl_timeo / 1000;
     608        if(timeout.tv_sec > 1)
     609          timeout.tv_sec = 1;
     610        else
     611          timeout.tv_usec = (curl_timeo % 1000) * 1000;
     612      }
     613
     614      /* get file descriptors from the transfers */
     615      mc = curl_multi_fdset(hInternet->handle, &fdread, &fdwrite, &fdexcep, &maxfd);
     616#endif
     617    }
     618    if(mc != CURLM_OK) {
     619      fprintf(stderr, "curl_multi failed, code %d.n", mc);
     620      break;
     621    }
    479622  }while(still_running); 
    480623  for(i=0;i<hInternet->nb;i++){
     
    482625    curl_easy_getinfo(hInternet->ihandle[i].handle,CURLINFO_CONTENT_TYPE,&tmp);
    483626    if(tmp!=NULL)
    484       hInternet->ihandle[i].mimeType=strdup(tmp);
     627      hInternet->ihandle[i].mimeType=zStrdup(tmp);
    485628    curl_easy_getinfo(hInternet->ihandle[i].handle,CURLINFO_RESPONSE_CODE,&hInternet->ihandle[i].code);
    486629    curl_multi_remove_handle(hInternet->handle, hInternet->ihandle[i].handle);
     
    498641 */
    499642int freeCookieList(HINTERNET hInternet){
    500   if(hInternet.ihandle[hInternet.nb].cookie)
    501     free(hInternet.ihandle[hInternet.nb].cookie);
    502   hInternet.ihandle[hInternet.nb].cookie=NULL;
     643  hInternet.ihandle[hInternet.nb].cookie=zStrdup("");
    503644#ifndef TIGER
    504645  curl_easy_setopt(hInternet.ihandle[hInternet.nb].handle, CURLOPT_COOKIELIST, "ALL");
     
    522663    fseek (hInternet.file , 0 , SEEK_END);
    523664    dwDataSize=ftell(hInternet.file); //taille du ficher
    524     rewind (hInternet.file);
     665    //dwDataSize=hInternet.nDataLen;
     666    //rewind (hInternet.file);
     667    fseek(hInternet.file, 0, SEEK_SET);
    525668  }
    526669  else{
     
    532675  }
    533676
    534   if( dwNumberOfBytesToRead /* buffer size */ < dwDataSize )
     677  if( dwNumberOfBytesToRead /* buffer size */ < dwDataSize ){
    535678    return 0;
     679  }
    536680
    537681#ifdef MSG_LAF_VERBOSE
    538   printf("\nfile size : %dko\n",dwDataSize/1024);
     682  fprintf(stderr,"\nfile size : %dko\n",dwDataSize/1024);
    539683#endif
    540684
    541685  if(hInternet.hasCacheFile>0){
    542     *lpdwNumberOfBytesRead = fread(lpBuffer,1,dwDataSize,hInternet.file);
     686    int freadRes = fread(lpBuffer,dwDataSize+1,1,hInternet.file);
     687    *lpdwNumberOfBytesRead = hInternet.nDataLen;
    543688  }
    544689  else{
  • trunk/zoo-project/zoo-kernel/ulinet.h

    r889 r917  
    22 * Author : Gérald FENOY
    33 *
    4  *  Copyright 2008-2009 GeoLabs SARL. All rights reserved.
     4 *  Copyright 2008-2019 GeoLabs SARL. All rights reserved.
    55 *
    66 * Permission is hereby granted, free of charge, to any person obtaining a copy
     
    2626#define _ULINET_H
    2727
    28 #include "fcgi_stdio.h"
    2928#include <stdlib.h>
    3029#include <fcntl.h>
    3130#include <curl/curl.h>
     31#include <curl/curlver.h>
    3232#include "service.h"
    3333#ifndef WIN32
     
    4444#include "jsapi.h"
    4545#endif
    46 /* knut: see new definition of bool in service.h
    47 #ifndef bool
    48 #define bool int
     46#ifndef __cplusplus
     47// knut: see new def of bool in service.h
     48//#ifndef bool
     49//#define bool int
     50//#endif
     51//#ifndef true
     52//#define true 1
     53//#define false 0
     54//#endif
    4955#endif
    50 #ifndef true
    51 #define true 1
    52 #define false 0
    53 #endif
    54 */
    5556
    5657#define MAX_REQ 50
     
    102103  size_t write_data_into(void*,size_t,size_t,void*);
    103104
     105  size_t write_data_into_file(void*,size_t,size_t,void*);
     106
    104107  size_t header_write_data(void*,size_t,size_t,void*);
    105108
     
    130133  HINTERNET InternetOpen(char*,int,char*,char*,int);
    131134
     135  char* getProvenance(maps*,const char*);
    132136  int isProtectedHost(const char*,const char*);
    133137  int AddMissingHeaderEntry(_HINTERNET*,const char*,const char*);
     
    153157  typedef size_t* LPDWORD;
    154158#endif
    155 /* knut: see new definition of bool in service.h
    156 #ifndef bool
    157 #define bool int
    158 #endif
    159 */
     159// knut: see new definition of bool in service.h
     160//#ifndef bool
     161//#define bool int
     162//#endif
    160163
    161164#  define CHECK_INET_HANDLE(h) (h.handle != 0)
    162165
    163   HINTERNET InternetOpenUrl(HINTERNET*,LPCTSTR,LPCTSTR,size_t,size_t,size_t);
     166  HINTERNET InternetOpenUrl(HINTERNET*,LPCTSTR,LPCTSTR,size_t,size_t,size_t,const maps*);
    164167
    165168  int processDownloads(HINTERNET*);
  • trunk/zoo-project/zoo-kernel/zoo_loader.c

    r843 r917  
    6565#endif
    6666
     67int cgiInit(){
     68  fprintf(FCGI_stderr,"ZOO-Kernel initialization %s %d ... \n",__FILE__,__LINE__);
     69  fflush(FCGI_stderr);
     70  return 0;
     71}
     72
    6773/**
    6874 * Main entry point for cgic.
     
    117123       if(res!=NULL)
    118124         free(res);
    119     }else{
     125    }else{             
    120126      char *buffer=new char[cgiContentLength+1];
    121127      if(fread(buffer,sizeof(char),cgiContentLength,cgiIn)>0){
     
    157163    }   
    158164  }
    159   else{
     165  else{   
    160166#ifdef DEBUG
    161167    dumpMap(tmpMap);
     
    181187    cgiStringArrayFree(array);
    182188  }
    183 
     189 
    184190#ifdef WIN32
    185   map *tmpReq=getMap(tmpMap,"rfile");
    186   if(tmpReq!=NULL){
    187     FILE *lf=fopen(tmpReq->value,"r");
     191  map *tmpReq=getMap(tmpMap,"rfile"); 
     192  if(tmpReq!=NULL){               
     193    FILE *lf=fopen(tmpReq->value,"r"); 
    188194    fseek(lf,0,SEEK_END);
    189195    long flen=ftell(lf);
     
    389395    }
    390396  }
    391 
     397 
    392398  if(strncasecmp(cgiContentType,"multipart/form-data",19)==0){
    393399    map* tmp=getMap(tmpMap,"dataInputs");
     
    402408  if(strQuery!=NULL)
    403409    free(strQuery);
    404 
     410 
    405411  runRequest(&tmpMap);
    406412
  • trunk/zoo-project/zoo-kernel/zoo_service_loader.c

    r889 r917  
    2626extern "C" int crlex ();
    2727
     28#ifdef META_DB
     29#include "ogrsf_frmts.h"
     30#if GDAL_VERSION_MAJOR >= 2
     31#include <gdal_priv.h>
     32#endif
     33#endif
     34
    2835#ifdef USE_OTB
    2936#include "service_internal_otb.h"
     37#endif
     38
     39#ifdef USE_R
     40#include "service_internal_r.h"
     41#endif
     42
     43#ifdef USE_HPC
     44#include "service_internal_hpc.h"
    3045#endif
    3146
     
    5570#endif
    5671
     72#ifdef META_DB
     73#include "meta_sql.h"
     74#endif
     75
    5776#ifdef USE_PYTHON
    5877#include "service_internal_python.h"
     
    87106#endif
    88107
     108#ifdef USE_CALLBACK
     109#include "service_json.h"
     110#include "service_callback.h"
     111#endif
     112
    89113#include <dirent.h>
    90114#include <signal.h>
     115#ifndef WIN32
     116#include <execinfo.h>
     117#endif
    91118#include <unistd.h>
    92119#ifndef WIN32
     
    105132#include <stdarg.h>
    106133
     134#include <libxml/tree.h>
     135#include <libxml/parser.h>
     136#include <libxml/xpath.h>
     137#include <libxml/xpathInternals.h>
     138
     139#include <libxslt/xslt.h>
     140#include <libxslt/xsltInternals.h>
     141#include <libxslt/transform.h>
     142#include <libxslt/xsltutils.h>
     143
    107144#ifndef WIN32
    108145extern char **environ;
     146#endif
     147
     148
     149#ifdef WIN32
     150extern "C"
     151{
     152  __declspec (dllexport) char *strcasestr (char const *a, char const *b)
     153#ifndef USE_MS
     154  {
     155    char *x = zStrdup (a);
     156    char *y = zStrdup (b);
     157
     158      x = _strlwr (x);
     159      y = _strlwr (y);
     160    char *pos = strstr (x, y);
     161    char *ret = pos == NULL ? NULL : (char *) (a + (pos - x));
     162      free (x);
     163      free (y);
     164      return ret;
     165  };
     166#else
     167   ;
     168#endif
     169}
    109170#endif
    110171
     
    119180
    120181#ifdef WIN32
    121   #ifndef PROGRAMNAME
    122     #define PROGRAMNAME "zoo_loader.cgi"
    123   #endif
     182#ifndef PROGRAMNAME
     183#define PROGRAMNAME "zoo_loader.cgi"
     184#endif
    124185#endif
    125186
     
    159220  lockShm (lid);
    160221#endif
    161   FILE *f3 = fopen (fbkp, "wb+"); 
    162   free (fbkp); 
     222  FILE *f3 = fopen (fbkp, "wb+");
     223  free (fbkp);
    163224  fseek (f2, 0, SEEK_END);
    164225  long flen = ftell (f2);
    165226  fseek (f2, 0, SEEK_SET);
    166227  char *tmps1 = (char *) malloc ((flen + 1) * sizeof (char));
    167   fread (tmps1, flen, 1, f2); 
     228  fread (tmps1, flen, 1, f2);
    168229#ifdef WIN32
    169230  /* knut: I think this block can be dropped; pchr may be NULL if result is not in XML format
    170   char *pchr=strrchr(tmps1,'>');   
    171   flen=strlen(tmps1)-strlen(pchr)+1; 
    172   tmps1[flen]=0; 
     231  char *pchr=strrchr(tmps1,'>');
     232  flen=strlen(tmps1)-strlen(pchr)+1;
     233  tmps1[flen]=0;
    173234  */
    174 #endif 
     235#endif
    175236  fwrite (tmps1, 1, flen, f3);
     237  fclose (f2);
     238  fclose (f3);
    176239  free(tmps1);
    177   fclose (f2);
    178   fclose (f3); 
    179240  return 1;
    180241}
     
    197258 */
    198259int
    199 recursReaddirF ( maps * m, registry *r, xmlNodePtr n, char *conf_dir,
     260recursReaddirF ( maps * m, registry *r, xmlDocPtr doc, xmlNodePtr n, char *conf_dir,
    200261                 char *prefix, int saved_stdout, int level,
    201                  void (func) (registry *, maps *, xmlNodePtr, service *) )
     262                 void (func) (registry *, maps *, xmlDocPtr, xmlNodePtr, service *) )
    202263{
    203264  struct dirent *dp;
     
    246307            setMapInMaps (m, "lenv", "level", levels1);
    247308            res =
    248               recursReaddirF (m, r, n, tmp, prefix, saved_stdout, level + 1,
     309              recursReaddirF (m, r, doc, n, tmp, prefix, saved_stdout, level + 1,
    249310                              func);
    250311            sprintf (levels1, "%d", level);
     
    264325      {
    265326        char* extn = strstr(dp->d_name, ".zcfg");
    266         if(dp->d_name[0] != '.' && extn != NULL && strlen(extn) == 5)
     327        if(dp->d_name[0] != '.' && extn != NULL && strlen(extn) == 5 && strlen(dp->d_name)>6)
    267328          {
    268329            int t;
     
    271332            snprintf (tmps1, 1024, "%s/%s", conf_dir, dp->d_name);
    272333
    273             char *tmpsn = zStrdup (dp->d_name);
    274             tmpsn[strlen (tmpsn) - 5] = 0;
     334            char *tmpsn = (char*)malloc((strlen(dp->d_name)-4)*sizeof(char));//zStrdup (dp->d_name);
     335            memset (tmpsn, 0, strlen(dp->d_name)-4);
     336            snprintf(tmpsn,strlen(dp->d_name)-4,"%s",dp->d_name);
    275337           
    276338            map* import = getMapFromMaps (m, IMPORTSERVICE, tmpsn);
    277339            if (import == NULL || import->value == NULL || zoo_path_compare(tmps1, import->value) != 0 ) { // service is not in [include] block
    278               service *s1 = (service *) malloc (SERVICE_SIZE);
     340              service *s1 = createService();
    279341              if (s1 == NULL)
    280342                {
    281                   dup2 (saved_stdout, fileno (stdout));
     343                  zDup2 (saved_stdout, fileno (stdout));
    282344                  errorException (m, _("Unable to allocate memory"),
    283345                                  "InternalError", NULL);
     
    300362                    sprintf (tmp01, _("Unable to parse the ZCFG file: %s."),
    301363                             dp->d_name);
    302                   dup2 (saved_stdout, fileno (stdout));
     364                  zDup2 (saved_stdout, fileno (stdout));
    303365                  errorException (m, tmp01, "InternalError", NULL);
    304366                  return -1;
     
    309371              fflush (stderr);
    310372  #endif
    311         inheritance(r,&s1);
    312               func (r, m, n, s1);
     373              if(s1!=NULL)
     374                inheritance(r,&s1);
     375              func (r, m, doc, n, s1);
    313376              freeService (&s1);
    314377              free (s1);
     
    344407sig_handler (int sig)
    345408{
     409 
    346410  char tmp[100];
    347411  const char *ssig;
     
    372436  sprintf (tmp,
    373437           _
    374            ("ZOO Kernel failed to process your request, receiving signal %d = %s"),
     438           ("ZOO Kernel failed to process your request, receiving signal %d = %s "),
    375439           sig, ssig);
    376440  errorException (NULL, tmp, "InternalError", NULL);
     
    420484#endif
    421485
    422   map* libp = getMapFromMaps(m, "main", "libPath");
    423 
     486  map* libp = getMapFromMaps(m, "main", "libPath"); 
    424487  if (strlen (r_inputs->value) == 1
    425488      && strncasecmp (r_inputs->value, "C", 1) == 0)
     
    610673  else
    611674
     675#ifdef USE_HPC
     676  if (strncasecmp (r_inputs->value, "HPC", 3) == 0)
     677    {
     678      *eres =
     679        zoo_hpc_support (&m, request_inputs, s1,
     680                            &request_input_real_format,
     681                            &request_output_real_format);
     682    }
     683  else
     684#endif
     685
    612686#ifdef USE_SAGA
    613   if (strncasecmp (r_inputs->value, "SAGA", 6) == 0)
     687  if (strncasecmp (r_inputs->value, "SAGA", 4) == 0)
    614688    {
    615689      *eres =
     
    622696
    623697#ifdef USE_OTB
    624   if (strncasecmp (r_inputs->value, "OTB", 6) == 0)
     698  if (strncasecmp (r_inputs->value, "OTB", 3) == 0)
    625699    {
    626700      *eres =
     
    633707#ifdef USE_PYTHON
    634708  if (strncasecmp (r_inputs->value, "PYTHON", 6) == 0)
     709    {             
     710      *eres =
     711        zoo_python_support (&m, request_inputs, s1,
     712                            &request_input_real_format,
     713                            &request_output_real_format);         
     714    }
     715  else
     716#endif
     717
     718#ifdef USE_R
     719  if (strncasecmp (r_inputs->value, "R", 6) == 0)
    635720    {     
    636721      *eres =
    637         zoo_python_support (&m, request_inputs, s1,
     722        zoo_r_support (&m, request_inputs, s1,
    638723                            &request_input_real_format,
    639724                            &request_output_real_format);
     
    713798    }
    714799  *myMap = m;
    715   *ioutputs = request_output_real_format;
     800  *ioutputs = request_output_real_format; 
    716801}
    717802
     
    902987#endif
    903988
     989 
    904990  map *r_inputs = NULL;
    905991  map *request_inputs = *inputs;
     992  //fprintf(stderr,"%s \n",json_object_to_json_string_ext(mapToJson(request_inputs),JSON_C_TO_STRING_PLAIN));
     993 
    906994#ifdef IGNORE_METAPATH
    907995  addToMap(request_inputs, "metapath", "");
     
    9351023#ifdef ETC_DIR
    9361024#ifndef WIN32
    937     getcwd (ntmp, 1024);
     1025  getcwd (ntmp, 1024);
    9381026#else
    939     _getcwd (ntmp, 1024);
     1027  _getcwd (ntmp, 1024);
    9401028#endif
    9411029#endif
     
    10131101      char tmp1[13];
    10141102      sprintf (tmp1, "LC_ALL=%s", tmp);
    1015       putenv (tmp1);
     1103      _putenv (tmp1);
    10161104#endif
    10171105      free (tmp);
     
    10251113      char tmp1[13];
    10261114      sprintf (tmp1, "LC_ALL=en_US");
    1027       putenv (tmp1);
     1115      _putenv (tmp1);
    10281116#endif
    10291117      setMapInMaps (m, "main", "language", "en-US");
     
    10351123  char tmp1[17];
    10361124  sprintf (tmp1, "LC_NUMERIC=C");
    1037   putenv (tmp1);
     1125  _putenv (tmp1);
    10381126#endif
    10391127  bind_textdomain_codeset ("zoo-kernel", "UTF-8");
     
    11271215  };
    11281216  r_inputs = getMap (request_inputs, "Request");
    1129   REQUEST = zStrdup (r_inputs->value);
     1217  if(r_inputs!=NULL)
     1218    REQUEST = zStrdup (r_inputs->value);
    11301219  int reqId=-1;
    11311220  if (strncasecmp (REQUEST, "GetCapabilities", 15) != 0){
     
    11341223    for(j=0;j<nbSupportedRequests;j++){
    11351224      if(requests[vid][j]!=NULL && requests[vid][j+1]!=NULL){
    1136         if(j<nbReqIdentifier && strncasecmp(REQUEST,requests[vid][j+1],strlen(REQUEST))==0){
     1225        if(j<nbReqIdentifier && strncasecmp(REQUEST,requests[vid][j+1],strlen(requests[vid][j+1]))==0){
    11371226          checkValidValue(request_inputs,&err,"identifier",NULL,1);
    11381227          reqId=j+1;
     
    11411230        else
    11421231          if(j>=nbReqIdentifier && j<nbReqIdentifier+nbReqJob &&
    1143              strncasecmp(REQUEST,requests[vid][j+1],strlen(REQUEST))==0){
     1232             strncasecmp(REQUEST,requests[vid][j+1],strlen(requests[vid][j+1]))==0){
    11441233            checkValidValue(request_inputs,&err,"jobid",NULL,1);
    11451234            reqId=j+1;
     
    12171306  registry* zooRegistry=NULL;
    12181307  if(reg!=NULL){
    1219     int saved_stdout = dup (fileno (stdout));
    1220     dup2 (fileno (stderr), fileno (stdout));
     1308#ifndef WIN32
     1309    int saved_stdout = zDup (fileno (stdout));
     1310    zDup2 (fileno (stderr), fileno (stdout));
     1311#endif
    12211312    if(createRegistry (m,&zooRegistry,reg->value)<0){
    12221313      map *message=getMapFromMaps(m,"lenv","message");
    12231314      map *type=getMapFromMaps(m,"lenv","type");
    1224       dup2 (saved_stdout, fileno (stdout));
     1315#ifndef WIN32
     1316      zDup2 (saved_stdout, fileno (stdout));
     1317#endif
    12251318      errorException (m, message->value,
    12261319                      type->value, NULL);
    12271320      return 0;
    12281321    }
    1229     dup2 (saved_stdout, fileno (stdout));
    1230     close(saved_stdout);
     1322#ifndef WIN32
     1323    zDup2 (saved_stdout, fileno (stdout));
     1324    zClose(saved_stdout);
     1325#endif
    12311326  }
    12321327
     
    12421337       * has been found in the zcfg and then printed on stdout
    12431338       */
    1244       int saved_stdout = dup (fileno (stdout));
    1245       dup2 (fileno (stderr), fileno (stdout));
     1339      int saved_stdout = zDup (fileno (stdout));
     1340      zDup2 (fileno (stderr), fileno (stdout));
    12461341
    12471342      maps* imports = getMaps(m, IMPORTSERVICE);
     
    12581353            }
    12591354            inheritance(zooRegistry, &svc);
    1260             printGetCapabilitiesForProcess(zooRegistry, m, n, svc);
     1355            printGetCapabilitiesForProcess(zooRegistry, m, doc, n, svc);
    12611356            freeService(&svc);
    12621357            free(svc);                             
     
    12671362
    12681363      if (int res =               
    1269           recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
     1364          recursReaddirF (m, zooRegistry, doc, n, conf_dir, NULL, saved_stdout, 0,
    12701365                          printGetCapabilitiesForProcess) < 0)
    12711366        {
     
    12821377        }
    12831378      fflush (stdout);
    1284       dup2 (saved_stdout, fileno (stdout));
    1285       printDocument (m, doc, getpid ());
     1379      zDup2 (saved_stdout, fileno (stdout));
     1380#ifdef META_DB
     1381      fetchServicesFromDb(zooRegistry,m,doc,n,printGetCapabilitiesForProcess,1);
     1382      close_sql(m,0);
     1383#endif     
     1384      printDocument (m, doc, zGetpid ());
    12861385      freeMaps (&m);
    12871386      free (m);
     
    12991398      r_inputs = getMap (request_inputs, "JobId");
    13001399      if(reqId>nbReqIdentifier){
    1301         if (strncasecmp (REQUEST, "GetStatus", strlen(REQUEST)) == 0 ||
    1302             strncasecmp (REQUEST, "GetResult", strlen(REQUEST)) == 0){
     1400        if (strncasecmp (REQUEST, "GetStatus", 9) == 0 ||
     1401            strncasecmp (REQUEST, "GetResult", 9) == 0){
    13031402          runGetStatus(m,r_inputs->value,REQUEST);
     1403#ifdef RELY_ON_DB
     1404          map* dsNb=getMapFromMaps(m,"lenv","ds_nb");
     1405          if(dsNb!=NULL && atoi(dsNb->value)>1)
     1406            close_sql(m,1);
     1407          close_sql(m,0);
     1408#endif
     1409         
    13041410          freeMaps (&m);
    1305           free (m);
     1411          free(m);
    13061412          if(zooRegistry!=NULL){
    13071413            freeRegistry(&zooRegistry);
     
    13551461            r_inputs = NULL;
    13561462            r_inputs = getMap (request_inputs, "version");
     1463#ifdef DEBUG
     1464            fprintf(stderr," ** DEBUG %s %d \n",__FILE__,__LINE__);
     1465            fflush(stderr);
     1466#endif
    13571467            xmlNodePtr n = printWPSHeader(doc,m,"DescribeProcess",
    13581468                                          root_nodes[vid][1],(version!=NULL?version->value:"1.0.0"),1);
     
    13621472            char *orig = zStrdup (r_inputs->value);
    13631473
    1364             int saved_stdout = dup (fileno (stdout));
    1365             dup2 (fileno (stderr), fileno (stdout));
     1474            int saved_stdout = zDup (fileno (stdout));
     1475            zDup2 (fileno (stderr), fileno (stdout));
    13661476            if (strcasecmp ("all", orig) == 0)
    13671477              {
     
    13791489                      }
    13801490                      inheritance(zooRegistry, &svc);
    1381                       printDescribeProcessForProcess(zooRegistry, m, n, svc);
     1491#ifdef USE_HPC
     1492                      addNestedOutputs(&svc);
     1493#endif
     1494
     1495                      printDescribeProcessForProcess(zooRegistry, m, doc, n, svc);
    13821496                      freeService(&svc);
    13831497                      free(svc);                             
     
    13881502 
    13891503                if (int res =
    1390                     recursReaddirF (m, zooRegistry, n, conf_dir, NULL, saved_stdout, 0,
     1504                    recursReaddirF (m, zooRegistry, doc, n, conf_dir, NULL, saved_stdout, 0,
    13911505                                    printDescribeProcessForProcess) < 0)
    13921506                  return res;
     1507#ifdef META_DB
     1508                fetchServicesFromDb(zooRegistry,m,doc,n,printDescribeProcessForProcess,0);
     1509                close_sql(m,0);
     1510#endif     
     1511
    13931512              }
    13941513            else
     
    14061525                    if (import != NULL && import->value != NULL)
    14071526                      {
    1408                         s1 = (service *) malloc (SERVICE_SIZE);
    1409                         t = readServiceFile (m, import->value, &s1, import->name);
     1527#ifdef META_DB                 
     1528                        service* s2=extractServiceFromDb(m,import->name,0);
     1529                        if(s2==NULL){
     1530#endif
     1531                          s1 = createService();
     1532                          t = readServiceFile (m, import->value, &s1, import->name);
    14101533               
    1411                         if (t < 0) // failure reading zcfg
    1412                           {
    1413                             map *tmp00 = getMapFromMaps (m, "lenv", "message");
    1414                             char tmp01[1024];
    1415                             if (tmp00 != NULL)
    1416                               sprintf (tmp01, _("Unable to parse the ZCFG file: %s (%s)"), import->value, tmp00->value);
    1417                             else
    1418                               sprintf (tmp01, _("Unable to parse the ZCFG file: %s."), import->value);
    1419 
    1420                             dup2 (saved_stdout, fileno (stdout));
    1421                             errorException (m, tmp01, "InternalError", NULL);
    1422            
    1423                             freeMaps (&m);
    1424                             free (m);
    1425 
    1426                             if(zooRegistry!=NULL){
    1427                               freeRegistry(&zooRegistry);
    1428                               free(zooRegistry);
     1534                          if (t < 0) // failure reading zcfg
     1535                            {
     1536                              map *tmp00 = getMapFromMaps (m, "lenv", "message");
     1537                              char tmp01[1024];
     1538                              if (tmp00 != NULL)
     1539                                sprintf (tmp01, _("Unable to parse the ZCFG file: %s (%s)"), import->value, tmp00->value);
     1540                              else
     1541                                sprintf (tmp01, _("Unable to parse the ZCFG file: %s."), import->value);
     1542                             
     1543                              zDup2 (saved_stdout, fileno (stdout));
     1544                              errorException (m, tmp01, "InternalError", NULL);
     1545                             
     1546                              freeMaps (&m);
     1547                              free (m);
     1548
     1549                              if(zooRegistry!=NULL){
     1550                                freeRegistry(&zooRegistry);
     1551                                free(zooRegistry);
     1552                              }
     1553                              free (orig);
     1554                              free (REQUEST);
     1555                              closedir (dirp);
     1556                              //xmlFreeDoc (doc);
     1557                              xmlCleanupParser ();
     1558                              zooXmlCleanupNs ();
     1559                   
     1560                              return 1;
    14291561                            }
    1430                             free (orig);
    1431                             free (REQUEST);
    1432                             closedir (dirp);
    1433                             xmlFreeDoc (doc);
    1434                             xmlCleanupParser ();
    1435                             zooXmlCleanupNs ();
    1436                    
    1437                             return 1;
    1438                           }
    1439 #ifdef DEBUG
    1440                         dumpService (s1);
    1441 #endif
    1442 
    1443                         inheritance(zooRegistry,&s1);
    1444                         printDescribeProcessForProcess (zooRegistry,m, n, s1);
    1445                         freeService (&s1);
    1446                         free (s1);
    1447                         s1 = NULL;
    1448                         scount++;
    1449                         hasVal = 1;               
    1450                     }
     1562#ifdef DEBUG
     1563                          dumpService (s1);
     1564#endif
     1565                          inheritance(zooRegistry,&s1);
     1566#ifdef USE_HPC
     1567                          addNestedOutputs(&s1);
     1568#endif
     1569                          printDescribeProcessForProcess (zooRegistry, m, doc, n, s1);
     1570                          freeService (&s1);
     1571                          free (s1);
     1572                          s1 = NULL;
     1573                          scount++;
     1574                          hasVal = 1;               
     1575#ifdef META_DB
     1576                        }
     1577#endif
     1578                      }
    14511579                    else if (strstr (corig, ".") != NULL)
    14521580                      {
     
    14571585                          addToMap (request_inputs, "metapath", tmpMap->value);
    14581586                        map *tmpMapI = getMapFromMaps (m, "lenv", "Identifier");
    1459 
    1460                         s1 = (service *) malloc (SERVICE_SIZE);
     1587                        /**
     1588                         * No support for dot in service name stored in metadb!?
     1589                         #ifdef META_DB
     1590                         service* s2=extractServiceFromDb(m,tmpMapI->value,0);
     1591                         if(s2==NULL){
     1592                         #endif
     1593                        */
     1594                        s1 = createService();
    14611595                        t = readServiceFile (m, buff1, &s1, tmpMapI->value);
    14621596                        if (t < 0)
     
    14741608                                       ("Unable to parse the ZCFG file for the following ZOO-Service: %s."),
    14751609                                       tmps);
    1476                             dup2 (saved_stdout, fileno (stdout));
     1610                            zDup2 (saved_stdout, fileno (stdout));
    14771611                            errorException (m, tmp01, "InvalidParameterValue",
    14781612                                            "identifier");
     
    14891623                            free (s1);
    14901624                            closedir (dirp);
    1491                             xmlFreeDoc (doc);
     1625                            //xmlFreeDoc (doc);
    14921626                            xmlCleanupParser ();
    14931627                            zooXmlCleanupNs ();
     
    14981632#endif
    14991633                        inheritance(zooRegistry,&s1);
    1500                         printDescribeProcessForProcess (zooRegistry,m, n, s1);
     1634#ifdef USE_HPC
     1635                        addNestedOutputs(&s1);
     1636#endif
     1637                        printDescribeProcessForProcess (zooRegistry, m, doc, n, s1);
    15011638                        freeService (&s1);
    15021639                        free (s1);
     
    15081645                    else
    15091646                      {
    1510                         memset (buff, 0, 256);
    1511                         snprintf (buff, 256, "%s.zcfg", corig);
    1512                         memset (buff1, 0, 1024);
    1513 #ifdef DEBUG
    1514                         printf ("\n#######%s\n########\n", buff);
    1515 #endif
    1516                         while ((dp = readdir (dirp)) != NULL)
    1517                           {
    1518                             if (strcasecmp (dp->d_name, buff) == 0)
    1519                               {
    1520                                 memset (buff1, 0, 1024);
    1521                                 snprintf (buff1, 1024, "%s/%s", conf_dir,
    1522                                           dp->d_name);
    1523                                 s1 = (service *) malloc (SERVICE_SIZE);
    1524                                 if (s1 == NULL)
    1525                                   {
    1526                                     dup2 (saved_stdout, fileno (stdout));
    1527                                     return errorException (m,
    1528                                                            _
    1529                                                            ("Unable to allocate memory"),
    1530                                                            "InternalError",
    1531                                                            NULL);
    1532                                   }
     1647#ifdef META_DB
     1648                        _init_sql(m,"metadb");
     1649                        //FAILED CONNECTING DB
     1650                        if(getMapFromMaps(m,"lenv","dbIssue")!=NULL){
     1651                          fprintf(stderr,"ERROR CONNECTING METADB");
     1652                        }
     1653                        service* s2=extractServiceFromDb(m,corig,0);
     1654                        if(s2!=NULL){
     1655                          inheritance(zooRegistry,&s2);
     1656#ifdef USE_HPC
     1657                          addNestedOutputs(&s2);
     1658#endif
     1659                          printDescribeProcessForProcess (zooRegistry,m, doc, n, s2);
     1660                          freeService (&s2);
     1661                          free (s2);
     1662                          s2 = NULL;
     1663                          hasVal = 1;
     1664                        }else /*TOTO*/{
     1665#endif
     1666                          memset (buff, 0, 256);
     1667                          snprintf (buff, 256, "%s.zcfg", corig);
     1668                          memset (buff1, 0, 1024);
     1669#ifdef DEBUG
     1670                          printf ("\n#######%s\n########\n", buff);
     1671#endif
     1672                          while ((dp = readdir (dirp)) != NULL)
     1673                            {
     1674                              if (strcasecmp (dp->d_name, buff) == 0)
     1675                                {
     1676                                  memset (buff1, 0, 1024);
     1677                                  snprintf (buff1, 1024, "%s/%s", conf_dir,
     1678                                            dp->d_name);
     1679                                  s1 = createService();
     1680                                  if (s1 == NULL)
     1681                                    {
     1682                                      zDup2 (saved_stdout, fileno (stdout));
     1683                                      return errorException (m,
     1684                                                             _
     1685                                                             ("Unable to allocate memory"),
     1686                                                             "InternalError",
     1687                                                             NULL);
     1688                                    }
    15331689#ifdef DEBUG_SERVICE_CONF
    1534                                 fprintf
    1535                                   (stderr,"#################\n(%s) %s\n#################\n",
    1536                                    r_inputs->value, buff1);
    1537 #endif
    1538                                 char *tmp0 = zStrdup (dp->d_name);
    1539                                 tmp0[strlen (tmp0) - 5] = 0;
    1540                                 t = readServiceFile (m, buff1, &s1, tmp0);
    1541                                 free (tmp0);
    1542                                 if (t < 0)
    1543                                   {
    1544                                     map *tmp00 =
    1545                                       getMapFromMaps (m, "lenv", "message");
    1546                                     char tmp01[1024];
    1547                                     if (tmp00 != NULL)
    1548                                       sprintf (tmp01,
    1549                                                _
    1550                                                ("Unable to parse the ZCFG file: %s (%s)"),
    1551                                                dp->d_name, tmp00->value);
    1552                                     else
    1553                                       sprintf (tmp01,
    1554                                                _
    1555                                                ("Unable to parse the ZCFG file: %s."),
    1556                                                dp->d_name);
    1557                                     dup2 (saved_stdout, fileno (stdout));
    1558                                     errorException (m, tmp01, "InternalError",
    1559                                                     NULL);
    1560                                     freeMaps (&m);
    1561                                     free (m);
    1562                                     if(zooRegistry!=NULL){
    1563                                       freeRegistry(&zooRegistry);
    1564                                       free(zooRegistry);
     1690                                  fprintf
     1691                                    (stderr,"#################\n(%s) %s\n#################\n",
     1692                                     r_inputs->value, buff1);
     1693#endif
     1694                                  char *tmp0 = zStrdup (dp->d_name);
     1695                                  tmp0[strlen (tmp0) - 5] = 0;
     1696                                  t = readServiceFile (m, buff1, &s1, tmp0);
     1697                                  free (tmp0);
     1698                                  if (t < 0)
     1699                                    {
     1700                                      map *tmp00 =
     1701                                        getMapFromMaps (m, "lenv", "message");
     1702                                      char tmp01[1024];
     1703                                      if (tmp00 != NULL)
     1704                                        sprintf (tmp01,
     1705                                                 _
     1706                                                 ("Unable to parse the ZCFG file: %s (%s)"),
     1707                                                 dp->d_name, tmp00->value);
     1708                                      else
     1709                                        sprintf (tmp01,
     1710                                                 _
     1711                                                 ("Unable to parse the ZCFG file: %s."),
     1712                                                 dp->d_name);
     1713                                      zDup2 (saved_stdout, fileno (stdout));
     1714                                      errorException (m, tmp01, "InternalError",
     1715                                                      NULL);
     1716                                      freeMaps (&m);
     1717                                      free (m);
     1718                                      if(zooRegistry!=NULL){
     1719                                        freeRegistry(&zooRegistry);
     1720                                        free(zooRegistry);
     1721                                      }
     1722                                      free (orig);
     1723                                      free (REQUEST);
     1724                                      closedir (dirp);
     1725                                      //xmlFreeDoc (doc);
     1726                                      xmlCleanupParser ();
     1727                                      zooXmlCleanupNs ();
     1728                                      return 1;
    15651729                                    }
    1566                                     free (orig);
    1567                                     free (REQUEST);
    1568                                     closedir (dirp);
    1569                                     xmlFreeDoc (doc);
    1570                                     xmlCleanupParser ();
    1571                                     zooXmlCleanupNs ();
    1572                                     return 1;
    1573                                   }
    1574 #ifdef DEBUG
    1575                                 dumpService (s1);
    1576 #endif
    1577                                 inheritance(zooRegistry,&s1);
    1578                                 printDescribeProcessForProcess (zooRegistry,m, n, s1);
    1579                                 freeService (&s1);
    1580                                 free (s1);
    1581                                 s1 = NULL;
    1582                                 scount++;
    1583                                 hasVal = 1;
    1584                               }
    1585                           }
    1586                       }
     1730#ifdef DEBUG
     1731                                  dumpService (s1);
     1732#endif
     1733                                  inheritance(zooRegistry,&s1);
     1734#ifdef USE_HPC
     1735                                  addNestedOutputs(&s1);
     1736#endif
     1737                                  /*json_object* jobj=serviceToJson(s1);
     1738                                  const char* jsonStr=json_object_to_json_string_ext(jobj,JSON_C_TO_STRING_PLAIN);
     1739                                  fprintf(stderr,"*** %s %d %s \n",__FILE__,__LINE__,jsonStr);*/
     1740
     1741                                  printDescribeProcessForProcess (zooRegistry,m, doc, n, s1);
     1742                                  freeService (&s1);
     1743                                  free (s1);
     1744                                  s1 = NULL;
     1745                                  scount++;
     1746                                  hasVal = 1;
     1747                                }
     1748                            }
     1749#ifdef META_DB
     1750                        }
     1751#endif
     1752                      }               
    15871753                    if (hasVal < 0)
    15881754                      {
     
    15971763                                   _("Unable to parse the ZCFG file: %s."),
    15981764                                   buff);
    1599                         dup2 (saved_stdout, fileno (stdout));
     1765                        zDup2 (saved_stdout, fileno (stdout));
    16001766                        errorException (m, tmp01, "InvalidParameterValue",
    16011767                                        "Identifier");
     
    16091775                        free (REQUEST);
    16101776                        closedir (dirp);
     1777                        if (corig != NULL)
     1778                          free (corig);
    16111779                        xmlFreeDoc (doc);
    16121780                        xmlCleanupParser ();
     
    16181786                    if (corig != NULL)
    16191787                      free (corig);
    1620                   }
     1788                  }               
    16211789              }
    16221790            closedir (dirp);
    16231791            fflush (stdout);
    1624             dup2 (saved_stdout, fileno (stdout));
     1792            zDup2 (saved_stdout, fileno (stdout));
    16251793            free (orig);
    1626             printDocument (m, doc, getpid ());
     1794            printDocument (m, doc, zGetpid ());
    16271795            freeMaps (&m);
    16281796            free (m);
     
    16341802            free (SERVICE_URL);
    16351803            fflush (stdout);
     1804#ifdef META_DB
     1805            close_sql(m,0);
     1806            //end_sql();
     1807#endif
    16361808            return 0;
    16371809          }
     
    16401812            map* version=getMapFromMaps(m,"main","rversion");
    16411813            int vid=getVersionId(version->value);           
    1642                 int len = 0;
    1643                 int j = 0;
     1814            int len = 0;
     1815            int j = 0;
    16441816            for(j=0;j<nbSupportedRequests;j++){
    16451817              if(requests[vid][j]!=NULL)
     
    17121884  }
    17131885  s1 = NULL;
    1714   s1 = (service *) malloc (SERVICE_SIZE);
    1715   if (s1 == NULL)
    1716     {
    1717       freeMaps (&m);
    1718       free (m);
    1719       if(zooRegistry!=NULL){
    1720         freeRegistry(&zooRegistry);
    1721         free(zooRegistry);
    1722       }
    1723       free (REQUEST);
    1724       free (SERVICE_URL);
    1725       return errorException (m, _("Unable to allocate memory"),
    1726                              "InternalError", NULL);
    1727     }
    1728 
     1886 
    17291887  r_inputs = getMap (request_inputs, "Identifier");
    1730 
    17311888  map* import = getMapFromMaps (m, IMPORTSERVICE, r_inputs->value);
    17321889  if (import != NULL && import->value != NULL) {
    1733       strncpy(tmps1, import->value, 1024);
    1734       setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
    1735       setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
     1890    strncpy(tmps1, import->value, 1024);
     1891    setMapInMaps (m, "lenv", "Identifier", r_inputs->value);
     1892    setMapInMaps (m, "lenv", "oIdentifier", r_inputs->value);
    17361893  }
    17371894  else {
     
    17571914
    17581915  r_inputs = getMapFromMaps (m, "lenv", "Identifier");
    1759   int saved_stdout = dup (fileno (stdout));
    1760   dup2 (fileno (stderr), fileno (stdout));
    1761   t = readServiceFile (m, tmps1, &s1, r_inputs->value);
    1762   inheritance(zooRegistry,&s1);
    1763   if(zooRegistry!=NULL){
    1764     freeRegistry(&zooRegistry);
    1765     free(zooRegistry);
     1916 
     1917#ifdef META_DB
     1918  int metadb_id=_init_sql(m,"metadb");
     1919  //FAILED CONNECTING DB
     1920  if(getMapFromMaps(m,"lenv","dbIssue")!=NULL || metadb_id<0){
     1921    fprintf(stderr,"ERROR CONNECTING METADB\n");
    17661922  }
    1767   fflush (stdout);
    1768   dup2 (saved_stdout, fileno (stdout));
    1769   if (t < 0)
    1770     {
    1771       char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
    1772       sprintf (tmpMsg,
    1773                _
    1774                ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
    1775                r_inputs->value);
    1776       errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
    1777       free (tmpMsg);
    1778       free (s1);
    1779       freeMaps (&m);
    1780       free (m);
    1781       free (REQUEST);
    1782       free (SERVICE_URL);
    1783       return 0;
    1784     }
    1785   close (saved_stdout);
    1786 
     1923  if(metadb_id>=0)
     1924    s1=extractServiceFromDb(m,r_inputs->value,0);
     1925  //close_sql(m,0);
     1926  if(s1!=NULL){
     1927    inheritance(zooRegistry,&s1);
     1928#ifdef USE_HPC
     1929    addNestedOutputs(&s1);
     1930#endif
     1931    if(zooRegistry!=NULL){
     1932      freeRegistry(&zooRegistry);
     1933      free(zooRegistry);
     1934    }
     1935  }else /* Not found in MetaDB */{
     1936#endif
     1937    s1 = createService();
     1938    if (s1 == NULL)
     1939      {
     1940        freeMaps (&m);
     1941        free (m);
     1942        if(zooRegistry!=NULL){
     1943          freeRegistry(&zooRegistry);
     1944          free(zooRegistry);
     1945        }
     1946        free (REQUEST);
     1947        free (SERVICE_URL);
     1948        return errorException (m, _("Unable to allocate memory"),
     1949                               "InternalError", NULL);
     1950      }
     1951
     1952    int saved_stdout = zDup (fileno (stdout));
     1953    zDup2 (fileno (stderr), fileno (stdout));
     1954    t = readServiceFile (m, tmps1, &s1, r_inputs->value);
     1955    if(t>=0){
     1956      inheritance(zooRegistry,&s1);
     1957#ifdef USE_HPC
     1958      addNestedOutputs(&s1);
     1959#endif
     1960    }
     1961    if(zooRegistry!=NULL){
     1962      freeRegistry(&zooRegistry);
     1963      free(zooRegistry);
     1964    }
     1965    fflush (stdout);
     1966    zDup2 (saved_stdout, fileno (stdout));
     1967    if (t < 0)
     1968      {
     1969        char *tmpMsg = (char *) malloc (2048 + strlen (r_inputs->value));
     1970        sprintf (tmpMsg,
     1971                 _
     1972                 ("The value for <identifier> seems to be wrong (%s). Please specify one of the processes in the list returned by a GetCapabilities request."),
     1973                 r_inputs->value);
     1974        errorException (m, tmpMsg, "InvalidParameterValue", "identifier");
     1975        free (tmpMsg);
     1976        free (s1);
     1977        freeMaps (&m);
     1978        free (m);
     1979        free (REQUEST);
     1980        free (SERVICE_URL);
     1981        return 0;
     1982      }
     1983    zClose (saved_stdout);
     1984#ifdef META_DB
     1985  }
     1986#endif
     1987 
    17871988#ifdef DEBUG
    17881989  dumpService (s1);
     
    18212022    return 0;
    18222023  }
    1823 
     2024  //InternetCloseHandle (&hInternet);
     2025 
    18242026  // Define each env variable in runing environment
    18252027  maps *curs = getMaps (m, "env");
     
    18622064                     2) * sizeof (char));
    18632065          sprintf (toto, "%s=%s", mapcs->name, mapcs->value);
    1864           putenv (toto);
     2066          _putenv (toto);
    18652067#ifdef DEBUG
    18662068          fflush (stderr);
    18672069#endif
    18682070#endif
     2071
    18692072#ifdef DEBUG
    18702073          fprintf (stderr, "[ZOO: setenv (%s=%s)]\n", mapcs->name,
     
    19592162
    19602163  int eres = SERVICE_STARTED;
    1961   int cpid = getpid ();
    1962 
     2164  int cpid = zGetpid ();
     2165
     2166  // Create a map containing a copy of the request map
     2167  maps *_tmpMaps = createMaps("request");
     2168  addMapToMap(&_tmpMaps->content,request_inputs);
     2169  addMapsToMaps (&m, _tmpMaps);
     2170  freeMaps (&_tmpMaps);
     2171  free (_tmpMaps);
    19632172  /**
    19642173   * Initialize the specific [lenv] section which contains runtime variables:
     
    19812190   *
    19822191   */
    1983   maps *_tmpMaps = createMaps("lenv");
     2192  _tmpMaps = createMaps("lenv");
    19842193  char tmpBuff[100];
    19852194  struct ztimeval tp;
     
    20092218    addToMap (_tmpMaps->content, "soap", "false");
    20102219
    2011   // Parse the session file and add it to the main maps
     2220  // Parse the session file and add it to the main maps
     2221  char* originalCookie=NULL;
    20122222  if (cgiCookie != NULL && strlen (cgiCookie) > 0)
    20132223    {
    20142224      int hasValidCookie = -1;
    2015       char *tcook = zStrdup (cgiCookie);
    2016       char *tmp = NULL;
     2225      char *tcook = originalCookie = zStrdup (cgiCookie);
    20172226      map *testing = getMapFromMaps (m, "main", "cookiePrefix");
    2018       if (testing == NULL)
     2227      parseCookie(&m,originalCookie);
     2228      map *sessId=getMapFromMaps(m,"cookies",(testing==NULL?"ID":testing->value));
     2229      if (sessId!=NULL)
    20192230        {
    2020           tmp = zStrdup ("ID=");
    2021         }
    2022       else
    2023         {
    2024           tmp =
    2025             (char *) malloc ((strlen (testing->value) + 2) * sizeof (char));
    2026           sprintf (tmp, "%s=", testing->value);
    2027         }
    2028       if (strstr (cgiCookie, ";") != NULL)
    2029         {
    2030           char *token, *saveptr;
    2031           token = strtok_r (cgiCookie, ";", &saveptr);
    2032           while (token != NULL)
    2033             {
    2034               if (strcasestr (token, tmp) != NULL)
    2035                 {
    2036                   if (tcook != NULL)
    2037                     free (tcook);
    2038                   tcook = zStrdup (token);
    2039                   hasValidCookie = 1;
    2040                 }
    2041               token = strtok_r (NULL, ";", &saveptr);
    2042             }
    2043         }
    2044       else
    2045         {
    2046           if (strstr (cgiCookie, "=") != NULL
    2047               && strcasestr (cgiCookie, tmp) != NULL)
    2048             {
    2049               tcook = zStrdup (cgiCookie);
    2050               hasValidCookie = 1;
    2051             }
    2052           if (tmp != NULL)
    2053             {
    2054               free (tmp);
    2055             }
    2056         }
    2057       if (hasValidCookie > 0)
    2058         {
    2059           addToMap (_tmpMaps->content, "sessid", strstr (tcook, "=") + 1);
     2231          addToMap (_tmpMaps->content, "sessid", sessId->value);
    20602232          char session_file_path[1024];
    20612233          map *tmpPath = getMapFromMaps (m, "main", "sessPath");
     
    20652237          if (tmp1 != NULL)
    20662238            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
    2067                      strstr (tmp1, "=") + 1);
     2239                     sessId->value);
    20682240          else
    20692241            sprintf (session_file_path, "%s/sess_%s.cfg", tmpPath->value,
    2070                      strstr (cgiCookie, "=") + 1);
     2242                     sessId->value);
    20712243          free (tcook);
    20722244          maps *tmpSess = (maps *) malloc (MAPS_SIZE);
     
    20762248          if (istat == 0 && file_status.st_size > 0)
    20772249            {
     2250              int saved_stdout = zDup (fileno (stdout));
     2251              zDup2 (fileno (stderr), fileno (stdout));
    20782252              conf_read (session_file_path, tmpSess);
    20792253              addMapsToMaps (&m, tmpSess);
    20802254              freeMaps (&tmpSess);
     2255              fflush(stdout);
     2256              zDup2 (saved_stdout, fileno (stdout));
     2257              zClose(saved_stdout);
    20812258            }
    20822259          free (tmpSess);
     
    20912268#endif
    20922269  int ei = 1;
    2093   char *s =
     2270 
    20942271#ifdef WIN32
    2095     GetEnvironmentStrings();
     2272  LPVOID orig = GetEnvironmentStrings();
     2273  LPTSTR s = (LPTSTR) orig;
    20962274#else
    2097     *environ;
    2098 #endif
     2275  char **orig = environ;
     2276  char *s=*orig;
     2277#endif
     2278
    20992279  _tmpMaps = createMaps("renv");
    2100   for (; s; ei++) {
    2101     char* tmpName=zStrdup(s);
    2102     char* tmpValue=strstr(s,"=")+1;
    2103     tmpName[strlen(tmpName)-strlen(tmpValue)-1]=0;
    2104     if(_tmpMaps->content == NULL)
    2105       _tmpMaps->content = createMap (tmpName,tmpValue);
    2106     else
    2107       addToMap (_tmpMaps->content,tmpName,tmpValue);
    2108     free(tmpName);
    2109     s = *(environ+ei);
     2280if(orig!=NULL)
     2281  for (;
     2282#ifdef WIN32
     2283       *s;
     2284       s++
     2285#else
     2286       s;
     2287       ei++
     2288#endif
     2289       ) {
     2290    if(strstr(s,"=")!=NULL && strlen(strstr(s,"="))>1){
     2291      int len=strlen(s);
     2292      char* tmpName=zStrdup(s);
     2293      char* tmpValue=strstr(s,"=")+1;
     2294      char* tmpName1=(char*)malloc((1+(len-(strlen(tmpValue)+1)))*sizeof(char));
     2295      snprintf(tmpName1,(len-strlen(tmpValue)),"%s",tmpName);
     2296      if(_tmpMaps->content == NULL)
     2297        _tmpMaps->content = createMap (tmpName1,tmpValue);
     2298      else
     2299        addToMap (_tmpMaps->content,tmpName1,tmpValue);
     2300      free(tmpName1);
     2301      free(tmpName);
     2302    }
     2303#ifndef WIN32
     2304    s = *(orig+ei);
     2305#endif
     2306  }
     2307  if(_tmpMaps->content!=NULL && getMap(_tmpMaps->content,"HTTP_COOKIE")!=NULL){
     2308    addToMap(_tmpMaps->content,"HTTP_COOKIE1",&cgiCookie[0]);
    21102309  }
    21112310  addMapsToMaps (&m, _tmpMaps);
    21122311  freeMaps (&_tmpMaps);
    21132312  free (_tmpMaps);
    2114 
     2313#ifdef WIN32
     2314  FreeEnvironmentStrings((LPCH)orig);
     2315#endif
     2316  if(postRequest!=NULL)
     2317    setMapInMaps (m, "renv", "xrequest", postRequest->value);
     2318  //dumpMaps(m);
    21152319#ifdef WIN32
    21162320  char *cgiSidL = NULL;
     
    21602364        return -1;
    21612365      }
     2366      map* testMap=getMapFromMaps(m,"main","memory");
     2367      if(testMap==NULL || strcasecmp(testMap->value,"load")!=0)
     2368        dumpMapsValuesToFiles(&m,&request_input_real_format);
    21622369      loadServiceAndRun (&m, s1, request_inputs, &request_input_real_format,
    2163                          &request_output_real_format, &eres);
     2370                         &request_output_real_format, &eres);     
     2371
     2372#ifdef META_DB
     2373      close_sql(m,0);     
     2374#endif     
    21642375    }
    21652376  else
     
    21692380      fprintf (stderr, "\nPID : %d\n", cpid);
    21702381#endif
    2171 
    21722382#ifndef WIN32
    21732383      pid = fork ();
     
    21752385      if (cgiSid == NULL)
    21762386        {
    2177           createProcess (m, request_inputs, s1, NULL, cpid,
    2178                         request_input_real_format,
    2179                         request_output_real_format);
    2180           pid = cpid;
     2387          createProcess (m, request_inputs, s1, NULL, cpid,
     2388                        request_input_real_format,
     2389                        request_output_real_format);
     2390          pid = cpid;
    21812391        }
    21822392      else
    21832393        {
    2184           pid = 0;
    2185           cpid = atoi (cgiSid);
     2394          pid = 0;
     2395          cpid = atoi (cgiSid);
    21862396          updateStatus(m,0,_("Initializing"));
    21872397        }
    21882398#endif
    21892399      if (pid > 0)
    2190         {
    2191           /**
    2192            * dady :
    2193            * set status to SERVICE_ACCEPTED
    2194            */
    2195 #ifdef DEBUG
    2196           fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
    2197                    getpid ());
    2198 #endif
    2199           eres = SERVICE_ACCEPTED;
    2200         }
     2400        {
     2401          //
     2402          // dady :
     2403          // set status to SERVICE_ACCEPTED
     2404          //
     2405#ifdef DEBUG
     2406          fprintf (stderr, "father pid continue (origin %d) %d ...\n", cpid,
     2407                   zGetpid ());
     2408#endif
     2409          eres = SERVICE_ACCEPTED;
     2410        }
    22012411      else if (pid == 0)
    2202         {
    2203           /**
    2204            * son : have to close the stdout, stdin and stderr to let the parent
    2205            * process answer to http client.
    2206            */
     2412        {
     2413          eres = SERVICE_ACCEPTED;
     2414          //
     2415          // son : have to close the stdout, stdin and stderr to let the parent
     2416          // process answer to http client.
     2417          //
    22072418          map* usid = getMapFromMaps (m, "lenv", "uusid");
    2208           map* tmpm = getMapFromMaps (m, "lenv", "osid");
    2209           int cpid = atoi (tmpm->value);
    2210           r_inputs = getMapFromMaps (m, "main", "tmpPath");
     2419          map* tmpm = getMapFromMaps (m, "lenv", "osid");
     2420          int cpid = atoi (tmpm->value);
     2421          pid=cpid;
     2422          r_inputs = getMapFromMaps (m, "main", "tmpPath");
     2423          setMapInMaps (m, "lenv", "async","true");
    22112424          map* r_inputs1 = createMap("ServiceName", s1->name);
    22122425
    22132426          // Create the filename for the result file (.res)
    2214           fbkpres =
    2215             (char *)
    2216             malloc ((strlen (r_inputs->value) +
    2217                      strlen (usid->value) + 7) * sizeof (char));                   
    2218           sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
     2427          fbkpres =
     2428            (char *)
     2429            malloc ((strlen (r_inputs->value) +
     2430                     strlen (usid->value) + 7) * sizeof (char));                   
     2431          sprintf (fbkpres, "%s/%s.res", r_inputs->value, usid->value);
    22192432          bmap = createMaps("status");
    22202433          bmap->content=createMap("usid",usid->value);
    22212434          addToMap(bmap->content,"sid",tmpm->value);
    2222           addIntToMap(bmap->content,"pid",getpid());
    2223                  
     2435          addIntToMap(bmap->content,"pid",zGetpid());
     2436         
    22242437          // Create PID file referencing the OS process identifier
    2225           fbkpid =
    2226             (char *)
    2227             malloc ((strlen (r_inputs->value) +
    2228                      strlen (usid->value) + 7) * sizeof (char));
    2229           sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
     2438          fbkpid =
     2439            (char *)
     2440            malloc ((strlen (r_inputs->value) +
     2441                     strlen (usid->value) + 7) * sizeof (char));
     2442          sprintf (fbkpid, "%s/%s.pid", r_inputs->value, usid->value);
    22302443          setMapInMaps (m, "lenv", "file.pid", fbkpid);
    22312444
    2232           f0 = freopen (fbkpid, "w+",stdout);
    2233           printf("%d",getpid());
     2445          f0 = freopen (fbkpid, "w+",stdout);
     2446          printf("%d",zGetpid());
    22342447          fflush(stdout);
    22352448
    22362449          // Create SID file referencing the semaphore name
    2237           fbkp =
    2238             (char *)
    2239             malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
    2240                      strlen (usid->value) + 7) * sizeof (char));
    2241           sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
     2450          fbkp =
     2451            (char *)
     2452            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
     2453                     strlen (usid->value) + 7) * sizeof (char));
     2454          sprintf (fbkp, "%s/%s.sid", r_inputs->value, usid->value);
    22422455          setMapInMaps (m, "lenv", "file.sid", fbkp);
    2243           FILE* f2 = freopen (fbkp, "w+",stdout);
     2456          FILE* f2 = freopen (fbkp, "w+",stdout);
    22442457          printf("%s",tmpm->value);
    22452458          fflush(f2);
    22462459          free(fbkp);
    22472460
    2248           fbkp =
    2249             (char *)
    2250             malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
    2251                      strlen (usid->value) + 7) * sizeof (char));
    2252           sprintf (fbkp, "%s/%s_%s.xml", r_inputs->value, r_inputs1->value,
    2253                    usid->value);
     2461          fbkp =
     2462            (char *)
     2463            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
     2464                     strlen (usid->value) + 7) * sizeof (char));
     2465          sprintf (fbkp, "%s/%s_%s.xml", r_inputs->value, r_inputs1->value,
     2466                   usid->value);
    22542467          setMapInMaps (m, "lenv", "file.responseInit", fbkp);
    2255           flog =
    2256             (char *)
    2257             malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
    2258                      strlen (usid->value) + 13) * sizeof (char));
    2259           sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
    2260                    r_inputs1->value, usid->value);
     2468          flog =
     2469            (char *)
     2470            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
     2471                     strlen (usid->value) + 13) * sizeof (char));
     2472          sprintf (flog, "%s/%s_%s_error.log", r_inputs->value,
     2473                   r_inputs1->value, usid->value);
    22612474          setMapInMaps (m, "lenv", "file.log", flog);
    22622475#ifdef DEBUG
    2263           fprintf (stderr, "RUN IN BACKGROUND MODE \n");
    2264           fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
    2265                    getpid ());
    2266           fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
    2267 #endif
    2268           freopen (flog, "w+", stderr);
    2269           fflush (stderr);
     2476          fprintf (stderr, "RUN IN BACKGROUND MODE \n");
     2477          fprintf (stderr, "son pid continue (origin %d) %d ...\n", cpid,
     2478                   zGetpid ());
     2479          fprintf (stderr, "\nFILE TO STORE DATA %s\n", r_inputs->value);
     2480#endif
     2481          freopen (flog, "w+", stderr);
     2482          fflush (stderr);
    22702483          f0 = freopen (fbkp, "w+", stdout);
    22712484          rewind (stdout);
     
    22772490          recordServiceStatus(m);
    22782491#endif
     2492#ifdef USE_CALLBACK
     2493          invokeCallback(m,NULL,NULL,0,0);
     2494#endif
    22792495          if(vid==0){
    2280             /**
    2281              * set status to SERVICE_STARTED and flush stdout to ensure full
    2282              * content was outputed (the file used to store the ResponseDocument).
    2283              * The rewind stdout to restart writing from the bgining of the file,
    2284              * this way the data will be updated at the end of the process run.
    2285              */
     2496            //
     2497            // set status to SERVICE_STARTED and flush stdout to ensure full
     2498            // content was outputed (the file used to store the ResponseDocument).
     2499            // Then, rewind stdout to restart writing from the begining of the file.
     2500            // This way, the data will be updated at the end of the process run.
     2501            //
    22862502            printProcessResponse (m, request_inputs, cpid, s1, r_inputs1->value,
    22872503                                  SERVICE_STARTED, request_input_real_format,
     
    22932509          }
    22942510
    2295           fflush (stderr);
    2296 
    2297           fbkp1 =
    2298             (char *)
    2299             malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
    2300                      strlen (usid->value) + 13) * sizeof (char));
    2301           sprintf (fbkp1, "%s/%s_final_%s.xml", r_inputs->value,
    2302                    r_inputs1->value, usid->value);
     2511          fflush (stderr);
     2512
     2513          fbkp1 =
     2514            (char *)
     2515            malloc ((strlen (r_inputs->value) + strlen (r_inputs1->value) +
     2516                     strlen (usid->value) + 13) * sizeof (char));
     2517          sprintf (fbkp1, "%s/%s_final_%s.xml", r_inputs->value,
     2518                   r_inputs1->value, usid->value);
    23032519          setMapInMaps (m, "lenv", "file.responseFinal", fbkp1);
    23042520
    2305           f1 = freopen (fbkp1, "w+", stdout);
    2306 
     2521          f1 = freopen (fbkp1, "w+", stdout);
     2522
     2523          map* serviceTypeMap=getMap(s1->content,"serviceType");
     2524          if(serviceTypeMap!=NULL)
     2525            setMapInMaps (m, "lenv", "serviceType", serviceTypeMap->value);
     2526
     2527          char *flenv =
     2528            (char *)
     2529            malloc ((strlen (r_inputs->value) +
     2530                     strlen (usid->value) + 12) * sizeof (char));
     2531          sprintf (flenv, "%s/%s_lenv.cfg", r_inputs->value, usid->value);
     2532          maps* lenvMaps=getMaps(m,"lenv");
     2533          dumpMapsToFile(lenvMaps,flenv,0);
     2534          free(flenv);
     2535
     2536#ifdef USE_CALLBACK
     2537          invokeCallback(m,request_input_real_format,NULL,1,0);
     2538#endif
    23072539          if(validateRequest(&m,s1,request_inputs, &request_input_real_format,&request_output_real_format,&hInternet)<0){
    23082540            freeService (&s1);
    23092541            free (s1);
     2542            fflush (stdout);
     2543            fflush (stderr);
    23102544            fclose (f0);
    23112545            fclose (f1);
    23122546            if(dumpBackFinalFile(m,fbkp,fbkp1)<0)
    23132547              return -1;
    2314             unlink (fbkpid);           
     2548#ifndef RELY_ON_DB
     2549            dumpMapsToFile(bmap,fbkpres,1);
     2550            removeShmLock (m, 1);
     2551#else
     2552            recordResponse(m,fbkp1);
     2553#ifdef USE_CALLBACK
     2554            invokeCallback(m,NULL,NULL,7,0);
     2555#endif
     2556#endif
     2557            zUnlink (fbkpid);
    23152558            unhandleStatus (m);
     2559#ifdef RELY_ON_DB
     2560#ifdef META_DB
     2561            cleanupCallbackThreads();
     2562            close_sql(m,1);
     2563#endif
     2564            close_sql(m,0);
     2565#endif
    23162566            freeMaps (&m);
    23172567            free (m);
     
    23242574            freeMaps (&tmpmaps);
    23252575            free (tmpmaps);
    2326             fflush (stdout);
    2327             fflush (stderr);
    23282576            return -1;
    23292577          }
    2330           loadServiceAndRun (&m, s1, request_inputs,
    2331                              &request_input_real_format,
    2332                              &request_output_real_format, &eres);
    2333         }
     2578          if(getMapFromMaps(m,"lenv","mapError")!=NULL){
     2579            setMapInMaps(m,"lenv","message",_("Issue with geographic data"));
     2580#ifdef USE_CALLBACK
     2581            invokeCallback(m,NULL,NULL,7,0);
     2582#endif
     2583            eres=-1;//SERVICE_FAILED;
     2584          }else{
     2585            map* testMap=getMapFromMaps(m,"main","memory");
     2586            if(testMap==NULL || strcasecmp(testMap->value,"load")!=0)
     2587              dumpMapsValuesToFiles(&m,&request_input_real_format);
     2588            loadServiceAndRun (&m, s1, request_inputs,
     2589                               &request_input_real_format,
     2590                               &request_output_real_format, &eres);
     2591          }
     2592        }
    23342593      else
    23352594        {
     
    23382597           * error response here !!!
    23392598           */
    2340           eres = -1;
    2341           errorException (m, _("Unable to run the child process properly"),
    2342                           "InternalError", NULL);
     2599          eres = -1;
     2600          errorException (m, _("Unable to run the child process properly"),
     2601                          "InternalError", NULL);
    23432602        }
    23442603    }
    2345 
    2346 #ifdef DEBUG
     2604       
     2605#ifdef DEBUG
     2606  fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
    23472607  dumpMaps (request_output_real_format);
    2348 #endif
    2349 
     2608  fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
     2609#endif
     2610  fflush(stdout);
     2611  rewind(stdout);
     2612
     2613  //fprintf(stderr,"%s %d %d\n",__FILE__,__LINE__,eres); 
    23502614  if (eres != -1)
    23512615    outputResponse (s1, request_input_real_format,
     
    23532617                    cpid, m, eres);
    23542618  fflush (stdout);
    2355 
     2619 
    23562620  /**
    23572621   * Ensure that if error occurs when freeing memory, no signal will return
     
    23672631  signal (SIGABRT, donothing);
    23682632#endif
    2369   if (((int) getpid ()) != cpid || cgiSid != NULL)
    2370     {     
     2633
     2634  if (((int) zGetpid ()) != cpid || cgiSid != NULL)
     2635    {
     2636      if (eres == SERVICE_SUCCEEDED)
     2637#ifdef USE_CALLBACK
     2638        invokeCallback(m,NULL,request_output_real_format,5,1);
     2639#endif
     2640      fflush(stderr);
     2641      fflush(stdout);
     2642
    23712643      fclose (stdout);
    2372       fclose (stderr);
    23732644
    23742645      fclose (f0);
    23752646      fclose (f1);
    2376          
    2377           if (dumpBackFinalFile(m, fbkp, fbkp1) < 0)
    2378                   return -1;
    2379        
    2380       unlink (fbkpid);   
     2647
     2648      if(dumpBackFinalFile(m,fbkp,fbkp1)<0)
     2649        return -1;
     2650      zUnlink (fbkpid);
    23812651      switch(eres){
    23822652      default:
     
    23902660        break;
    23912661      }     
    2392 #ifndef RELY_ON_DB       
     2662#ifndef RELY_ON_DB
    23932663      dumpMapsToFile(bmap,fbkpres,1);
    23942664      removeShmLock (m, 1);
    23952665#else
    23962666      recordResponse(m,fbkp1);
     2667      if (eres == SERVICE_SUCCEEDED)
     2668#ifdef USE_CALLBACK
     2669        invokeCallback(m,NULL,request_output_real_format,6,0);
     2670#endif
    23972671#endif
    23982672      freeMaps(&bmap);
    23992673      free(bmap);
    2400       unlink (fbkp1);
    2401       unlink (flog);
     2674      zUnlink (fbkp1);
    24022675      unhandleStatus (m);
     2676#ifdef RELY_ON_DB
     2677#ifdef META_DB
     2678      cleanupCallbackThreads();
     2679      close_sql(m,1);
     2680#endif
     2681      close_sql(m,0);
     2682      end_sql();
     2683#endif
    24032684      free(fbkpid);
    24042685      free(fbkpres);
    2405       free (flog);           
    24062686      free (fbkp1);
    2407       // free (tmps1); // tmps1 is stack memory and should not be freed
    24082687      if(cgiSid!=NULL)
    24092688        free(cgiSid);
    2410     }
    2411 
     2689      //InternetCloseHandle (&hInternet);
     2690      fprintf (stderr, "RUN IN BACKGROUND MODE %s %d \n",__FILE__,__LINE__);
     2691      fflush(stderr);
     2692      fclose (stderr);
     2693      zUnlink (flog);
     2694      free (flog);
     2695    }
     2696  else{
     2697    //InternetCloseHandle (&hInternet); 
     2698#ifdef META_DB
     2699    close_sql(m,0);
     2700#endif
     2701  }
     2702 
    24122703  freeService (&s1);
    24132704  free (s1);
     
    24292720#endif
    24302721
    2431   if (((int) getpid ()) != cpid || cgiSid != NULL)
     2722  if (((int) zGetpid ()) != cpid || cgiSid != NULL)
    24322723    {
    24332724      exit (0);
Note: See TracChangeset for help on using the changeset viewer.

Search

Context Navigation

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