-
Notifications
You must be signed in to change notification settings - Fork 33
/
mod_R.c
2487 lines (2122 loc) · 81.7 KB
/
mod_R.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** Copyright 2012 Vanderbilt University
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*************************************************************************
*
* Headers and macros
*
*************************************************************************/
#define MOD_R_VERSION "1.2.8"
#include "mod_R.h"
#include <sys/types.h>
#include <unistd.h>
/*
* DARWIN's dyld.h defines an enum { FALSE TRUE} which conflicts with R
*/
#ifdef DARWIN
#define ENUM_DYLD_BOOL
enum DYLD_BOOL{ DYLD_FALSE, DYLD_TRUE};
#endif
/*
* Apache Server headers
*/
#include "httpd.h"
#include "http_log.h"
#include "http_config.h"
#include "http_protocol.h"
#include "util_filter.h"
#include "util_script.h"
#include "ap_mpm.h"
/*
* Apache Portable Runtime
*/
#include "apr.h"
#include "apr_errno.h"
#include "apr_strings.h"
#include "apr_env.h"
#include "apr_pools.h"
#include "apr_hash.h"
#include "apr_thread_mutex.h"
/*
* libapreq headers
*/
#include "apreq.h"
#include "apreq_cookie.h"
#include "apreq_parser.h"
#include "apreq_param.h"
#include "apreq_util.h"
/*
* R headers
*/
#include <R.h>
#include <Rversion.h>
#include <Rinternals.h>
#include <Rdefines.h>
/* Waiting for confirmation if this is exposed in R API.*/
/* void Rf_PrintWarnings(void); */
/*#define PrintWarnings Rf_PrintWarnings*/
/*
* sprintf and friends
*/
#include <stdio.h>
#include <string.h>
#define R_INTERFACE_PTRS
#define CSTACK_DEFNS
/*
* APR pulls in stdint.h which defines uintptr_t, so we need to tell R
* headers that. R defines uintptr_t slightly differently than
* stdint.h, although they *should* be the same size
*/
#define HAVE_UINTPTR_T
#include <Rinterface.h>
#include <Rembedded.h>
#include <R_ext/Parse.h>
#include <R_ext/Callbacks.h>
#include <R_ext/Rdynload.h>
#include <R_ext/Memory.h>
/*************************************************************************
*
* RApache types
*
*************************************************************************/
typedef enum {
R_HANDLER = 1,
R_SCRIPT,
R_INFO
} RApacheHandlerType;
typedef struct {
char *file;
char *dirname;
char *function;
char *evalcode;
char *package;
char *handlerKey;
char *cmdpath;
} RApacheDirective;
typedef struct {
SEXP exprs;
SEXP envir;
apr_time_t mtime;
} RApacheParsedFile;
typedef struct {
SEXP expr;
SEXP envir;
RApacheParsedFile *parsedFile;
RApacheDirective *directive;
} RApacheHandler;
typedef struct {
request_rec *r;
int postParsed;
int readStarted;
apr_table_t *argsTable;
apr_table_t *postTable;
apr_table_t *cookiesTable;
SEXP filesVar;
SEXP serverVar;
int outputErrors;
char *errorPrefix;
char *errorSuffix;
RApacheHandler *handler;
char *oldwd;
} RApacheRequest;
/*************************************************************************
*
* Globals; prefixed with MR_ (if R ever becomes threaded, or can at least
* run multiple interpreters at once, we'll bundle these up into contexts).
*
*************************************************************************/
/* Current request_rec */
static RApacheRequest MR_Request = { NULL, 0, 0, NULL, NULL, NULL, NULL , NULL, -1, NULL, NULL, NULL,NULL};
/* Number of times apache has parsed config files; we'll do stuff on second pass */
static int MR_ConfigPass = 1;
/* Don't start R more than once, if the flag is 1 it's already started */
static int MR_InitStatus = 0;
/*
* Child pid. If we fork() we don't want to do certain
* cleanup steps, especially on cgi fork, so we cache the original
* pid.
*/
static unsigned long MR_pid;
/* Per-child memory for configuration */
static apr_pool_t *MR_Pool = NULL;
static apr_bucket_alloc_t *MR_Bucket_Alloc = NULL;
static apr_hash_t *MR_HandlerCache = NULL;
static apr_hash_t *MR_ParsedFileCache = NULL;
static apr_table_t *MR_OnStartup = NULL;
/*
* Bucket brigades for reading and writing to client
* TODO: stuff these into MR_Request
*/
static apr_bucket_brigade *MR_BBin;
static apr_bucket_brigade *MR_BBout;
static apr_bucket_brigade *MR_BBerr;
/*
* RApache environment
*/
static SEXP MR_RApacheEnv;
/*
* RApache code; evaluated in the above environment.
*/
static const char MR_RApacheSource[] = "\
setStatus <- function(status) .Call('RApache_setStatus',as.integer(status))\n\
setContentType <- function(type) .Call('RApache_setContentType',type)\n\
setHeader <- function(header,value) .Call('RApache_setHeader',header,value)\n\
setCookie <- function(name=NULL,value='',expires=NULL,path=NULL,domain=NULL,...){\n\
args <- list(...)\n\
therest <- ifelse(length(args)>0,paste(paste(names(args),args,sep='='),collapse=';'),'')\n\
.Call('RApache_setCookie',name,value,expires,path,domain,therest)}\n\
urlEncode <- function(str) .Call('RApache_urlEnDecode',str,TRUE)\n\
urlDecode <- function(str) .Call('RApache_urlEnDecode',str,FALSE)\n\
RApacheInfo <- function() .Call('RApache_RApacheInfo')\n\
sendBin <- function(object, con=stdout(), size=NA_integer_, endian=.Platform$endian){\n\
swap <- endian != .Platform$endian\n\
if (!is.vector(object) || mode(object) == 'list') stop('can only write vector objects')\n\
.Call('RApache_sendBin',object,size,swap)}\n\
receiveBin <- function(length=-1L) .Call('RApache_receiveBin',length)\n\
RApacheOutputErrors <- function(status=TRUE,prefix=NULL,suffix=NULL) warning('RApacheOutputErrors has been deprecated!')\n\
.ResetCGIVars <- function(){\n\
re <- as.environment('rapache')\n\
delayedAssign('GET', .Call('RApache_parseGet'),re,re)\n\
delayedAssign('COOKIES', .Call('RApache_parseCookies'),re,re)\n\
delayedAssign('POST', .Call('RApache_parsePost'),re,re)\n\
delayedAssign('FILES', .Call('RApache_parseFiles'),re,re)\n\
delayedAssign('SERVER', .Call('RApache_getServer'),re,re)\n\
}";
/*
* Global Thread Mutex
*/
static apr_thread_mutex_t *MR_mutex = NULL;
/*************************************************************************
*
* Function declarations
*
* AP_* functions are called by apache code base
*
*************************************************************************/
/*
* Module functions
*/
static void *AP_create_dir_cfg(apr_pool_t *p, char *dir);
static void *AP_merge_dir_cfg(apr_pool_t *p, void *parent, void *new);
static void *AP_create_srv_cfg(apr_pool_t *p, server_rec *s);
static void *AP_merge_srv_cfg(apr_pool_t *p, void *parent, void *new);
static void AP_register_hooks (apr_pool_t *p);
/*
* Command functions
*/
static const char *AP_cmd_RHandler(cmd_parms *cmd, void *conf, const char *handler);
static const char *AP_cmd_RFileHandler(cmd_parms *cmd, void *conf, const char *handler);
static const char *AP_cmd_REval(cmd_parms *cmd, void *conf, const char *tmpcode);
static const char *AP_cmd_RFileEval(cmd_parms *cmd, void *conf, const char *tmpcode);
static const char *AP_cmd_REvalOnStartup(cmd_parms *cmd, void *conf, const char *evalstr);
static const char *AP_cmd_RSourceOnStartup(cmd_parms *cmd, void *conf, const char *evalstr);
static const char *AP_cmd_ROutputErrors(cmd_parms *cmd, void *mconfig);
static const char *AP_cmd_RPreserveEnv(cmd_parms *cmd, void *mconfig);
/*
* Module Hook functions
*/
static int AP_hook_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s);
static void AP_hook_child_init(apr_pool_t *p, server_rec *s);
static int AP_hook_request_handler (request_rec *r);
/*
* Exit callback
*/
static apr_status_t AP_child_exit(void *data);
/*
* R interface callbacks
*/
static void Suicide(const char *s){ };
static void ShowMessage(const char *s);
static int ReadConsole(const char *, unsigned char *, int, int);
static void WriteConsoleEx(const char *, int, int);
static void WriteConsoleStderr(const char *, int, int);
static void WriteConsoleErrorOnly(const char *, int, int);
static void NoOpConsole(){ };
static void NoOpBusy(int i) { };
static void NoOpCleanUp(SA_TYPE s, int i, int j){ };
static int NoOpShowFiles(int i, const char **j, const char **k, const char *l, Rboolean b, const char *c){ return 1;};
static int NoOpChooseFile(int i, char *b,int s){ return 0;};
static int NoOpEditFile(const char *f){ return 0;};
static void NoOpHistoryFun(SEXP a, SEXP b, SEXP c, SEXP d){ };
/*
* The Rest.
*/
static void init_config_pass(apr_pool_t *p);
static void init_R(apr_pool_t *);
static int SetUpRequest(const request_rec *,RApacheHandlerType);
static void TearDownRequest(int flush);
static RApacheHandler *GetHandlerFromRequest(const request_rec *r);
static int RApacheResponseError(char *msg);
static void RApacheError(char *msg);
static void InitTempDir(apr_pool_t *p);
static void RegisterCallSymbols();
static SEXP NewLogical(int tf);
static SEXP NewInteger(int tf);
static SEXP NewEnv(SEXP enclos);
static SEXP ParseText(const char *text, int *parseError);
static SEXP EvalExprs(SEXP exprs, SEXP env, int *evalError); /* more than one expression evaluator*/
static SEXP ParseEval(const char *code,SEXP env, int *evalError);
static SEXP CallFun1str(const char *fun, const char *arg, SEXP env, int *evalError);
static SEXP CallFun1expr(const char *fun, SEXP arg, SEXP env, int *evalError);
static int PrepareFileExprs(RApacheHandler *h, const request_rec *r, int *fileParsed);
static int PrepareHandlerExpr(RApacheHandler *h, const request_rec *r, int handlerType);
static void InitRApacheEnv();
static void RefreshRApacheEnv();
static void InitRApachePool();
static int OnStartupCallback(void *rec, const char *key, const char *value);
static SEXP MyfindFun(SEXP fun, SEXP envir);
static int RApacheInfo();
static SEXP AprTableToList(apr_table_t *, apr_table_do_callback_fn_t *);
static void PrintTraceback(void);
static int ReadRequestBody(unsigned char *buf, int size);
static char *dirname(const char *path, apr_pool_t *p);
/*************************************************************************
*
* Command array
*
*************************************************************************/
static const command_rec MR_cmds[] = {
AP_INIT_TAKE1("RHandler", AP_cmd_RHandler, NULL, OR_OPTIONS, "R function to handle request. "),
AP_INIT_TAKE1("RFileHandler", AP_cmd_RFileHandler, NULL, OR_OPTIONS, "File containing R code or function to handle request."),
AP_INIT_TAKE1("REval", AP_cmd_REval, NULL, OR_OPTIONS, "R code to evaluate on each request. "),
AP_INIT_TAKE1("RFileEval", AP_cmd_RFileEval, NULL, OR_OPTIONS, "File and code to evalueate on each request."),
AP_INIT_TAKE1("REvalOnStartup", AP_cmd_REvalOnStartup, NULL, OR_OPTIONS,"R expressions to evaluate on start."),
AP_INIT_TAKE1("RSourceOnStartup", AP_cmd_RSourceOnStartup, NULL, OR_OPTIONS,"File containing R expressions to evaluate on start."),
AP_INIT_NO_ARGS("ROutputErrors", AP_cmd_ROutputErrors, NULL, OR_OPTIONS, "Deprecated. Option to print error messages to output."),
AP_INIT_NO_ARGS("RPreserveEnv", AP_cmd_RPreserveEnv, NULL, OR_OPTIONS, "Deprecated. Option to preserve handler environment across requests."),
{ NULL},
};
/*************************************************************************
*
* Module definition
*
*************************************************************************/
module AP_MODULE_DECLARE_DATA R_module =
{
STANDARD20_MODULE_STUFF,
AP_create_dir_cfg, /* dir config creater */
AP_merge_dir_cfg, /* dir merger --- default is to override */
AP_create_srv_cfg, /* server config */
AP_merge_srv_cfg, /* merge server config */
MR_cmds, /* table of config file commands */
AP_register_hooks, /* register hooks */
};
/*************************************************************************
*
* Module functions: called by apache code base
*
*************************************************************************/
static void *AP_create_dir_cfg(apr_pool_t *p, char *dir){
RApacheDirective *cfg;
cfg = (RApacheDirective *)apr_pcalloc(p,sizeof(RApacheDirective));
return (void *)cfg;
}
void *AP_merge_dir_cfg(apr_pool_t *pool, void *parent, void *new){
RApacheDirective *c;
RApacheDirective *n = (RApacheDirective *)new;
/* print_cfg("AP_merge_dir_cfg","Parent",p,"New",n); */
c = (RApacheDirective *)apr_pcalloc(pool,sizeof(RApacheDirective));
/* add new config stuff, overriding parent */
memcpy(c,n,sizeof(RApacheDirective));
return (void *)c;
}
/* first mod_R.c function called when apache starts */
void *AP_create_srv_cfg(apr_pool_t *p, server_rec *s){
RApacheDirective *c;
init_config_pass(s->process->pool);
c = (RApacheDirective *)apr_pcalloc(p,sizeof(RApacheDirective));
return (void *)c;
}
void *AP_merge_srv_cfg(apr_pool_t *pool, void *parent, void *new){
RApacheDirective *c;
RApacheDirective *n = (RApacheDirective *)new;
/* print_cfg("AP_merge_srv_cfg","Parent",p,"New",n); */
c = (RApacheDirective *)apr_pcalloc(pool,sizeof(RApacheDirective));
/* add new config stuff, overriding parent */
memcpy(c,n,sizeof(RApacheDirective));
return (void *)c;
}
static void AP_register_hooks (apr_pool_t *p)
{
ap_hook_post_config(AP_hook_post_config, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(AP_hook_child_init, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_handler(AP_hook_request_handler, NULL, NULL, APR_HOOK_MIDDLE);
}
/*************************************************************************
*
* Command functions: called by apache code base
*
*************************************************************************/
static const char *AP_cmd_RHandler(cmd_parms *cmd, void *conf, const char *handler){
const char *part, *function;
RApacheDirective *c = (RApacheDirective *)conf;
ap_directive_t *d = cmd->directive;
InitRApachePool();
if (ap_strchr(handler,'/')){
fprintf(stderr,"\n\tWARNING! %s seems to contain a file. If this is true, then use the RFileHandler directive instead.\n",handler);
fflush(stderr);
}
c->handlerKey = apr_pstrdup(cmd->pool,handler);
part = ap_strstr(handler,"::");
if (part) {
c->package = apr_pstrmemdup(cmd->pool,handler,part - handler);
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "e:%s on line %u of %s",
d->directive,d->line_num,d->filename),
apr_psprintf(cmd->pool,"library(%s)",c->package));
function = part + 2;
} else {
function = handler;
}
c->function = apr_pstrdup(cmd->pool,function);
c->cmdpath = apr_pstrdup(cmd->pool,cmd->path);
return NULL;
}
static const char *AP_cmd_RFileHandler(cmd_parms *cmd, void *conf, const char *handler){
const char *part;
RApacheDirective *c = (RApacheDirective *)conf;
apr_finfo_t finfo;
InitRApachePool();
c->handlerKey = apr_pstrdup(cmd->pool,handler);
part = ap_strstr(handler,"::");
if (part) {
c->file = apr_pstrmemdup(cmd->pool,handler,part - handler);
c->function = apr_pstrdup(cmd->pool,part + 2);
} else {
c->file = apr_pstrdup(cmd->pool,handler);
}
if (apr_stat(&finfo,c->file,APR_FINFO_TYPE,cmd->pool) != APR_SUCCESS){
return apr_psprintf(cmd->pool,"RFileHandler: %s file not found!",c->file);
}
c->cmdpath = apr_pstrdup(cmd->pool,cmd->path);
/* Cache directory of file */
c->dirname = dirname(c->file,cmd->pool);
return NULL;
}
static const char *AP_cmd_REval(cmd_parms *cmd, void *conf, const char *tmpcode){
const char *part;
RApacheDirective *c = (RApacheDirective *)conf;
ap_directive_t *d = cmd->directive;
InitRApachePool();
if (ap_strchr(tmpcode,'/')){
fprintf(stderr,"\n\tWARNING! %s seems to contain a file. If this is true, then use the RFileEval directive instead.\n",tmpcode);
fflush(stderr);
}
c->handlerKey = apr_pstrdup(cmd->pool,tmpcode);
part = ap_strstr(tmpcode,"::");
if (part) {
c->package = apr_pstrmemdup(cmd->pool,tmpcode,part - tmpcode);
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "e:%s on line %u of %s",
d->directive,d->line_num,d->filename),
apr_psprintf(cmd->pool,"library(%s)",c->package));
}
c->evalcode = c->handlerKey;
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "p:%s on line %u of %s",
d->directive,d->line_num,d->filename),
c->evalcode);
c->cmdpath = apr_pstrdup(cmd->pool,cmd->path);
return NULL;
}
static const char *AP_cmd_RFileEval(cmd_parms *cmd, void *conf, const char *filecode){
const char *part;
RApacheDirective *c = (RApacheDirective *)conf;
apr_finfo_t finfo;
ap_directive_t *d = cmd->directive;
InitRApachePool();
c->handlerKey = apr_pstrdup(cmd->pool,filecode);
part = ap_strstr(filecode,":");
if (part) {
c->file = apr_pstrmemdup(cmd->pool,filecode,part - filecode);
c->evalcode = apr_pstrdup(cmd->pool,part+1);
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "p:%s on line %u of %s",
d->directive,d->line_num,d->filename),
c->evalcode);
part = ap_strstr(c->evalcode,"::");
if (part) {
c->package = apr_pstrmemdup(cmd->pool,c->evalcode,part - c->evalcode);
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "e:%s on line %u of %s",
d->directive,d->line_num,d->filename),
apr_psprintf(cmd->pool,"library(%s)",c->package));
}
} else {
return apr_pstrdup(cmd->pool,"RFileEval: Takes a filename and an expression!");
}
if (apr_stat(&finfo,c->file,APR_FINFO_TYPE,cmd->pool) != APR_SUCCESS){
return apr_psprintf(cmd->pool,"RFileEval: %s file not found!",c->file);
}
c->cmdpath = apr_pstrdup(cmd->pool,cmd->path);
/* Cache directory of file */
c->dirname = dirname(c->file,cmd->pool);
return NULL;
}
static const char *AP_cmd_REvalOnStartup(cmd_parms *cmd, void *conf, const char *evalstr){
ap_directive_t *d = cmd->directive;
InitRApachePool();
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "e:%s on line %u of %s",
d->directive,d->line_num,d->filename),
evalstr
);
return NULL;
}
static const char *AP_cmd_RSourceOnStartup(cmd_parms *cmd, void *conf, const char *file){
ap_directive_t *d = cmd->directive;
InitRApachePool();
if (MR_ConfigPass == 1){
apr_finfo_t finfo;
if (apr_stat(&finfo,file,APR_FINFO_TYPE,cmd->pool) != APR_SUCCESS){
return apr_psprintf(cmd->pool,"RSourceFile: %s file not found!",file);
}
return NULL;
}
apr_table_add(
MR_OnStartup,
apr_psprintf( cmd->pool, "e:%s on line %u of %s",
d->directive,d->line_num,d->filename),
apr_psprintf(cmd->pool,"source('%s')",file)
);
return NULL;
}
static const char *AP_cmd_ROutputErrors(cmd_parms *cmd, void *conf){
fprintf(stderr,"Warning: ROutputErrors has been deprecated!");
return NULL;
}
static const char *AP_cmd_RPreserveEnv(cmd_parms *cmd, void *conf){
fprintf(stderr,"Warning: RPreserveEnv has been deprecated!");
return NULL;
}
/*************************************************************************
*
* Hook functions: called by apache code base
*
*************************************************************************/
static int AP_hook_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s){
ap_add_version_component(pconf,apr_psprintf(pconf,"mod_R/%s",MOD_R_VERSION));
ap_add_version_component(pconf,apr_psprintf(pconf,"R/%s.%s",R_MAJOR,R_MINOR));
return OK;
}
static void AP_hook_child_init(apr_pool_t *p, server_rec *s){
MR_pid=(unsigned long)getpid();
init_R(p);
apr_pool_cleanup_register(p, p, AP_child_exit, AP_child_exit);
}
static int AP_hook_request_handler (request_rec *r)
{
RApacheHandlerType handlerType = 0;
RApacheHandler *h;
SEXP ret=R_NilValue;
int evalError=1,fileParsed=1;
if (apr_filepath_get(&MR_Request.oldwd,APR_FILEPATH_NATIVE,r->pool) != APR_SUCCESS)
return HTTP_INTERNAL_SERVER_ERROR;
/* Only handle our handlers */
if (strcmp(r->handler,"r-handler")==0) handlerType = R_HANDLER;
else if (strcmp(r->handler,"r-script")==0) handlerType = R_SCRIPT;
else if (strcmp(r->handler,"r-info")==0) handlerType = R_INFO;
else return DECLINED;
if (!SetUpRequest(r,handlerType)) return HTTP_INTERNAL_SERVER_ERROR;
h = MR_Request.handler;
if (handlerType == R_INFO){
int val = RApacheInfo();
TearDownRequest(1);
return val;
}
RefreshRApacheEnv(); /* ensures we're on search path, updates CGI vars, etc. */
/* Prepare file if needed */
if (h->directive->file){
/* Set working directory to dirname of file */
if (apr_filepath_set(h->directive->dirname,MR_Pool) != APR_SUCCESS)
return RApacheResponseError(NULL);
fileParsed = 1;
if (!PrepareFileExprs(h,r,&fileParsed)) return RApacheResponseError(NULL);
if (fileParsed || (!h->directive->function && !h->directive->evalcode)){
if (h->parsedFile->envir) R_ReleaseObject(h->parsedFile->envir);
h->parsedFile->envir = NewEnv(R_GlobalEnv);
R_PreserveObject(h->parsedFile->envir);
evalError = 1;
ret = EvalExprs(h->parsedFile->exprs,h->parsedFile->envir,&evalError);
if (evalError) {
/*PrintWarnings();*/
PrintTraceback();
return RApacheResponseError(NULL);
}
}
h->envir = h->parsedFile->envir;
} else {
if (h->envir) R_ReleaseObject(h->envir);
h->envir = NewEnv(R_GlobalEnv);
R_PreserveObject(h->envir);
}
/* Eval handler expression if set */
if (h->directive->function || h->directive->evalcode){
if (!PrepareHandlerExpr(h,r,handlerType)) {
return RApacheResponseError(NULL);
}
ret = EvalExprs(h->expr,h->envir,&evalError);
if (evalError) {
/*PrintWarnings();*/
PrintTraceback();
return RApacheResponseError(NULL);
}
}
/*PrintWarnings();*/
if (IS_INTEGER(ret) && LENGTH(ret) == 1){
int result = asInteger(ret);
TearDownRequest(1);
/* Set status to HTTP_mumble */
if (result != OK) r->status = result;
return result;
} else if (inherits(ret,"try-error")){
return RApacheResponseError(apr_psprintf(r->pool,"Function %s returned an object of 'try-error'.\n",h->directive->function));
} else {
TearDownRequest(1);
return DONE; /* user didn't specify return code, so presume done.*/
}
}
static apr_status_t AP_child_exit(void *data){
/* R_dot_Last(); */
unsigned long pid;
pid = (unsigned long)getpid();
/* Only run if we've actually initialized AND
* we haven't forked (for mod_cgi).
*/
if (MR_InitStatus && MR_pid == pid){
MR_InitStatus = 0;
}
/*if (MR_Pool) {
apr_bucket_alloc_destroy(MR_Bucket_Alloc);
apr_pool_destroy(MR_Pool);
MR_Pool = NULL;
} */
return APR_SUCCESS;
}
/*************************************************************************
*
* R interface callbacks
*
*************************************************************************/
static void ShowMessage(const char *s){
(ptr_R_WriteConsoleEx)(s,strlen(s),1);
}
static void WriteConsoleEx(const char *buf, int size, int errorFlag){
if (MR_Request.r){
if (!errorFlag) {
/* ap_fwrite(MR_Request.r->output_filters,MR_BBout,buf,size); */
apr_brigade_write(MR_BBout,NULL,NULL,buf,size);
}
else RApacheError(apr_pstrmemdup(MR_Request.r->pool,buf,size));
} else {
WriteConsoleStderr(buf,size,errorFlag);
}
}
static void WriteConsoleErrorOnly(const char *buf, int size, int errorFlag){
if (MR_Request.r)
RApacheError(apr_pstrmemdup(MR_Request.r->pool,buf,size));
else
WriteConsoleStderr(buf,size,errorFlag);
}
static void WriteConsoleStderr(const char *buf, int size, int errorFlag){
fprintf(stderr,"%*s",size,buf);
fflush(stderr);
}
/* according to R 2.7.2 the true size of buf is size+1 */
static int ReadConsole(const char *prompt, unsigned char *buf, int size, int addHist){
int len = ReadRequestBody(buf,size);
buf[len] = '\0';
return len;
}
static int ReadRequestBody(unsigned char *buf, int size){
apr_size_t len, bpos=0;
apr_status_t rv;
const char *data;
if (!MR_Request.r){
ap_log_rerror(APLOG_MARK,APLOG_ERR,0,MR_Request.r,"Can't read with R since MR_Request.r is NULL!");
return 0;
}
if (MR_Request.postParsed){
//the user should be able to avoid this now. Warning seems appropriate.
RApacheError("Can't read with R since libapreq already started!");
return 0;
}
MR_Request.readStarted = 1;
if (MR_BBin == NULL){
MR_BBin = apr_brigade_create(MR_Request.r->pool, MR_Request.r->connection->bucket_alloc);
}
while (bpos < size) {
len = size - bpos;
if (len > HUGE_STRING_LEN) {
len = HUGE_STRING_LEN;
}
rv = ap_get_brigade(MR_Request.r->input_filters,MR_BBin,AP_MODE_READBYTES,APR_BLOCK_READ,len);
if (rv != APR_SUCCESS) {
break;
}
rv = apr_brigade_flatten(MR_BBin, buf+bpos, &len);
if (rv != APR_SUCCESS) {
break;
}
apr_brigade_cleanup(MR_BBin);
if (len == 0) {
break;
}
bpos += len;
}
return (int)bpos;
}
/*************************************************************************
*
* Helper functions
*
*************************************************************************/
static RApacheHandler *GetHandlerFromRequest(const request_rec *r){
RApacheDirective *d = ap_get_module_config(r->per_dir_config,&R_module);
RApacheHandler *h;
if (d == NULL || d->handlerKey == NULL){
ap_set_content_type((request_rec *)r,"text/html");
RApacheError(apr_psprintf(r->pool,"No RApache Directive specified for 'SetHandler %s'",r->handler));
return NULL;
}
h = (RApacheHandler *)apr_hash_get(
MR_HandlerCache,d->handlerKey,APR_HASH_KEY_STRING);
if (!h){
h = (RApacheHandler *)apr_pcalloc(MR_Pool,sizeof(RApacheHandler));
apr_hash_set(MR_HandlerCache,d->handlerKey,APR_HASH_KEY_STRING,h);
}
if (h == NULL || (d->file == NULL && d->function == NULL && d->evalcode == NULL)){
ap_set_content_type((request_rec *)r,"text/html");
RApacheError(apr_psprintf(r->pool,"Invalid RApache Directive: %s",d->handlerKey));
return NULL;
}
h->directive = d;
return(h);
}
static int SetUpRequest(const request_rec *r,RApacheHandlerType handlerType){
/* Acquire R mutex */
if (MR_mutex != NULL && apr_thread_mutex_lock(MR_mutex) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,"RApache Mutex error!");
return 0;
}
/* Set current request_rec */
MR_Request.r = (request_rec *)r;
/* Init reading */
MR_BBin = NULL;
/* Set output brigade */
if ((MR_BBout = apr_brigade_create(r->pool, r->connection->bucket_alloc)) == NULL){
RApacheError("RApache MR_BBout error!");
TearDownRequest(0);
return 0;
}
if (handlerType != R_INFO){
MR_Request.handler = GetHandlerFromRequest(r);
if (!MR_Request.handler){
TearDownRequest(0);
return 0;
}
}
return 1;
}
/* No need to free any memory here since it was allocated out of the request pool */
static void TearDownRequest(int flush){
int evalError;
apr_bucket *bucket;
apr_size_t len;
const char *data;
apr_status_t status;
/* Change to oldwd */
if (MR_Request.oldwd != NULL)
apr_filepath_set(MR_Request.oldwd,MR_Pool);
/* Clean up reading */
if (MR_BBin){
if (MR_Request.readStarted) {
/* TODO: check if this succeeds */
ParseEval(".Internal(clearPushBack(stdin()))",R_GlobalEnv,&evalError);
}
apr_brigade_cleanup(MR_BBin);
apr_brigade_destroy(MR_BBin);
}
MR_BBin = NULL;
/* Clean up writing, e.g. flush output */
if (MR_BBout){
/* A reason not to flush when the brigade is not empty is to
* preserve error conditons
*/
if(!APR_BRIGADE_EMPTY(MR_BBout) && flush){
ap_filter_flush(MR_BBout,MR_Request.r->output_filters);
}
apr_brigade_cleanup(MR_BBout);
apr_brigade_destroy(MR_BBout);
}
MR_BBout = NULL;
/* Output errors */
if (MR_BBerr){
/* Write contents of MR_BBerr to log */
for (bucket = APR_BRIGADE_FIRST(MR_BBerr); bucket != APR_BRIGADE_SENTINEL(MR_BBerr); bucket = APR_BUCKET_NEXT(bucket)) {
if (APR_BUCKET_IS_EOS(bucket)) {
break;
}
/* We can't do much with this. */
if (APR_BUCKET_IS_FLUSH(bucket)) {
continue;
}
/* read */
status = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
if (status != APR_SUCCESS){
fprintf(stderr,"WARNING! apr_bucket_read returned %d\n",status);
}
status = apr_file_write(MR_Request.r->server->error_log,data,&len);
if (status != APR_SUCCESS){
fprintf(stderr,"WARNING! apr_file_write returned %d\n",status);
}
}
apr_file_flush(MR_Request.r->server->error_log);
apr_brigade_cleanup(MR_BBerr);
apr_brigade_destroy(MR_BBerr);
}
MR_BBerr = NULL;
bzero(&MR_Request,sizeof(RApacheRequest));
if (MR_mutex != NULL) apr_thread_mutex_unlock(MR_mutex);
}
/* Can be called with NULL msg to force proper request handler return
* value.
*/
static int RApacheResponseError(char *msg){
if (msg) RApacheError(msg);
TearDownRequest(0); /* delete all buffered output */
return HTTP_INTERNAL_SERVER_ERROR;
}
static void RApacheError(char *msg){
if (!msg) return;
if (MR_BBerr == NULL){
/* Allocated out of Global rApache pool */
if ((MR_BBerr = apr_brigade_create(MR_Pool, MR_Bucket_Alloc)) == NULL){
fprintf(stderr,"FATAL ERROR! RApacheError cannot create MR_BBerr brigade\n");
exit(-1);
}
ap_log_rerror(APLOG_MARK,APLOG_ERR,0,MR_Request.r,"rApache Notice!");
}
if (apr_brigade_puts(MR_BBerr,NULL,NULL,msg) != APR_SUCCESS){
fprintf(stderr,"FATAL ERROR! RApacheError cannot write to MR_BBerr brigade\n");
exit(-1);
}
}
static void init_R(apr_pool_t *p){
char *argv[] = {"mod_R", "--gui=none", "--slave", "--silent", "--vanilla","--no-readline"};
int argc = sizeof(argv)/sizeof(argv[0]);
int threaded;
apr_status_t rv;
if (MR_InitStatus != 0) return;
MR_InitStatus = 1;
InitRApachePool(); /* possibly done already if REvalOnStartup or RSourceOnStartup set */
/* Setup thread mutex if we're running in a threaded server.*/
rv = ap_mpm_query(AP_MPMQ_IS_THREADED,&threaded);
if (rv != APR_SUCCESS){
fprintf(stderr,"Fatal Error: Can't query the server to dermine if it's threaded!\n");
exit(-1);
}
if (threaded){
rv = apr_thread_mutex_create(&MR_mutex,APR_THREAD_MUTEX_DEFAULT,MR_Pool);
if (rv != APR_SUCCESS){
fprintf(stderr,"Fatal Error: unable to create R mutex!\n");
exit(-1);
}
}
if (apr_env_set("R_HOME",R_HOME,p) != APR_SUCCESS){
fprintf(stderr,"Fatal Error: could not set R_HOME from init!\n");