File: HttpDaemon.R

package info (click to toggle)
r-cran-r.rsp 0.46.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,472 kB
  • sloc: javascript: 612; tcl: 304; sh: 18; makefile: 16
file content (883 lines) | stat: -rw-r--r-- 19,595 bytes parent folder | download | duplicates (2)
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
###########################################################################/**
# @RdocClass HttpDaemon
#
# @title "The HttpDaemon class"
#
# \description{
#  @classhierarchy
#
#  A minimalistic HTTP daemon (web server) that also preprocesses RSP.
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \section{Fields and Methods}{
#  @allmethods
# }
#
# \details{
#  The actual server is written in Tcl such that it runs in a non-blocking
#  mode, which means that the R prompt will be available for other things.
#  This class is tightly coupled with the source code of the Tcl script.
#
#  For security reasons, the server only accept connections from the
#  local host (127.0.0.1).  This lowers the risk for external computers
#  to gain access to the R session.
#  This is asserted by the \code{accept_connect} Tcl procedure in
#  r-httpd.tcl (located in \code{system.file("tcl/", package="R.rsp")}).
#  If access from other hosts are wanted, then this procedure needs to
#  be modified.
#
#  The Tcl server was written by Steve Uhlers, and later adopted for R by
#  Philippe Grosjean and Tom Short (Rpad package author) [1].
# }
#
# @examples "../incl/HttpDaemon.Rex"
#
# \references{
#   [1] Rpad package, Tom Short, 2005.\cr
# }
#
# @author
#
# @keyword IO
# @keyword internal
#*/###########################################################################
setConstructorS3("HttpDaemon", function(...) {
  this <- extend(Object(), "HttpDaemon",
    .debug = FALSE,
    .count = 0L,
    .rootPaths = NULL
  )

  this$count <- this$count + 1L

  # Check if another server is already running.
  if (this$count > 1L) {
    throw("ERROR: There is already an HttpDaemon running. Sorry, but the current implementation allows only one per R session.")
  }

  this
})

setMethodS3("finalize", "HttpDaemon", function(this, ...) {
  if (isStarted(this))
    terminate(this)
  this$count <- this$count - 1L
}, protected=TRUE, createGeneric=FALSE)


setMethodS3("getCount", "HttpDaemon", function(static, ...) {
  as.integer(static$.count)
}, protected=TRUE)


setMethodS3("setCount", "HttpDaemon", function(static, count, ...) {
  static$.count <- as.integer(count)
}, protected=TRUE)



###########################################################################/**
# @RdocMethod as.character
#
# @title "Returns a short string describing the HTTP daemon"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns a @character string.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
# @keyword programming
#*/###########################################################################
setMethodS3("as.character", "HttpDaemon", function(x, ...) {
  # To please R CMD check
  static <- x

  s <- paste(class(static)[1L], ":", sep="")
  if (isStarted(static)) {
    s <- paste(s, " HTTP daemon is started.", sep="")
    s <- paste(s, " Current root paths: ", paste(getRootPaths(static), collapse=";"), ".", sep="")
    s <- paste(s, " Port: ", getPort(static), ".", sep="")
    s <- paste(s, " Default filename: ", getDefaultFilenamePattern(static),
                                                        ".", sep="")
  } else {
    s <- paste(s, " HTTP daemon is not started.", sep="")
  }
  s
})



#########################################################################/**
# @RdocMethod openUrl
#
# @title "Starts the HTTP daemon and launches the specified URL"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{url}{The URL to be opened.}
#   \item{host}{The host where the HTTP server is running.}
#   \item{port}{The port to be used.}
#   \item{path}{The path to the document to be opened.}
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   Called by for instance @seemethod "startHelp".
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("openUrl", "HttpDaemon", function(static, url=sprintf("http://%s:%d/%s", host, port, path), host="127.0.0.1", port=8074, path="", ...) {
  # - - - - - - - g- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Validate arguments
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Argument 'port':
  port <- Arguments$getInteger(port, range=c(0,65535))


  # Start HTTP server, if not started.
  if (!isStarted(static)) {
    # Start the web server
    rootPath <- system.file("rsp", package="R.rsp")
    start(static, rootPath=rootPath, port=port, ...)
  }

  if (!is.null(url))
    browseURL(url)
})


#########################################################################/**
# @RdocMethod startHelp
#
# @title "Starts the HTTP daemon and launches the help page"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Arguments passed to @seemethod "openUrl".}
# }
#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("startHelp", "HttpDaemon", function(static, ...) {
  openUrl(static, path="R/Help/", ...)
})








#########################################################################/**
# @RdocMethod getConfig
#
# @title "Retrieves the server's 'config' structure from Tcl"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns a tclArray object.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("getConfig", "HttpDaemon", function(static, ...) {
  # Load required package
  requireNamespace("tcltk") || stop("Package not installed/found: tcltk")

  config <- tcltk::as.tclObj("config")
  class(config) <- c("tclArray", class(config))
  config
}, static=TRUE, protected=TRUE)





#########################################################################/**
# @RdocMethod getHttpRequest
#
# @title "Gets the HTTP request"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns a @see "HttpRequest" object.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("getHttpRequest", "HttpDaemon", function(static, ...) {
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Local functions
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  getRequestUri <- function(...) {
    url <- NA
    tryCatch({
      url <- as.character(tcltk::tclvalue("url"))
    }, error = function(ex) {
    })
    url
  }

  getData <- function(field=NULL, ...) {
    data <- tcltk::as.tclObj("data")
    class(data) <- c("tclArray", class(data))
    if (is.null(field))
      return(data)
    value <- data[[field]]
    if (is.null(value))
      return(NULL)
    value <- tcltk::tclvalue(value)
    value
  }

  getRequestParameters <- function(...) {
    params <- list()
    query <- getData("query")
    if (!is.null(query)) {
      query <- strsplit(query, split="&", fixed=TRUE)[[1L]]
      if (length(query) == 0L)
        return(params)

      query <- strsplit(query, split="=", fixed=TRUE)

      for (kk in seq_along(query)) {
        pair <- query[[kk]]
        name <- URLdecode(pair[1L])
        value <- URLdecode(pair[2L])
        params[[kk]] <- value
        names(params)[kk] <- name
      }
    }

    params
  }

  HttpRequest(
    serverPort    = getPort(static),
    contextRoot   = getParent(as.character(tcltk::tclvalue("mypath"))),
    requestUri    = getData("url"),
    queryString   = getData("query"),
    remoteAddress = getData("ipaddr"),
    parameters    = getRequestParameters(static)
  )
}, static=TRUE)




#########################################################################/**
# @RdocMethod getPort
#
# @title "Gets the socket port of the HTTP daemon"
#
# \description{
#  @get "title", if started.
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns an @integer if started, otherwise @NA.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("getPort", "HttpDaemon", function(static, ...) {
  config <- getConfig(static)
  as.integer(config$port)
}, static=TRUE)




#########################################################################/**
# @RdocMethod getRootPaths
#
# @title "Gets the root directories of the HTTP daemon"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns a @vector of @character string if started, otherwise @NA.
# }
#
# @author
#
# \seealso{
#   @seemethod setRootPaths
#   @seemethod appendRootPaths
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("getRootPaths", "HttpDaemon", function(static, ...) {
  # If server is started, updated rootPaths from the servers settings
  if (isStarted(static)) {
    paths <- tcltk::tcl("getRootPaths")
    paths <- as.character(paths)
    static$.rootPaths <- paths
  }

  static$.rootPaths
}, static=TRUE)




#########################################################################/**
# @RdocMethod setRootPaths
#
# @title "Sets a new set of root directories for the HTTP daemon"
#
# \description{
#  @get "title", if started.
# }
#
# @synopsis
#
# \arguments{
#   \item{paths}{A @vector of paths.}
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns (invisibly) the previously known root directories.
# }
#
# @author
#
# \seealso{
#   @seemethod getRootPaths
#   @seemethod appendRootPaths
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("setRootPaths", "HttpDaemon", function(static, paths, ...) {
  oldPaths <- getRootPaths(static)

  # Keep only unique paths
  paths <- unlist(strsplit(paths, split=";", fixed=TRUE), use.names=FALSE)
  paths <- unique(paths)
  static$.rootPaths <- paths

  # If server is started, updated servers settings
  if (isStarted(static)) {
    paths <- paste(paths, collapse=";")
    res <- tcltk::tcl("setRootPaths", paths)
  }

  invisible(oldPaths)
}, static=TRUE)


## setMethodS3("refreshRootPaths", "HttpDaemon", function(static, ...) {
##   # If server is started, updated servers settings
##   if (isStarted(static)) {
##     paths <- getRootPaths(static)
##     paths <- paste(paths, collapse=";")
##     res <- tcltk::tcl("setRootPaths", paths)
##   }
##   invisible(getRootPaths(static))
## }, static=TRUE)



#########################################################################/**
# @RdocMethod appendRootPaths
# @aliasmethod insertRootPaths
#
# @title "Appends and inserts new paths to the list of known root directories"
#
# \description{
#  @get "title", if started.
# }
#
# @synopsis
#
# \arguments{
#   \item{paths}{A @vector of paths.}
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns (invisibly) the previously known root directories.
# }
#
# @author
#
# \seealso{
#   @seemethod getRootPaths
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("appendRootPaths", "HttpDaemon", function(static, paths, ...) {
  setRootPaths(static, c(getRootPaths(static), paths), ...)
}, static=TRUE)


setMethodS3("insertRootPaths", "HttpDaemon", function(static, paths, ...) {
  setRootPaths(static, c(paths, getRootPaths(static)), ...)
}, static=TRUE)





#########################################################################/**
# @RdocMethod getDefaultFilenamePattern
#
# @title "Gets the default filename pattern to be loaded by the HTTP daemon"
#
# \description{
#  @get "title", if started.
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns an @character string if started, otherwise @NA.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("getDefaultFilenamePattern", "HttpDaemon", function(static, ...) {
  config <- getConfig(static)
  as.character(config$default)
}, static=TRUE)




#########################################################################/**
# @RdocMethod isStarted
#
# @title "Checks if the HTTP daemon is started"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns @TRUE if the server is started, otherwise @FALSE.
# }
#
# @author
#
# \seealso{
#   @seemethod "start" and @seemethod "terminate".
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("isStarted", "HttpDaemon", function(x, ...) {
  # To please R CMD check...
  static <- x

  port <- getPort(static)
  (length(port) != 0L)
}, static=TRUE)




#########################################################################/**
# @RdocMethod sourceTcl
#
# @title "Loads the Tcl source for the HTTP daemon into R"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("sourceTcl", "HttpDaemon", function(static, ...) {
  # Load required package
  requireNamespace("tcltk") || stop("Package not installed/found: tcltk")

  tclPath <- system.file("tcl", package="R.rsp")
  pathname <- file.path(tclPath, "r-httpd.tcl")
  if (!isFile(pathname))
    stop("Tcl source code file not found: ", pathname)

  res <- tcltk::tcl("source", pathname)
  invisible(res)
}, static=TRUE, protected=TRUE)




#########################################################################/**
# @RdocMethod start
#
# @title "Starts the HTTP daemon"
#
# \description{
#  @get "title".  Currently, only one HTTP daemon can run at each time,
#  regardless of port used.
# }
#
# @synopsis
#
# \arguments{
#   \item{rootPaths}{The path(s) to act as the root of the web server file
#       system.  Files in parent directories of the root, will not be
#       accessible.  If @NULL, the preset paths will be used,
#       cf. @seemethod "setRootPaths".}
#   \item{port}{The socket port the server listens to.}
#   \item{default}{The default filename pattern to be retrieved if
#       not specified.}
#   \item{...}{Not used.}
# }

#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   @seemethod "setRootPaths".
#   @seemethod "isStarted".
#   @seemethod "terminate".
#   @seemethod "restart".
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("start", "HttpDaemon", function(x, rootPaths=NULL, port=8080, default="^index[.](html|.*)$", ...) {
  # The R.rsp package needs to be attached in order to make certain
  # R functions of R.rsp available to the Tcl HTTP daemon.
  use("R.rsp", quietly=TRUE)

  # To please R CMD check...
  static <- x

  # Is HTTP daemon already started?
  if (isStarted(static))
    stop("HTTP daemon is already started: ", as.character(static))

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Validate arguments
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # Argument 'rootPaths':
  if (length(rootPaths) > 0L) {
    rootPaths <- unlist(strsplit(rootPaths, split=";", fixed=TRUE), use.names=FALSE)
    rootPaths <- unlist(sapply(rootPaths, FUN=function(path) {
      Arguments$getReadablePathname(path, mustExist=TRUE)
    }), use.names=FALSE)
    setRootPaths(static, rootPaths)
  } else {
    rootPaths <- getRootPaths(static)
  }

  # Argument 'port':
  port <- Arguments$getInteger(port, range=c(0L,65535L))

  # Argument 'default':
  default <- Arguments$getCharacter(default, nchar=c(1L,256L))

  # Source the TCL httpd code
  sourceTcl(static)

  # Start the HTTP daemon (the webserver)
  res <- tcltk::tcl("server", paste(rootPaths, collapse=";"), port, default)

  # Validate opened port.
  port <- Arguments$getInteger(tcltk::tclvalue(res), range=c(0L,65535L))

  invisible(port)
}, static=TRUE, createGeneric=FALSE)




#########################################################################/**
# @RdocMethod terminate
#
# @title "Terminates the HTTP daemon"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   @seemethod "isStarted".
#   @seemethod "start".
#   @seemethod "restart".
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("terminate", "HttpDaemon", function(static, ...) {
  # Is HTTP daemon already started?
  if (!isStarted(static))
    stop("HTTP daemon is not started.")

  # Close the httpd socket.
  tcltk::.Tcl("close $config(listen)")
  tcltk::.Tcl("unset config")

  invisible(TRUE)
}, static=TRUE)




#########################################################################/**
# @RdocMethod restart
#
# @title "Restarts the HTTP daemon"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{Not used.}
# }
#
# \value{
#  Returns nothing.
# }
#
# @author
#
# \seealso{
#   @seemethod "isStarted".
#   @seemethod "start".
#   @seemethod "terminate".
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("restart", "HttpDaemon", function(static, ...) {
  if (!isStarted(static))
    throw("HTTP daemon not started.")

  rootPaths <- getRootPaths(static)
  port <- getPort(static)
  default <- getDefaultFilenamePattern(static)

  terminate(static, ...)

  start(static, rootPaths=rootPaths, port=port, default=default, ...)
}, static=TRUE)




#########################################################################/**
# @RdocMethod writeResponse
#
# @title "Writes a string to the HTTP output connection"
#
# \description{
#  @get "title".
# }
#
# @synopsis
#
# \arguments{
#   \item{...}{A set of @character strings to be outputted.}
# }
#
# \details{
#   \emph{Note: For efficiency, there is no check if the HTTP daemon is
#         started or not.}
# }
#
# \value{
#  Returns (invisibly) the number of characters written.
# }
#
# @author
#
# \seealso{
#   @seeclass
# }
#
# @keyword IO
#*/#########################################################################
setMethodS3("writeResponse", "HttpDaemon", function(static, ...) {
  str <- paste(..., collapse="", sep="")

  # Nothing to do?
  if (nchar(str) == 0L) {
    return(invisible(0L))
  }

  if (isTRUE(static$.debug)) {
    mcat("=========================================================\n")
    mcat("= BEGIN: Fake HttpDaemon response\n")
    mcat("=========================================================\n")
    mcat(str)
    mcat("=========================================================\n")
    mcat("= END: Fake HttpDaemon response\n")
    mcat("=========================================================\n")
  } else {
    # Escape certain characters, by converting the string to a Tcl string
    # and back.
    str <- as.character(tcltk::tclVar(str))

    # Write the string to HTTP output connection.
    tcltk::.Tcl(paste("catch { puts $sock $", str, " }", sep=""))
  }

  invisible(nchar(str))
})