-
Notifications
You must be signed in to change notification settings - Fork 0
/
rugby-debug.r
executable file
·1397 lines (1276 loc) · 38.2 KB
/
rugby-debug.r
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
REBOL [
Title: "Rugby"
File: %rugby-debug.r
]
current-port: none
hipe-serv: make object!
[
server-ports: copy []
server-map: copy []
port-q: copy []
object-q: copy []
threads: copy []
current-thread: none
conn-timeout: 0:0:30
max-thread-waiting: 0
add-thread: func [o [object!] {The thread to add}]
[
append hipe-serv/threads o
o
]
remove-thread: func [o [object!] {The thread to remove}]
[
remove find head hipe-serv/threads o
]
process-thread: func [/local do-thread]
[
do-thread: none
if empty? hipe-serv/threads
[ return ]
if none? current-thread [ current-thread: head hipe-serv/threads]
if tail? current-thread [current-thread: head current-thread]
do-thread: pick current-thread 1
if object? do-thread
[
either 'clean-up = do-thread/code-pointer
[
error? try [ do do-thread/clean-up ]
remove-thread do-thread
]
[
if error? try [ do get/any in do-thread do-thread/code-pointer]
[
if found? find first do-thread 'clean-up
[
;do additional cleanup
error? try
[
do do-thread/clean-up
]
]
remove-thread do-thread
]
]
]
if not tail? current-thread [ current-thread: next current-thread]
]
get-handler: func
[
{Returns the handler for a given server port}
p [port!]
]
[
return select server-map p
]
add-server-port: func
[
{Adds a server port and its handler to the list and the map}
p [port!]
handler [any-function!]
]
[
append server-ports p
append server-map p
append server-map :handler
return
]
remove-server-port: func
[
{Removes a server from our list and map}
]
[
remove find server-ports p
remove remove find server-map p
return
]
port-q-delete: func
[
{Removes a port from our port list.}
target [port!]
]
[
remove find port-q target
]
port-q-insert: func
[
{Inserts a port into our port list.}
target [port!]
]
[
append port-q target
]
object-q-insert: func
[
{Inserts a port and its corresponding object into the object queue.}
serv [port!] {The server port}
target [port!] {The connection}
/local o my-handler
]
[
my-handler: get-handler serv
append hipe-serv/object-q target
o: make object! [port: target handler: :my-handler user-data: none
lastaccess: now]
append hipe-serv/object-q o
]
object-q-delete: func
[
{Removes a port and its corresponding object from the object queue.}
target [port!]
]
[
remove/part find hipe-serv/object-q target 2
]
start: func
[
{Initializes everything for a client connection on application level.}
serv [port!] {The server port}
conn [port!] {The connection port}
]
[
port-q-insert conn
object-q-insert serv conn
]
stop: func
[
{Cleans up after a client connection.}
conn [port!]
/local conn-object
]
[
port-q-delete conn
error? try
[
conn-object: select hipe-serv/object-q conn
close conn-object/port
object-q-delete conn
]
]
init-server-port: func
[
{Initializes our main server port.}
p [port! url!]
conn-handler [any-function!]
/local dest
]
[
either url? p
[ dest: make port! p]
[ dest: p]
add-server-port dest :conn-handler
append port-q dest
; Increase the backlog for this server. 15 should be possible (default
; is 5)
;REMOVE this for compatibility (o.a. Mac) or set it to 5 or so.
p/backlog: 15
open/no-wait dest
]
process-ports: func
[
{Processes all ports that have events.}
portz [block!] {The port list}
/local temp-obj
]
[
repeat item portz
[
current-port: item
either (found? find server-ports item)
[
either item/scheme = 'udp
;udp, so call our handler
[
temp-obj: get-handler item
temp-obj copy item
]
[
start item first item
]
]
[
if item/scheme = 'tcp
[
temp-obj: select hipe-serv/object-q item
temp-obj/lastaccess: now
temp-obj/handler temp-obj
]
]
]
]
serve: func
[
{Starts serving. Does a blocking wait until there are events.
Processes thread in the background as well!}
/local portz
]
[
forever
[
portz: wait/all join port-q 0.005 ; <--- problem caused probably by the timeout
either none? portz
[ process-thread ]
[
process-ports portz
;If there are more than 100 threads, start processing anyway
if hipe-serv/max-thread-waiting < length? hipe-serv/threads
[ process-thread ]
]
]
]
]
set 'add-thread get in hipe-serv 'add-thread
set 'remove-thread get in hipe-serv 'remove-thread
; This object implements the server side of a request broker.
rugby-server: make hipe-serv
[
http-srv: none
compression: no
ip-address: system/network/host-address
; Block containg words that are allowed to be executed.
exec-env: copy []
; Block containing generated stub code.
stubs: none
build-proxy: func
[
name [word!]
/secure-code
/with hp [integer!]
/local hu command f spec my-spec f-name meta-f p1 p2 li
]
[
;Don't make stubs on things that aren't functions
if not any-function? get/any name
[ throw make error! "Rugby error: trying to generate a proxy on a type that is not a function" ]
hu: rejoin [ http:// rugby-server/ip-address ":" either with [hp][8002] ]
command: either secure-code [{sexec}] [{rexec} ]
;Get the function and its specs
f: get name
spec: third :f
my-spec: first :f
f-name: mold name
;The meta function.
;This is the actual code block that is returned upon invocation
;The generated defined function use a use context extension to
;get access to itself.
meta-f: copy/deep
[
;the function name
(to-set-word f-name )
;Our use context to give acces to ourself
func (meta-spec)
[
http-port: {_*http*_}
statement: copy []
rugby-statement: copy []
ref-mode: on
rugby-comm: copy (command)
append rugby-comm "/with"
comm: copy (f-name)
my-spec: copy (meta-spec)
if found? index: find my-spec /local
[my-spec: copy/part my-spec index]
p1: [(p1)]
p2: [(p2)]
parse my-spec [ any [ p1 | p2 | skip ]]
insert head statement to-path comm
insert rugby-statement to-path rugby-comm
append/only rugby-statement statement
append rugby-statement http-port
do bind rugby-statement 'do
]
]
;The two parse rules for meta-f.
;Due to the parens in parse rules and compose....
;p1 matches refinements and adds them to comm (the remote function)
;or rugby-comm (rexec or sexec)
;If a refinement is matched and active, ref-mode goes on so that variables
;are copied in p2
p1: [ set r refinement!
(either get bind to-word r 'comm
[
either any [ r = /deferred r = /oneway]
[
append rugby-comm mold r
]
[
append comm mold r
]
ref-mode: on
]
[ ref-mode: off ]
)
]
;matches words and copies their values to the statement if ref-mode = on
;HMK: Changed to allow lit-words to be copied in verbatim, but
;I'm not sure this fix covers everything.
p2: [set w word!
(if ref-mode [
w: get bind to-word w 'comm
append/only statement either any-word? :w [to lit-word! :w][:w]
])
]
;this is buggy for lit-word!
;p2: [set w word!
; (if ref-mode [append/only statement get bind to-word w 'comm])]
;Get only the code to /local from the signature block
if found? li: find spec /local
[ spec: copy/part spec ((index? li) - 1) ]
;Generate the function signature
;do mold because of the type conservation
meta-spec: do mold spec
;Append the extra stub refinements
append meta-spec [ /deferred /oneway ]
;append some local variables
append meta-spec [ /local http-port statement my-spec
p1 p2 ref-mode comm r index what-ref rugby-statement
rugby-comm]
;Compose does block flattening, hence an extra block.
meta-spec: append/only copy [] meta-spec
return compose/deep meta-f
]
build-stubs: func
[
{Builds stub code that allows remote invocation of exposed functions
asif they were local to the client.}
expose-list [block!] {List of functions to expose.}
/secure-code
/with hp [integer!] {Number of the http port.}
/local stub num
]
[
stub: copy []
;build our stubs
num: either with [hp] [8002]
repeat entry expose-list
[
either secure-code
[ append stub build-proxy/with/secure-code to-word entry num ]
[ append stub build-proxy/with to-word entry num]
];repeat
return stub
]
get-stubs: func []
[
return stubs
]
nargs: func
[
{Returns the total number of args of a function (with and without
refinements)}
f [word! lit-path!]
/local argc f-blk f-ref f-sig ref-pos next-ref-pos
]
[
;The total number or arguments
argc: 0
;We either have a path or a function
;If we have a path, we count the number
;of arguments of the supplied refinements first.
either path? f
[
;Translate the path to a block
f-blk: to-block f
;Is it a function?
if not any-function? get/any first f-blk
[throw make error! "Rugby error: invocation not on a function"]
bind f-blk 'do
;The refinements used
f-ref: next head f-blk
;the function signature
f-sig: first get first f-blk
;Now get the number of arguments foreach refinement
;and add them to argc
repeat ref f-ref
[
;Find the ref refinement
ref-pos: find/tail f-sig to-refinement ref
;If succeed in the find
if not none? ref-pos
[
;try to find the next one
next-ref-pos: find ref-pos refinement!
if not none? next-ref-pos
[
argc: argc + ((index? next-ref-pos) - (index? ref-pos))
];if not none next-ref-pos
];if not none? ref-pos
];foreach ref f-ref
];either path? f first clause
[
if not any-function? get/any f
[ throw make error! "Rugby error: invocation not on a function" ]
f-sig: first get f
];either path? f second clause
;Add the number of function arguments
argc: argc + -1 + index? any [ find f-sig refinement! tail f-sig ]
];nargs
compose-msg: func
[
{Creates a message for on the wire transmission.}
msg [any-block!]
]
[
f-msg: reduce [checksum/secure mold do mold msg msg]
return either self/compression
[ mold compress mold f-msg ]
[ mold/all f-msg ] ; using mold/all here does not halt execution!
]
clear-buffer: func
[
cleary [port!]
/upto {clear a specified amount of bytes}
n {the number of bytes to be cleared}
/local msg size-read
]
[
msg: copy {}
loop either upto [ n ][ 1 ]
[
until
[
size-read: read-io cleary msg 1
;1 = size-read ; HMK: Size-read is sometimes 0, which hangs this line
1 >= size-read ; HMK
]
]
]
decompose-msg: func
[
{Extracts a message that has been transmitted on the wire.}
msg [any-string!]
/local im1 im2
]
[
either self/compression
[
im1: trim/all msg
; either all [ #"#" = first msg #"{" = second msg #"}" = last msg ]
either parse to-block msg [ set im1 binary! ]
; [ im2: decompress do im1]
[im2: decompress im1 ]
[ make error! {Invalid message format.} ]
]
[
im2: to-block msg
type? first im2
]
; either all [ #"[" = first im2 #"]" = last im2]
either parse to-block im2 [ set im1 block! ]
; [return do im2]
[ return im1 ]
[ make error! {Invalid message format}]
]
check-msg: func
[
{Check message integrity.}
msg [any-block!]
]
[
;HMK: changed to reflect correctly what happens in compose-msg
return (checksum/secure mold do mold second msg) = first msg
]
write-msg: func
[
{Does a low-level write of a message.}
msg
dest [port!]
/local length
]
[
; We try to write at least 16000 bytes at a time
either 16000 > length? msg
[
length: write-io dest msg length? msg
; Message written, we're done
either length = length? msg
[
return true
]
; We're not done. Return what we have written
[
return length
]
]; either 16000 > first clause
[
length: write-io dest msg 16000
]
; We're done, port is closed
if 0 > length [ return true]
return length
]
safe-exec: func
[
{Safely executes a message. Checks the exec-env variable for a list of
valid commands to execute.}
statement [any-block!]
env [any-block!]
/local n stm act-args stm-blok
]
[
if found? find env either path? statement/1 [statement/1/1][statement/1]
[
n: nargs to-lit-path statement/1
act-args: n
stm-blok: copy statement
until
[
stm-blok: find/tail stm-blok [make object!]
act-args: act-args + 2
not found? stm-blok
]
stm: copy/part statement act-args
return do stm
]
make error! rejoin [ "Rugby server error: Unsupported function: "
mold statement ]
]
send-header: func
[
{Send a http OK header}
client-port
]
[
insert client-port {HTTP/1.0 200 OK^/Content-type: text/plain ^/^/}
]
request-read?: func
[
{Checks to see whether a HTTP request has been read}
req [string!] {The request to be analyzed}
]
[
find/last req "xtra-info:"
]
web-clearies: func
[
req [string!]
/local r r1 t1
]
[
return (length? " 1234567891011121314") -
(length? find/tail req "xtra-info:")
]
suspend: func [] [
;We have to make sure hipe isn't sending events to the port/handler
;anymore!
port-q-delete current-port
object-q-delete current-port
throw 'suspend
]
resume: func [
value
port [port!]
]
[
write-result value port
return
]
get-request: func
[
{Extracts a Rugby request from a HTTP request.}
req [string!] {The request to extract}
/local rule rugby-req
]
[
rule: [ thru "rugby-rq: " thru "[***" copy rugby-req to "***]" ]
parse req rule
return rugby-req
]
;Our web server handler
web-handler: func
[
o [object!]
/local ud data-read the-request result wr-res
cl offset ; HMK
]
[
catch
[
;This is the first time we enter for this object!
;Initialize the user data
if none? o/user-data
[
o/user-data: make object!
[
request-read: false
request-data: copy {}
result-data: copy {}
request-length: 0 ; HMK
content-length: 0 ; HMK
content-remaining: 0 ; HMK
result: copy {}
header-written: false
result-written: false
]
]
;Just a short-hand
ud: o/user-data
;We still have data to read
unless ud/request-read
[
until [
insert tail ud/request-data copy/part o/port 16
ud/content-length: find/last/tail ud/request-data "Content-Length: "
]
ud/content-length:
to integer! head clear find copy/part ud/content-length 10 newline
ud/request-length: 2048 ; max copy length allowed
probe ud/content-remaining: max 0 ud/content-length
probe head insert tail ud/request-data copy/part o/port ud/content-length + 10
ud/request-read: true
return
]
;We have our data, but did not do a rexec yet.
if (empty? ud/result)
[
if error? try [ the-request: decompose-msg get-request ud/request-data ]
[
stop o/port
return
]
either check-msg the-request
[
if error? set/any 'result try
[ safe-exec bind pick the-request 2 'do exec-env]
[
result: disarm result
]
;Do we have a return value at all?
ud/result: compose-msg either value? 'result
[
append/only copy [] get/any 'result
]
[
copy [unset!]
]
insert ud/result copy {[***}
append ud/result copy {***]}
]
[
;We can't do a rexec, hence we do not proxy. Kill'em all (might be
; a malicious hacker!)
;clear-buffer o/port
stop o/port
return
]
]; if empty? ud/result
;Write the header
if not ud/header-written
[
send-header o/port
ud/header-written: true
return
]
;Is the result returned?
if not ud/result-written
[
wr-res: write-msg ud/result o/port
either logic? wr-res
[
ud/result-written: true
clear-buffer/upto o/port web-clearies ud/request-data
stop o/port
]
[
remove/part ud/result wr-res
]; either
return
]
] 'suspend
attempt [
clear-buffer/upto o/port web-clearies ud/request-data
]
];web-handler
write-result: func [
value
port [port!]
/local message wr-res
][
if error? value [ value: disarm value]
message: compose-msg append/only copy [] value
insert message copy {[***}
append message copy {***]}
send-header port
wr-res: write-msg message port
while [not logic? wr-res][
remove/part message wr-res
wr-res: write-msg message port
]
stop port
return
]
init-rugby: func
[
{Inits our server according to our server port-spec and with rugby's
do-handler}
x-env [any-block!]
http-num [integer!]
]
[
rugby-server/http-srv: http-num
append exec-env x-env
; Build the stubs and store them in our object variable.
stubs: copy build-stubs/with exec-env http-num
]
init-http-proxy: func
[
{Inits our http proxy}
port-spec [port!]
]
[
init-server-port port-spec :web-handler
]
]
set 'get-stubs get in rugby-server 'get-stubs
set 'suspend get in rugby-server 'suspend
set 'resume get in rugby-server 'resume
serve: func
[
{Exposes a set of commands as a remote service}
commands [block!] {The commands to expose}
/with {Expose on a different port than tcp://:8002}
p [url!] {Other port}
/restrict {Restrict access to a block of ip numbers}
r [block!] {ip numbers}
/nostubs {Don't provide access to stubs with get-stubs function.}
/local local-commands http-dest
]
[
local-commands: copy commands
; We only add a function to get at the stubs if we are asked to.
if not nostubs
[
append local-commands [ get-stubs ]
]
;On what port do we do the http proxy
http-dest: make port! either with [ p ][ tcp://:8002 ]
rugby-server/init-http-proxy http-dest
rugby-server/init-rugby local-commands http-dest/port-id
rugby-server/serve
]
tunnel-ctx: context
[
default-proxy: http://localhost:8002
default-deferred-proxy: httpr://localhost:8002
deferred-index: 0
deferred-ports: copy []
ret-vals: copy []
compression: no
transform-url: func
[
{Transforms a http url in a httpr url}
u [url!]
/local mark mu
]
[
replace copy u 'http 'httpr
]
result?: func
[
{Checks to see whether a string is a result}
s [string! none!]
/local val
]
[
if none? s [make error! {Rugby error: no result available for this index}]
val: none
parse/all s [ thru {[***} copy val to {***]} ]
either none? val [ return false] [return true]
]
wait-for-result: func
[
{waits for a http result}
index [integer!]
]
[
until
[
wait 0.003 ; bug fix for potential hang. see also wait-for-secure-result
; a wait on the client. Could we do some timeout stuff here?
result-available? index
]
return get-result index
]
append-port: func
[
{Appends a port to the deferred-ports list}
p [port!]
/local res
]
[
res: copy {}
deferred-index: 1 + deferred-index
repend deferred-ports [ deferred-index p]
repend ret-vals [deferred-index res]
return deferred-index
]
to-result: func
[
{Return a result from a http request}
ret-val [string!]
/local res ret
]
[
;extract the result string
parse/all ret-val [ thru {[***} copy res to {***]} ]
ret: second decompose-msg res
do ret
]
compose-msg: func
[
{Creates a message for on the wire transmission.}
msg [any-block!]
]
[
f-msg: reduce [checksum/secure mold do mold msg msg]
return either self/compression
[ mold compress mold f-msg]
[ mold/all f-msg]
]
decompose-msg: func
[
{Extracts a message that has been transmitted on the wire.}
msg [any-string!]
/local im1 im2
]
[
either self/compression
[
im1: trim/all msg
either all [ #"#" = first msg #"{" = second msg #"}" = last msg ]
[ im2: decompress do im1]
[ make error! {Invalid message format.} ]
]
[
im2: msg
]
either all [ #"[" = first im2 #"]" = last im2]
[ return do im2 ]
[ make error! {Invalid message format}]
]
check-msg: func
[
{Check message integrity.}
msg [any-block!]
]
[
;HMK: changed to reflect correctly what happens in compose-msg
return (checksum/secure mold do mold second msg) = first msg
]
;Not used anymore, doesn't work with suspend/resume (but why?)
tunnel: func
[
{Tunnels a command using http as a transport layer}
command [block!]
/via
v [url!]
/local cmd-block cmd-string proxy
]
[
proxy: either via [ v ][ default-proxy ]
cmd-block: compose-msg command
cmd-string: rejoin [ {rugby-rq: [***} cmd-block
{***] xtra-info: "1234567891011121314} ]
return to-result read/custom proxy reduce [ 'post cmd-string ]
]
remove-request: func [
{Removes a request and closes the port}
index [integer!]
]
[
close select deferred-ports index
remove remove find ret-vals index
remove remove find deferred-ports index
return
]
get-result: func
[
{returns the result of a deferred http request}
index [integer!]
/local res
]
[
result-available? index
if result? select ret-vals index