/
elnode.el
2861 lines (2469 loc) · 94.9 KB
/
elnode.el
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
;;; elnode.el --- a simple emacs async HTTP server -*- lexical-binding: t -*-
;; Copyright (C) 2010, 2011, 2012 Nic Ferrier
;; Author: Nic Ferrier <nferrier@ferrier.me.uk>
;; Maintainer: Nic Ferrier <nferrier@ferrier.me.uk>
;; Created: 5th October 2010
;; Version: 0.9.3
;; Keywords: lisp, http, hypermedia
;; Package-Requires: ((fakir "0.0.4")(creole "0.8.4"))
;; This file is NOT part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; This is an elisp version of the popular node.js asynchronous
;; webserver toolkit.
;;
;; You can define HTTP request handlers and start an HTTP server
;; attached to the handler. Many HTTP servers can be started, each
;; must have it's own TCP port. Handlers can defer processing with a
;; signal (which allows comet style resource management)
;;
;; See elnode-start for how to start an HTTP server.
;;; Source code
;;
;; elnode's code can be found here:
;; http://github.com/nicferrier/elnode
;;; Style note
;;
;; This codes uses the Emacs style of:
;;
;; elnode--private-function
;;
;; for private functions.
;;; Code:
(require 'mm-encode)
(require 'mailcap)
(require 'url-util)
(require 'json)
;; the wiki needs this
(require 'vc)
(require 'creole)
;; only needed for tests
(require 'ert)
(require 'fakir)
(eval-when-compile (require 'cl))
(defconst ELNODE-FORM-DATA-TYPE "application/x-www-form-urlencoded"
"The type of HTTP Form POSTs.")
(defgroup elnode nil
"An extensible asynchronous web server for Emacs."
:group 'applications)
(defvar elnode-server-socket nil
"Where we store the server sockets.
This is an alist of proc->server-process:
(port . process)")
;; Error log handling
(defun elnode-trunc (data)
"Truncate and clean DATA."
(replace-regexp-in-string
"[\r\n]" "."
(substring data 0 (if (> 20 (length data)) (length data) 20))))
(defun elnode-trim (str)
"Trim off whitespace."
(string-match "[ \t\n\r]*$" str)
(setq str (replace-match "" nil nil str))
(string-match "^[ \t\n\r]*" str)
(replace-match "" nil nil str))
(defcustom elnode-error-log-to-messages t
"Wether to send elnode logging through the messaging system."
:group 'elnode
:type '(boolean))
(defvar elnode-server-error-log "*elnode-server-error*"
"The buffer where error log messages are sent.")
(defun elnode--get-error-log-buffer ()
"Returns the buffer for the error-log."
(get-buffer-create elnode-server-error-log))
(defmacro elnode-error (msg &rest args)
"Log MSG with ARGS as an error.
This function is available for handlers to call. It is also used
by elnode iteslf.
There is only one error log, in the future there may be more."
`(let* ((fmtmsg
(format
"elnode-%s: %s"
(format-time-string "%Y%m%d%H%M%S")
(apply 'format (list ,msg ,@args)))))
(with-current-buffer (elnode--get-error-log-buffer)
(goto-char (point-max))
(insert (concat fmtmsg "\n")))
(when elnode-error-log-to-messages
(message "elnode-error: %s" fmtmsg))))
(ert-deftest elnode-test-error-log ()
(let ((err-message "whoops!! something went wrong! %s" )
(err-include "some included value"))
(with-temp-buffer
(let ((test-log-buf (current-buffer)))
;; Setup a fake server log buffer
(flet ((elnode--get-error-log-buffer () test-log-buf))
(elnode-error err-message err-include))
;; Assert the message sent to the log buffer is correctly formatted.
(should (string-match
(format
"^elnode-.*: %s\n$"
(apply 'format `(,err-message ,@(list err-include))))
(buffer-substring (point-min) (point-max))))))))
(ert-deftest elnode-test-error-log-list ()
(let ((err-message "whoops!! something went wrong! %s %s")
(err-include '("included value 1" "included value 2")))
(with-temp-buffer
(let ((test-log-buf (current-buffer)))
;; Setup a fake server log buffer
(flet ((elnode--get-error-log-buffer () test-log-buf))
(elnode-error
err-message
"included value 1" "included value 2"))
;; Assert the message sent to the log buffer is correctly formatted.
(should (string-match
(format
"^elnode-.*: %s\n$"
(apply 'format `(,err-message ,@err-include)))
(buffer-substring (point-min) (point-max))))))))
(defun elnode-log-access (logname httpcon)
"Log the HTTP access in buffer LOGNAME.
This function is available for handlers to call. It is also used
by elnode iteslf."
;; TODO I'd like this to work deeper than this, maybe a if a buffer
;; is named after the handler (or the matched host or path or something)
;; then automatically log to the buffer
;;
;; The buffer could have local variables specifying it's
;; serialization, so Elnode could be told to save it all the time,
;; or in an idle-timer or maybe to make the log file an actual
;; process instead of a buffer (that would be *most* safe?)
(with-current-buffer
(get-buffer-create
(format "*%s-elnode-access*" logname))
(goto-char (point-max))
(insert (format "%s %s % 6d %s %s\n"
(format-time-string "%Y-%m-%d-%H:%M:%S")
(process-get httpcon :elnode-httpresponse-status)
(or (process-get httpcon :elnode-bytes-written) 0)
(elnode-http-method httpcon)
(elnode-http-pathinfo httpcon)))))
;; Defer stuff
(progn
;; Sets up the elnode defer signal
(put 'elnode-defer 'error-conditions '(elnode-defer)))
(defvar elnode--deferred '()
"List of deferred pairs: (socket . handler).")
(defun elnode-defer-now (handler)
"The function you call to defer processing of the current socket.
Pass in the current HANDLER.
FIXME: We could capture the current handler somehow? I think the
point is that whatever signals elnode-defer should be getting
control back when the deferred is re-processed."
(signal 'elnode-defer handler))
(defmacro elnode-defer-or-do (guard &rest body)
"Test GUARD and defer if it succeeds and BODY if it doesn't.
`httpcon' is captured in this macro which means the macro can
only be expanded where there is an inscope `httpcon'."
(declare (indent defun))
(let ((bv (make-symbol "bv")))
`(let ((,bv (lambda (httpcon) ,@body)))
(if ,guard
(elnode-defer-now ,bv)
(progn
(funcall ,bv httpcon))))))
(defun elnode--deferred-add (httpcon handler)
"Add the specified HTTPCON/HANDLER pair to the deferred list."
(elnode-error "deferred-add: adding a defer for %s" httpcon)
(push (cons httpcon handler) elnode--deferred))
(defun elnode--deferred-processor ()
"Process the deferred queue."
(let ((new-deferred (list)))
(loop for pair in elnode--deferred
do
(let ((httpcon (car pair))
(handler (cdr pair)))
(elnode-error "elnode-deferred handling %s %s" httpcon handler)
(condition-case signal-value
(funcall handler httpcon)
('elnode-defer
(push
(cons httpcon (cdr signal-value))
new-deferred))
(error
(elnode-error
"elnode-deferred found an error processing %s" httpcon)))))
;; Set the correct queue
(setq elnode--deferred new-deferred)))
(ert-deftest elnode-deferring ()
"Testing the defer setup."
(let* ((result :not-done)
(httpcon :fake)
(handler (lambda (httpcon) (setq result :done)))
(elnode--deferred (list)))
;; The queue starts empty
(should (equal 0 (length elnode--deferred)))
;; Then we add to it...
(elnode--deferred-add httpcon handler)
(should (equal 1 (length elnode--deferred)))
;; Then we process it...
(elnode--deferred-processor)
;; ... that should have emptied it out...
(should (eq result :done))
(should (equal 0 (length elnode--deferred)))
;; Now we add a handler that defers...
(elnode--deferred-add httpcon
(lambda (httpcon)
(elnode-defer-now handler)))
(should (equal 1 (length elnode--deferred)))
;; Now we process...
(elnode--deferred-processor)
;; ... should still have the deferred handler in it...
(should (equal 1 (length elnode--deferred)))
;; ... process again ...
(elnode--deferred-processor)
(should (equal 0 (length elnode--deferred)))))
(defvar elnode--defer-timer nil
"The timer used by the elnode defer processing.
This is initialized by `elnode--init-deferring'.")
(defun elnode--init-deferring ()
"Initialize elnode defer processing.
Necessary for running comet apps."
(setq elnode--defer-timer
(run-with-idle-timer 0.1 't 'elnode--deferred-processor)))
(defun elnode-deferred-queue (arg)
"Message the length of the deferred queue."
(interactive "P")
(if (not arg)
(message
"elnode deferred queue: %d %s"
(length elnode--deferred)
elnode--defer-timer)
(setq elnode--deferred (list))
(message "elnode deferred queue reset!")))
(defun elnode-deferred-queue-stop ()
"Stop any running deferred queue processor."
(interactive)
(when elnode--defer-timer
(cancel-timer elnode--defer-timer)
(setq elnode--defer-timer nil)))
;;; Basic response mangling
(defcustom elnode-default-response-table
'((201 . "Created")
(400 . "Bad request")
(404 . "Not found")
(500 . "Server error")
(t . "Ok"))
"The status code -> default message mappings.
When Elnode sends a default response these are the text used.
Alter this if you want to change the messages that Elnode sends
with the following functions:
'elnode-send-400'
'elnode-send-404'
'elnode-send-500'
The function `elnode-send-status' also uses these."
:group 'elnode
:type '(alist :key-type integer
:value-type string))
(defun elnode--format-response (status &optional msg)
"Format the STATUS and optionally MESSAGE as an HTML return."
(format "<h1>%s</h1>%s\r\n"
(cdr (or (assoc status elnode-default-response-table)
(assoc t elnode-default-response-table)))
(if msg (format "<p>%s</p>" msg) "")))
;; Main control functions
(defun elnode--sentinel (process status)
"Sentinel function for the main server and for the client sockets."
(elnode-error
"elnode--sentinel %s for process %s"
(elnode-trunc status)
(process-name process))
(cond
;; Server status
((and
(assoc (process-contact process :service) elnode-server-socket)
(equal status "deleted\n"))
(kill-buffer (process-buffer process))
(elnode-error "Elnode server stopped"))
;; Client socket status
((equal status "connection broken by remote peer\n")
(if (process-buffer process)
(progn
(kill-buffer (process-buffer process))
(elnode-error "Elnode connection dropped %s" process))))
((equal status "open\n") ;; this says "open from ..."
(elnode-error "Elnode opened new connection"))
;; Default
(t
(elnode-error "Elnode status: %s %s" process (elnode-trim status)))))
(defun elnode--process-send-string (proc data)
"Elnode adapter for `process-send-string'.
Sends DATA to the HTTP connection PROC (which is an HTTP
connection) using `elnode-http-send-string'.
This is used by `elnode-worker-elisp' to implement a protocol for
sending data through an elnode connection transparently."
(elnode-http-send-string proc data))
(defun elnode--process-send-eof (proc)
"Elnode adapter for `process-send-eof'.
Sends EOF to the HTTP connection PROC (which is an HTTP
connection) in a way that chunked encoding is endeed properly.
This is used by `elnode-worker-elisp' to implement a protocol for
sending data through an elnode connection transparently."
(elnode-error "elnode--process-send-eof on %s" proc)
(elnode-http-send-string proc "")
(process-send-string proc "\r\n")
(elnode--http-end proc))
(defun elnode--http-parse (httpcon)
"Parse the HTTP header for the process.
If the request is not fully complete (if the header has not
arrived yet or we don't have all the content-length yet for
example) this can throw `elnode-parse-http'. The thing being
waited for is indicated.
Important side effects of this function are to add certain
process properties to the HTTP connection. These are the result
of succesful parsing."
(with-current-buffer (process-buffer httpcon)
(save-excursion
(goto-char (point-min))
(let ((hdrend (re-search-forward "\r\n\r\n" nil 't)))
(when (not hdrend)
(throw 'elnode-parse-http 'header))
;; FIXME: we don't handle continuation lines of anything like
;; that
(let* ((lines
(split-string
(buffer-substring (point-min) hdrend)
"\r\n"
't))
(status (car lines)) ;; the first line is the status line
(header (cdr lines)) ;; the rest of the lines are the header
(header-alist-strings
(mapcar
(lambda (hdrline)
(if (string-match "\\([A-Za-z0-9_-]+\\): \\(.*\\)" hdrline)
(cons
(match-string 1 hdrline)
(match-string 2 hdrline))))
header))
(header-alist-syms
(mapcar
(lambda (hdr)
(cons (intern (downcase (car hdr)))
(cdr hdr)))
header-alist-strings))
(content-len (assq 'content-length header-alist-syms)))
;; Check the content if we have it.
(when content-len
(let* ((available-content (- (point-max) hdrend)))
(when (> (string-to-number (cdr content-len))
available-content)
(throw 'elnode-parse-http 'content))))
(process-put httpcon :elnode-header-end hdrend)
(process-put httpcon :elnode-http-status status)
(process-put httpcon :elnode-http-header-syms header-alist-syms)
(process-put httpcon :elnode-http-header header-alist-strings)))))
;; Return a symbol to indicate done-ness
'done)
(defun elnode--http-make-hdr (method resource &rest headers)
"Convenience function to make an HTTP header.
METHOD is the method to use. RESOURCE is the path to use.
HEADERS should be pairs of strings indicating the header values:
(elnode--http-make-hdr 'get \"/\" '(host . \"localhost\"))
Where symbols are encountered they are turned into strings.
Inside headers they are capitalized.
A header pair with the key `body' can be used to make a content body:
(elnode--http-make-hdr 'get \"/\" '(body . \"some text\"))
=>
GET / HTTP/1.1
some text
No other transformations are done on the body, no content type
added or content length computed."
(let (body)
(format "%s %s HTTP/1.1\r\n%s\r\n%s"
(upcase (if (symbolp method) (symbol-name method) method))
resource
(mapconcat
(lambda (header)
(let ((name (if (symbolp (car header))
(symbol-name (car header))
(car header))))
(if (not (equal name "body"))
(format "%s: %s\r\n"
(capitalize name)
(cdr header))
(setq body (cdr header))
"")))
headers
"")
;; If we have a body then add that as well
(or body ""))))
(ert-deftest elnode--make-http-hdr ()
"Test the construction of headers"
(should
(equal
(elnode--http-make-hdr
'get "/"
'(host . "host1")
'(user-agent . "test-agent"))
"GET / HTTP/1.1\r
Host: host1\r
User-Agent: test-agent\r
\r
"))
(should
(equal
(elnode--http-make-hdr
'get "/"
'(host . "host2")
'(user-agent . "test-agent")
'(body . "my data"))
"GET / HTTP/1.1\r
Host: host2\r
User-Agent: test-agent\r
\r
my data")))
(ert-deftest elnode--http-parse-header-complete ()
"Test the HTTP parsing."
(fakir-mock-process
((:buffer
(elnode--http-make-hdr
'get "/"
'(host . "localhost")
'(user-agent . "test-agent"))))
;; Parse the header
(should
(equal 'done
(catch 'elnode-parse-http
(elnode--http-parse nil))))
;; Now check the side effects
(should
(equal
(process-get nil :elnode-http-header)
'(("Host" . "localhost")
("User-Agent" . "test-agent"))))))
(ert-deftest elnode--http-parse-header-incomplete ()
"Test the HTTP parsing of an incomplete header.
An HTTP request with an incomplete header is setup and tested,
then we finish the request (fill out the header) and then test
again."
(fakir-mock-process
((:buffer
"GET / HTTP/1.1\r\nHost: localh"))
;; Now parse
(should
;; It fails with incomplete 'header signal
(equal 'header
(catch 'elnode-parse-http
(elnode--http-parse nil))))
;; Now put the rest of the header in the buffer
(with-current-buffer (process-buffer nil)
(goto-char (point-max))
(insert "ost\r\n\r\n"))
(should
;; Now it succeeds with the 'done signal
(equal 'done
(catch 'elnode-parse-http
(elnode--http-parse nil))))))
(ert-deftest elnode--http-parse-body-incomplete ()
"Tests the HTTP parsing of an incomplete body.
An HTTP request with an incomplete body is setup and tested, then
we finish the request (fill out the content to content-length)
and then test again."
(fakir-mock-process
((:buffer
(elnode--http-make-hdr
'get "/"
'(host . "localhost")
'(user-agent . "test-agent")
`(content-length . ,(format "%d" (length "this is not finished")))
'(body . "this is not fin"))))
;; Now parse
(should
(equal 'content
(catch 'elnode-parse-http
(elnode--http-parse nil))))
;; Now put the rest of the text in the buffer
(with-current-buffer (process-buffer nil)
(goto-char (point-max))
(insert "ished"))
;; And test again
(should
(equal 'done
(catch 'elnode-parse-http
(elnode--http-parse nil))))))
(defun elnode--get-server-prop (process key)
"Get the value of the KEY from the server attached to PROCESS.
Server properties are bound with `elnode-start' which sets up
`elnode--log-fn' to ensure that all sockets created have a link
back to the server."
(let* ((server (process-get process :server))
(value (process-get server key)))
value))
(defun elnode--make-send-string ()
"Make a function to send a string to an HTTP connection."
(lambda (httpcon str)
"Send STR to the HTTPCON.
Does any necessary encoding."
(elnode--process-send-string httpcon str)))
(defun elnode--make-send-eof ()
"Make a function to send EOF to an HTTP connection."
(lambda (con)
"Send EOF to the HTTPCON.
Does any necessary encoding."
(elnode--process-send-eof con)))
(defun elnode--filter (process data)
"Filtering DATA sent from the client PROCESS..
This does the work of finding and calling the user HTTP
connection handler for the request on PROCESS.
A buffer for the HTTP connection is created, uniquified by the
port number of the connection."
(let ((buf
(or
(process-buffer process)
;; Set the process buffer (because the server doesn't
;; automatically allocate them)
;;
;; The name of the buffer has the client port in it
;; the space in the name ensures that emacs does not list it
;;
;; We also use this moment to setup functions required by
;; elnode-worker-lisp
(let* ((port (cadr (process-contact process)))
(send-string-func (elnode--make-send-string))
(send-eof-func (elnode--make-send-eof)))
(process-put
process :send-string-function
send-string-func)
;; ... and this one does closing the connection properly
;; with elnode's chunked encoding.
(process-put
process :send-eof-function
send-eof-func)
;; Now do the buffer creation
(set-process-buffer
process
(get-buffer-create (format " *elnode-request-%s*" port)))
(process-buffer process)))))
(with-current-buffer buf
(insert data)
;; Try and parse...
(case (catch 'elnode-parse-http
(elnode--http-parse process))
;; If this fails with one of these specific codes it's
;; ok... we'll finish it when the data arrives
('(header content)
(elnode-error "elnode--filter: partial header data received"))
;; We were successful so we can call the user handler.
('done
(save-excursion
(goto-char (process-get process :elnode-header-end))
(let ((handler
(elnode--get-server-prop process :elnode-http-handler)))
;; This is where we call the user handler
;; TODO: this needs error protection so we can return an error?
(condition-case signal-value
(progn
(elnode-error "filter: calling handler on %s" process)
(funcall handler process)
(elnode-error "filter: handler returned on %s" process))
('elnode-defer
(elnode-error "filter: defer caught on %s" process)
(case (elnode--get-server-prop process :elnode-defer-mode)
((:managed 'managed)
(elnode--deferred-add process
(cdr signal-value)))
((:immediate 'immediate)
(elnode-error "filter: immediate defer on %s" process)
(funcall (cdr signal-value) process))))
('t
;; FIXME: we need some sort of check to see if the
;; header has been written
(elnode-error "elnode--filter: default handling")
(process-send-string
process
(elnode--format-response 500)))))))))))
(defmacro with-elnode-mock-server (handler &rest body)
"Execute BODY with a fake server which is bound to HANDLER.
This is useful for doing end to end client testing:
(ert-deftest elnode-some-page ()
(with-elnode-mock-server 'elnode-hostpath-default-handler
(elnode-test-call \"/something/test\")))
The test call with be passed to the
`elnode-hostpath-default-handler' via the normal HTTP parsing
routines."
(declare
(indent defun)
(debug t))
`(flet ((elnode--get-server-prop
(proc key)
(cond
((eq key :elnode-http-handler)
,handler))))
,@body))
(defun* elnode-test-call (path
&key
(method "GET")
(parameters '())
(headers '()))
"Fake a call to elnode with the PATH.
In addition you can specify some extra HTTP stuff:
:method one of GET, POST, DELETE, etc...
:parameters POST parameters, will be turned into a POST body
:headers any specific headers you require, you may override
test-call headers.
For example:
(elnode-test-call \"/wiki/test\")
or:
(elnode-test-call \"/wiki/test\"
:method \"POST\"
:parameters '((\"a\" . 10)))
For header and parameter names, strings MUST be used currently."
(let ((fakir-mock-process-require-specified-buffer t))
(fakir-mock-process ()
(let ((hdrtext
(apply
'elnode--http-make-hdr
`(,method
,path
,@headers
(body ""))))
(http-connection t))
;; Capture the real eof-func and then override it to do fake ending.
(let ((eof-func (elnode--make-send-eof))
(the-end 0)
result-data)
(flet
((elnode--make-send-eof
()
(lambda (httpcon)
;; Flet everything in elnode--http-end
(flet ((process-send-eof
(proc)
;; Signal the end
(setq the-end 't))
(delete-process
(proc)
;; Do nothing - we want the test proc
)
(kill-buffer
(buffer)
;; Again, do nothing, we want this buffer
(with-current-buffer buffer
(setq
result-data
(buffer-substring (point-min) (point-max))))
;; Return true, don't really kill the buffer
t))
;; Now call the captured eof-func
(funcall eof-func httpcon)))))
(elnode--filter http-connection hdrtext)
;; Now we sleep till the-end is true
(while (not the-end)
(sleep-for 0 10))
(when the-end
(list
:result-data
result-data
:buffer
(process-buffer http-connection)
;; These properties are set by elnode-http-start
:status
(process-get
http-connection
:elnode-httpresponse-status)
:header
(process-get
http-connection
:elnode-httpresponse-header)))))))))
(defun elnode-test-handler (httpcon)
"A simple handler for testing 'elnode-test-call"
(elnode-http-start httpcon 200 '("Content-Type" . "text/html"))
(elnode-http-return
httpcon
"<html><body><h1>Hello World</h1></body></html>"))
(ert-deftest elnode-test-call-page ()
(with-elnode-mock-server
;; Test dispatcher
(lambda (httpcon)
(elnode-hostpath-dispatcher
httpcon
'(("[^/]+/test/.*" . elnode-test-handler))))
(let ((r (elnode-test-call "/test/test.something")))
(should (equal (plist-get r :status) 200)))))
(defun elnode--log-fn (server con msg)
"Log function for elnode.
Serves only to connect the server process to the client processes"
(process-put con :server server))
(defvar elnode-handler-history '()
"The history of handlers bound to servers.")
(defvar elnode-port-history '()
"The history of ports that servers are started on.")
(defvar elnode-host-history '()
"The history of hosts that servers are started on.")
;;;###autoload
(defun* elnode-start (request-handler
&key
port
(host "localhost")
(defer-mode :managed))
"Start a server using REQUEST-HANDLER.
REQUEST-HANDLER will handle requests on PORT on HOST (which is
'localhost' by default).
REQUEST-HANDLER is a function which is called with the request.
The function is called with one argument, which is the
http-connection.
You can use functions such as `elnode-http-start' and
`elnode-http-send-body' to send the http response.
Example:
(defun nic-server (httpcon)
(elnode-http-start httpcon 200 '((\"Content-Type: text/html\")))
(elnode-http-return httpcon \"<html><b>BIG!</b></html>\")
)
(elnode-start 'nic-server)
Now visit http://127.0.0.1:8000
If PORT is non-nil, then run server on PORT, otherwise default to
8000.
If HOST is non-nil, then run the server on the specified local IP
address, otherwise use localhost. A few names are predefined:
\"localhost\" is 127.0.0.1
\"*\" is 0.0.0.0
Additionally, you may specifiy an IP address, e.g \"1.2.3.4\"
Note that although HOST may be specified, elnode does not
disambiguate on running servers by HOST. So you cannot start two
elnode servers on the same port on different hosts."
(interactive
(let ((handler (completing-read "Handler function: "
obarray 'fboundp t nil nil))
(port (read-number "Port: " 8000))
(host (read-string "Host: " "localhost" 'elnode-host-history)))
(list (intern handler) :port port :host host)))
(let ((port (or port 8000))
(host (or host "localhost")))
(unless (assoc port elnode-server-socket)
;; Add a new server socket to the list
(setq elnode-server-socket
(cons
(cons port
(let ((buf (get-buffer-create "*elnode-webserver*")))
(make-network-process
:name "*elnode-webserver-proc*"
:buffer buf
:server t
:nowait 't
:host (cond
((equal host "localhost") 'local)
((equal host "*") nil)
(t host))
:service port
:coding '(raw-text-unix . raw-text-unix)
:family 'ipv4
:filter 'elnode--filter
:sentinel 'elnode--sentinel
:log 'elnode--log-fn
:plist (list
:elnode-http-handler request-handler
:elnode-defer-mode defer-mode))))
elnode-server-socket)))))
;; TODO: make this take an argument for the
(defun elnode-stop (port)
"Stop the elnode server attached to PORT."
(interactive "nPort: ")
(let ((server (assoc port elnode-server-socket)))
(if server
(progn
(delete-process (cdr server))
(setq elnode-server-socket
;; remove-if
(let ((test (lambda (elem)
(= (car elem) port)))
(l elnode-server-socket)
result)
(while (car l)
(let ((p (pop l))
(r (cdr l)))
(if (not (funcall test p))
(setq result (cons p result)))))
result))))))
(defun elnode-list-buffers ()
"List the current buffers being managed by Elnode."
(interactive)
(with-current-buffer (get-buffer-create "*elnode-buffers*")
(erase-buffer)
(mapc
(lambda (b)
(save-excursion
(if (string-match " \\*elnode-.*" (buffer-name b))
(insert (format "%s\n" b)))
))
(sort (buffer-list)
(lambda (a b)
(string-lessp (buffer-name b) (buffer-name a))))))
(display-buffer (get-buffer "*elnode-buffers*")))
(defun elnode-time-encode (time-str)
"Basic TIME-STR to time encoding."
(apply 'encode-time (parse-time-string time-str)))
;; HTTP API methods
(defun elnode--http-hdr (httpcon)
"Return the header cons for the HTTPCON.
The status-line and the header alist."
(cons
(process-get httpcon :elnode-http-status)
(process-get httpcon :elnode-http-header)))
(defun elnode-http-header (httpcon name &optional convert)
"Get the header specified by NAME from the HTTPCON.
HEADER may be a string or a symbol. If NAME is a symbol it is
case insensitve.
If optional CONVERT is specified it may specify a conversion,
currently supported conversions are:
:time - to convert a time value properly"
(let* ((key (if (symbolp name)
(intern (downcase (symbol-name name)))
name))
(hdr (process-get
httpcon
(if (symbolp key)
:elnode-http-header-syms
:elnode-http-header)))
(val (cdr (assoc key hdr))))
(case convert
(:time
(when val
(elnode-time-encode val)))
(t
val))))
(ert-deftest elnode-http-header ()
"Test that we have headers."
(fakir-mock-process
((:buffer
(elnode--http-make-hdr
'get "/"
'(host . "localhost")
'(user-agent . "test-agent")
'(if-modified-since . "Mon, Feb 27 2012 22:10:21 GMT")
`(content-length . ,(format "%d" (length "this is finished")))
'(body . "this is finished"))))
;; Now parse
(should
(equal 'done
(catch 'elnode-parse-http
(elnode--http-parse nil))))
(should
(equal "test-agent"
(elnode-http-header :httpcon "User-Agent")))
(should
(equal "test-agent"
(elnode-http-header :httpcon 'user-agent)))
(should
(equal "test-agent"
(elnode-http-header :httpcon 'User-Agent)))
(should
(equal '(20299 65357)
(elnode-http-header :httpcon 'if-modified-since :time)))
;; FIXME - add a test for bad time encoding
(should