id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
8,247
dom.lisp
evrim_core-server/src/markup/dom.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| DOM Library ;;+---------------------------------------------------------------------------- ;; ;; This file contains data structures, parsers, renderers for generic document ;; object model of W3C (ie html, xml, rss, rdf) ;; ;; ---------------------------------------------------------------------------- ;; DOM Elements Metaclass ;; ---------------------------------------------------------------------------- ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (defclass dom-element+ (class+) ;; ((attributes :initarg :attributes)))) ;; (defmethod dom-element+.attributes ((dom-element+ dom-element+)) ;; (if (null (car (slot-value dom-element+ 'attributes))) ;; nil ;; (slot-value dom-element+ 'attributes))) ;; ;;----------------------------------------------------------------------------- ;; ;; Generic Document Object Model Element ;; ;;----------------------------------------------------------------------------- ;; (defclass dom-element () ;; ((tag :accessor dom.tag :initarg :tag :initform nil :host none) ;; (namespace :accessor dom.namespace :initarg :namespace :initform nil :host none) ;; (attributes :accessor dom.attributes :initarg :attributes :initform nil :host none) ;; (children :accessor dom.children :initarg :children :initform nil :host none)) ;; (:metaclass dom-element+) ;; (:attributes nil) ;; (:documentation "DOM Element")) ;; (defmethod print-object ((self dom-element) stream) ;; (print-unreadable-object (self stream :type t :identity t) ;; (if (dom.namespace self) ;; (format stream "~A:~A(~D)" ;; (dom.tag self) (dom.namespace self) (length (dom.children self))) ;; (format stream "~A(~D)" ;; (dom.tag self) (length (dom.children self)))))) ;; (defun make-dom-element (tag ns attributes &rest children) ;; "Returns a fresh instance of dom-element class, ctor" ;; (make-instance 'dom-element ;; :tag tag ;; :namespace ns ;; :attributes attributes ;; :children (flatten children))) ;; (defun dom-successor (element) ;; "Returns successors of dom 'element'" ;; (if (typep element 'dom-element) (dom.children element))) ;; (defmethod get-attribute ((element dom-element) name) ;; (cdr (assoc name (dom.attributes element) :test #'string=))) ;; (defmethod set-attribute ((element dom-element) name value) ;; (prog1 element ;; (if (assoc name (dom.attributes element)) ;; (setf (cdr (assoc name (dom.attributes element) :test #'string=)) value) ;; (setf (dom.attributes element) ;; (cons (cons name value) (dom.attributes element)))))) ;; (defmethod get-elements-by-tag-name ((element dom-element) tag-name) ;; (let ((result) ;; (tag-name (string-downcase tag-name))) ;; (core-search (list element) ;; (lambda (a) ;; (if (and (typep a 'dom-element) ;; (equal tag-name (string-downcase (dom.tag a)))) ;; (pushnew a result)) ;; nil) ;; #'dom-successor ;; #'append) ;; result)) ;; ;;--------------------------------------------------------------------------- ;; ;; DOM Parser ;; ;;--------------------------------------------------------------------------- ;; (defrule dom-attribute-name? (c (attribute (make-accumulator)) namespace) ;; (:oom (:or (:type alphanum? c) ;; (:and #\- (:do (setq c #\-)))) ;; (:collect c attribute)) ;; (:optional ;; #\: ;; (:do (setq namespace attribute) ;; (setq attribute (make-accumulator))) ;; (:oom (:or (:type alphanum? c) ;; (:and #\- (:do (setq c #\-)))) ;; (:collect c attribute))) ;; (:return (if namespace ;; (values attribute namespace);; (format nil "~A:~A" namespace attribute) ;; attribute))) ;; (defrule dom-attribute-value? (c (val (make-accumulator))) ;; (:or (:and ;; #\" ;; (:zom (:checkpoint #\" (:return val)) ;; (:checkpoint #\> (:rewind-return val)) ;; (:type (or visible-char? space?) c) ;; (:collect c val))) ;; (:and ;; #\' ;; (:zom (:checkpoint #\' (:return val)) ;; (:checkpoint #\> (:rewind-return val)) ;; (:type (or visible-char? space?) c) ;; (:collect c val)))) ;; (:return val)) ;; (defrule dom-attribute? (name value) ;; (:dom-attribute-name? name) ;; #\= ;; (:dom-attribute-value? value) ;; (:return (cons name value))) ;; (defrule dom-tag-name? (tag namespace) ;; (:dom-attribute-name? tag namespace) ;; (:return (values tag namespace))) ;; (defrule dom-lwsp? (c) ;; (:oom (:or (:and (:type (or space? tab?))) ;; (:and (:type (or carriage-return? linefeed?)) ;; (:do (setf c t)))) ;; (:if c ;; (:return #\Newline) ;; (:return #\Space)))) ;; (defrule dom-text-node? (c (acc (make-accumulator))) ;; (:not #\<) ;; (:oom (:checkpoint #\< (:rewind-return acc)) ;; (:or (:dom-lwsp? c) ;; (:type octet? c)) ;; (:collect c acc)) ;; (:if (> (length acc) 0) ;; (:return acc))) ;; (defrule dom-cdata? (c (acc (make-accumulator))) ;; (:seq "<![CDATA[") ;; (:zom (:not (:seq "]]>")) ;; (:type octet? c) ;; (:collect c acc)) ;; (:return acc)) ;; (defrule dom-comment? (c (acc (make-accumulator))) ;; (:seq "<!--") ;; (:collect #\< acc) (:collect #\! acc) ;; (:collect #\- acc) (:collect #\- acc) ;; (:zom (:not (:seq "-->")) ;; (:type octet? c) ;; (:collect c acc)) ;; (:collect #\- acc) (:collect #\- acc) (:collect #\> acc) ;; (:return acc)) ;; ;;----------------------------------------------------------------------------- ;; ;; Generic Document Parser ;; ;;----------------------------------------------------------------------------- ;; (defparser dom-element? (tag namespace attr attrs child children) ;; (:lwsp?) ;; (:checkpoint (:seq "<?xml") ;; (:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit)) ;; (:checkpoint (:seq "<!DOCTYPE") ;; (:zom (:not #\>) (:type octet?)) (:lwsp?) (:commit)) ;; #\< ;; (:dom-tag-name? tag namespace) ;; (:zom (:lwsp?) ;; (:dom-attribute? attr) ;; (:do (push attr attrs))) ;; (:or (:and (:lwsp?) ;; (:seq "/>") ;; (:return (make-dom-element tag namespace (nreverse attrs)))) ;; (:and #\> ;; (:zom (:lwsp?) ;; (:or (:dom-element? child) ;; (:dom-comment? child) ;; (:dom-text-node? child) ;; (:dom-cdata? child)) ;; (:do (push child children))) ;; (:seq "</") ;; (:if namespace ;; (:and (:sci namespace) #\: (:sci tag)) ;; (:sci tag)) ;; #\> ;; (:return (make-dom-element tag namespace (nreverse attrs) (nreverse children)))))) ;; ;;----------------------------------------------------------------------------- ;; ;; Generic Document Render ;; ;;----------------------------------------------------------------------------- ;; (defparameter +dom-indentation-increment+ 1) ;; (defmethod dom-element! ((stream core-stream) (element t) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; stream) ;; (defmethod dom-element! ((stream core-stream) (element string) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; (string! stream element)) ;; (defmethod dom-element! ((stream core-stream) (element number) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; (fixnum! stream element) ;; stream) ;; (defmethod dom-element! ((stream core-stream) (element pathname) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; (string! stream (namestring element)) ;; stream) ;; (defmethod dom-element! ((stream core-stream) (element dom-element) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; (write-stream (make-html-stream stream) element)) ;; (defmethod dom-element! ((stream core-stream) (function function) ;; &optional (indentation 0)) ;; (declare (ignore indentation)) ;; (prog1 stream (funcall function stream))) ;; (defun dom2string (element) ;; "Returns rendered string representation of 'element'" ;; (with-core-stream (s "") ;; (dom-element! s element) ;; (return-stream s))) ;; (deftrace dom-parsers ;; '(dom-element? dom-tag-name? dom-attribute? dom-attribute-value? dom-attribute-name? dom-text-node? ;; dom-comment? make-dom-element dom-element!)) (defun dom2string (element) "Returns rendered string representation of 'element'" (with-core-stream (s "") (write-stream (make-html-stream s) element) (return-stream s))) (defmethod get-elements-by-tag-name ((element xml) tag-name) (let ((result) (tag-name (string-downcase tag-name))) (xml-search (list element) (lambda (a) (if (and (typep a 'xml) (equal tag-name (string-downcase (xml.tag a)))) (pushnew a result)) nil)) result))
9,543
Common Lisp
.lisp
230
40.108696
104
0.556059
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
baaa47306af6ea6f4a6e1ab9f9bb44ee8186f14ec7f91dfab28a8ce17c2fb9eb
8,247
[ -1 ]
8,248
wsdl.lisp
evrim_core-server/src/markup/wsdl.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Web Services Description Markup ;; ------------------------------------------------------------------------- (defxml-namespace wsdl (make-xml-schema-pathname "wsdl20.xsd"))
280
Common Lisp
.lisp
5
54.8
76
0.350365
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dcef5ae0bceb856273f18ec06ddffb49c06ffe8b1d4138d5f572b87af1d9e531
8,248
[ -1 ]
8,249
errno.lisp
evrim_core-server/src/io/errno.lisp
(in-package :core-ffi) ;;;----------------------------------------------------------------------------- ;;; ERROR HANDLING ROUTINES FOR KERNEL CALLS ;;;----------------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel) (defvar +error-symbols+ (make-hash-table :test #'eq))) (eval-when (:compile-toplevel :load-toplevel) (defmacro deferrno (symbol errno docstring) `(progn (defvar ,symbol ,errno ,docstring) (setf (gethash ,errno +error-symbols+) ',symbol) ',symbol))) ;;;----------------------------------------------------------------------------- ;;; UNIX ERROR CODES ;;;----------------------------------------------------------------------------- ;;; fixme: get those values from grovel. (deferrno +ECFFI+ -1 "Can't get errno from CFFI") (deferrno +EPERM+ 1 "Operation not permitted") (deferrno +ENOENT+ 2 "No such file or directory") (deferrno +ESRCH+ 3 "No such process") (deferrno +EINTR+ 4 "Interrupted system call") (deferrno +EIO+ 5 "I/O error") (deferrno +ENXIO+ 6 "No such device or address") (deferrno +E2BIG+ 7 "Argument list too long") (deferrno +ENOEXEC+ 8 "Exec format error") (deferrno +EBADF+ 9 "Bad file number") (deferrno +ECHILD+ 10 "No child processes") (deferrno +EAGAIN+ 11 "Try again") (deferrno +ENOMEM+ 12 "Out of memory") (deferrno +EACCES+ 13 "Permission denied") (deferrno +EFAULT+ 14 "Bad address") (deferrno +ENOTBLK+ 15 "Block device required") (deferrno +EBUSY+ 16 "Device or resource busy") (deferrno +EEXIST+ 17 "File exists") (deferrno +EXDEV+ 18 "Cross-device link") (deferrno +ENODEV+ 19 "No such device") (deferrno +ENOTDIR+ 20 "Not a directory") (deferrno +EISDIR+ 21 "Is a directory") (deferrno +EINVAL+ 22 "Invalid argument") (deferrno +ENFILE+ 23 "File table overflow") (deferrno +EMFILE+ 24 "Too many open files") (deferrno +ENOTTY+ 25 "Not a typewriter") (deferrno +ETXTBSY+ 26 "Text file busy") (deferrno +EFBIG+ 27 "File too large") (deferrno +ENOSPC+ 28 "No space left on device") (deferrno +ESPIPE+ 29 "Illegal seek") (deferrno +EROFS+ 30 "Read-only file system") (deferrno +EMLINK+ 31 "Too many links") (deferrno +EPIPE+ 32 "Broken pipe") (deferrno +EDOM+ 33 "Math argument out of domain of func") (deferrno +ERANGE+ 34 "Math result not representable") (deferrno +EDEADLK+ 35 "Resource deadlock would occur") (deferrno +ENAMETOOLONG+ 36 "File name too long") (deferrno +ENOLCK+ 37 "No record locks available") (deferrno +ENOSYS+ 38 "Function not implemented") (deferrno +ENOTEMPTY+ 39 "Directory not empty") (deferrno +ELOOP+ 40 "Too many symbolic links encountered") (deferrno +EWOULDBLOCK+ +EAGAIN+ "Operation would block") (deferrno +ENOMSG+ 42 "No message of desired type") (deferrno +EIDRM+ 43 "Identifier removed") (deferrno +ECHRNG+ 44 "Channel number out of range") (deferrno +EL2NSYNC+ 45 "Level 2 not synchronized") (deferrno +EL3HLT+ 46 "Level 3 halted") (deferrno +EL3RST+ 47 "Level 3 reset") (deferrno +ELNRNG+ 48 "Link number out of range") (deferrno +EUNATCH+ 49 "Protocol driver not attached") (deferrno +ENOCSI+ 50 "No CSI structure available") (deferrno +EL2HLT+ 51 "Level 2 halted") (deferrno +EBADE+ 52 "Invalid exchange") (deferrno +EBADR+ 53 "Invalid request descriptor") (deferrno +EXFULL+ 54 "Exchange full") (deferrno +ENOANO+ 55 "No anode") (deferrno +EBADRQC+ 56 "Invalid request code") (deferrno +EBADSLT+ 57 "Invalid slot") (deferrno +EDEADLOCK+ +EDEADLK+ "Resource deadlock would occur") (deferrno +EBFONT+ 59 "Bad font file format") (deferrno +ENOSTR+ 60 "Device not a stream") (deferrno +ENODATA+ 61 "No data available") (deferrno +ETIME+ 62 "Timer expired") (deferrno +ENOSR+ 63 "Out of streams resources") (deferrno +ENONET+ 64 "Machine is not on the network") (deferrno +ENOPKG+ 65 "Package not installed") (deferrno +EREMOTE+ 66 "Object is remote") (deferrno +ENOLINK+ 67 "Link has been severed") (deferrno +EADV+ 68 "Advertise error") (deferrno +ESRMNT+ 69 "Srmount error") (deferrno +ECOMM+ 70 "Communication error on send") (deferrno +EPROTO+ 71 "Protocol error") (deferrno +EMULTIHOP+ 72 "Multihop attempted") (deferrno +EDOTDOT+ 73 "RFS specific error") (deferrno +EBADMSG+ 74 "Not a data message") (deferrno +EOVERFLOW+ 75 "Value too large for defined data type") (deferrno +ENOTUNIQ+ 76 "Name not unique on network") (deferrno +EBADFD+ 77 "File descriptor in bad state") (deferrno +EREMCHG+ 78 "Remote address changed") (deferrno +ELIBACC+ 79 "Can not access a needed shared library") (deferrno +ELIBBAD+ 80 "Accessing a corrupted shared library") (deferrno +ELIBSCN+ 81 ".lib section in a.out corrupted") (deferrno +ELIBMAX+ 82 "Attempting to link in too many shared libraries") (deferrno +ELIBEXEC+ 83 "Cannot exec a shared library directly") (deferrno +EILSEQ+ 84 "Illegal byte sequence") (deferrno +ERESTART+ 85 "Interrupted system call should be restarted") (deferrno +ESTRPIPE+ 86 "Streams pipe error") (deferrno +EUSERS+ 87 "Too many users") (deferrno +ENOTSOCK+ 88 "Socket operation on non-socket") (deferrno +EDESTADDRREQ+ 89 "Destination address required") (deferrno +EMSGSIZE+ 90 "Message too long") (deferrno +EPROTOTYPE+ 91 "Protocol wrong type for socket") (deferrno +ENOPROTOOPT+ 92 "Protocol not available") (deferrno +EPROTONOSUPPORT+ 93 "Protocol not supported") (deferrno +ESOCKTNOSUPPORT+ 94 "Socket type not supported") (deferrno +EOPNOTSUPP+ 95 "Operation not supported on transport endpoint") (deferrno +EPFNOSUPPORT+ 96 "Protocol family not supported") (deferrno +EAFNOSUPPORT+ 97 "Address family not supported by protocol") (deferrno +EADDRINUSE+ 98 "Address already in use") (deferrno +EADDRNOTAVAIL+ 99 "Cannot assign requested address") (deferrno +ENETDOWN+ 100 "Network is down") (deferrno +ENETUNREACH+ 101 "Network is unreachable") (deferrno +ENETRESET+ 102 "Network dropped connection because of reset") (deferrno +ECONNABORTED+ 103 "Software caused connection abort") (deferrno +ECONNRESET+ 104 "Connection reset by peer") (deferrno +ENOBUFS+ 105 "No buffer space available") (deferrno +EISCONN+ 106 "Transport endpoint is already connected") (deferrno +ENOTCONN+ 107 "Transport endpoint is not connected") (deferrno +ESHUTDOWN+ 108 "Cannot send after transport endpoint shutdown") (deferrno +ETOOMANYREFS+ 109 "Too many references: cannot splice") (deferrno +ETIMEDOUT+ 110 "Connection timed out") (deferrno +ECONNREFUSED+ 111 "Connection refused") (deferrno +EHOSTDOWN+ 112 "Host is down") (deferrno +EHOSTUNREACH+ 113 "No route to host") (deferrno +EALREADY+ 114 "Operation already in progress") (deferrno +EINPROGRESS+ 115 "Operation now in progress") (deferrno +ESTALE+ 116 "Stale NFS file handle") (deferrno +EUCLEAN+ 117 "Structure needs cleaning") (deferrno +ENOTNAM+ 118 "Not a XENIX named type file") (deferrno +ENAVAIL+ 119 "No XENIX semaphores available") (deferrno +EISNAM+ 120 "Is a named type file") (deferrno +EREMOTEIO+ 121 "Remote I/O error") (deferrno +EDQUOT+ 122 "Quota exceeded") (deferrno +ENOMEDIUM+ 123 "No medium found") (deferrno +EMEDIUMTYPE+ 124 "Wrong medium type") (deferrno +ECANCELED+ 125 "Operation Canceled") (deferrno +ENOKEY+ 126 "Required key not available") (deferrno +EKEYEXPIRED+ 127 "Key has expired") (deferrno +EKEYREVOKED+ 128 "Key has been revoked") (deferrno +EKEYREJECTED+ 129 "Key was rejected by service") (deferrno +EOWNERDEAD+ 130 "Owner died") (deferrno +ENOTRECOVERABLE+ 131 "State not recoverable") ;;;----------------------------------------------------------------------------- ;;; ERRNO VARIABLE a.k.a. extern int errno; ;;;----------------------------------------------------------------------------- ;;; fixme: doesn't work with linux/sbcl-1.x (defcvar ("errno" errno) :int) (defun errno () #+sbcl (sb-alien:get-errno) #-sbcl (if (eq 1 (pointer-address (get-var-pointer '+errno+))) -1 +errno+)) ;;;----------------------------------------------------------------------------- ;;; KERNEL ERROR CONDITION FOR PROPER HANDLING ;;;----------------------------------------------------------------------------- (define-condition kernel-error (error) ((errno :initarg :errno :reader kernel-error.errno)) (:report (lambda (c stream) (format stream "Kernel error: ~A:~D:~A" (gethash (kernel-error.errno c) +error-symbols+) (kernel-error.errno c) (documentation (gethash (kernel-error.errno c) +error-symbols+) 'variable)))) (:documentation "Signalled when the kernel call ret a negative value.")) (defmethod eagain? ((c kernel-error)) (eq +EAGAIN+ (kernel-error.errno c))) ;;;----------------------------------------------------------------------------- ;;; PROPER CFFI RETURN TYPE FOR KERNEL CALLS ;;;----------------------------------------------------------------------------- (defmethod translate-from-foreign (value retval) (if (minusp value) (error 'kernel-error :errno (errno)) value)) ;; (defmacro %ret (form) ;; (with-unique-names (errno ret) ;; `(let ((,ret ,form)) ;; (if (plusp ,ret) ;; ,ret ;; (let ((,errno #+sbcl (sb-alien:get-errno) ;; #-sbcl 0)) ;; (error "Kernel error! errno:~D ~A" ,errno ;; #+sbcl (documentation (gethash (sb-alien:get-errno) +error-symbols+) 'variable) ;; #-sbcl nil))))))
9,688
Common Lisp
.lisp
188
50
88
0.636852
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
45cf4b3d359e55d0771b203b79a31316d61d99bd78595220310ab70c99aaa67b
8,249
[ -1 ]
8,250
events.lisp
evrim_core-server/src/io/events.lisp
(in-package :core-server) ;;; example usage? ;; (let ((accepter (with-listener-socket (listener "127.0.0.1" 9000) ;; (make-instance 'accept-unit :socket listener)))) ;; (add-worker accepter 4) ;; (start accepter)) ;;; ;;; non-blocking io stream ;;; (defclass nio-socket-stream (core-fd-io-stream) ((worker-unit :accessor nio-socket-stream.worker-unit))) (defmethod stream.worker ((self nio-socket-stream)) (nio-socket-stream.worker-unit self)) (defmethod stream.dispatcher ((stream nio-socket-stream)) (event-dispatcher (stream.worker stream))) (defmethod stream.queue ((stream nio-socket-stream)) (event-queue (stream.dispatcher stream))) (defmethod stream.rqueue ((stream nio-socket-stream)) (event-dispatcher.rfds (stream.dispatcher stream))) (defmethod stream.wqueue ((stream nio-socket-stream)) (event-dispatcher.wfds (stream.dispatcher stream))) (defmethod read-stream ((stream nio-socket-stream)) (flet ((retk (val) (return-from read-stream val))) (handler-bind ((kernel-error (lambda (c) (if (eagain? c) (progn (setf (gethash (stream.fd stream) (stream.rqueue stream)) #'(lambda () (send-message (stream.worker stream) #'(lambda () (funcall (function retk) (read-stream stream)))))) (add-fd (stream.queue stream) (stream.fd stream) `(epollin epollet)) (run (event-dispatcher stream))))))) (call-next-method)))) (defmethod write-stream ((stream nio-socket-stream) octet) (flet ((retk (val) (return-from write-stream val))) (handler-bind ((kernel-error (lambda (c) (if (eagain? c) (progn (setf (gethash (stream.fd stream) (stream.wqueue stream)) #'(lambda () (send-message (worker-unit stream) #'(lambda () (funcall (function retk) (read-stream stream)))))) (add-fd (stream.queue stream) (stream.fd stream) '(epollout epollet)) (run (event-dispatcher stream))))))) (call-next-method)))) (defclass event-dispatcher (unit) ((epoll-device :accessor event-dispatcher.epoll-device :initarg :epoll-device :initform (make-epoll-device)) (rfds :accessor event-dispatcher.rfds :initarg :rfds :initform (make-hash-table)) (wfds :accessor event-dispatcher.wfds :initarg :wfds :initform (make-hash-table)) (efds :accessor event-dispatcher.efds :initarg :efds :initform (make-hash-table)))) (defmethod event-queue ((self event-dispatcher)) (event-dispatcher.epoll-device self)) (defmethod recipient? ((self event-dispatcher) event) (or (apply #'gethash (epoll-event-data event) (cond ((eq epollin (logand epollin (epoll-event-events event))) (event-dispatcher.rfds self)) ((eq epollout (logand epollout (epoll-event-events event))) (event-dispatcher.wfds self)) ((eq epollerr (logand epollerr (epoll-event-events event))) (event-dispatcher.efds self)))) #'(lambda () (format t "missed event on fd: ~D" (epoll-event-data event))))) (defmethod/unit run ((self event-dispatcher)) (loop (mapcar #'(lambda (ev) (funcall (recipient? self ev))) (wait (epoll-device self) 100)))) ;;; ;;; Worker Unit (worker for each new client) ;;; (defclass nio-worker-unit (unit) ((accept-unit :accessor nio-worker-unit.accept-unit :initarg :accept-unit) (event-dispatcher :accessor nio-worker-unit.event-dispatcher :initarg :event-dispatcher))) (defmethod event-dispatcher ((self nio-worker-unit)) (nio-worker-unit.event-dispatcher self)) (defmethod/cc handle-fd ((self nio-worker-unit) socket) ;; create nio-socket for each client. (let ((s (make-instance 'nio-socket-stream :worker-unit self :socket socket))) ;; request response cycle here... (print-response (eval-request (read-request s))))) ;;; ;;; Fixed entrypoint ;;; (defclass accept-unit (unit) ((event-dispatcher :accessor accept-unit.event-dispatcher :initarg :event-dispatcher :initform (make-instance 'event-dispatcher)) (socket :accessor accept-unit.socket :initarg :socket :initform nil) (workers :accessor accept-unit.workers :initarg :workers :initform nil))) (defmethod add-worker ((self accept-unit) num) (let ((workers (loop for i from 1 to num collect (make-instance 'worker-unit :accept-unit self :event-dispatcher (accept-unit.event-dispatcher self))))) (mapcar #'(lambda (w) (start w) (push w (accept-unit.workers self))) workers))) (defmethod/unit run ((self accept-unit)) (loop (mapcar #'(lambda (w) (handle-fd w (accept (socket self)))) (accept-unit.workers self))))
4,631
Common Lisp
.lisp
112
36.758929
93
0.684082
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b1cc0908ad92d8f2a895e19b0e99318ad3cd4dca28532c8adea2a7cbe4e277e2
8,250
[ -1 ]
8,251
grovel.lisp
evrim_core-server/src/io/grovel.lisp
(in-package :tr.gen.core.ffi) (ctype retval "int") ;;;----------------------------------------------------------------------------- ;;; GETPROTOBYNAME, GETHOSTBYNAME TYPE DEFINITIONS ;;;----------------------------------------------------------------------------- (include "netdb.h") (cstruct protoent "struct protoent" (name "p_name" :type :string) (aliases "p_aliases" :type :pointer) (proto "p_proto" :type :int)) (cstruct hostent "struct hostent" (name "h_name" :type :string) (aliases "h_aliases" :type :pointer) (type "h_addrtype" :type :int) (len "h_length" :type :int) (list "h_addr_list" :type :pointer)) (include "sys/socket.h") (constant (af-inet "AF_INET" "PF_INET") :documentation "IPv4 Protocol family") (constant (af-unspec "AF_UNSPEC")) ;; possible values for "ai-flags" (constant (flag-ai-passive "AI_PASSIVE")) (constant (flag-ai-canonname "AI_CANONNAME")) (constant (flag-ai-numerichost "AI_NUMERICHOST")) (constant (flag-ai-v4mapped "AI_V4MAPPED")) (constant (flag-ai-all "AI_ALL")) (constant (flag-ai-addrconfig "AI_ADDRCONFIG")) (constant (flag-ai-idn "AI_IDN")) (constant (flag-ai-canonidn "AI_CANONIDN")) ;; +---------------------------------------------------------------------------- ;; |IPV4 SOCKET ADDRESS ;; +---------------------------------------------------------------------------- (include "sys/socket.h") (ctype socklen "socklen_t") (ctype sa-family "sa_family_t") ;;; socket() - socket address family (constant (af-inet "AF_INET" "PF_INET") :documentation "IPv4 Protocol family") (constant (af-local "AF_UNIX" "AF_LOCAL" "PF_UNIX" "PF_LOCAL") :documentation "File domain sockets") ;;; socket() - socket type (constant (sock-stream "SOCK_STREAM") :documentation "TCP") (constant (sock-dgram "SOCK_DGRAM") :documentation "UDP") ;;; socket() - socket protocols (constant (ipproto-tcp "IPPROTO_TCP")) (constant (ipproto-udp "IPPROTO_UDP")) (cstruct sockaddr "struct sockaddr" (family "sa_family" :type sa-family) (sa-data "sa_data" :type :char :count 14)) ;; GETNAMEINFO, GETADDRINFO (include "sys/types.h" "sys/socket.h" "netdb.h") (ctype size-t "size_t") (ctype ssize-t "ssize_t") (include "sys/sendfile.h") (ctype off-t "off_t") (constant (ni-numerichost "NI_NUMERICHOST")) (constant (ni-numericserv "NI_NUMERICSERV")) (constant (ni-maxhost "NI_MAXHOST")) (constant (ni-maxserv "NI_MAXSERV")) ;; struct addrinfo { ;; int ai_flags; ;; int ai_family; ;; int ai_socktype; ;; int ai_protocol; ;; size_t ai_addrlen; ;; struct sockaddr *ai_addr; ;; char *ai_canonname; ;; struct addrinfo *ai_next; ;; }; (cstruct addrinfo "struct addrinfo" (ai-flags "ai_flags" :type :int) (ai-family "ai_family" :type :int) (ai-socktype "ai_socktype" :type :int) (ai-protocol "ai_protocol" :type :int) (ai-addrlen "ai_addrlen" :type size-t) (ai-addr "ai_addr" :type :pointer) (ai-canonname "ai_canonname" :type :pointer) (ai-next "ai_next" :type :pointer)) (cstruct linger "struct linger" (l-onoff "l_onoff" :type :int) (l-linger "l_linger" :type :int)) ;; +---------------------------------------------------------------------------- ;; |SOCKET ADDRESS ;; +---------------------------------------------------------------------------- (include "netinet/in.h") (ctype in-port "in_port_t") (ctype in-addr "in_addr_t") (cstruct sockaddr-in "struct sockaddr_in" "An IPv4 socket address." (family "sin_family" :type sa-family) (port "sin_port" :type in-port) (addr "sin_addr" :type in-addr)) (cstruct in-addr-struct "struct in_addr" (addr "s_addr" :type :uint32)) (include "netinet/tcp.h") (progn (constant (tcp-nodelay "TCP_NODELAY"))) ;; +---------------------------------------------------------------------------- ;; |SET/GETSOCKOPT ;; +---------------------------------------------------------------------------- (progn (constant (sol-socket "SOL_SOCKET")) (constant (so-debug "SO_DEBUG")) (constant (so-reuseaddr "SO_REUSEADDR")) (constant (so-type "SO_TYPE")) (constant (so-error "SO_ERROR")) (constant (so-keepalive "SO_KEEPALIVE")) (constant (so-rcvtimeo "SO_RCVTIMEO")) (constant (so-sndtimeo "SO_SNDTIMEO")) (constant (so-linger "SO_LINGER"))) ;; +---------------------------------------------------------------------------- ;; |SEND/RECV FLAGS ;; +---------------------------------------------------------------------------- (progn (constant (msg-dontwait "MSG_DONTWAIT"))) ;; +---------------------------------------------------------------------------- ;; |FCNTL ;; +---------------------------------------------------------------------------- (include "fcntl.h") ;; FCNTL FLAGS (progn (constant (rdonly "O_RDONLY")) (constant (wdonly "O_WRONLY")) (constant (nonblock "O_NONBLOCK"))) ;; FCNTL COMMANDS (progn (constant (getfd "F_GETFD")) (constant (setfd "F_SETFD")) (constant (getfl "F_GETFL")) (constant (setfl "F_SETFL")) (constant (setown "F_SETOWN")) (constant (getown "F_GETOWN")) (constant (setsig "F_SETSIG")) (constant (getsig "F_GETSIG"))) ;; +---------------------------------------------------------------------------- ;; | TIME ;; +---------------------------------------------------------------------------- (include "time.h") (ctype time_t "time_t") (ctype suseconds "suseconds_t") (cstruct timespec "struct timespec" "UNIX time specification in seconds and nanoseconds." (sec "tv_sec" :type time_t) (nsec "tv_nsec" :type :long)) ;;;----------------------------------------------------------------------------- ;;; EPOLL TYPE DEFINITIONS ;;;----------------------------------------------------------------------------- (include "sys/epoll.h" "sys/ioctl.h") (ctype uint32-t "uint32_t") (progn ;; (ctype sigset-t "sigset_t") ;; broken (cunion epoll-data "epoll_data_t" (ptr "ptr" :type :pointer) (fd "fd" :type :int) (u32 "u32" :type :uint32) (u64 "u64" :type :uint64)) (cstruct epoll-event "struct epoll_event" (events "events" :type uint32-t) (data "data" :type epoll-data)) ;;--------------------------------------------------------------------------- ;; EPOLL EVENTS ;;--------------------------------------------------------------------------- (constant (epollin "EPOLLIN")) (constant (epollrdnorm "EPOLLRDNORM")) (constant (epollrdband "EPOLLRDBAND")) (constant (epollpri "EPOLLPRI")) (constant (epollout "EPOLLOUT")) (constant (epollwrnorm "EPOLLWRNORM")) (constant (epollwrband "EPOLLWRBAND")) (constant (epollerr "EPOLLERR")) (constant (epollhup "EPOLLHUP")) (constant (epollmsg "EPOLLMSG")) ;;-------------------------------------------------------------------------- ;; EPOLL OPERATIONS FOR EPOLL_CTL() ;;-------------------------------------------------------------------------- (constant (epoll-ctl-add "EPOLL_CTL_ADD")) (constant (epoll-ctl-del "EPOLL_CTL_DEL")) (constant (epoll-ctl-mod "EPOLL_CTL_MOD"))) ;;(include "uuid/uuid.h") ;;(ctype uuid-t "uuid_t")
7,064
Common Lisp
.lisp
179
37.067039
80
0.516487
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5ec314f6a87f332b6eddf1554b862e17f205ae8a31070d08f7811b7b11aaa14a
8,251
[ -1 ]
8,252
uuid.lisp
evrim_core-server/src/io/uuid.lisp
(in-package :core-ffi) (define-foreign-library libuuid (:unix "libuuid.so") (t (:default "libuuid"))) (use-foreign-library libuuid) (defcfun ("uuid_unparse" %uuid-unparse) :void (uu :pointer) (char :pointer)) (defcfun ("uuid_generate" %uuid-generate) :void (uu :pointer))
286
Common Lisp
.lisp
10
26.2
47
0.705882
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d7a72a95addb5db0c5a11691b41fd1ecb862bedad7ad5646fb24f1c406a957dc
8,252
[ -1 ]
8,253
bsd.lisp
evrim_core-server/src/io/bsd.lisp
(in-package :tr.gen.core.ffi) ;; +---------------------------------------------------------------------------- ;; | Helpers ;; +---------------------------------------------------------------------------- (defctype fd :int) ;;; void bzero(void *s, size_t n); (defcfun ("bzero" %bzero) :void (s :pointer) (n size-t)) ;; +---------------------------------------------------------------------------- ;; | Name Resolution ;; +---------------------------------------------------------------------------- ;;; int getnameinfo(const struct sockaddr *sa, socklen_t salen, ;;; char *host, size_t hostlen, ;;; char *serv, size_t servlen, int flags); (declaim (inline %getnameinfo)) (defcfun ("getnameinfo" %getnameinfo) retval (sa :pointer) ;; const struct sockaddr *sa (salen socklen) ;; socklen_t salen (host :string) ;; char *host (hostlen size-t) ;; size_t hostlen (serv :string) ;; char* serv (servlen size-t) ;; size_t servlen (flags :int) ;; int flags ) ;;; int getaddrinfo(const char *node, const char *service, ;;; const struct addrinfo *hints, ;;; struct addrinfo **res); (declaim (inline %getaddrinfo)) (defcfun ("getaddrinfo" %getaddrinfo) retval (node :string) (service :string) (hints :pointer) (res :pointer) ) ;;; void freeaddrinfo(struct addrinfo *res); (defcfun ("freeaddrinfo" %freeaddrinfo) retval (res :pointer)) ;;; const char *gai_strerror(int errcode); (defcfun ("gai_strerror" %gai_strerror) retval (errcode :int)) ;; +---------------------------------------------------------------------------- ;; | Sockets ;; +---------------------------------------------------------------------------- ;; int inet_pton(int af, const char *src, void *dst); (defcfun ("inet_pton" %inet-pton) retval (af :int) (src :string) (dst :pointer)) ;; char *inet_ntop(int af, const void *src,char *dst, socklen_t cnt); (defcfun ("inet_ntop" %inet-ntop) retval (af :int) (sockaddr :pointer) (dst :pointer) (len :int)) ;; uint32_t htonl(uint32_t hostlong); (defcfun ("htonl" %htonl) :uint32 (hostlong :uint32)) ;; uint32_t ntohl(uint32_t netlong); (defcfun ("ntohl" %ntohl) :uint32 (netlong :uint32)) ;; uint16_t htons(uint16_t hostshort); (defcfun ("htons" %htons) :uint16 (hostshort :uint16)) ;; uint16_t ntohs(uint16_t netshort); (defcfun ("ntohs" %ntohs) :uint16 (netshort :uint16)) ;; int socket(int domain, int type, int protocol); (declaim (inline %socket)) (defcfun ("socket" %socket) retval (domain :int) (type :int) (protocol :int)) ;; int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) (declaim (inline %bind)) (defcfun ("bind" %bind) retval (sockfd :int) (addr :pointer) (addrlen socklen)) ;; int listen(int sockfd, int backlog); (declaim (inline %listen)) (defcfun ("listen" %listen) retval (sockfd :int) (backlog :int)) ;; int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); (declaim (inline %accept)) (defcfun ("accept" %accept) retval (sockfd :int) (addr :pointer) (addrlen :pointer)) ;; int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); (declaim (inline %connect)) (defcfun ("connect" %connect) retval (sockfd :int) (addr :pointer) (addrlen socklen)) ;; ssize_t recv(int socket, void *buffer, size_t length, int flags); (defcfun ("recv" %recv) retval (fd fd) (buffer :pointer) (len :int) (flags :int)) ;; ssize_t send(int s, const void *buf, size_t len, int flags); (defcfun ("send" %send) retval (fd :int) (buffer :pointer) (len :int) (flags :int)) ;; ssize_t read(int fd, void *buf, size_t count); (defcfun ("read" %read) ssize-t (fd :int) (buf :pointer) (count size-t)) ;; ssize_t write(int fd, const void *buf, size_t count); (defcfun ("write" %write) ssize-t (fd :int) (buf :pointer) (count size-t)) ;; int close(int fd); (declaim (inline %close)) (defcfun ("close" %close) retval (fd :int)) ;; ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count); (defcfun ("sendfile" %sendfile) retval (out-fd :int) (in-fd :int) (offset off-t) (count size-t)) ;; int setsockopt(int s,int level,int optname,void *optval,socklen_t optlen); (defcfun ("setsockopt" %setsockopt) retval (fd fd) (level :int) (option :int) (value :pointer) (len :int)) ;; int fcntl(int fd, int cmd, long arg); (defcfun ("fcntl" %fcntl) retval (fd :int) (cmd :int) (options :long)) (declaim (inline %getprotobyname)) (defcfun ("getprotobyname" %getprotobyname) protoent (name :string)) (declaim (inline %gethostbyname)) (defcfun ("gethostbyname" %gethostbyname) hostent (name :string)) ;; +---------------------------------------------------------------------------- ;; | EPOLLUTION ;; +---------------------------------------------------------------------------- ;; (defbitfield epoll-events ;; (:IN #x001) ;; (:PRI #x002) ;; (:OUT #x004) ;; (:ERR #x008) ;; (:HUP #x010) ;; (:RDNORM #x040) ;; (:RDBAND #x080) ;; (:WRNORM #x100) ;; (:RWBAND #x200) ;; (:MSG #x400) ;; (:ONESHOT #.(ash 1 30)) ;; (:ET #.(ash 1 31))) ;; (defcenum :EPOLL-OP ;; (:ADD 1) ;; (:DEL 2) ;; (:MOD 3)) ;; int epoll_create(int size); (defcfun ("epoll_create" %epoll-create) retval (size :int)) ;; int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event); (defcfun ("epoll_ctl" %epoll-ctl) retval (epfd :int) (op :int) (fd :int) (event :pointer)) ;; int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout); (defcfun ("epoll_wait" %epoll-wait) retval (epfd :int) (events :pointer) (maxevents :int) (timeout :int)) ;; int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask); (defcfun ("epoll_pwait" %epoll-pwait) retval (epfd :int) (events :pointer) (maxevents :int) (timeout :int) (sigmask :pointer)) (defbitfield epoll-events :epollin epollin :epollrdnorm epollrdnorm :epollrdband epollrdband :epollpri epollpri :epollout epollout :epollwrnorm epollwrnorm :epollwrband epollwrband :epollerr epollerr :epollhup epollhup :epollmsg epollmsg :epolloneshot epolloneshot :epollet epollet )
6,294
Common Lisp
.lisp
202
28.99505
110
0.593162
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ce000cd236c366358d880d59637c5807e91864e1bb087ce115277449f442b00c
8,253
[ -1 ]
8,254
interface.lisp
evrim_core-server/src/io/interface.lisp
(in-package :tr.gen.core.ffi) (defun np () (null-pointer)) (defun bzero (s n) (%bzero s n)) (defun print-range (ptr len &optional (type :uint8)) (loop for i from 0 below len do (format t "~2,'0D " (or (and (= 0 (mem-ref ptr type i)) #\.) (mem-ref ptr type i))) do (if (= 0 (mod len 80)) (format t "~%")))) (defvar epolloneshot #.(ash 1 30)) (defvar epollet #.(ash 1 31)) ;; addrinfo helpers (define-c-struct-wrapper addrinfo ()) (define-c-struct-wrapper sockaddr ()) (define-c-struct-wrapper sockaddr-in ()) (define-c-struct-wrapper linger ()) ;; (defun make-addrinfo (ptr &optional (family 0) (socktype 0) (flags af-unspec) ;; (protocol 'sock-stream) (canonname (np)) (addr (np)) (next (np))) ;; (bzero ptr size-of-addrinfo) ;; (with-foreign-slots ((ai-flags ai-family ai-socktype ai-protocol ai-canonname ai-addr ai-next) ptr addrinfo) ;; (setf ai-family family ;; ai-socktype socktype ;; ai-flags flags ;; ai-protocol protocol ;; ai-canonname canonname ;; ai-addr addr ;; ai-next next)) ;; (values ptr)) (defmacro with-addrinfo ((var family socktype flags protocol) &body body) `(with-foreign-object (,var 'addrinfo) (with-foreign-slots ((ai-family ai-flags ai-socktype ai-protocol) ,var addrinfo) (setf ai-family ,family ai-flags ,flags ai-socktype ,socktype ai-protocol ,protocol) ,@body))) (defun connect (node service &optional (protocol :tcp)) (with-foreign-object (res :pointer) ;; construct an addrinfo for hints (with-addrinfo (hints af-inet (ecase protocol (:tcp sock-stream) (:udp sock-dgram)) flag-ai-passive 0) ;; call getaddrinfo (let ((r (%getaddrinfo node (if (numberp service) (format nil"~D" service) service) hints res))) (if (not (eq 0 r)) (error (format nil "getaddrinfo: ~A" (%gai_strerror r))) ;; otherwise we'll have addrinfos in res. let's recurse ;; over them to bind any (labels ((bind-any (ptr) (cond ((null-pointer-p ptr) nil) (t (let* ((obj (make-instance 'addrinfo :pointer (mem-ref ptr 'addrinfo))) (sfd (%socket (addrinfo-ai-family obj) (addrinfo-ai-socktype obj) (addrinfo-ai-protocol obj)))) (with-slots (ai-addr ai-addrlen ai-next) obj (if (not (eq sfd -1)) (arnesi::aif (eq 0 (%connect sfd ai-addr ai-addrlen)) sfd arnesi::it) (bind-any ai-next)))))))) (bind-any (mem-ref res :pointer)))))))) (defun bind (node service &optional (protocol :tcp) (backlog 10) (reuse-address t)) ;; ptr for results (with-foreign-object (res :pointer) ;; construct an addrinfo for hints (with-addrinfo (hints af-inet (ecase protocol (:tcp sock-stream) (:udp sock-dgram)) flag-ai-passive 0) ;; call getaddrinfo (let ((r (%getaddrinfo node (if (numberp service) (format nil"~D" service) service) hints res))) (if (not (eq 0 r)) (error (format nil "getaddrinfo: ~A" (%gai_strerror r))) ;; otherwise we'll have addrinfos in res. let's recurse ;; over them to bind any (labels ((bind-any (ptr) (cond ((null-pointer-p ptr) nil) (t (let* ((obj (make-instance 'addrinfo :pointer (mem-ref ptr 'addrinfo))) (sfd (%socket (addrinfo-ai-family obj) (addrinfo-ai-socktype obj) (addrinfo-ai-protocol obj)))) (with-foreign-objects ((l 'linger) (o :int)) (setf (mem-ref o :int) 1) (bzero l size-of-linger) (%setsockopt sfd sol-socket so-reuseaddr o (foreign-type-size :int)) (%setsockopt sfd sol-socket so-keepalive o (foreign-type-size :int)) (%setsockopt sfd sol-socket so-linger l (foreign-type-size 'linger)) (%setsockopt sfd ipproto-tcp tcp-nodelay o (foreign-type-size :int))) (with-slots (ai-addr ai-addrlen ai-next) obj (if (not (eq sfd -1)) (if (eq 0 (%bind sfd ai-addr ai-addrlen)) (progn (%listen sfd backlog) sfd) (progn (format t "Bind error: ~D" (errno)) (%close sfd))) (bind-any ai-next)))))))) (bind-any (mem-ref res :pointer)))))))) (defmethod accept (fd) (with-foreign-object (peer 'sockaddr-in) (bzero peer size-of-sockaddr-in) (with-foreign-object (len :int) (setf (mem-ref len :int) size-of-sockaddr) (let* ((newfd (%accept fd peer len)) (peeraddr (with-foreign-object (port :string 5) (with-foreign-object (host :string 255) (bzero host 255) (bzero port 5) (%getnameinfo peer size-of-sockaddr-in host 255 port 5 (logior ni-numerichost ni-numericserv)) (list (foreign-string-to-lisp host) (foreign-string-to-lisp port)))))) (values newfd peeraddr))))) (defun set-nonblock (fd) (%fcntl fd setfl (logior nonblock (%fcntl fd getfl 0)))) ;; EPOLLUTION (define-c-struct-wrapper epoll-event ()) (defvar +epoll-size+ 131072) (defvar +epoll-max-events+ 100) (defun epoll-create (size) (%epoll-create size)) (defun epoll-ctl (epfd op fd event) (%epoll-ctl epfd op fd event)) (defun epoll-wait (epfd events maxevents timeout) (%epoll-wait epfd events maxevents timeout)) ;; actual interface (defclass epoll-device (core-server::local-unit) ((fd :accessor fd :initarg :fd :initform nil) (listenfd :accessor listenfd :initarg :listenfd) (handler :accessor handler :initarg :handler) (max-events :accessor max-events :initarg :max-events :initform +epoll-max-events+) (state :accessor state :initarg :state :initform (make-hash-table)))) (defun make-epoll-device (listen handler &optional (size +epoll-size+)) (make-instance 'epoll-device :fd (epoll-create size) :listenfd listen :handler handler)) (defmethod add ((self epoll-device) fd (modes list)) (with-foreign-object (ev 'epoll-event) (bzero ev size-of-epoll-event) (with-foreign-slots ((events data) ev epoll-event) (setf events (apply #'logior modes) (foreign-slot-value (foreign-slot-value ev 'epoll-event 'data) 'epoll-data 'fd) fd)) (epoll-ctl (fd self) epoll-ctl-add fd ev))) (defmethod del ((self epoll-device) fd) ;; Since Linux 2.6.9, event can be specified as NULL when using ;; EPOLL_CTL_DEL. (epoll-ctl (fd self) epoll-ctl-del fd (np))) (defmethod wait ((self epoll-device) timeout) (with-foreign-object (events 'epoll-event (max-events self)) (bzero events (* (max-events self) size-of-epoll-event)) (labels ((collect (i &optional acc) (cond ((< i 0) acc) (t ;; (let ((ee (make-instance 'epoll-event :pointer (mem-ref events 'epoll-event (- i 1))))) ;; (collect (1- i) (cons ee acc))) (collect (1- i) (cons (mem-ref events 'epoll-event (- i 1)) acc)) )))) (let ((n (epoll-wait (fd self) events (max-events self) timeout))) (cond ((eq n 0) nil) (t (collect n))))))) (defmethod core-server::run ((self epoll-device)) (format t "Running on listenfd: ~D~%" (slot-value self 'listenfd)) (loop (with-slots (listenfd handler-callback) self (labels ((ev-fd (e) (foreign-slot-value (foreign-slot-value e 'epoll-event 'data) 'epoll-data 'fd)) (newconn? (e) (eq listenfd (ev-fd e)))) (add self listenfd (list epollin #.(ash 1 31))) (let ((events (wait self 1000))) (with-foreign-object (ev 'epoll-event) (bzero ev size-of-epoll-event) (when (> (length events) 0) (format t "Wait returns: ~D~%" (length events))) (mapcar #'(lambda (e) (format t "Event on fd: ~D~%" (ev-fd e)) (if (newconn? e) (let ((client (accept (ev-fd e)))) (format t "accepted connection fd: ~D~%" client) (if (< client 0) (format t "error: accept") (progn (set-nonblock (ev-fd e)) (add self client (list epollin #.(ash 1 31)))))) (funcall #'handler-callback self (ev-fd e)))) events))))))) (defmethod core-server::stop ((self epoll-device)) (%close (slot-value self 'listenfd)) (%close (slot-value self 'fd)) (core-server::thread-kill (slot-value self 'core-server::%thread))) (defparameter *read-bufsize* 1024) (defparameter *response* "HTTP/1.1 200 OK Content-Type: text/html;charset=UTF-8 <html> <head><title>Core-Server Evloop Backend</title></head> <body><p>Default worker answering your request.</p></body> <p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p> </html> ") (defparameter *static-response* (foreign-alloc :string :count (length *response*))) (lisp-string-to-foreign *response* *static-response* (length *response*)) ;; read from fd, write to it, when EAGAIN occurs, save the state (defmethod handler-callback ((self epoll-device) fd) (format t "handler-callback with fd: ~D~%" fd) (with-foreign-object (buf :string *read-bufsize*) (bzero buf *read-bufsize*) (format t "read: ~D~%" (%read fd buf *read-bufsize*)) (format t "write: ~D~%" (%write fd *static-response* (length *response*))) (%close fd) (del self fd))) (defun test (port) (let* ((listen (bind "localhost" port)) (dev (make-epoll-device listen #'handler-callback))) (core-server::start dev) dev)) ;; (defun uuid-generate () ;; (with-foreign-objects ((uu :uchar 16) (out :char 36)) ;; (%uuid-generate uu) ;; (%uuid-unparse uu out) ;; out)) (defun uuid-generate () (with-foreign-object (s :uchar 16) (with-foreign-pointer-as-string (o 37) (%uuid-generate s) (%uuid-unparse s o) o)))
11,882
Common Lisp
.lisp
237
43.561181
2,055
0.681568
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
315833b208e18665ef5c298ab903f212fe37cbe311ea2a14514a8c36d2bb1938
8,254
[ -1 ]
8,255
libev.lisp
evrim_core-server/src/io/libev/libev.lisp
(in-package :core-ffi) ;; helpers and reimplementations (define-c-struct-wrapper ev-watcher ()) (defmacro defevfun (name return-type &body body) `(defcfun ,name ,return-type (loop :pointer) ,@body)) (defcfun "ev_default_loop_init" :pointer (flags :unsigned-int)) (defcvar "ev_default_loop_ptr" :pointer) (defun ev-default-loop (flags) (let ((loop *ev-default-loop-ptr*)) (if (null-pointer-p loop) (setf loop (ev-default-loop-init flags))) loop)) ;; GENERAL FUNS (defcfun "ev_time" ev-tstamp) (defcfun "ev_sleep" :void (delay ev-tstamp)) (defcfun "ev_version_major" :int) (defcfun "ev_version_minor" :int) (defcfun "ev_supported_backends" :unsigned-int) ;; ev_set_allocator (void *(*cb)(void *ptr, long size)) (defcfun "ev_set_allocator" :void (cb :pointer)) ;; ev_set_syserr_cb (void (*cb)(const char *msg)); (defcfun "ev_set_syserr_cb" :void (cb :pointer)) ;; FUNCTIONS CONTROLLING THE EVENT LOOP (defcfun "ev_loop_new" :pointer (flags :unsigned-int)) (defcfun "ev_default_destroy" :void) (defevfun "ev_loop_destroy" :void) (defevfun "ev_loop_fork" :void) (defevfun "ev_loop_count" :unsigned-int) (defevfun "ev_backend" :unsigned-int) (defevfun "ev_now" ev-tstamp) (defevfun "ev_loop" :void (flags :int)) (defevfun "ev_unloop" :void (how :int)) (defevfun "ev_ref" :void) (defevfun "ev_unref" :void) ;; +---------------------------------------------------------------------------- ;; | GENERIC WATCHER FUNCTIONS ;; +---------------------------------------------------------------------------- (defun ev-init (watcher cback) (with-foreign-slots ((active pending priority cb) watcher ev-watcher) (setf active 0 pending 0 priority 0 cb cback))) (defun ev-is-active (ev) (foreign-slot-value ev 'ev-watcher 'active)) (defun ev-is-pending (ev) (foreign-slot-value ev 'ev-watcher 'pending)) (defun ev-cb (ev) (foreign-slot-value ev 'ev-watcher 'cb)) (defun ev-cb-set (ev cb) (setf (foreign-slot-value ev 'ev-watcher 'cb) cb)) (defun ev-priority (ev) (foreign-slot-value ev 'ev-watcher 'priority)) (defun ev-set-priority (ev priority) (setf (foreign-slot-value ev 'ev-watcher 'priority) priority)) (defevfun "ev_invoke" :void (watcher :pointer) (revents :int)) (defevfun "ev_clear_pending" :int (watcher :pointer)) ;; ev_io - is this file descriptor readable or writable? (defun ev-io-set (watcher fd_ events_) (with-foreign-slots ((fd events) watcher ev-io) (setf fd fd_ events (logior events_ ev-iofdset)))) (defun ev-io-init (watcher cb fd events) (ev-init watcher cb) (ev-io-set watcher fd events)) (defevfun "ev_io_start" :void (watcher :pointer)) (defevfun "ev_io_stop" :void (watcher :pointer)) ;; ev_timer - relative and optionally repeating timeouts (defun ev-timer-set (watcher after repeat_) (setf (foreign-slot-value watcher 'ev-watcher-time 'at) after) (setf (foreign-slot-value watcher 'ev-timer 'repeat) repeat_)) (defun ev-timer-init (watcher cb after repeat) (ev-init watcher cb) (ev-timer-set watcher after repeat)) (defevfun "ev_timer_start" :void (watcher :pointer)) (defevfun "ev_timer_stop" :void (watcher :pointer)) (defevfun "ev_timer_again" :void (watcher :pointer)) ;; ev_periodic - to cron or not to cron? (defun ev-periodic-set (watcher offset_ interval_ reschedule-cb_) (with-foreign-slots ((offset interval reschedule-cb) watcher ev-periodic) (setf offset offset_ interval interval_ reschedule-cb reschedule-cb_))) (defun ev-periodic-init (watcher callback after repeat reschedule-cb) (ev-init watcher callback) (ev-periodic-set watcher after repeat reschedule-cb)) (defevfun "ev_periodic_start" :void (watcher :pointer)) (defevfun "ev_periodic_stop" :void (watcher :pointer)) (defevfun "ev_periodic_again" :void (watcher :pointer)) (defun ev-periodic-at (watcher) (foreign-slot-value watcher 'ev-watcher-time 'at)) ;; ev_signal - signal me when a signal gets signalled! (defun ev-signal-set (watcher signum) (setf (foreign-slot-value watcher 'ev-signal 'signum) signum)) (defun ev-signal-init (watcher callback signum) (ev-init watcher callback) (ev-signal-set watcher signum)) (defevfun "ev_signal_start" :void (watcher :pointer)) (defevfun "ev_signal_stop" :void (watcher :pointer)) ;; ev_child - watch out for process status changes (defun ev-child-set (watcher pid_ flags_) (with-foreign-slots ((pid flags) watcher ev-child) (setf pid pid_ flags flags_))) (defun ev-child-init (watcher callback pid trace) (ev-init watcher callback) (ev-child-set watcher pid trace)) (defevfun "ev_child_start" :void (watcher :pointer)) (defevfun "ev_child_stop" :void (watcher :pointer)) ;; ev_stat - did the file attributes just change? (defun ev-stat-set (watcher path_ interval_) (with-foreign-slots ((path interval wd) watcher ev-stat) (setf path path_ interval interval_ wd -2))) (defun ev-stat-init (watcher callback path interval) (ev-init watcher callback) (ev-stat-set watcher path interval)) (defevfun "ev_stat_start" :void (watcher :pointer)) (defevfun "ev_stat_stop" :void (watcher :pointer)) (defevfun "ev_stat_stat" :void (watcher :pointer)) ;; ev_idle - when you've got nothing better to do... (defun ev-idle-init (watcher callback) (ev-init watcher callback)) (defevfun "ev_idle_start" :void (watcher :pointer)) (defevfun "ev_idle_stop" :void (watcher :pointer)) ;; ev_prepare and ev_check - customise your event loop! (defun ev-prepare-init (watcher callback) (ev-init watcher callback)) (defevfun "ev_prepare_start" :void (watcher :pointer)) (defevfun "ev_prepare_stop" :void (watcher :pointer)) (defun ev-check-init (watcher callback) (ev-init watcher callback)) (defevfun "ev_check_start" :void (watcher :pointer)) (defevfun "ev_check_stop" :void (watcher :pointer)) ;; ev_embed - when one backend isn't enough... (defun ev-embed-set (watcher other) (setf (foreign-slot-value watcher 'ev-embed 'other) other)) (defun ev-embed-init (watcher callback other) (ev-init watcher callback) (ev-embed-set watcher other)) (defevfun "ev_embed_start" :void (watcher :pointer)) (defevfun "ev_embed_stop" :void (watcher :pointer)) (defevfun "ev_embed_sweep" :void (watcher :pointer)) ;; ev_fork - the audacity to resume the event loop after a fork (defun ev-fork-init (watcher callback) (ev-init watcher callback)) (defevfun "ev_fork_start" :void (watcher :pointer)) (defevfun "ev_fork_stop" :void (watcher :pointer)) ;; ev_async - how to wake up another event loop (defun ev-async-set (watcher) (setf (foreign-slot-value watcher 'ev-async 'sent) 0)) (defun ev-async-init (watcher callback) (ev-init watcher callback) (ev-async-set watcher)) (defevfun "ev_async_start" :void (watcher :pointer)) (defevfun "ev_async_stop" :void (watcher :pointer)) (defevfun "ev_async_send" :void (watcher :pointer)) ;; +---------------------------------------------------------------------------- ;; | Other functions ;; +---------------------------------------------------------------------------- (defevfun ev-once :void (fd :int) (events :int) (timeout ev-tstamp) (callback :pointer)) (defevfun ev-feed-event :void (watcher :pointer) (revents :int)) (defevfun ev-feed-fd-event :void (fd :int) (revents :int)) (defevfun ev-feed-signal-event :void (signum :int)) ;; +---------------------------------------------------------------------------- ;; | Examples from the docs ;; +---------------------------------------------------------------------------- ;; Example: Call stdin_readable_cb when STDIN_FILENO has become, well ;; readable, but only once. Since it is likely line-buffered, you ;; could attempt to read a whole line in the callback. (defcallback stdin-readable-cb :void ((loop :pointer) (watcher :pointer) (revents :int)) (declare (ignorable revents)) (format t "Callbacked") (ev-io-stop loop watcher) (ev-unloop loop evunloop-all)) (defun example1 (fd) (let ((loop (ev-default-loop 0)) (cb (callback stdin-readable-cb))) (with-foreign-object (watcher 'ev-io) (bzero watcher size-of-ev-io) (ev-io-init watcher cb fd ev-read) (ev-io-start loop watcher) (ev-loop loop 0)))) ;; Example: Create a timer that fires after 60 seconds. (defcallback one-minute-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable revents)) (format t "One minute over.") (ev-timer-stop loop w) (ev-unloop loop evunloop-all)) (defun example2 () (let ((loop (ev-default-loop 0)) (cb (callback one-minute-cb))) (with-foreign-object (watcher 'ev-timer) (bzero watcher size-of-ev-timer) (ev-timer-init watcher cb 60.0d0 0.0d0) (ev-timer-start loop watcher) (ev-loop loop 0)))) ;; Example: Create a timeout timer that times out after 10 seconds of ;; inactivity. (defcallback timeout-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable loop w revents)) (format t "ten seconds without any activity")) (defun example3 () (let ((loop (ev-default-loop 0)) (cb (callback timeout-cb))) (with-foreign-object (watcher 'ev-timer) (bzero watcher size-of-ev-timer) (ev-timer-init watcher cb 0 10) (ev-timer-again loop watcher) (ev-loop loop 0)))) ;; Example: Call a callback every hour, or, more precisely, whenever ;; the system clock is divisible by 3600. The callback invocation ;; times have potentially a lot of jitter, but good long-term ;; stability. (defcallback every-hour-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable loop w revents)) (format t "its now a full hour (UTC, or TAI or whatever your clock follows)")) (defun example4 () (let ((loop (ev-default-loop 0)) (cb (callback every-hour-cb))) (with-foreign-object (hourly-tick 'ev-periodic) (bzero hourly-tick size-of-ev-periodic) (ev-periodic-init hourly-tick cb 0.0d0 3600.0d0 0) (ev-periodic-start loop hourly-tick) (ev-loop loop 0)))) ;; Example: Try to exit cleanly on SIGINT and SIGTERM. (defcallback sigint-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable w revents)) (ev-unloop loop evunloop-all)) (defun example5 () (let ((loop (ev-default-loop 0)) (cb (callback sigint-cb))) (with-foreign-object (w 'ev-signal) (bzero w size-of-ev-signal) (ev-signal-init w cb sigint) (ev-signal-start loop w) (ev-loop loop 0)))) ;; Example: fork() a new process and install a child handler to wait ;; for its completion. (defcallback child-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable revents)) (ev-child-stop loop w) ;; printf ("process %d exited with status %x\n", w->rpid, w->rstatus); (with-foreign-slots ((rpid rstatus) w ev-child) (format t "process ~D exited with status ~D" rpid rstatus))) (defun example6 () (let ((loop (ev-default-loop 0)) (cb (callback child-cb))) (with-foreign-object (w 'ev-child) (bzero w size-of-ev-child) (let ((pid (sb-posix::fork))) (cond ((= pid 0) ;;child here (sb-unix:unix-exit 1)) (t ;; parent here (ev-child-init w cb pid 0) (ev-child-start loop w) (ev-loop loop 0))))))) ;; Example: Watch /tmp/passwd for attribute changes. (defcallback passwd-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable loop revents)) (let ((attr (foreign-slot-value w 'ev-stat 'attr))) (with-foreign-slots ((st-nlink st-size st-atim st-mtim) attr stat) (if (< 0 st-nlink) ;; file exists (format t "size: ~f, atime: ~f, mtime:~f ~%" st-size st-atim st-mtim) ;; file not found (format t "file not found~%"))))) (defun example7 () (let ((loop (ev-default-loop 0)) (cb (callback passwd-cb))) (with-foreign-object (w 'ev-stat) (bzero w size-of-ev-stat) (ev-stat-init w cb "/tmp/passwd" 0.0d0) (ev-stat-start loop w) (ev-loop loop 0)))) ;; Example: Like above, but additionally use a one-second delay so we ;; do not miss updates (however, frequent updates will delay ;; processing, too, so one might do the work both on ev_stat callback ;; invocation and on ev_timer callback invocation). (defparameter *example8-timer* (foreign-alloc 'ev-timer)) (defcallback timer-cb :void ((loop :pointer) (timer :pointer) (revents :int)) (declare (ignorable revents)) (ev-timer-stop loop timer) (format t "now it's one second after the most recent passwd change~%")) (defcallback stat-cb :void ((loop :pointer) (stat :pointer) (revents :int)) (declare (ignorable stat revents)) (ev-timer-again loop *example8-timer*)) (defun example8 () (let ((loop (ev-default-loop 0)) (cb1 (callback timer-cb)) (cb2 (callback stat-cb))) (with-foreign-object (passwd 'ev-stat) (bzero passwd size-of-ev-stat) (bzero *example8-timer* size-of-ev-timer) (ev-stat-init passwd cb2 "/tmp/passwd" 0.0d0) (ev-stat-start loop passwd) (ev-timer-init *example8-timer* cb1 0.0d0 1.02d0) (ev-loop loop 0)))) ;; Example: Dynamically allocate an ev_idle watcher, start it, and in ;; the callback, free it. Also, use no error checking, as usual. (defcallback idle-cb :void ((loop :pointer) (w :pointer) (revents :int)) (declare (ignorable loop revents)) (format t "event loop is idle~%") (ev-idle-stop loop w) (foreign-free w)) (defun example9 () (let ((loop (ev-default-loop 0)) (cb (callback idle-cb)) (idle-watcher (foreign-alloc 'ev-idle))) (bzero idle-watcher size-of-ev-idle) (ev-idle-init idle-watcher cb) (ev-idle-start loop idle-watcher) (ev-loop loop 0)))
13,524
Common Lisp
.lisp
323
38.98452
88
0.67972
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4a17b5ef93ae9eb6a16348b09236d1f5a0635c1275406b83455c786e370e26da
8,255
[ -1 ]
8,256
grovel.lisp
evrim_core-server/src/io/libev/grovel.lisp
(in-package :core-ffi) (include "ev.h" "signal.h" "sys/stat.h") (constant (sigint "SIGINT")) ;; (define "EV_MULTIPLICITY") (constant (evflag-auto "EVFLAG_AUTO")) (constant (evflag-noenv "EVFLAG_NOENV")) (constant (evflag-forkcheck "EVFLAG_FORKCHECK")) (constant (evbackend-select "EVBACKEND_SELECT")) (constant (evbackend-poll "EVBACKEND_POLL")) (constant (evbackend-epoll "EVBACKEND_EPOLL")) (constant (evbackend-kqueue "EVBACKEND_KQUEUE")) (ctype ev-tstamp "double") (ctype nlink-t "__UWORD_TYPE") (ctype off-t "__SLONGWORD_TYPE") (ctype ev-atomic-t "EV_ATOMIC_T") (constant (evloop-nonblock "EVLOOP_NONBLOCK")) (constant (evloop-oneshot "EVLOOP_ONESHOT")) (constant (evunloop-cancel "EVUNLOOP_CANCEL")) (constant (evunloop-one "EVUNLOOP_ONE")) (constant (evunloop-all "EVUNLOOP_ALL")) (constant (ev-undef "EV_UNDEF")) (constant (ev-none "EV_NONE")) (constant (ev-read "EV_READ")) (constant (ev-write "EV_WRITE")) (constant (ev-iofdset "EV_IOFDSET")) (constant (ev-timeout "EV_TIMEOUT")) (constant (ev-periodic "EV_PERIODIC")) (constant (ev-signal "EV_SIGNAL")) (constant (ev-child "EV_CHILD")) (constant (ev-stat "EV_STAT")) (constant (ev-idle "EV_IDLE")) (constant (ev-prepare "EV_PREPARE")) (constant (ev-check "EV_CHECK")) (constant (ev-embed "EV_EMBED")) (constant (ev-fork "EV_FORK")) (constant (ev-async "EV_ASYNC")) (constant (ev-error "EV_ERROR")) (cstruct ev-watcher "struct ev_watcher" (active "active" :type :int) (pending "pending" :type :int) (priority "priority" :type :int) (data "data" :type :pointer) ;; void (*cb)(EV_P_ struct type *w, int revents); (cb "cb" :type :pointer)) (cstruct ev-watcher-time "struct ev_watcher_time" (at "at" :type :double)) (cstruct ev-io "struct ev_io" (fd "fd" :type :int) (events "events" :type :int)) (cstruct ev-timer "struct ev_timer" (repeat "repeat" :type :double)) (cstruct ev-periodic "struct ev_periodic" (offset "offset" :type :double) (interval "interval" :type :double) ;; ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now); (reschedule-cb "reschedule_cb" :type :pointer) ) (cstruct ev-signal "struct ev_signal" (signum "signum" :type :int)) (cstruct ev-child "struct ev_child" (flags "flags" :type :int) (pid "pid" :type :int) (rpid "rpid" :type :int) (rstatus "rstatus" :type :int)) (cstruct ev-statdata "struct stat") (cstruct ev-stat "struct ev_stat" (timer "timer" :type :double) (interval "interval" :type :double) (path "path" :type :string) (prev "prev" :type ev-statdata) (attr "attr" :type ev-statdata) (wd "wd" :type :int)) (cstruct ev-idle "struct ev_idle") (cstruct ev-prepare "struct ev_prepare") (cstruct ev-check "struct ev_check") (cstruct ev-fork "struct ev_fork") (cstruct ev-embed "struct ev_embed" (other "other" :type :pointer) (io "io" :type ev-io) (prepare "prepare" :type ev-prepare) (check "check" :type ev-check) (timer "timer" :type ev-timer) (periodic "periodic" :type ev-periodic) (idle "idle" :type ev-idle) (fork "fork" :type ev-fork)) (cstruct ev-async "struct ev_async" (sent "sent" :type ev-atomic-t)) ;; stat (ctype time_t "time_t") (cstruct timespec "struct timespec" "UNIX time specification in seconds and nanoseconds." (sec "tv_sec" :type time_t) (nsec "tv_nsec" :type :long)) (cstruct stat "struct stat" (st-nlink "st_nlink" :type nlink-t) (st-size "st_size" :type off-t) (st-atim "st_atim" :type timespec) (st-mtim "st_mtim" :type timespec) (st-ctim "st_ctim" :type timespec))
3,565
Common Lisp
.lisp
99
33.323232
70
0.684165
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
50a7ffd92ee9fe8b0909c0e708a25842a8db7a74fbdcadc0920a3fde7c651047
8,256
[ -1 ]
8,257
interface.lisp
evrim_core-server/src/io/libev/interface.lisp
(in-package :core-ffi) (defmacro defwatcher-cb (name &body body) `(defcallback ,name :void ((loop :pointer) (watcher :pointer) (revents :int)) (declare (ignorable loop watcher revents)) ,@body))
208
Common Lisp
.lisp
5
38
79
0.693069
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5cfd11374484e41afbd2ddd66412f28a3116990eea47cc5a3c4f19f25d1b01f1
8,257
[ -1 ]
8,258
libev-lib.lisp
evrim_core-server/src/io/libev/libev-lib.lisp
(in-package :core-ffi) (define-foreign-library libev (:unix (:or "libev.so" "libev.so.3.0.0")) (t (:default "libev"))) (use-foreign-library libev)
153
Common Lisp
.lisp
5
28.4
43
0.678082
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
af91d9bc403bddced9c159123453a33651e7fcef8ad50ae3d4fa6d0a58ab040b
8,258
[ -1 ]
8,259
cps.lisp
evrim_core-server/src/javascript/cps.lisp
(in-package :core-server) ;; +---------------------------------------------------------------------------- ;; | Javascript CPS Conversion ;; +---------------------------------------------------------------------------- ;; ;; Author: Evrim Ulu <[email protected]> ;; Date: 29/11/2008 (eval-when (:compile-toplevel :load-toplevel :execute) (defvar +javascript-cps-functions+ (make-hash-table))) ;; ---------------------------------------------------------------------------- ;; Function Homomorphism ;; ---------------------------------------------------------------------------- (fmakunbound 'javascript->cps) (defgeneric javascript->cps (form expand k env) (:documentation "Expanders for lisp to javascript cps transformation")) (defmacro defcps-expander/js (class (&rest slots) &body body) `(eval-when (:load-toplevel :compile-toplevel :execute) (defmethod javascript->cps ((form ,class) expand k env) (declare (ignorable expand)) (with-slots ,slots form ,@body)))) (defcps-expander/js form (source) source) (defcps-expander/js constant-form (value) `(,k ,value)) (defcps-expander/js variable-reference (name) `(,k ,name)) (defcps-expander/js lambda-function-form (arguments declares body) (with-unique-names (k1) (if k `(,k (lambda (,@(unwalk-lambda-list arguments) ,k1) ,(call-next-method form expand k1 env))) `(lambda (,@(unwalk-lambda-list arguments) ,k1) ,(call-next-method form expand k1 env))))) (defcps-expander/js implicit-progn-mixin (body) (case (length body) (1 (funcall expand (car body) expand k env)) (t (funcall expand (car body) expand (reduce (lambda (k form) (with-unique-names (value) `(lambda (,value) ,(funcall expand form expand k env)))) (butlast (reverse body)) :initial-value k) env)))) (defcps-expander/js application-form (operator arguments) (case operator (let/cc (let ((k-arg (unwalk-form (car arguments)))) `(let ((,k-arg ,k)) ,(funcall expand (make-instance 'implicit-progn-mixin :body (cdr arguments)) expand k-arg env)))) ;; (new ;; (let ((ctor (car arguments))) ;; `(make-instance ,k ,(operator ctor) ,@(unwalk-forms (arguments ctor))) ;; ;; (funcall expand ;; ;; (walk-js-form ;; ;; ) ;; ;; expand k env) ;; )) (javascript-cps-method-body `(let ((self (or self this)) ;; (,k (or ,k window.k)) ) ,(funcall expand (make-instance 'implicit-progn-mixin :body arguments) expand k env)) ;; (with-unique-names (k1) ;; `(,k (lambda (,@(slot-value (car arguments) 'source) ,k1) ;; (let ((self (or self this))) ;; ,(funcall expand ;; (make-instance 'implicit-progn-mixin ;; :body (cdr arguments)) ;; expand k1 env))))) ) (suspend nil) (reset (arnesi::extend env :let 'reset k) (funcall expand (make-instance 'implicit-progn-mixin :body arguments) expand k env)) (shift (let ((r (arnesi::lookup env :let 'reset))) (assert (not (null r)) nil "Reset is not found in js cps env") (funcall expand (make-instance 'implicit-progn-mixin :body arguments) expand r env))) (event `(,k (lambda (,@(slot-value (car arguments) 'source)) ,@(mapcar (lambda (a) (slot-value a 'source)) (cdr arguments))))) (:catch `(:catch ,(slot-value (car arguments) 'source) ,(funcall expand (make-instance 'implicit-progn-mixin :body (cdr arguments)) expand k env))) (try `(try ,(funcall expand (make-instance 'implicit-progn-mixin :body (butlast arguments)) expand k env) ,(funcall expand (last1 arguments) expand k env))) (t (flet ((constant-p (form) (or (typep form 'constant-form) (typep form 'variable-reference)))) (let* ((arguments (mapcar (lambda (arg) (if (constant-p arg) (cons arg (unwalk-form arg)) (cons arg (gensym)))) arguments)) (lazy-arguments (reverse (filter (compose #'not #'constant-p #'car) arguments)))) (reduce (lambda (k arg) (let ((form (car arg)) (symbol (cdr arg))) (funcall expand form expand `(lambda (,symbol) ,k) env))) lazy-arguments :initial-value (cond ((typep operator 'lambda-function-form) (funcall expand operator expand `(lambda (fun) (fun ,@(mapcar #'cdr arguments) ,k)) env)) ((gethash operator +javascript-cps-functions+) `(,operator ,@(mapcar #'cdr arguments) ,k)) ((eq 'call/cc operator) `(,(cdr (car arguments)) ,@(mapcar #'cdr (cdr arguments)) ,k)) (t ;; (describe operator) `(,k (,operator ,@(mapcar #'cdr arguments))))))))))) (defcps-expander/js let-form (binds body) (funcall expand (make-instance 'lambda-application-form :operator (make-instance 'lambda-function-form :arguments (walk-lambda-list (mapcar #'car binds) (parent form) nil) :body body) :arguments (mapcar #'cdr binds) :parent (parent form)) expand k env)) (defcps-expander/js let*-form (binds body) (labels ((recursive-let (binds body) `(let ((,(caar binds) ,(unwalk-form (cdar binds)))) ,@(if (null (cdr binds)) (unwalk-forms body) (list (recursive-let (cdr binds) body)))))) (funcall expand (walk-form (recursive-let binds body)) expand k env))) (defcps-expander/js flet-form (binds body) `(let ,(mapcar (lambda (bind) `(,(car bind) ,(funcall expand (cdr bind) expand nil env))) binds) ,(funcall expand (make-instance 'implicit-progn-mixin :body body) expand k env))) (defcps-expander/js labels-form (binds body) `(let ,(mapcar (lambda (bind) `(,(car bind) ,(funcall expand (cdr bind) expand nil env))) binds) ,(funcall expand (make-instance 'implicit-progn-mixin :body body) expand k env))) (defcps-expander/js if-form (consequent then else) (with-unique-names (value) (funcall expand consequent expand `(lambda (,value) (if ,value ,(funcall expand then expand k env) ,(if else (funcall expand else expand k env) `(,k nil)))) env))) (defcps-expander/js cond-form (conditions) (if (typep (caar conditions) 'constant-form) (funcall expand (make-instance 'implicit-progn-mixin :body (cdar conditions)) expand k env) (funcall expand (walk-js-form (macroexpand-1 (slot-value form 'source))) expand k env))) (defcps-expander/js setq-form (var value) (with-unique-names (temp var1 value1) (if (not (or (typep var 'constant-form) (typep var 'variable-reference))) (funcall expand value expand `(lambda (,value1) ,(funcall expand var expand `(lambda (,var1) (,k (setq ,var1 ,value1))) env)) env) (funcall expand value expand `(lambda (,temp) (,k (setq ,(slot-value var 'source) ,temp))) env)))) (defcps-expander/js defun-form (name arguments body) (error "Please use defun/cc outside with-call/cc.")) ;; +---------------------------------------------------------------------------- ;; | Poor mans reduction: Fix Excessive Recursions (alpha,beta) ;; +---------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defun fix-excessive-recursion (form) ;; (describe (list 'start (unwalk-form form))) (flet ((replace-form (source target) (prog1 target (change-class target (class-name (class-of source))) (mapcar (lambda (slot) (setf (slot-value target slot) (slot-value source slot))) (remove 'parent (mapcar #'slot-definition-name (class-slots (class-of source)))))))) (let ((applications (ast-search-type form 'lambda-application-form))) (mapcar (lambda (application) (let ((operator (slot-value application 'operator))) (mapcar (lambda (arg value) (cond ((typep value 'lambda-function-form) (mapcar (lambda (ref) (replace-form value ref)) (filter (lambda (ref) (eq arg (slot-value ref 'name))) (ast-search-type operator 'variable-reference))) (mapcar (lambda (ref) (change-class ref 'lambda-application-form) (let ((new-form (walk-js-form (unwalk-form value)))) (setf (slot-value ref 'operator) new-form (slot-value new-form 'parent) ref)) (fix-excessive-recursion ref)) (filter (lambda (ref) (eq arg (slot-value ref 'operator))) (ast-search-type operator 'application-form)))) ((typep value 'constant-form) (mapcar (lambda (ref) (replace-form value ref)) (filter (lambda (ref) (eq arg (slot-value ref 'name))) (ast-search-type operator 'variable-reference)))) ((typep value 'variable-reference) (mapcar (lambda (ref) (replace-form value ref)) (filter (lambda (ref) (eq arg (slot-value ref 'name))) (ast-search-type operator 'variable-reference))) (mapcar (lambda (ref) (setf (slot-value ref 'operator) (unwalk-form value))) (filter (lambda (ref) (eq arg (slot-value ref 'operator))) (ast-search-type operator 'application-form)))) (t (let ((refs (append (filter (lambda (ref) (eq arg (slot-value ref 'operator))) (ast-search-type operator 'application-form)) (filter (lambda (ref) (eq arg (slot-value ref 'name))) (ast-search-type operator 'variable-reference))))) (cond ((eq 0 (length refs)) (setf (slot-value operator 'body) (cons value (slot-value operator 'body)))) ((and (eq 1 (length refs)) (not (typep (car refs) 'application-form))) (replace-form value (car refs))) (t (setf (slot-value operator 'body) (list (make-instance 'let-form :binds (list (cons arg value)) :body (slot-value operator 'body) :parent operator))))))))) (if (slot-boundp operator 'arguments) (mapcar #'unwalk-form (slot-value operator 'arguments))) (if (slot-boundp application 'arguments) (slot-value application 'arguments))) (change-class application 'progn-form) (setf (slot-value application 'body) (slot-value operator 'body)))) applications))) ;; (describe (list 'end (unwalk-form form))) form) ;; +---------------------------------------------------------------------------- ;; | Fix lambda default kontinuations ;; +---------------------------------------------------------------------------- (defun fix-lambda-k (form) (prog1 form (let ((funs (filter (lambda (a) (> (length (slot-value a 'arguments)) 1)) (ast-search-type form 'lambda-function-form)))) (mapcar (lambda (form) (let ((last1 (last1 (if (slot-boundp form 'arguments) (slot-value form 'arguments))))) (when last1 (setf (slot-value form 'body) (list (make-instance 'let-form :binds (let ((k-arg (unwalk-form last1))) (list `(,k-arg . ,(walk-js-form `(or ,k-arg window.k))))) :body (slot-value form 'body) :parent (parent form))))))) funs)))) (defun fix-progn (form) (cond ((and (typep form 'progn-form) (eq (length (slot-value form 'body)) 1)) (car (slot-value form 'body))) (t form)))) ;; ---------------------------------------------------------------------------- ;; Interface ;; ---------------------------------------------------------------------------- (defmacro/js with-call/cc (&body body) (unwalk-form (fix-lambda-k (fix-progn (fix-excessive-recursion (walk-js-form (javascript->cps (walk-js-form (if (= 1 (length body)) (car body) `(progn ,@body))) #'javascript->cps '(lambda (val) val) nil))))))) (defmacro/js defun/cc (name args &body body) (with-unique-names (k) (eval-when (:compile-toplevel :execute :load-toplevel) (setf (gethash name +javascript-cps-functions+) t)) `(defun ,name (,@args ,k) (setf ,k (or ,k window.k)) ,(unwalk-form (fix-lambda-k (fix-excessive-recursion (walk-js-form (javascript->cps (walk-js-form `(progn ,@body)) #'javascript->cps k nil)))))))) ;; (let ((a (fun-a))) ;; (list a a a)) ;; (fun-a (lambda (a) ;; (list a a a)))
12,509
Common Lisp
.lisp
334
31.52994
81
0.573957
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e5768c17e734fa132c662b0055ca3a5cd5dc8a5d6e2d9a5af50fedcc0875c781
8,259
[ -1 ]
8,260
util.lisp
evrim_core-server/src/javascript/util.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;; Got from parenscript. ;;; This is just an effort to fix http-equiv conversion problem ;;; ecmascript standard: ;;; http://www.ecma-international.org/publications/standards/Ecma-262.htm ;;; FIXme: We should clean this or add license information about this ;;; file -evrim ;; javascript name conversion (defparameter *special-chars* '((#\! . "Bang") (#\? . "What") (#\# . "Hash") (#\@ . "At") (#\% . "Percent") (#\+ . "Plus") (#\* . "Star") (#\/ . "Slash"))) ;;; wie herrlich effizient (defun list-to-string (list) (reduce #'(lambda (str1 &optional (str2 "")) (concatenate 'string str1 str2)) list)) (defun list-join (list elt) (let (res) (dolist (i list) (push i res) (push elt res)) (pop res) (nreverse res))) (defun string-join (strings elt) (list-to-string (list-join strings elt))) (defun string-split (string separators) (do ((len (length string)) (i 0 (1+ i)) (last 0) res) ((= i len) (nreverse (if (> i last) (cons (subseq string last i) res) res))) (when (member (char string i) separators) (push (subseq string last i) res) (setf last (1+ i))))) (defun string-chars (string) (coerce string 'list)) (defun constant-string-p (string) (let ((len (length string)) (constant-chars '(#\+ #\*))) (and (> len 2) (member (char string 0) constant-chars) (member (char string (1- len)) constant-chars)))) (defun first-uppercase-p (string) (and (> (length string) 1) (member (char string 0) '(#\+ #\*)))) (defun untouchable-string-p (string) (and (> (length string) 1) (char= #\: (char string 0)))) (defun symbol->js (symbol) (when (symbolp symbol) (setf symbol (symbol-name symbol))) (let ((symbols (string-split symbol '(#\.)))) (cond ((null symbols) "") ((= (length symbols) 1) (let (res (do-not-touch nil) (lowercase t) (all-uppercase nil)) (cond ((constant-string-p symbol) (setf all-uppercase t symbol (subseq symbol 1 (1- (length symbol))))) ((first-uppercase-p symbol) (setf lowercase nil symbol (subseq symbol 1))) ((untouchable-string-p symbol) (setf do-not-touch t symbol (subseq symbol 1)))) (flet ((reschar (c) (push (cond (do-not-touch c) ((and lowercase (not all-uppercase)) (char-downcase c)) (t (char-upcase c))) res) (setf lowercase t))) (dotimes (i (length symbol)) (let ((c (char symbol i))) (cond ;; :http--equiv => "http-equiv" ((and (not lowercase) (eql c #\-)) (reschar #\-)) ((eql c #\-) (setf lowercase (not lowercase))) ((assoc c *special-chars*) (dolist (i (coerce (cdr (assoc c *special-chars*)) 'list)) (reschar i))) (t (reschar c)))))) (coerce (nreverse res) 'string))) (t (string-join (mapcar #'symbol-to-js symbols) "."))))) (defun symbol-to-js (symbol) (symbol->js symbol))
4,006
Common Lisp
.lisp
112
29.098214
73
0.586429
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d58e194897f8661563f0efa215e8b6056308d7778e43c07a5d24c842d7a6492c
8,260
[ -1 ]
8,261
transform.lisp
evrim_core-server/src/javascript/transform.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+----------------------------------------------------------------------------- ;;| Javascript AST Transformers ;;+----------------------------------------------------------------------------- ;; ;; This file contains transformations that makes javascript more lispy. ;; ;;----------------------------------------------------------------------------- ;; Javascript Functionalization ;;----------------------------------------------------------------------------- ;; This is a preprocessor to solve the return problem of javascript ie: ;; ;; (print ((lambda (a) a) 1)) ;; ;; should print 1, but javascript is broken, so we add returns implicitly. ;; (eval-when (:load-toplevel :compile-toplevel :execute) (defgeneric find-form-leaf (form) (:documentation "Returns list of termination subforms the 'form'")) (defmethod find-form-leaf ((form t)) form) (defmethod find-form-leaf ((form implicit-progn-mixin)) (find-form-leaf (last1 (body form)))) (defmethod find-form-leaf ((form if-form)) (append (ensure-list (find-form-leaf (then form))) (ensure-list (find-form-leaf (else form))))) (defmethod find-form-leaf ((form cond-form)) (nreverse (reduce0 (lambda (acc atom) (cons (find-form-leaf (last1 atom)) acc)) (conditions form)))) (defmethod find-form-leaf ((form let-form)) (find-form-leaf (last1 (body form)))) (defmethod find-form-leaf ((form application-form)) (cond ((eq 'try (operator form)) ;; (describe form) (arguments form) nil) (t form))) (defun fix-javascript-returns (form) "Alters 'form' destructively and adds implicit return statements to 'form'" (flet ((transform-to-implicit-return (form) (let ((new-form (walk-js-form (unwalk-form form) (parent form)))) (unless (or (typep form 'throw-form) (and (typep form 'application-form) (eq 'return (operator form)))) (change-class form 'application-form) (setf (operator form) 'return) (setf (arguments form) (list new-form))) new-form))) (let ((funs (ast-search-type form 'lambda-function-form))) (mapcar #'transform-to-implicit-return (flatten (mapcar #'find-form-leaf funs)))) ;; (let ((implicit-returns (let (lst) ;; (ast-search form ;; (lambda (atom) ;; (if (and (not (typep atom 'application-form)) ;; (not (typep (parent atom) 'implicit-progn-mixin))) ;; (pushnew atom lst)))) ;; lst))) ;; ;; (mapcar #'describe implicit-returns) ;; ) form)) (defun fix-javascript-methods (form self) (let ((applications (ast-search-type form 'application-form))) (mapcar (lambda (app) (when (and (typep (car (arguments app)) 'variable-reference) (eq (name (car (arguments app))) self)) (if (eq (operator app) 'slot-value) (setf (arguments app) (cons (walk-js-form 'this app) (cdr (arguments app)))) (setf (operator app) (intern (format nil "THIS.~A" (operator app))) (arguments app) (cdr (arguments app)))))) applications) form)) ;; TODO: Handle (setf a b c d) (defun fix-javascript-accessors (form accessors &optional (get-prefix "GET-") (set-prefix "SET-")) (let ((applications (ast-search-type form 'application-form))) (mapcar (lambda (app) (cond ((and (eq 'setf (operator app)) (typep (car (arguments app)) 'application-form) (member (operator (car (arguments app))) accessors)) (setf (operator app) (intern (format nil "~A~A" set-prefix (operator (car (arguments app))))) (arguments app) (cons (car (arguments (car (arguments app)))) (cdr (arguments app))))) ((and (member (operator app) accessors) (not (and (typep (parent app) 'application-form) (eq 'setf (operator (parent app)))))) (setf (operator app) (intern (format nil "~A~A" get-prefix (operator app))))))) applications) form))) ;; ;;----------------------------------------------------------------------------- ;; ;; External Variable For Fast Rendering ;; ;;----------------------------------------------------------------------------- ;; (eval-when (:load-toplevel :compile-toplevel :execute) ;; (defclass external-variable-reference (variable-reference) ;; ()) ;; (defjavascript-expander external-variable-reference (name) ;; `(:json! ,name)) ;; ;; FIxme: put something meaningful here. -evrim. ;; ;; This transformer overrides free-variable-references. Arguments of defrender/js ;; ;; are transformed into exnternal-variable-references to that they can ;; ;; the client. We use json serialized to be fast. ;; (defun fix-javascript-external-variables (form variables) ;; (let ((references (reduce (lambda (acc var) ;; (mapcar (lambda (reference) ;; (if (or (eq (name reference) var) (boundp (name reference))) ;; (pushnew reference acc))) ;; (ast-search-type form 'free-variable-reference)) ;; acc) ;; variables :initial-value nil))) ;; (mapcar (lambda (reference) ;; (prog1 (change-class reference 'external-variable-reference) ;; (describe reference))) ;; references) ;; form)))
5,954
Common Lisp
.lisp
130
42.092308
100
0.610699
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fb115e206cfe7ed90efae33245a0979a4e4b0ccba319e87a30d56048676569c0
8,261
[ -1 ]
8,262
library.lisp
evrim_core-server/src/javascript/library.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+-------------------------------------------------------------------------- ;;| Javascript Library ;;+-------------------------------------------------------------------------- ;; ;; This file contains javascript library functions. ;; (defrender/js core-library! (&optional (loading-gif +loading-gif+) (theme-root +theme-root+) (current-theme +default-theme+)) (defun atom (a) (cond ((null a) t) ((null a.length) t) ((typep a 'string) t) (t nil))) (defun listp (a) (not (atom a))) (defun null-p (a) (or (null a) (eq "undefined" a) (eq "" a))) (defun/cc reduce-cc (fun lst initial-value) (if (or (null lst) (= 0 lst.length)) initial-value (reduce-cc fun (cdr lst) (call/cc fun initial-value (car lst))))) (defun reduce (fun lst initial-value) (if (null lst) nil (let ((result (or (and (not (typep initial-value 'undefined)) initial-value) nil))) (if (not (null lst.length)) (dolist (item lst) (setf result (fun result item))) (doeach (item lst) (setf result (fun result (aref lst item))))) result))) (defun/cc reduce0-cc (fun lst) (reduce-cc fun lst nil)) (defun reduce0 (fun lst) (reduce fun lst nil)) (defun/cc reverse-cc (lst) (if (null lst) nil (reduce0-cc (lambda (acc a) (cons a acc)) lst))) (defun reverse (lst) (if (null lst) nil (reduce0 (lambda (acc a) (cons a acc)) lst))) (defun flatten (lst acc) (if (typep acc 'undefined) (setf acc (list))) (cond ((null lst) nil) ((not (instanceof lst *array)) (cons lst acc)) ((not lst.length) acc) (t (flatten (car lst) (flatten (cdr lst) acc))))) (defun flatten1 (lst) (reduce0 (lambda (acc a) (if acc (.concat a acc) (list a))) lst)) (defun filter (fun lst) (reverse (reduce0 (lambda (acc atom) (if (fun atom) (cons atom acc) acc)) lst))) (defun take (n lst) (if (typep lst 'string) (.join (take n (.split lst "")) "") (cond ((null (car lst)) nil) ((> n 0) (cons (car lst) (take (- n 1) (cdr lst)))) (t nil)))) (defun drop (n lst) (if (typep lst 'string) (.join (drop n (.split lst "")) "") (cond ((> n 0) (drop (- n 1) (cdr lst))) (t lst)))) (defun/cc filter-cc (fun lst) (reverse-cc (reduce0-cc (lambda (acc a) (if (call/cc fun a) (cons a acc) acc)) lst))) (defun cons (an-atom lst) (cond ((null lst) (array an-atom)) ((atom lst) (array an-atom lst)) (t (.concat (array an-atom) (if (instanceof lst *array) lst (list lst)))))) (defun car (lst) (cond ((null lst) nil) ((and (not (null lst.length)) (eq lst.length 0)) nil) ((instanceof lst *array) (aref lst 0)) ((and (typep lst 'object) (not (null lst.length)) (> lst.length 0)) (aref lst 0)) ((typep lst 'object) (let ((result)) (doeach (i lst) (setf result (aref lst i))) result)) (t nil))) (defun cdr (lst) (cond ((null lst) nil) ((atom lst) lst) ((and (or (typep lst '*array) (typep lst 'object)) (not (null (slot-value lst 'slice)))) (.slice lst 1)) (t (cdr (mapcar (lambda (a) (return a)) lst))))) (defun nth (seq lst) (if (= 0 seq) (car lst) (nth (1- seq) (cdr lst)))) (defun position (atom lst) (let ((n -1)) (cond ((null lst) n) (t (mapcar2 (lambda (a b) (if (eq a atom) (setf n b))) lst (seq (slot-value lst 'length))) n)))) (defun/cc mapcar-cc (fun lst) (reverse-cc (reduce-cc (lambda (acc atom) (cons (call/cc fun atom) acc)) lst null))) (defun mapcar (fun lst) (reverse (reduce (lambda (acc atom) (cons (fun atom) acc)) lst))) (defun mapcar2 (fun lst1 lst2) (mapcar (lambda (index) (fun (nth index lst1) (nth index lst2))) (seq (*math.min (slot-value lst1 'length) (slot-value lst2 'length))))) (defun/cc mapcar2-cc (fun lst1 lst2) (mapcar-cc (lambda (index) (call/cc fun (nth index lst1) (nth index lst2))) (seq (*math.min (slot-value lst1 'length) (slot-value lst2 'length))))) (defun any (fun lst) (dolist (i lst) (if (fun i) (return i))) (return nil)) (defun seq (num) (cond ((>= num 1) (reverse (cons (- num 1) (reverse (seq (- num 1)))))) (t (array)))) (defun mapobject (fun obj) (let ((result (new (*object)))) (doeach (i obj) (setf (slot-value result i) (fun i (slot-value obj i)))) result)) (defun describe (obj) (_debug obj)) (defun object-to-list (obj) (let ((result)) (mapobject (lambda (k v) (setf result (cons (list k v) result))) obj) (reverse result))) (defun describe-object (obj) (describe (object-to-list obj))) (defun member (obj lst) (reduce (lambda (acc atom) (or acc (equal atom obj))) lst)) (defun sort (fun lst) (let ((first (car lst)) (rest (cdr lst))) (if first (flet ((compare (a) (fun first a))) (append (sort fun (filter compare rest)) (cons first (sort fun (filter (lambda (a) (not (compare a))) rest)))))))) (defun uniq (key-fun lst) (reverse (reduce (lambda (acc atom) (if (eq (key-fun (car acc)) (key-fun atom)) acc (cons atom acc))) (sort (lambda (a b) (eq (key-fun a) (key-fun b))) lst)))) (defun remove (item lst) (reverse (reduce0 (lambda (acc atom) (if (eq item atom) acc (cons atom acc))) lst))) (defun has-class (node class-name) (if (member class-name (node.class-name.split " ")) t nil)) (defun remove-class (node class-name) (let ((classes (node.class-name.split " "))) (when (and classes classes.length) (let ((classes (filter (lambda (a) (not (equal class-name a))) classes))) (if (and classes classes.length) (setf node.class-name (.join classes " ")) (setf node.class-name ""))))) node) (defun add-class (node class-name) (remove-class node class-name) (setf node.class-name (+ class-name " " node.class-name)) node) (defun replace-node (old-node new-node) (old-node.parent-node.replace-child new-node old-node) new-node) (defun trim (str) (.replace (new (*string str)) (regex "/^\\s+|\\s+$/g") "")) (defun show (node) (when (and node (slot-value node 'style)) (setf node.style.display "block")) node) (defun is-showing (node) (not (eq "none" node.style.display))) (defun hide (node) (when (and node (slot-value node 'style)) (setf node.style.display "none")) node) (defun inline (node) (when (and (slot-value node 'style)) (setf node.style.display "inline")) node) (defun connect (target event lambda) (if (typep target 'string) (setf (slot-value ($ target) event) lambda) (setf (slot-value target event) lambda))) (defun prepend (to item) (if to.first-child (to.insert-before item to.first-child) (to.append-child item))) (defun append (to item) (if (null to) item (if (null item) to (if (slot-value to 'node-name) (if (typep item 'string) (to.append-child (document.create-text-node item)) (to.append-child item)) (reduce (flip cons) (reduce (flip cons) to) (reverse (reduce (flip cons) item))))))) (defun scroll-to-node (node) (labels ((parent-search (root acc) (cond ((and root (slot-value root 'offset-parent)) (parent-search (slot-value root 'offset-parent) (cons root acc))) (t acc)))) (let* ((parents (parent-search node (list))) (pos-x (reduce (lambda (acc atom) (+ acc (slot-value atom 'offset-left))) parents 0)) (pos-y (reduce (lambda (acc atom) (+ acc (slot-value atom 'offset-top))) parents 0))) (window.scroll-to pos-x (- pos-y 50))))) (defun flip (fun) (return (lambda (a b) (fun b a)))) (defun flip-cc (fun k) (return (lambda (a b k) (fun b a k)))) (defun node-search (goal-p context) (let ((context (or context document))) (filter goal-p (.get-elements-by-tag-name context "*")))) (defun parent-search (goal-p context) (cond ((null context) nil) ((goal-p context) context) (t (parent-search goal-p (slot-value context 'parent-node))))) (defun find (goal-p lst) (reduce (lambda (acc atom) (or acc (and (goal-p atom) atom))) lst nil)) (defun/cc find-cc (goal-p lst) (reduce-cc (lambda (acc atom) (or acc (and (call/cc goal-p atom) atom))) lst nil)) (defun node2str (item) (try (return (.serialize-to-string (new (*x-m-l-serializer)) item)) (:catch (e) (try (return item.xml) (:catch (e) (throw (new (*error (+ "Node " item " cannot be serialized to string."))))))))) (defun serialize (object) (labels ((serialize (object) (cond ((typep object 'undefined) "{}") ((typep object 'boolean) (if object "true" "false")) ((null object) "null") ((typep object 'number) object) ((typep object 'string) (+ "\"" ;; (.replace (.replace (new (*string object)) ;; (regex "/\\\\/g") ;; "\\\\\\\\") ;; (regex "/\"/g") ;; "\\\\\"") (.replace (new (*string object)) (regex "/\"/g") "\\\"") "\"")) ((instanceof object '*array) (if (> (slot-value object 'length) 0) (+ "[" (.join (mapcar (lambda (item) (return (serialize item))) object) ",") "]") "[]")) ((typep (slot-value object 'get-time) 'function) (serialize (.get-time object))) ((and (typep object 'object) (slot-value object '_reference-p)) (serialize (jobject :_reference (slot-value object 'instance-id)))) ((typep object 'object) (let ((result "{") (keys)) (labels ((one (key value) (setf result (+ result (serialize key) ":" (serialize value))))) (doeach (i object) (setf keys (cons i keys))) (when (car keys) (one (car keys) (slot-value object (car keys)))) (mapcar (lambda (key) (setf result (+ result ",")) (one key (slot-value object key))) (cdr keys)) (return (+ result "}"))))) (t (throw (new (*error (+ "Could not serialize " object)))) nil)))) (serialize object))) (defun funcall (action arguments) (if window.*active-x-object (setf xhr (new (*active-x-object "Microsoft.XMLHTTP"))) (setf xhr (new (*x-m-l-http-request)))) (xhr.open "POST" action false) (xhr.set-request-header "Content-Type" "text/json") (xhr.send (serialize arguments)) (if (not (= 200 xhr.status)) (throw (new (*error (+ "Server error occured: " xhr.status))))) (let ((content-type (xhr.get-response-header "Content-Type"))) (if (null content-type) (throw (new (*error "Content-Type of the response is not defined")))) (setf content-type (aref (content-type.split ";") 0)) (cond ((or (eq content-type "text/json") (eq content-type "text/javascript")) (eval (+ "(" xhr.response-text ")"))) ((eq content-type "text/html") (let ((div (document.create-element "div"))) (setf div.inner-h-t-m-l xhr.response-text) (cond ((eq 0 div.child-nodes.length) nil) ((eq 1 div.child-nodes.length) (aref div.child-nodes 0)) (t div))))))) (defun local-url-exists-p (url) (try (progn (funcall url nil) (return t)) (:catch (e) (return nil)))) (defun local-serialize-to-uri (arg) (let ((result "")) (mapobject (lambda (k v) (setf result (+ result k "=" (encode-u-r-i-component v) "&"))) arg) result)) (defun local-funcall (action arguments) (if window.*active-x-object (setf xhr (new (*active-x-object "Microsoft.XMLHTTP"))) (setf xhr (new (*x-m-l-http-request)))) (xhr.open "POST" action false) (xhr.set-request-header "Content-Type" "application/x-www-form-urlencoded") (xhr.send (local-serialize-to-uri arguments)) (if (not (= 200 xhr.status)) (throw (new (*error (+ "Server error occured: " xhr.status))))) (let ((content-type (xhr.get-response-header "Content-Type"))) (if (null content-type) (throw (new (*error "Content-Type of the response is not defined")))) (setf content-type (aref (content-type.split ";") 0)) (cond ((or (eq content-type "text/json") (eq content-type "text/javascript")) (eval (+ "(" xhr.response-text ")"))) ((eq content-type "text/html") (let ((div (document.create-element "div"))) xhr.response-text ;; (setf div.inner-h-t-m-l xhr.response-text) ;; (cond ;; ((eq 0 div.child-nodes.length) ;; nil) ;; ((eq 1 div.child-nodes.length) ;; (aref div.child-nodes 0)) ;; (t ;; div)) ))))) (defun local-funcall-head (action arguments) (if window.*active-x-object (setf xhr (new (*active-x-object "Microsoft.XMLHTTP"))) (setf xhr (new (*x-m-l-http-request)))) (xhr.open "HEAD" action false) (xhr.set-request-header "Content-Type" "application/x-www-form-urlencoded") (xhr.send (local-serialize-to-uri arguments)) (return xhr)) (defun serialize-to-uri (arg) (let ((arg (object-to-list arg))) (reduce (lambda (acc a) (+ acc "&" (car a) "=" (encode-u-r-i-component (serialize (car (cdr a)))))) (cdr arg) (+ (car (car arg)) "=" (encode-u-r-i-component (serialize (car (cdr (car arg))))))))) (defun _debug (what k) (if (and (not (null console)) (not (null console.debug))) (console.debug what)) (if (typep k '*function) (k what) what)) (defun/cc funcall-long-cc (action args) (labels ((do-parts (str acc) (if (and str (> (slot-value str 'length) 0)) (call/cc do-parts (.substr str 1000) (cons (.slice (new (*string str)) 0 1000) acc)) acc)) (get-multipart-url () (let* ((lst (reverse (.split (.substr action 7) "/"))) (name (car lst)) (dirs (reverse (cdr lst))) (session (car (.split (car (reverse (.split name "?"))) "$")))) (+ "http://" (reduce-cc (lambda (a b) (+ a "/" b)) (cdr dirs) (car dirs)) "/multipart.core?" session)))) (let ((url (call/cc get-multipart-url)) (args (serialize-to-uri args))) (funcall-cc (+ url (reduce-cc (lambda (acc atom) (funcall-cc (+ url acc "$") (jobject :data atom))) (reverse-cc (do-parts args nil)) (funcall-cc (+ url "$") (jobject :action action))) "$") (jobject :commit t))))) (defun/cc funcall2-cc (action args callback-name) (_debug (list "funcall/cc" action args)) (let/cc current-continuation (let* ((args (if (null args) (jobject) args)) (hash (if (slot-value args '__hash) (let ((__hash (slot-value args '__hash))) (delete-slot args '__hash) __hash) (+ "__result" (.get-time (new (*date))) (.substr (.concat "" (*math.random 10)) 3 5))))) (let ((img (make-dom-element "IMG" (jobject :class-name "core-loading" :src loading-gif) nil))) (setf (slot-value args (or callback-name "__hash")) hash) (let* ((a (serialize-to-uri args)) (script (make-dom-element "script" (jobject :type "text/javascript") nil)) (head (aref (.get-elements-by-tag-name document "HEAD") 0)) (body (slot-value document 'body))) (cond ((and a (slot-value a 'length) (> (slot-value a 'length) 2000)) (funcall-long-cc action args)) (t (setf (slot-value window hash) (event (val) (when (not (null (slot-value script 'parent-node))) ;; (.remove-child head script) (if (and (slot-value img 'parent-node) body) (.remove-child body img))) (current-continuation val))) (if body (append body img)) (append head script) (setf (slot-value script 'src) (+ "" action a)) (suspend)))))))) (defun/cc funcall-cc (action args) (funcall2-cc action args nil)) (defun make-dom-element (tag properties children) (let ((element (document.create-element tag)) (children (flatten children))) (when (slot-value properties 'type) (setf (slot-value element 'type) (slot-value properties 'type)) (delete-slot properties 'type) (when (or (eq "checkbox" (slot-value element 'type)) (eq "radio" (slot-value element 'type))) (let ((fr (document.create-document-fragment))) (fr.append-child element)))) (mapcar (lambda (i) (cond ((not (null (slot-value i 'tag-name))) (element.append-child i)) (t (element.append-child (document.create-text-node i))))) children) (extend properties element) element)) (defun make-object-to-extend (dom-tag to-extend) (if dom-tag (cond ((null to-extend) (document.create-element dom-tag)) ((null (slot-value to-extend 'node-name)) (extend to-extend (document.create-element dom-tag))) (to-extend to-extend) (t (new (*object)))) (or to-extend (new (*object))))) (defun get-cookie (name) (let* ((cookies (mapcar (lambda (a) (.split a "=")) (.split document.cookie ";"))) (found (find (lambda (a) (eq (trim (car a)) name)) cookies))) (if found (return (car (cdr found))) (return nil)))) (defun set-cookie (name value) (setf document.cookie (+ name "=" value))) (defun get-parameter (name href) ;; (_debug (list "get-parameter" name href)) (let* ((href (or (and href (.substr (.substr href (.search href "#")) 1)) (+ (.substr (.substr window.location.href (.search window.location.href "#")) 1) "$" (.substr window.location.search 1)))) (key-value (reduce (lambda (acc a) (let ((b (.split a "="))) (if (eq (slot-value b 'length) 1) (let ((b (.split a ":"))) (if (eq (slot-value b 'length) 1) acc (cons b acc))) (cons b acc)))) (reduce (lambda (acc a) (let ((b (.split a "&"))) (if (eq (slot-value b 'length) 1) (cons a acc) (.concat acc b)))) (.split href "$") (list)) (list))) (result (find (lambda (item) (if (eq name (car item)) t)) key-value))) (if result (return (decode-u-r-i-component (car (cdr result)))) (return nil)))) (defun set-parameter (name value) ;; (_debug (list "set-parameter" name value)) (if (eq (get-parameter name) value) (return nil)) (let* ((found nil) (result (reduce (lambda (acc atom) (cond ((or (null (car (cdr atom))) (eq (car (cdr atom)) "")) acc) ((and (or (null value) (eq value "")) (eq name (car atom))) (setf found t) acc) ((eq name (car atom)) (setf found t) (+ acc (car atom) ":" (encode-u-r-i-component value) "$")) (t (+ acc (car atom) ":" (car (cdr atom)) "$")))) (mapcar (lambda (a) (.split a ":")) (.split (.substr window.location.hash 1) "$")) (new (*string ""))))) (if (or found (or (null value) (eq "" value))) (setf window.location.hash result) (setf window.location.hash (+ result name ":" value))))) (defun get-style (node) (cond ((and document.default-view document.default-view.get-computed-style) (document.default-view.get-computed-style node null)) ((slot-value node 'current-style) (slot-value node 'current-style)) (t (_debug (list "cant (get-style " node ")"))))) (defun css (node attributes) (flip extend)) (defvar *css-refcount-table* (jobject)) (defun load-css (url) (flet ((_load-css () (let ((link (make-dom-element "LINK" (jobject :href url :rel "stylesheet" :type "text/css")))) (.append-child (aref (document.get-elements-by-tag-name "head") 0) link) (return link)))) (cond ((slot-value *css-refcount-table* url) (setf (slot-value *css-refcount-table* url) (+ 1 (slot-value *css-refcount-table* url)))) (t (setf (slot-value *css-refcount-table* url) 1) (_load-css))) url)) (defun remove-css (url) (flet ((_unload-css () (mapcar (lambda (link) (when (eq link.href url) (link.parent-node.remove-child link))) (document.get-elements-by-tag-name "LINK")))) (cond ((and (slot-value *css-refcount-table* url) (eq (slot-value *css-refcount-table* url) 1)) (setf (slot-value *css-refcount-table* url) 0) (_unload-css)) ((slot-value *css-refcount-table* url) (setf (slot-value *css-refcount-table* url) (- (slot-value *css-refcount-table* url) 1)))) url)) (defvar +theme-root+ theme-root) (defvar +current-theme+ current-theme) (defun load-theme-css (name) (load-css (+ +theme-root+ +current-theme+ "/" name))) (defun remove-theme-css (name) (remove-css (+ +theme-root+ +current-theme+ "/" name))) (defvar *loading-table* (jobject)) (defun/cc load-javascript (url loaded-p) (when (slot-value *loading-table* url) (make-web-thread (lambda () (load-javascript url loaded-p))) (suspend)) (let/cc current-continuation (let* ((img (make-dom-element "IMG" (jobject :class-name "coretal-loading" :src (+ "http://www.coretal.net/" "style/login/loading.gif")) nil)) (script (make-dom-element "SCRIPT" (jobject :type "text/javascript" :src url) nil)) (body (slot-value document 'body)) (head (aref (.get-elements-by-tag-name document "HEAD") 0)) (time (.get-time (new (*date)))) (recurse (lambda (r) (cond ((loaded-p window.k) (when (not (null (slot-value script 'parent-node))) ;; (.remove-child head script) (if body (.remove-child body img))) (delete (slot-value *loading-table* url)) (current-continuation null)) (t (make-web-thread (lambda () (Y r))) (suspend)))))) (cond (loaded-p (unless (call/cc loaded-p) (_debug (list "load-javascript" url loaded-p)) (if body (append body img)) (append head script) (setf (slot-value *loading-table* url) t) (Y recurse))) (t (_debug (list "load-javascript" url loaded-p)) (append head script)))))) ;; +------------------------------------------------------------------------- ;; | Identity Continuation ;; +------------------------------------------------------------------------- (defun k (value) value) (defun extend (source target) (let ((target (or target (new (*object))))) (mapobject (lambda (k v) (try (setf (slot-value target k) v) (:catch (err) (_debug err)))) source) target)) (defun remove-slots (source slots) (mapcar (lambda (slot) (if (and (slot-value source 'has-attribute) (.has-attribute source slot)) (.remove-attribute source slot) (try (delete (slot-value source slot)) (:catch (e) (setf (slot-value source slot) undefined))))) slots)) (defun apply (fun scope args kX) (fun.apply scope (reverse (cons kX (reverse args))))) (defun make-web-thread (fun k) (let ((k (or k (lambda (a) a)))) (k (window.set-timeout (lambda () (fun (lambda (a) a))) 0)))) ;; FIX IE stack overflow bug (defvar *recursion-count* 0) (defun make-method (method) (if (> (.search navigator.user-agent "MSIE") 0) (return (lambda () (let ((args arguments) (self this)) (cond ((> *recursion-count* 11) (setf *recursion-count* 0) (make-web-thread (lambda () (apply method self args)))) (t (setf *recursion-count* (+ *recursion-count* 1)) (apply method self args)))))) method)) (defun compose-prog1 (fun1 fun2) (cond ((not (eq "function" (typeof fun2))) fun1) ((not (eq "function" (typeof fun1))) fun2) (t (return (lambda () (let* ((args (reverse (reverse arguments))) (self this) (result (apply fun1 self args window.k))) (apply fun2 self args window.k) result)))))) (defun compose-prog1-cc (fun1 fun2) (cond ((not (eq "function" (typeof fun2))) fun1) ((not (eq "function" (typeof fun1))) fun2) (t (return (lambda () (let* ((args (reverse (reverse arguments))) (k (car (reverse args))) (args (reverse (cdr (reverse args)))) (self this)) (apply fun1 self args (lambda (val) (apply fun2 self args k))))))))) (defun coretal-on-load (fun) (if (and (not (null (slot-value window 'coretal))) (not (null (slot-value coretal 'loaded-p)))) (make-web-thread fun) (make-web-thread (lambda () (coretal-on-load fun))))) (defun add-on-load (fun) (if (eq "complete" document.ready-state) ;; (or (eq "complete" document.ready-state) ;; (eq "interactive" document.ready-state)) ;; yalan bu ya (fun) (if (typep window.onload 'function) (let ((current window.onload)) (setf window.onload (lambda () (current) (fun)))) (setf window.onload fun)))) (defvar +default-language+ "en-us") (defvar +language-data+ (jobject)) (defun gettext-lang (lang str args) (flet ((combine (str args) (return (.replace str (regex "/%[1-9]/gi") (lambda (a) (return (aref args (- (parse-int (.substr a 1)) 1)))))))) (let ((lang (slot-value +language-data+ lang))) (if lang (combine (or (slot-value lang str) str) args) (combine str args))))) (defun gettext (str args) (gettext-lang +default-language+ str args)) (defun/cc pop-up (url name width height) (let* ((width (if width width (if (> screen.width 0) (*math.floor (/ (- screen.width 10) 2)) 400))) (height (if height height (if (> screen.height 0) (*math.floor (/ (- screen.height 10) 2)) 400))) (left (*math.floor (/ (- screen.width width) 2))) (top (*math.floor (/ (- screen.height height) 2))) (params (+ "left=" left ", top=" top ",width=" width ", height=" height ", screenX=" left ", screenY=" top ", toolbar=no, status=yes, " "location=no, menubar=no, directories=no, " "scrollbars=yes, resizable=yes"))) (describe (list "popUp" url "height" height "width" width "param" params)) (window.open url name params))) (defun random-string (len) (let ((len (or len 8)) (alphabet (+ "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXTZ" "abcdefghiklmnopqrstuvwxyz"))) (flet ((one () (aref alphabet (*math.floor (* (*math.random) (slot-value alphabet 'length)))))) (reduce (lambda (acc atom) (+ acc (one))) (seq (- len 1)) (one))))) (defun lisp-date-to-javascript (universal-time) (let ((b 3155666400) (a 946677600000)) (new (*date (+ a (* 1000 (- universal-time b))))))) (defvar *months* (array "January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December")) (defun date-to-string (date) (flet ((pad-me (foo) (if (< foo 10) (+ "0" foo) foo))) (+ (pad-me (date.get-date)) "/" (pad-me (+ 1 (date.get-month))) "/" (date.get-full-year) " - " (pad-me (date.get-hours)) ":" (pad-me (date.get-minutes)) ":" (pad-me (date.get-seconds))))) (defun date-to-string2 (date) (.join (take 10 (.split (date-to-string date) "")) "")) (defun capitalize (str) (+ (.to-upper-case (.char-at str 0)) (.slice str 1))) (defun/cc Y (f) (f f) (suspend)) (defun/cc Y1 (arg1 f) (f arg1 f) (suspend)) (defvar *gc* (jobject)) (defun/cc gc () (mapobject (lambda (url destroy-list) (funcall-cc (+ url "$") (jobject :objects destroy-list)) (delete (slot-value *gc* url))) *gc*)) (set-interval (lambda () (gc window.k)) 5000) (defun/cc add-to-gc (fun) (destructuring-bind (url id) (call/cc fun) (setf (slot-value *gc* url) (cons id (slot-value *gc* url))))) (setf (slot-value window 'core-server-library-loaded-p) t (slot-value window 'component-cache) (jobject))) (eval-when (:compile-toplevel :execute :load-toplevel) (setf (gethash 'make-component +javascript-cps-functions+) t (gethash 'make-service +javascript-cps-functions+) t (gethash 'apply +javascript-cps-functions+) t (gethash 'funcall-cc +javascript-cps-functions+) t (gethash 'funcall2-cc +javascript-cps-functions+) t (gethash 'make-web-thread +javascript-cps-functions+) t (gethash 'mapcar-cc +javascript-cps-functions+) t (gethash 'reverse-cc +javascript-cps-functions+) t (gethash 'reduce0-cc +javascript-cps-functions+) t (gethash 'reduce-cc +javascript-cps-functions+) t (gethash 'filter-cc +javascript-cps-functions+) t (gethash 'load-javascript +javascript-cps-functions+) t (gethash 'find-cc +javascript-cps-functions+) t (gethash 'flip-cc +javascript-cps-functions+) t (gethash 'mapcar2-cc +javascript-cps-functions+) t)) (defun write-core-library-to-file (pathname &optional (indented t)) (let ((s (make-core-file-output-stream pathname))) (checkpoint-stream s) (core-server::core-library! (if indented (make-indented-stream s) (make-compressed-stream s))) (commit-stream s) (close-stream s))) ;; (defvar *registry* (create)) ;; (defun/cc make-service (name properties) ;; (let ((service (slot-value *registry* name))) ;; (if (not (null service)) ;; service ;; (let ((retval (funcall-cc "service.core?" (create :service name)))) ;; (let ((instance (call/cc retval properties null))) ;; (setf (slot-value *registry* name) instance) ;; instance))))) ;; (defun/cc make-component (name properties to-extend) ;; (let ((retval (slot-value *registry* name))) ;; (if (not (null retval)) ;; (call/cc retval properties to-extend) ;; (progn ;; (setf (slot-value *registry* name) ;; (funcall-cc "component.core?" (create :component name))) ;; (make-component name properties to-extend))))) ;; ;; +------------------------------------------------------------------------- ;; ;; | 'new' Operator replacement for Continuations ;; ;; +------------------------------------------------------------------------- ;; (defun make-instance (k ctor arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8) ;; (if (> arguments.length 9) ;; (throw (new (*error (+ "Cannot makeInstance, too many arguments:" ;; arguments.length ", ctor:" ctor)))) ;; (cond ;; ((not (typep arg8 'undefined)) ;; (k (new (ctor arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8)))) ;; ((not (typep arg7 'undefined)) ;; (k (new (ctor arg1 arg2 arg3 arg4 arg5 arg6 arg7)))) ;; ((not (typep arg6 'undefined)) ;; (k (new (ctor arg1 arg2 arg3 arg4 arg5 arg6)))) ;; ((not (typep arg5 'undefined)) ;; (k (new (ctor arg1 arg2 arg3 arg4 arg5)))) ;; ((not (typep arg4 'undefined)) ;; (k (new (ctor arg1 arg2 arg3 arg4)))) ;; ((not (typep arg3 'undefined)) ;; (k (new (ctor arg1 arg2 arg3)))) ;; ((not (typep arg2 'undefined)) ;; (k (new (ctor arg1 arg2)))) ;; ((not (typep arg1 'undefined)) ;; (k (new (ctor arg1)))) ;; (t ;; (k (new (ctor))))))) ;; (defun get-parameter (name href) ;; (flet ((eval-item (_value) ;; (cond ;; ((or (eq _value "") (eq _value "null")) ;; (return nil)) ;; ((and (eq "string" (typeof _value)) ;; (.match _value (regex "/^\".*\"$/gi"))) ;; (try ;; (let ((val (eval _value))) ;; ;; (_debug (list name val _value)) ;; (cond ;; ((eq val nil) ;; (return nil)) ;; ((or (eq (typeof val) "function") ;; (eq (typeof val) "object") ;; (eq (typeof val) "undefined")) ;; (throw (new (*error)))) ;; (t (return val)))) ;; (:catch (e) ;; (return _value)))) ;; (t ;; (return _value)))) ;; (_get-value (_value) ;; (return ;; (decode-u-r-i-component ;; (reduce (lambda (acc atom) (+ acc ":" atom)) (cdr _value) (car _value)))))) ;; (let ((data nil)) ;; (if (not (null href)) ;; (setf data (.substr (.substr href (.search href "#")) 1)) ;; (setf data (+ (.substr window.location.hash 1) "$" ;; (.substr window.location.search 1)))) ;; (if (null name) ;; (let ((_value (decode-u-r-i-component (car (.split data "$"))))) ;; (return (eval-item _value))) ;; (let ((_value (car ;; (filter (lambda (a) (eq (car a) name)) ;; (mapcar ;; (lambda (a) ;; (flatten (mapcar (lambda (b) (.split b "=")) ;; (.split a ":")))) ;; (.split data "$")))))) ;; (return (eval-item (_get-value (cdr _value))))))))) ;; (defun set-parameter (name new-value) ;; (if (null name) ;; (setf window.location.hash new-value) ;; (let* ((new-value (serialize new-value)) ;; (append2 (lambda (a b) ;; (if (null a) b (if (null b) "" (+ a b))))) ;; (one (lambda (a) (append2 (car a) (append2 ":" (car (cdr a)))))) ;; (found nil) ;; (elements (reverse ;; (reduce ;; (lambda (acc a) ;; (destructuring-bind (key value) a ;; (cond ;; ((eq name key) ;; (setf found t) ;; (if (eq new-value "null") ;; acc ;; (cons (cons name new-value) acc))) ;; (t (cons a acc))))) ;; (mapcar (lambda (a) (.split a ":")) ;; (.split (.substr window.location.hash 1) "$")))))) ;; (if (and (null found) name (not (eq new-value "null"))) ;; (setf elements (cons (cons name new-value) elements))) ;; (let ((value (reduce (lambda (acc a) ;; (append2 acc (append2 "$" (one a)))) ;; (cdr elements) ;; (if (and (null new-value) ;; (null (car (cdr (car elements))))) ;; name ;; (one (car elements)))))) ;; (setf window.location.hash (or value ""))))))
35,120
Common Lisp
.lisp
1,032
28.825581
92
0.572278
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d95453ef4c024454d829149eb8fd324509a0f8a75ec971457aa1367634436c3e
8,262
[ -1 ]
8,263
macro.lisp
evrim_core-server/src/javascript/macro.lisp
(in-package :core-server) ;;+----------------------------------------------------------------------------- ;;| Javascript Macros ;;+----------------------------------------------------------------------------- ;;This file contains javascript macros functions. (defmacro/js list (&rest args) `(new (*array ,@args))) (defmacro/js make-array (&rest args) `(list ,@args)) (defmacro/js create (&rest args) `(jobject ,@args)) (defmacro/js 1+ (arg) `(+ ,arg 1)) (defmacro/js 1- (arg) `(- ,arg 1)) (defmacro/js when (a &body b) `(if ,a (progn ,@b))) (defmacro/js awhen (a &body b) `(let ((it ,a)) (when it ,@b))) (defmacro/js unless (a &body b) `(if (not ,a) (progn ,@b))) (defmacro/js setf (&rest rest) (assert (evenp (length rest))) `(progn ,@(let (state) (nreverse (reduce (lambda (acc atom) (if (null state) (prog1 acc (setf state atom)) (prog1 (cons `(setq ,state ,atom) acc) (setq state nil)))) rest :initial-value nil))))) (defmacro/js case (object &rest cases) (flet ((one (case) (if (eq 't (car case)) `(t ,@(cdr case)) `((eq ,object ,(car case)) ,@(cdr case))))) `(cond ,@(mapcar #'one cases)))) (defmacro/js with-slots (slots object &body body) `(let ,(mapcar (lambda (slot) (list slot `(slot-value ,object ',slot))) slots) ,@body)) (defmacro/js s-v (b) `(slot-value self ,b)) (defmacro/js destructuring-bind (list val &body body) (with-unique-names (g) `(let ((,g ,val)) (let ,(mapcar (lambda (a seq) `(,a (nth ,seq ,g))) list (seq (length list))) ,@body)))) (defmacro/js aif (a b &optional c) `((lambda (it) (if it ,b ,c)) ,a)) (defmacro/js typep (object type) `(= ,(if (eq 'quote (car type)) (symbol-to-js (cadr type)) type) (typeof ,object))) (defmacro/js null (atom) `(or (typep ,atom 'undefined) (eq 'null ,atom))) (defmacro/js defined (atom) `(not (typep ,atom 'undefined))) (defmacro/js by-id (id) `(document.get-element-by-id ,id)) (defmacro/js make-component (ctor &rest args) `(call/cc ,ctor (jobject ,@args))) (defmacro/js delete-slots (self &rest slots) `(remove-slots ,self (array ,@(mapcar (lambda (a) (symbol-to-js (cadr a))) ;; cadr is for (quote somesymbol) ;; -evrim. slots)))) (defmacro/js delete-slot (self slot) `(delete-slots ,self ,slot)) ;; ------------------------------------------------------------------------- ;; Lift Macros for 0 arg & 1 arg functions ;; ------------------------------------------------------------------------- (defmacro/js lift1 (fun) `(lambda (arg) (call/cc ,fun arg))) (defmacro/js lift0 (fun) `(lambda () (call/cc ,fun))) ;; ------------------------------------------------------------------------- ;; Lift Javascript Event Handler with a call/cc function. ;; ------------------------------------------------------------------------- (defmacro/js lifte (fun &rest args) (if (atom fun) `(event (e) (try (with-call/cc (call/cc ,fun ,@args)) (:catch (e) (_debug e))) false) `(event (e) (try (with-call/cc ,fun) (:catch (e) (_debug e))) false))) (defmacro/js lifte2 (fun &rest args) (if (atom fun) `(event (e) (try (with-call/cc (call/cc ,fun ,@args)) (:catch (e) (_debug e))) true) `(event (e) (try (with-call/cc ,fun) (:catch (e) (_debug e))) true))) ;; ------------------------------------------------------------------------- ;; Method Macro ;; ------------------------------------------------------------------------- (defmacro/js method (lambda-list &rest body) `(lambda ,lambda-list (javascript-cps-method-body ,@body))) ;; ------------------------------------------------------------------------- ;; Localization Macro ;; ------------------------------------------------------------------------- (defmacro/js _ (str &rest args) `(gettext ,str (array ,@args))) ;; ------------------------------------------------------------------------- ;; Cosmetix Macro: With-field ;; ------------------------------------------------------------------------- (defmacro with-field (label input &optional (validation nil)) "Syntactic sugar to handle form label and values" `(<:div :class "field" (<:div :class "label" ,label) (<:div :class "value" ,input) ,(if validation validation))) (defjsmacro with-field (label input &optional validation) (macroexpand-1 `(with-field ,label ,input ,validation))) ;; ------------------------------------------------------------------------- ;; Rebinding-js ;; ------------------------------------------------------------------------- (defmacro rebinding-js (vars stream &body body) (let ((vars (mapcar #'ensure-list vars))) `(let (,@(reduce0 (lambda (acc a) (if (null (cdr a)) acc (cons a acc))) (reverse vars))) (with-js ,(mapcar #'car vars) ,stream (let ,(mapcar (lambda (a) (list (car a) (car a))) vars) (add-on-load (lambda () ,@body))))))) ;; ------------------------------------------------------------------------- ;; Rebinding-js/cc ;; ------------------------------------------------------------------------- (defmacro rebinding-js/cc (vars stream &body body) `(rebinding-js ,vars ,stream (with-call/cc ,@body))) ;; ------------------------------------------------------------------------- ;; Bookmarklet Macro ;; ------------------------------------------------------------------------- (defmacro/js bookmarklet-script (url) `(+ "javascript:void((function(){" (decode-u-r-i-component "var%20a=document.createElement(\"SCRIPT\");") "a.type=\"text/javascript\";" "a.src=\"" ,url "\";" "document.getElementsByTagName(\"HEAD\")[0].appendChild(a);" "})())")) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2012 Metin Evrim Ulu ;; 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/>. ;; (defmacro/js $ (id) ;; `(document.get-element-by-id ,id)) ;; (defmacro/js $idoc (iframe-id) ;; `(slot-value ($ ,iframe-id) 'content-document)) ;; (defmacro/js doc-body () ;; `(aref (document.get-elements-by-tag-name "body") 0)) ;; (defmacro/js input-value (id) ;; `(slot-value ($ ,id) 'value)) ;; (defmacro/js $fck (id) ;; `(*f-c-keditor-a-p-i.*get-instance ,id))
6,892
Common Lisp
.lisp
181
34.60221
80
0.500375
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
63798ea723b6f10156d29b083290acaee613d85ce673b09f263bc645a3a78721
8,263
[ -1 ]
8,264
interface.lisp
evrim_core-server/src/javascript/interface.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+----------------------------------------------------------------------------- ;;| Javascript Interface ;;+----------------------------------------------------------------------------- ;; ;; This file contains interface function to use Javascript library. ;; (eval-when (:compile-toplevel :load-toplevel :execute) (defvar +indent-javascript+ t)) (defmacro js (&body body) "Converts unevaluated body to javascript and returns it as a string" (let ((render (expand-render (optimize-render-1 (walk-grammar `(:and ,@(mapcar (compose (rcurry #'expand-javascript #'expand-javascript) #'fix-javascript-returns #'walk-js-form) body)))) #'expand-render 's))) `(let ((s ,(if +indent-javascript+ `(make-indented-stream (make-core-stream "")) `(make-compressed-stream (make-core-stream ""))))) (funcall (lambda () (block rule-block ,render))) (return-stream s)))) (defmacro js* (&body body) `(eval `(js ,,@body))) (defmacro with-js (vars stream &body body) (with-unique-names (s) (let ((+js-free-variables+ vars)) (labels ((expander (form expander) (expand-render (optimize-render-1 (expand-javascript form expander)) #'expand-render s))) `(block rule-block (let ((,s ,stream)) ,(expand-render (optimize-render-1 (walk-grammar (expand-javascript (fix-javascript-returns (walk-js-form (if (= 1 (length body)) (car body) `(progn ,@body)))) #'expand-javascript))) #'expander s)) ;; (char! ,stream #\Newline) ,stream))))) (defmacro defrender/js (name args &body body) (with-unique-names (stream) `(eval-when (:load-toplevel :compile-toplevel :execute) (defmethod ,name ((,stream core-stream) ,@args) (with-js ,(extract-argument-names args) ,stream ,@body) (char! ,stream #\Newline) ,stream)))) (defmacro defun/javascript (name params &body body) "Defun a function in both worlds (lisp/javascript)" `(prog1 (defun ,name ,params ,@body) (defrender/js ,(intern (string-upcase (format nil "~A/JS" name))) () (setq ,name (lambda ,params ,@body))))) (defparameter +js-no-capture+ '(document window)) (defmacro jambda (arguments &body body) (let* ((form (walk-js-form `(lambda ,arguments ,@body))) (env (mapcar (lambda (ref) (with-slots (name) ref `(list* :let ',name ,name))) (filter (lambda (a) (not (member (slot-value a 'name) +js-no-capture+ :test #'string=))) (ast-search-type form 'free-variable-reference))))) `(make-instance 'arnesi::closure/cc :code ,(fix-lambda-k (fix-progn (fix-excessive-recursion (walk-js-form (javascript->cps form #'javascript->cps `(lambda (a) a) nil))))) :env (list ,@env))))
3,600
Common Lisp
.lisp
96
32.885417
80
0.628866
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b12c864bdf731c74f8e07b9c2366d85c0a11425194d4c39edf4c8920b6f2fbdf
8,264
[ -1 ]
8,265
render.lisp
evrim_core-server/src/javascript/render.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+-------------------------------------------------------------------------- ;;| [Core-serveR] Javascript Renderer ;;+-------------------------------------------------------------------------- ;; Hash tables that hold macros, infix and syntax operators (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *javascript-macros* (make-hash-table)) (defvar *javascript-setf-macros* (make-hash-table)) (defvar *javascript-infix* (make-hash-table)) (defvar *javascript-syntax* (make-hash-table))) ;;----------------------------------------------------------------------------- ;; Javascript Infix Operators ;;----------------------------------------------------------------------------- (defmacro defjsinfix (name &optional (js-operator nil)) "Define a 'Javascript Infix' operator" `(setf (gethash ',name *javascript-infix*) ',(or js-operator name))) (defjsinfix +) (defjsinfix -) (defjsinfix *) (defjsinfix /) (defjsinfix >) (defjsinfix >=) (defjsinfix <) (defjsinfix <=) (defjsinfix = "==") (defjsinfix eq "===") (defjsinfix eql "===") (defjsinfix equal "===") (defjsinfix or "||") (defjsinfix and "&&") (defjsinfix instanceof "instanceof") (defjsinfix mod "%") (defun seperated-by (seperator args) `(:and ,@(nreverse (reduce (lambda (acc arg) (cons arg (cons seperator acc))) (cdr args) :initial-value (list (car args)))))) (defun s-b (seperator args) (seperated-by seperator args)) ;;----------------------------------------------------------------------------- ;; Javascript Syntax operators ;; These are used to make the library more parenscript friendly ;; and to cover javascript hacks. ;;----------------------------------------------------------------------------- (defmacro defjssyntax (name args &body body) "Define a 'Javascript Syntax' operator" `(setf (gethash ',name *javascript-syntax*) #'(lambda (arguments expander) (declare (ignorable expander)) (destructuring-bind ,args arguments ,@body)))) (defjssyntax stream-escape (&rest args) `(:and ,@(unwalk-forms args))) (defjssyntax array (&rest a) `(:and "[ " ,(s-b ", " (mapcar (rcurry expander expander) a)) " ]")) (defjssyntax aref (target slot) `(:and ,(funcall expander target expander) "[" ,(funcall expander slot expander) "]")) (defjssyntax incf (arg) `(:and "++" ,(funcall expander arg expander))) (defjssyntax decf (arg) `(:and "--" ,(funcall expander arg expander))) (defjssyntax ++ (arg) `(:and ,(funcall expander arg expander) "++")) (defjssyntax -- (arg) `(:and ,(funcall expander arg expander) "--")) (defjssyntax not (arg) (if (and (typep arg 'application-form) (js-infix-op-p (operator arg))) `(:and "!(" ,(funcall expander arg expander) ")") `(:and "!" ,(funcall expander arg expander)))) (defjssyntax typeof (arg) `(:and "(typeof " ,(funcall expander arg expander) ")")) (defjssyntax instanceof (arg1 arg2) `(:and ,(funcall expander arg1 expander) " instanceof " ,(funcall expander arg2 expander))) (defjssyntax return (arg) `(:and "return " ,(funcall expander arg expander))) (defjssyntax delete (arg) `(:and "delete " ,(funcall expander arg expander))) (defjssyntax break () "break") (defjssyntax defvar (var value &optional doc) (declare (ignore doc)) `(:and "var " ,(funcall expander var expander) " = " ,(funcall expander value expander))) (defjssyntax while (consequent &rest body) `(:and "while (" ,(funcall expander consequent expander) ") {" (:indent) #\Newline ,(s-b (format nil ";~%") (mapcar (rcurry expander expander) body)) ";" (:deindent) #\Newline "}")) (defjssyntax regex (expression) (unwalk-form expression)) (defjssyntax new (expression) `(:and "new " ,(funcall expander expression expander))) (defjssyntax jobject (&rest arguments) (if arguments `(:and "{" (:indent) #\Newline ,(seperated-by (format nil ",~%") (reverse (mapcar (lambda (b a) `(:and ,(funcall expander a expander) ": " ,(funcall expander b expander))) (reduce (lambda (acc atom) (if (oddp (position atom arguments)) (cons atom acc) acc)) arguments :initial-value nil) (reduce (lambda (acc atom) (if (evenp (position atom arguments)) (cons atom acc) acc)) arguments :initial-value nil)))) (:deindent) #\Newline "}") `(:and "{}"))) (defjssyntax with (object &rest body) `(:and "with (" ,(funcall expander object expander) ") {" (:indent) #\Newline ,(funcall expander (let ((progn (make-instance 'progn-form :body body))) (mapc (lambda (b) (setf (parent b) progn)) body) progn) expander) (:deindent) #\Newline "}")) (defjssyntax doeach (iterator &rest body) `(:and "for (var " ,(symbol-to-js (operator iterator)) " in " ,(funcall expander (car (arguments iterator)) expander) ") {" (:indent) #\Newline ,(funcall expander (make-instance 'progn-form :body body) expander) (:deindent) #\Newline "}")) (defjssyntax slot-value (object slot) (if (and (typep slot 'constant-form) (typep (value slot) 'symbol)) `(:and ,(funcall expander object expander) "." ,(funcall expander slot expander)) `(:and ,(funcall expander object expander) "[" ,(funcall expander slot expander) "]"))) (defjssyntax switch (object &rest cases) `(:and "switch (" ,(funcall expander object expander) ") {" (:indent) #\Newline ,(seperated-by #\Newline (mapcar (lambda (case) (cond ((or (eq 'default (operator case)) (eq 't (operator case))) `(:and "default:" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expander expander) (arguments case))) ";" (:deindent))) ((atom (operator case)) `(:and "case " ,(funcall expander (walk-js-form (operator case)) expander) ":" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expander expander) (arguments case))) ";" (:deindent))) (t `(:and ,(seperated-by #\Newline (mapcar (lambda (case) (if (or (eq 'default case) (eq 't case)) "default" `(:and "case " ,(funcall expander (walk-js-form case) expander) ":"))) (operator case))) (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expander expander) (arguments case))) ";" (:deindent))))) cases)) (:deindent) #\Newline "}")) ;; NOTE: This is very ugly but needed only for backward compat with parenscript ;; I'll try to implement handler-bind, catch for the use of the newer compiler. ;; -evrim. (defjssyntax try (body &optional catch finally) (let ((body (walk-js-form (unwalk-form body)))) ;; Hack to make progn work. `(:and "try {" (:indent) #\Newline ,(funcall expander body expander) (:deindent) #\Newline "}" ,(when catch (assert (eq :catch (operator catch))) (let* ((op (operator (car (arguments catch)))) (catch (walk-js-form `(progn ,@(unwalk-forms (cdr (arguments catch))))))) `(:and " catch (" ,(symbol-to-js op) ") {" (:indent) #\Newline ,(funcall expander catch expander) (:deindent) #\Newline "}"))) ,(when finally (assert (eq :finally (operator finally))) (let ((finally (walk-js-form `(progn ,@(unwalk-forms (arguments finally)))))) `(:and " finally {" (:indent) #\Newline ,(funcall expander finally expander) (:deindent) #\Newline "}")))))) ;;--------------------------------------------------------------------------- ;; Javascript macros ;;--------------------------------------------------------------------------- (defmacro defmacro/js (name args &body body) "Define a 'Javascript macro' operator" (with-unique-names (rest) `(eval-when (:compile-toplevel :execute :load-toplevel) (setf (gethash ',name *javascript-macros*) #'(lambda (&rest ,rest) (destructuring-bind ,args ,rest ,@body)))))) (defmacalias defmacro/js defjsmacro) (defmacro defmacro-import/js (name) `(defmacro/js ,name (&rest args) (macroexpand-1 `(,',name ,@args)))) (defmacro-import/js acond) (defmacro-import/js cond-bind) (defmacro-import/js if-bind) (defmacro-import/js prog1) ;; -------------------------------------------------------------------------- ;; Javascript Setf Macros ;; -------------------------------------------------------------------------- (defmacro defsetf/js (name args &body body) (with-unique-names (rest) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (gethash ',name *javascript-setf-macros*) #'(lambda (&rest ,rest) (destructuring-bind ,args ,rest ,@body)))))) ;;----------------------------------------------------------------------------- ;; Javascript Macro Expander ;;----------------------------------------------------------------------------- (defun macroexpand-js-1 (form &optional env) (declare (ignore env)) (acond ((and (listp form) (gethash (car form) *javascript-macros*)) (values (apply it (cdr form)) t)) ((and (listp form) (or (eq (car form) 'setf) (eq (car form) 'setq)) (listp (cadr form)) (gethash (caadr form) *javascript-setf-macros*)) (values (apply it (cons (last1 form) (cdadr form))) t)) (t (values form nil)))) ;;----------------------------------------------------------------------------- ;; Javascript Form Walker ;;----------------------------------------------------------------------------- (defun walk-js-form (form &optional (parent nil) (env (make-walk-env))) (let ((arnesi::*walker-expander* #'macroexpand-js-1)) (walk-form form parent env))) ;;----------------------------------------------------------------------------- ;; Javascript expanders for Lisp2 Forms ;;----------------------------------------------------------------------------- ;; ;; Note: These are used along with walk-js-form ;; (defmacro defjavascript-expander (class (&rest slots) &body body) "Define a javascript expander (ie. unwalker) which is fed to renderer" `(defmethod expand-javascript ((form ,class) (expand function)) (declare (ignorable expand)) (with-slots ,slots form ,@body))) (defjavascript-expander form () (call-next-method)) (defjavascript-expander constant-form (value) (if (eq value t) "true" (typecase value (string (with-core-stream (s "") (quoted! s value #\') (return-stream s)) ;; (format nil "'~A'" value) ) (null "null") (symbol (symbol-to-js value)) (list `(:and "[ " ,(seperated-by ", " (mapcar (lambda (v) (symbol-to-js (format nil "~S" v))) value)) " ]")) (t (format nil "~A" value))))) (defjavascript-expander variable-reference (name) (cond ((eq 't name) "true") ((eq 'nil name) "null") (t (symbol-to-js name)))) (defvar +js-free-variables+ nil) (defjavascript-expander free-variable-reference (name) (cond ((member name +js-free-variables+) `(:json! ,name)) (t (call-next-method)))) (defjavascript-expander implicit-progn-mixin (body) `(:and "{" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)) ";" (:deindent) #\Newline "}")) (defun js-infix-op-p (operator) (if (gethash operator *javascript-infix*) t)) (defjavascript-expander application-form (operator arguments) (acond ((gethash operator *javascript-infix*) (if (and (typep (parent form) 'application-form) (gethash (operator (parent form)) *javascript-infix*)) `(:and "(" ,(seperated-by (format nil " ~A " (if (symbolp it) (format nil "~A" it) it)) (mapcar (rcurry expand expand) arguments)) ")") (seperated-by (format nil " ~A " (if (symbolp it) (format nil "~S" it) it)) (mapcar (rcurry expand expand) arguments)))) ((char= #\. (aref (symbol-to-js operator) 0)) `(:and ,(funcall expand (car arguments) expand) ,(symbol-to-js operator) "(" ,(seperated-by ", " (mapcar (rcurry expand expand) (cdr arguments))) ")")) ((gethash operator *javascript-syntax*) (funcall it arguments expand)) ((gethash operator *javascript-macros*) (error "Error while rendering javascript, js macros should be expanded in walker") ;; (funcall expand (walk-js-form ;; (apply it (mapcar #'unwalk-form arguments)) ;; (parent form)) ;; expand) ) (t `(:and ,(symbol-to-js operator) "(" ,(seperated-by ", " (mapcar (rcurry expand expand) arguments)) ")")))) (defjavascript-expander lambda-application-form (operator arguments) `(:and "(" ,(funcall expand operator expand) ")" "(" ,(seperated-by ", " (mapcar (rcurry expand expand) arguments)) ,(if (or (typep (parent form) 'progn-form) (typep (parent form) 'application-form)) ")" ")"))) ;; sonda ";" vardi kaldirdim dom2js yuzunden (defjavascript-expander lambda-function-form (arguments body declares) `(:and "function (" ,(seperated-by ", " (mapcar (rcurry expand expand) arguments)) ") " ,(call-next-method))) (defjavascript-expander function-argument-form (name) (symbol-to-js name)) (defjavascript-expander specialized-function-argument-form (name specializer) (call-next-method)) (defjavascript-expander optional-function-argument-form (name default-value supplied-p-parameter) (call-next-method)) (defjavascript-expander keyword-function-argument-form (keyword-name name default-value supplied-p-parameter) (call-next-method)) (defjavascript-expander allow-other-keys-function-argument-form () (error "bune-olm-allow-other-keys-falan")) (defjavascript-expander rest-function-argument-form (name) (call-next-method)) (defjavascript-expander declaration-form () nil) ;;;; BLOCK/RETURN-FROM ;; `(block ,name ,@(unwalk-forms body)) (defjavascript-expander block-form (name body) (warn "Blocks support only scope, not return") (call-next-method)) (defjavascript-expander return-from-form (target-block result) ;; `(return-from ,(name target-block) ,(unwalk-form result)) (error "cant do return-from")) ;;;; CATCH/THROW ;; `(catch ,(unwalk-form tag) ,@(unwalk-forms body)) ;; This is implicit-progn-mixin (defjavascript-expander catch-form (tag body) (error "Implement catch-form") `(:and "try {" ,@(mapcar (rcurry expand expand) body) "}")) ;; `(throw ,(unwalk-form tag) ,(unwalk-form value)) (defjavascript-expander throw-form (tag value) `(:and "throw " ,value)) ;;;; EVAL-WHEN (defjavascript-expander eval-when-form (body eval-when-times) (call-next-method)) ;;;; IF (defjavascript-expander if-form (consequent then else) (if (and (not (typep (parent form) 'implicit-progn-mixin)) (not (typep (parent form) 'if-form))) `(:and "(" ,(funcall expand consequent expand) " ? " ,(funcall expand then expand) " : " ,(if else (funcall expand else expand) "null") ")") `(:and "if " "(" ,(funcall expand consequent expand) ") {" (:indent) #\Newline ,(funcall expand then expand) ,(if (not (typep then 'progn-form)) ";") (:deindent) #\Newline "}" ,@(if else `(" else {" (:indent) #\Newline ,(funcall expand else expand) ,(if (not (typep else 'progn-form)) ";") (:deindent) #\Newline "}"))))) ;;;; COND (defjavascript-expander cond-form (conditions) (if (typep (parent form) 'application-form) `(:and ,@(nreverse (reduce (lambda (acc atom) (cons `(:and ,(funcall expand (car atom) expand) " ? (" ,(seperated-by ", " (mapcar (rcurry expand expand) (cdr atom))) ") : ") acc)) (cdr conditions) :initial-value (list `(:and ,(funcall expand (caar conditions) expand) " ? (" ,(seperated-by ", " (mapcar (rcurry expand expand) (cdar conditions))) ") : ")))) "null") `(:and ,@(nreverse (reduce (lambda (acc atom) (cons (if (and (typep (car atom) 'constant-form) (eq 't (value (car atom)))) `(:and " else {" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) (cdr atom))) ";" (:deindent) #\Newline "}") `(:and " else if(" ,(funcall expand (car atom) expand) ") {" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) (cdr atom))) ";" (:deindent) #\Newline "}")) acc)) (cdr conditions) :initial-value (list `(:and "if(" ,(funcall expand (caar conditions) expand) ") {" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) (cdar conditions))) ";" (:deindent) #\Newline "}"))))))) ;;;; FLET/LABELS ;; The cdadr is here to remove (function (lambda ...)) of the function ;; bindings. ;; (flet ((unwalk-flet (binds) ;; (mapcar #'(lambda (bind) ;; (cons (car bind) ;; (cdadr (unwalk-form (cdr bind))))) ;; binds))) ;; `(flet ,(unwalk-flet binds) ;; ,@(unwalk-declarations declares) ;; ,@(unwalk-forms body))) (defjavascript-expander flet-form (binds body declares) `(:and ,@(mapcar (lambda (bind) `(:and "var " ,(symbol-to-js (car bind)) "=" ,(funcall expand (cdr bind) expand) ";" #\Newline)) binds) ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)))) (defjavascript-expander labels-form (binds body declares) `(:and ,@(mapcar (lambda (bind) `(:and "var " ,(symbol-to-js (car bind)) "=" ,(funcall expand (cdr bind) expand) ";" #\Newline)) binds) ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)))) ;;;; LET/LET* (defjavascript-expander let-form (binds body declares) `(:and ,@(mapcar (lambda (bind) `(:and "var " ,(symbol-to-js (car bind)) " = " ,(funcall expand (cdr bind) expand) ";" #\Newline)) binds) ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)))) (defjavascript-expander let*-form (binds body declares) `(:and ,@(mapcar (lambda (bind) `(:and "var " ,(symbol-to-js (car bind)) " = " ,(funcall expand (cdr bind) expand) ";" #\Newline)) binds) ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)))) ;;;; LOAD-TIME-VALUE (defjavascript-expander arnesi::load-time-value-form (value read-only-p) value) ;;;; LOCALLY (defjavascript-expander locally-form (body declares) (call-next-method)) ;;;; MACROLET ;; FIXmE: Implement macro expansion (defjavascript-expander macrolet-form (body binds declares) ;; We ignore the binds, because the expansion has already taken ;; place at walk-time. (error "Fix macrolet-form") (call-next-method)) ;;;; MULTIPLE-VALUE-CALL (defjavascript-expander multiple-value-call-form (func arguments) (error "unimplemented:multiplave-value-call-form")) ;;;; MULTIPLE-VALUE-PROG1 (defjavascript-expander multiple-value-prog1-form (first-form other-forms) (error "unimplemented:multiple-value-prog1-form")) ;;;; PROGV ;; (defunwalker-handler progv-form (body vars-form values-form) ;; `(progv ,(unwalk-form vars-form) ,(unwalk-form values-form) ,@(unwalk-forms body))) ;;;; SETQ ;;;; TODO: FIX setq walker to walk var (easy) ;;;; TODO: FIX call/cc to unwalk var before going in. -evrim. (defjavascript-expander setq-form (var value) `(:and ;; ,(let ((+js-free-variables+ nil)) ;; (funcall expand var expand)) ,(funcall expand var expand) " = " ,(funcall expand value expand))) ;;;; SYMBOL-MACROLET ;; We ignore the binds, because the expansion has already taken ;; place at walk-time. ;;; (declare (ignore binds)) ;;; `(locally ,@(unwalk-declarations declares) ,@(unwalk-forms body)) (defjavascript-expander symbol-macrolet-form (body binds declares) (error "unimplemented: symbol-macrolet-form")) ;;;; TAGBODY/GO ;; `(tagbody ,@(unwalk-forms body)) (defjavascript-expander tagbody-form (body) (error "unimplemented: tagbody")) (defjavascript-expander go-tag-form (name) (error "unimplemented: go-tag-form")) ;;`(go ,name) (defjavascript-expander go-form (name) (error "unimplemented: go-form")) ;;;; THE ;; TODO: Value is evaluated twice. ;; No problem if value is a reference or a constant. ;; Aslinda buraya birsey uydur durumu var sanirim biraz ;; -evrim (defjavascript-expander the-form (type-form value) `(:and "(typeof " ,(funcall expand value expand) " == " ,(format nil "~A" type-form) ")" " ? " ,(funcall expand value expand) " : " ,(format nil "throw new Error('~A is not typeof ~A')" (unwalk-form value) type-form))) ;;;; UNWIND-PROTECT (defjavascript-expander unwind-protect-form (protected-form cleanup-form) (error "unimplemented: unwind-protect-form")) ;;;; PROGN (defjavascript-expander progn-form (body) (if (typep (parent form) 'application-form) `(:and "(" ,(seperated-by ", " (mapcar (rcurry expand expand) body)) ")") `(:and ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)) ,(if (not (typep (parent form) 'implicit-progn-mixin)) ";")))) (defjavascript-expander throw-form (tag value) `(:and "throw " ,(funcall expand tag expand))) (defjavascript-expander dotimes-form (var how-many body) `(:and "for (var " ,(symbol-to-js var) " = 0; " ,(symbol-to-js var) " < " ,(funcall expand how-many expand) "; " ,(symbol-to-js var) " = " ,(symbol-to-js var) " + 1) " ,(call-next-method))) (defjavascript-expander dolist-form (var lst body) (let ((i (symbol-to-js (gensym "tmp"))) (j (symbol-to-js (gensym "tmp")))) `(:and "for (var " ,i "=0," ,j "=" ,(funcall expand lst expand) "; " ,i " < " ,j ".length; " ,i "++) {" (:indent) #\Newline "var " ,(symbol-to-js var) " = " ,j "[" ,i "];" #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)) ";" (:deindent) #\Newline "}"))) (defjavascript-expander do-form (varlist endlist declares body) `(:and "for (var " ,(seperated-by ", " (mapcar (lambda (var) `(:and ,(symbol-to-js (car var)) "=" ,(funcall expand (cadr var) expand))) varlist)) "; " "!(" ,(funcall expand (car endlist) expand) "); " ,(seperated-by ", " (mapcar (lambda (var) `(:and ,(symbol-to-js (car var)) "=" ,(funcall expand (caddr var) expand))) varlist)) ") " ,(call-next-method))) (defjavascript-expander defun-form (name arguments declares body) `(:and "function " ,(symbol-to-js name) "(" ,(seperated-by ", " (mapcar (rcurry expand expand) arguments)) ") {" (:indent) #\Newline ,(seperated-by (format nil ";~%") (mapcar (rcurry expand expand) body)) ";" (:deindent) #\Newline "}")) ;;----------------------------------------------------------------------------- ;; Javascript Functionalization ;;----------------------------------------------------------------------------- ;; This is a preprocessor to solve the return problem of javascript ie: ;; ;; (print ((lambda (a) a) 1)) ;; ;; should print 1, but javascript is broken, so we add returns implicitly. ;; (eval-when (:load-toplevel :compile-toplevel :execute) (defgeneric find-form-leaf (form) (:documentation "Returns list of termination subforms the 'form'")) (defmethod find-form-leaf ((form t)) form) (defmethod find-form-leaf ((form implicit-progn-mixin)) (find-form-leaf (last1 (body form)))) (defmethod find-form-leaf ((form if-form)) (append (ensure-list (find-form-leaf (then form))) (ensure-list (find-form-leaf (else form))))) (defun fix-javascript-returns (form) "Alters form destructive and adds implicit return statements to 'form'" (flet ((transform-to-implicit-return (form) (let ((new-form (walk-form-no-expand (unwalk-form form)))) (unless (and (typep form 'application-form) (eq 'return (operator form))) (change-class form 'application-form) (setf (operator form) 'return) (setf (arguments form) (list new-form))) new-form))) (let ((funs (ast-search-type form 'lambda-function-form))) (mapcar #'transform-to-implicit-return (flatten (mapcar #'find-form-leaf funs))) form))) (defun fix-javascript-methods (form self) (let ((applications (ast-search-type form 'application-form))) (mapcar (lambda (app) (when (and (typep (car (arguments app)) 'variable-reference) (eq (name (car (arguments app))) self)) (setf (operator app) (intern (format nil "THIS.~A" (operator app))) (arguments app) (cdr (arguments app))))) applications) form)) ;; TODO: Handle (setf a b c d) (defun fix-javascript-accessors (form accessors &optional (get-prefix "GET-") (set-prefix "SET-")) (let ((applications (ast-search-type form 'application-form))) (mapcar (lambda (app) (cond ((and (eq 'setf (operator app)) (typep (car (arguments app)) 'application-form) (member (operator (car (arguments app))) accessors)) ;; (describe app) (setf (operator app) (intern (format nil "~A~A" set-prefix (operator (car (arguments app))))) (arguments app) (cons (car (arguments (car (arguments app)))) (cdr (arguments app))))) ((and (member (operator app) accessors) (not (and (typep (parent app) 'application-form) (eq 'setf (operator (parent app)))))) (setf (operator app) (intern (format nil "~A~A" get-prefix (operator app))))))) applications) form)))
26,364
Common Lisp
.lisp
679
34.630339
109
0.607863
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c27c6438c766855ad64064d2e5f4629855870ee13cabc47d935e6b12abcd2a81
8,265
[ -1 ]
8,266
http.lisp
evrim_core-server/src/peers/http.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| HTTP Peer ;;+---------------------------------------------------------------------------- ;; ;; This file contains implementation of HTTP Handling peer. Its server is ;; an instance of http-server. ;; (defclass http-peer (stream-peer) ((peer-type :accessor http-peer.peer-type :initform 'http :documentation "Current peer type, it can be 'http' or 'mod-lisp'")) (:default-initargs :name "Http Peer Handling Unit") (:documentation "HTTP Peer - This peer handles HTTP requests and evaulates to a HTTP response. Its' server is an instance of http-server")) (defvar +default-encoding-for-remote-mimes+ :utf-8 "FIXME: Browser shoudl supply in which encoding did it encode data.") (defmethod parse-request ((self http-peer) stream) "Returns a fresh RFC 2616 HTTP Request object parsing from 'stream', nil if stream data is invalid" (multiple-value-bind (peer-type method uri version general-headers request-headers entity-headers unknown-headers) (http-request-headers? stream) (setf (http-peer.peer-type self) peer-type) (if method (let* ((request (make-instance 'http-request :stream stream)) (content-type (cadr (assoc 'content-type entity-headers))) (content-length (cadr (assoc 'content-length entity-headers))) (stream (if (and content-length (> content-length 0)) (make-bounded-stream stream content-length)))) (cond ;; content-type = '("multipart" "form-data") ((and (string-equal "multipart" (car content-type)) (string-equal "form-data" (cadr content-type))) ;; eat lineer whayt spaces. (lwsp? stream) (setf (http-message.entities request) (rfc2388-mimes? stream (cdr (assoc "boundary" (caddr content-type) :test #'string=)))) (setf (uri.queries uri) (append (uri.queries uri) (reduce0 (lambda (acc media) (cond ((mime.filename media) (cons (cons (mime.name media) media) acc)) ((mime.name media) (cons (cons (mime.name media) (octets-to-string (mime.data media) +default-encoding-for-remote-mimes+)) acc)) (t (warn "Unkown media received:~A" media) acc))) (filter (lambda (a) (typep a 'top-level-media)) (http-message.entities request)))))) ;; content-type = '("application" "x-www-form-urlencoded") ((and (string-equal "application" (car content-type)) (string-equal "x-www-form-urlencoded" (string-upcase (cadr content-type)))) ;; eat lineer whayt spaces. (lwsp? stream) (setf (uri.queries uri) (append (uri.queries uri) (aif (json? stream) (hash-to-alist it) (x-www-form-urlencoded? stream)))))) (setf (http-message.general-headers request) general-headers (http-message.unknown-headers request) unknown-headers (http-request.headers request) request-headers (http-request.entity-headers request) entity-headers (http-request.uri request) uri (http-request.method request) method (http-message.version request) version) request)))) ;;; (mapcar #'(lambda (mime) ;;; (describe mime) ;;; (when (and (mime.filename mime) (mime.data mime)) ;;; (with-core-stream (stream (pathname (concatenate 'string "/tmp/" (mime.filename mime)))) ;;; (describe (length (mime.data mime))) ;;; (reduce #'(lambda (s a) ;;; (prog1 s (write-stream s a))) ;;; (mime.data mime) :initial-value stream)))) ;;; (http-message.entities request)) ;; (describe (mime-part.data (nth 3 (http-message.entities request)))) (defmethod render-http-headers ((self http-peer) stream response) "Renders RFC 2616 HTTP 'response' to 'stream'" (http-response-headers! stream response) (char! stream #\Newline)) (defmethod render-mod-lisp-headers ((self http-peer) stream response) "Renders Mod-Lisp HTTP 'response' to 'stream'" (mod-lisp-response-headers! stream response) (string! stream "end") (char! stream #\Newline)) (defmethod render-headers ((self http-peer) stream response) "Renders HTTP headers from 'response' to 'stream'" (if (eq 'mod-lisp (s-v 'peer-type)) (render-mod-lisp-headers self stream response) (render-http-headers self stream response))) (defun make-response (&optional (stream (make-core-stream ""))) "Returns an empty HTTP Response object" (let ((response (make-instance 'http-response :stream stream))) (setf (http-message.general-headers response) (list (cons 'date (get-universal-time)) ;; (list 'pragma 'no-cache) (cons 'connection 'keep-alive)) (http-response.entity-headers response) (list (cons 'content-type (list "text" "html" (list "charset" "UTF-8")))) (http-response.response-headers response) (list (cons 'server "Core-serveR - www.core.gen.tr"))) response)) (defmethod eval-request ((self http-peer) request) "Evaluates request and returns response, to be overriden by subclasses" (let ((response (make-response (make-core-stream (slot-value (http-request.stream request) '%stream))))) (checkpoint-stream (http-response.stream response)) response)) (defmethod render-response ((self http-peer) stream response request) "Renders HTTP/Mod-Lisp 'response' to 'stream'" (let ((content-length (length (slot-value (http-response.stream response) '%write-buffer)))) (http-response.add-entity-header response 'content-length content-length) (render-headers self stream response) (commit-stream stream) (if (not (eq 'head (http-request.method request))) (commit-stream (http-response.stream response))))) (defmethod render-error ((self http-peer) stream) "Renders a generic server error response to 'stream'" (let ((response (make-response stream))) (checkpoint-stream stream) (setf (http-response.status-code response) (make-status-code 500)) (render-headers self stream response) (with-html-output stream (<:html (<:body "An error condition occured and ignored."))) (commit-stream stream))) (defmethod/unit handle-stream :async-no-return ((self http-peer) stream address) (flet ((handle-error (condition) (if (typep condition 'sb-int::simple-stream-error) (return-from handle-stream nil)) (flet ((ignore-error (unit) (render-error unit stream) (close-stream stream)) (retry-error (unit) (do ((i (current-checkpoint stream) (current-checkpoint stream))) ((< (the fixnum i) 0) nil) (rewind-stream stream)) (handle-stream unit stream address))) (debug-condition (aif (s-v '%debug-unit) it self) condition (lambda () (send-message self #'ignore-error)) (lambda () (send-message self #'retry-error))) (return-from handle-stream nil)))) (handler-bind ((error #'handle-error)) (checkpoint-stream stream) (let ((request (parse-request self stream))) (if request (let ((response (eval-request self request))) (if response (render-response self stream response request)))) (close-stream stream))))) (deftrace http-peer '(handle-stream render-error render-response eval-request parse-request render-headers make-response render-http-headers render-mod-lisp-headers)) (defclass nio-http-peer-mixin (unit) ((continuations :initform (make-hash-table) :accessor continuations)) (:default-initargs :name "NIO Http Peer Handling Unit")) (defmethod queue-stream ((self nio-http-peer-mixin) stream k) (setf (gethash stream (continuations self)) k)) (defmethod/unit handle-stream :dispatch ((self nio-http-peer-mixin) stream address) (call-next-method (make-instance 'core-fd-nio-stream :stream stream :worker self) address)) ;; FIXmE: what to do with below? ;; (defparameter *req1* ;; "server-protocol ;; HTTP/1.1 ;; method ;; POST ;; url ;; /gee.gee ;; content-type ;; multipart/form-data; boundary=---------------------------1883461282365618981994564355 ;; content-length ;; 1095 ;; server-ip-addr ;; 127.0.0.1 ;; server-ip-port ;; 80 ;; remote-ip-addr ;; 127.0.0.1 ;; script-filename ;; /var/www/localhost/htdocs/gee.gee ;; remote-ip-port ;; 45445 ;; server-id ;; evrim ;; server-baseversion ;; Apache/2.0.58 ;; modlisp-version ;; 1.3.1 ;; modlisp-major-version ;; 2 ;; Host ;; localhost ;; User-Agent ;; Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0 ;; Accept ;; text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 ;; Accept-Language ;; tr,en;q=0.7,en-us;q=0.3 ;; Accept-Encoding ;; gzip,deflate ;; Accept-Charset ;; ISO-8859-9,utf-8;q=0.7,*;q=0.7 ;; Keep-Alive ;; 300 ;; Connection ;; keep-alive ;; Content-Type ;; multipart/form-data; boundary=---------------------------1883461282365618981994564355 ;; Content-Length ;; 1095 ;; end ;; -----------------------------1883461282365618981994564355 ;; Content-Disposition: form-data; name=\"gee\" ;; gee123 ;; -----------------------------1883461282365618981994564355 ;; Content-Disposition: form-data; name=\"abuzer1\" ;; bas bakalim ;; -----------------------------1883461282365618981994564355 ;; Content-Disposition: form-data; name=\"abuzer2\"; filename=\"a.html\" ;; Content-Type: text/html ;; <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> ;; <html ;; ><body ;; ><form action=\"http://localhost/gee.gee\" method=\"POST\" ;; enctype=\"multipart/form-data\" ;; ><input name=\"gee\" type=\"text\" value=\"gee123\" ;; /><input type=\"submit\" name=\"abuzer1\" value=\"bas bakalim\"> ;; <input type=\"file\" name=\"abuzer2\"> ;; <input type=\"file\" name=\"abuzer3\"> ;; </form ;; ></body ;; ></html ;; > ;; -----------------------------1883461282365618981994564355 ;; Content-Disposition: form-data; name=\"abuzer3\"; filename=\"\" ;; Content-Type: application/octet-stream ;; -----------------------------1883461282365618981994564355-- ;; ")
10,862
Common Lisp
.lisp
260
38.226923
116
0.666288
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
34f1a9944aeec388f3ea9aeb9a495a67ed6f458f0dcc2402e55252eaf330c764
8,266
[ -1 ]
8,267
units.lisp
evrim_core-server/src/units/units.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| Units Framework for [Core-serveR] ;;+---------------------------------------------------------------------------- ;; ;; Most servers use worker threads to accomplish certain tasks like handling ;; incoming connections, evaluating requests and rendering responses. ;; ;; Units framework is the abstraction of worker threads on top of the usual ;; objects. It allows certain messages to be sent and received transparently. ;; ;; There are two type of units: ;; - local-unit: Runs locally ;; - remote-unit: Runs on another node (not implemented yet) ;; ;; To define a new unit, just inherit a new class from local-unit. make a ;; new instance of that class and say (start *unit*). This would create a ;; worker thread which eventually will receive and execute your commands. ;; ;; To specify commands that unit will execute, use defmethod/unit macro. ;; When unit is started, your method body will be executed by the worker ;; thread and result will be passed back. ;; ;; Example: ;; ;; (defclass my-unit (local-unit) ;; ()) ;; ;; (defmethod/unit :sync ((self my-unit) param-1 param-2) ;; (list param-1 param-2)) ;; ;; There are three types of unit methods: ;; ;; i) :sync - Runs method synchronized, you will be blocked ;; ii) :async - Runs method asyncronized, it'll return a zero-arg lambda ;; that you can funcall later to get the result. ;; iii) :async-no-return/:dispatch - Use this if you do not care about ;; the return value of the method. (defclass unit (server) ((name :accessor unit.name :initarg :name :initform "[Core-serveR] Unit")) (:documentation "Units Framework Abstract Base Class")) (defgeneric run (unit) (:documentation "Run method to make this unit work") (:method ((self null)) nil) (:method ((self unit)) t)) (defgeneric unitp (unit) (:documentation "Returns t if 'unit' is a unit") (:method ((self null)) nil) (:method ((self unit)) t)) (defvar +debug-units-on-error+ t "Debugging flag for Units") (defclass standard-unit (unit) ()) (defclass local-unit (standard-unit) ((%thread :initform nil) (%debug-unit :initform nil :initarg :debug-unit)) (:documentation "A Local Unit that would execute methods defined by defmethod/unit")) (defmethod local-unit.status ((self local-unit)) "Return t if local-unit is alive and running" (and (threadp (s-v '%thread)) (thread-alive-p (s-v '%thread)))) (defmethod start ((self local-unit)) "Start the local-unit" (if (not (local-unit.status self)) (prog1 t (setf (s-v '%thread) (thread-spawn #'(lambda () (run self)) :name (unit.name self)))))) (defmethod stop ((self local-unit)) "Stop the local-unit" (if (local-unit.status self) (thread-send (s-v '%thread) 'shutdown)) t) (defmethod status ((self local-unit)) "Returns t if local-unit is running and alive" (local-unit.status self)) (defmethod me-p ((self local-unit)) "Returns t if current thread is same as local-units' worker thread" (or (equal (current-thread) (s-v '%thread)) (not (status self)))) (defmethod send-message ((self local-unit) message) "Send 'message' to the local-unit that would be queued for execution" (thread-send (s-v '%thread) message)) (defmethod receive-message ((self local-unit)) "Pop a message from local-units thread queue" (thread-receive)) (defmethod run ((self local-unit)) "Main loop that runs a local-unit" (flet ((l00p (message) (cond ((eq message 'shutdown) (return-from run nil)) ((functionp message) (funcall message self)) (t (format *standard-output* "Unit ~A Got unknown message:~A~%" self message))))) (loop (l00p (receive-message self))))) (defmacro defmethod/unit (name &rest args) "Define a method that would be run by the worker thread of the unit" (let* ((method-keyword (if (keywordp (car args)) (prog1 (car args) (setq args (cdr args))))) (method-body (cdr args)) (method-args (car args)) (arg-names (extract-argument-names method-args :allow-specializers t)) (self (car arg-names))) `(progn (defgeneric ,name ,(mapcar #'(lambda (arg) (if (listp arg) (car arg) arg)) method-args)) (defmethod ,name ,method-args ,@method-body) ,(cond ((or (eq method-keyword :async-no-return) (eq method-keyword :dispatch)) `(defmethod ,name :around ,method-args (if (me-p ,self) (call-next-method) (dispatch-method-call ,self ',name ,@(rest arg-names))))) ((eq method-keyword :async) `(defmethod ,name :around ,method-args (if (me-p ,self) (call-next-method) (async-method-call ,self ',name ,@(rest arg-names))))) ((or (null method-keyword) (eq method-keyword :sync)) `(defmethod ,name :around ,method-args (if (me-p ,self) (call-next-method) (funcall (async-method-call ,self ',name ,@(rest arg-names)))))) (t (error "Keyword you've entered is not a valid (i.e. :async, :dispatch (or :async-no-return),:sync), or try usual defmethod."))) (warn "defmethod/unit overrides :around method.")))) (defmethod/unit debug-condition :async ((self local-unit) (condition condition) (ignore function) (retry function)) (if +debug-units-on-error+ (let ((swank::*sldb-quit-restart* 'ignore-error)) (restart-case (swank:swank-debugger-hook condition nil) (ignore-error () :report "Ignore the error and return (values)" (funcall ignore)) (retry () :report "Retry the funcall" (funcall retry)))) (funcall ignore))) (defmethod ignore-lambda ((self local-unit) method-name &rest args) (let ((me (current-thread))) (lambda () (thread-send me nil)))) (defmethod retry-lambda ((self local-unit) method-name &rest args) (lambda () (if (slot-value self '%debug-unit) (send-message self #'unit-execution) (unit-execution self)))) (defmethod async-method-call ((self local-unit) method-name &rest args) (let ((me (current-thread))) (labels ((unit-execution (unit) (handler-bind ((error #'(lambda (condition) (debug-condition (if (slot-value unit '%debug-unit) (slot-value unit '%debug-unit) unit) condition (lambda () (thread-send me nil)) (lambda () (send-message unit #'unit-execution))) (return-from unit-execution nil)))) (let ((result (multiple-value-list (apply method-name unit args)))) (thread-send me result))))) (send-message self #'unit-execution) #'(lambda () (apply #'values (thread-receive)))))) (defmethod dispatch-method-call ((self local-unit) method-name &rest args) (labels ((unit-execution (unit) (handler-bind ((error #'(lambda (condition) (debug-condition (if (slot-value unit '%debug-unit) (slot-value unit '%debug-unit) unit) condition (lambda () nil) (lambda () (send-message unit #'unit-execution))) (return-from unit-execution nil)))) (apply method-name unit args)))) (send-message self #'unit-execution) (values))) (deftrace unit '(async-method-call start stop send-message receive-message me-p run debug-condition)) ;; TODO: Implement Remote-units, unit manager. -evrim ;; ;;;----------------------------------------------------------------------------- ;; ;;; STANDARD UNIT ;; ;;;----------------------------------------------------------------------------- ;; (defclass standard-unit (unit) ;; ((%pid :reader get-pid :initarg :pid :initform -1) ;; (%server :initarg :server :initform nil) ;; (%continuations :initform (make-hash-table :test #'equal) ;; :documentation "Captured continuations."))) ;; (defmethod register-continuation ((self standard-unit) lambda &optional (k-id (current-thread))) ;; (setf (gethash k-id (s-v '%continuations)) lambda)) ;; (defmethod unregister-continuation ((self standard-unit) &optional (k-id (current-thread))) ;; (remhash k-id (s-v '%continuations))) ;; (defmethod find-continuation ((self standard-unit) k-id) ;; (gethash k-id (s-v '%continuations))) ;; (defmethod run ((self standard-unit)) ;; (flet ((control-loop-error (condition) ;; (if +debug-units-on-error+ ;; (swank:swank-debugger-hook condition nil) ;; (invoke-restart 'ignore-error))) ;; (l00p () ;; (let ((message (receive-message self))) ;; (cond ;; ((eq message 'shutdown) ;; ;; (format t "Shutting down unit:~A~%" self) ;; (return-from run (values))) ;; ((and (listp message) (functionp (cdr message))) ;; (funcall (cdr message) self)) ;; (t ;; (format t "Got unknown message:~A~%" message)))))) ;; (loop ;; (handler-bind ((error #'control-loop-error)) ;; (restart-case (l00p) ;; (ignore-error () ;; :report "Ignore the error and continue processing.")))))) ;; ;; (defmethod run ((self local-unit)) ;; ;; (flet ((l00p () ;; ;; (let ((message (receive-message self))) ;; ;; (cond ;; ;; ((eq message 'shutdown) (return-from run (values))) ;; ;; ((and (listp message) (functionp (cdr message))) ;; ;; (handler-bind ((error ;; ;; #'(lambda (condition) ;; ;; (thread-send (if (slot-value (s-v 'debug-unit) '%thread) ;; ;; (slot-value (s-v 'debug-unit) '%thread) ;; ;; (car message)) ;; ;; #'(lambda () ;; ;; (if +debug-units-on-error+ ;; ;; (restart-case (swank:swank-debugger-hook condition nil) ;; ;; (ignore-error () ;; ;; :report "Ignore the error and continue processing.") ;; ;; (retry () ;; ;; :report "Retry the funcall" ;; ;; (send-message self (current-thread) (cdr message)) ;; ;; (funcall #'(lambda () ;; ;; (apply #'values (funcall (thread-receive)))))))))) ;; ;; (return-from l00p nil)))) ;; ;; (funcall (cdr message) self))) ;; ;; (t (format t "Got unknown message:~A~%" message)))))) ;; ;; (loop (l00p)))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; LOCAL UNITS a.k.a. THREADS ;; ;;;----------------------------------------------------------------------------- ;; (defclass local-unit (standard-unit) ;; ((%thread :initform nil :documentation "Local thread that this unit runs.") ;; (%debug-unit :initform nil :initarg :debug-unit)) ;; (:default-initargs :name "Core-serveR Local Unit")) ;; (defmethod send-message ((self local-unit) remote message) ;; (thread-send (s-v '%thread) (cons remote message))) ;; (defmethod receive-message ((self local-unit)) ;; (thread-receive)) ;; (defmethod start ((self local-unit)) ;; (if (not (local-unit.status self)) ;; (prog1 t ;; (setf (s-v '%thread) ;; (thread-spawn #'(lambda () (run self)) :name (unit.name self)))))) ;; (defmethod stop ((self local-unit)) ;; (if (local-unit.status self) (thread-send (s-v '%thread) 'shutdown)) ;; t) ;; (defmethod status ((self local-unit)) ;; (local-unit.status self)) ;; (defmethod local-unit.status ((self local-unit)) ;; (and (threadp (s-v '%thread)) (thread-alive-p (s-v '%thread)))) ;; (defmethod me-p ((self local-unit)) ;; (or (equal (current-thread) (s-v '%thread)) (not (status self)))) ;; (defvar +ret+ nil) ;; (defmethod async-method-call-with-no-return ((self local-unit) method-name &rest args) ;; (send-message self (current-thread) ;; #'(lambda (unit) ;; (apply method-name unit args))) ;; (values)) ;; (defmethod async-method-call ((self local-unit) method-name &rest args) ;; (let ((me (current-thread))) ;; (send-message self (current-thread) ;; #'(lambda (unit) ;; (block unit-execution ;; (let ((+ret+ #'(lambda (val) ;; (format t "funki +ret+~A~%" val) ;; (thread-send me (list val)) ;; ;; (return-from unit-execution t) ;; (format t "before run~%") ;; (run unit) ;; ))) ;; (let ((result (multiple-value-list ;; (apply method-name unit args)))) ;; (thread-send me #'(lambda () result)))))))) ;; #'(lambda () ;; (apply #'values (funcall (thread-receive))))) ;; (defmacro defmethod/unit (name &rest args) ;; (let* ((method-keyword (if (keywordp (car args)) ;; (prog1 (car args) (setq args (cdr args))))) ;; (method-body (cdr args)) ;; (method-args (car args)) ;; (arg-names (extract-argument-names method-args :allow-specializers t)) ;; (self (car arg-names))) ;; `(progn ;; (defmethod ,name ,method-args ,@method-body) ;; ,(cond ;; ((eq method-keyword :async-no-return) ;; `(defmethod ,name :around ,method-args ;; (if (me-p ,self) ;; (call-next-method) ;; (async-method-call-with-no-return ,self ',name ,@(rest arg-names))))) ;; ((eq method-keyword :async) ;; `(defmethod ,name :around ,method-args ;; (if (me-p ,self) ;; (if (null +ret+) ;; (let ((+ret+ #'(lambda (val) ;; (return-from ,name val)))) ;; (call-next-method)) ;; (call-next-method)) ;; (async-method-call ,self ',name ,@(rest arg-names))))) ;; ((or (null method-keyword) (eq method-keyword :sync)) ;; `(defmethod ,name :around ,method-args ;; (if (me-p ,self) ;; (if (null +ret+) ;; (let ((+ret+ #'(lambda (val) ;; (return-from ,name val)))) ;; (call-next-method)) ;; (call-next-method)) ;; (funcall ;; (async-method-call ,self ',name ,@(rest arg-names)))))) ;; (t (error "Keyword you've entered is not a valid, try usual defmethod."))) ;; (warn "defmethod/unit overrides :around method.")))) ;; (defmethod async-method-call ((self local-unit) method-name &rest args) ;; (let ((me (current-thread))) ;; (send-message self ;; #'(lambda (unit) ;; (let ((atomic nil)) ;; (let* ((+unit-return+ #'(lambda (val) ;; (setf atomic t) ;; (thread-send me (list val)))) ;; (result (multiple-value-list ;; (apply method-name unit args)))) ;; (unless atomic ;; (thread-send me result)))))) ;; #'(lambda () ;; (prog1 (apply #'values (thread-receive)) ;; (cleanup-mailbox me))))) ;; (defmethod async-method-call-with-no-return ((self local-unit) method-name &rest args) ;; (let ((me (current-thread))) ;; (send-message self ;; #'(lambda (unit) ;; (apply method-name unit args)))) ;; (values)) ;; (defmacro defmethod/unit (name &rest args) ;; (let* (;; (method-name (intern (format nil "%~:@(~A~)" name))) ;; (method-keyword (if (keywordp (car args)) ;; (prog1 (car args) ;; (setq args (cdr args))))) ;; (method-body (cdr args)) ;; (method-args (car args)) ;; (arg-names (extract-argument-names method-args :allow-specializers t)) ;; (self (car arg-names))) ;; (cond ;; ((eq method-keyword :async) ;; `(defmethod ,name ,method-args ;; (if (me-p ,self) ;; (funcall #'(lambda ,arg-names ;; (declare (ignorable ,(car arg-names))) ;; (block ,name ;; ,@method-body)) ,@arg-names) ;; (async-method-call ,self ',name ,@(rest arg-names))))) ;; ((eq method-keyword :async-no-return) ;; `(defmethod ,name ,method-args ;; (if (me-p ,self) ;; (funcall #'(lambda ,arg-names ;; (declare (ignorable ,(car arg-names))) ;; (block ,name ;; ,@method-body)) ,@arg-names) ;; (async-method-call-with-no-return ,self ',name ,@(rest arg-names))) ;; (values))) ;; ((or (null method-keyword) (eq method-keyword :sync)) ;; `(defmethod ,name ,method-args ;; (if (me-p ,self) ;; (funcall #'(lambda ,arg-names ;; (declare (ignorable ,(car arg-names))) ;; (block ,name ;; (let ((+unit-return+ #'(lambda (val) ;; (return-from ,name val)))) ;; ,@method-body))) ,@arg-names) ;; (funcall (apply #'async-method-call ,self ',name ;; (list ,@(rest arg-names))))))) ;; (t ;; `(defmethod ,name ,method-keyword ,method-args ,@method-body))))) ;; (defclass u1 (local-unit) ;; ()) ;; (defvar *u1 (make-instance 'u1)) ;; (defmethod/unit t1 :sync ((self u1)) ;; ;; (format *standard-output* "gee:~A" self) ;; (error "gee") ;; (values 88 99 100)) ;; (defgeneric send-message (unit message) ;; (:documentation "Send message to unit.")) ;; (defgeneric receive-message (unit) ;; (:documentation "Receive message from unit.")) ;; ;;;----------------------------------------------------------------------------- ;; ;;; UNIT SERVER ;; ;;;----------------------------------------------------------------------------- ;; (defclass unit-server (server) ;; ((host :initarg :host :initform "0.0.0.0") ;; (port :initarg :port :initform 3999) ;; (%units :initform (make-hash-table :test #'equal :weakness :value)))) ;; (defmethod find-unit ((self unit-server) pid) ;; (find pid (s-v '%units) :test #'equal :key #'get-pid)) ;; ;;;----------------------------------------------------------------------------- ;; ;;; LOCAL UNIT SERVER ;; ;;;----------------------------------------------------------------------------- ;; (defclass local-unit-server (unit-server) ;; ((%remote-unit-servers :initform '()) ;; %socket %thread)) ;; (defmethod add-remote-server ((self local-unit-server) host port) ;; (let ((server (make-instance 'remote-unit-server ;; :host host ;; :port port ;; :local-unit-server self))) ;; (start server) ;; (setf (s-v '%remote-unit-servers) ;; (cons server (s-v '%remote-unit-servers))) ;; server)) ;; (defmethod remove-remote-server ((self local-unit-server) server) ;; (stop server) ;; (setf (s-v '%remote-unit-servers) (remove server (s-v '%remote-unit-servers))) ;; server) ;; (defmethod remote-servers ((self local-unit-server)) ;; (copy-list (s-v '%remote-unit-servers))) ;; (defmethod find-remote-server ((self local-unit-server) host port) ;; (find-if #'(lambda (s) (if (and (equal (slot-value s 'host) host) ;; (equal (slot-value s 'port) port)) ;; t)) ;; (s-v '%remote-unit-servers))) ;; (defmethod start ((self unit-server)) ;; (if (not (status self)) ;; (prog1 t ;; (setf (s-v '%socket) (make-server :host (s-v 'host) ;; :port (s-v 'port) ;; :reuse-address t ;; :backlog 1 ;; :protocol :tcp) ;; (s-v '%thread) (spawn #'(lambda () (run self)) ;; :name (format nil "Local Unit Server ~A:~A" ;; (s-v 'host) (s-v 'port))))) ;; nil)) ;; (defmethod stop ((self unit-server)) ;; (if (status self) ;; (let ((socket (s-v '%socket))) ;; (setf (s-v '%socket) nil) ;; (close-socket socket) ;; (kill-thread (s-v '%thread)) ;; t) ;; nil)) ;; (defmethod status ((self unit-server)) ;; (and (s-v '%socket) (threadp (s-v '%thread)) (thread-alive-p (s-v '%thread)))) ;; (defmethod run ((self unit-server)) ;; (loop (when (s-v '%socket)) ;; (multiple-value-bind (stream host port) (accept (s-v '%socket)) ;; (let ((remote-server (make-instance 'remote-unit-server ;; :host host ;; :port port ;; :stream stream ;; :local-unit-server self))) ;; (start remote-server) ;; (setf (s-v '%remote-unit-servers) ;; (cons remote-server (s-v '%remote-unit-servers))) ;; (format t "Got remote unit server ~A:~A" host port))))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; REMOTE UNIT SERVER ;; ;;;----------------------------------------------------------------------------- ;; (defclass remote-unit-server (unit-server) ;; ((%local-unit-server :initarg :local-unit-server :initform nil) ;; (%stream :initarg :stream :initform nil) ;; %thread)) ;; (defmethod start ((self remote-unit-server)) ;; (if (null (s-v '%stream)) ;; (setf (s-v '%stream) (connect (s-v 'host) (s-v 'port)))) ;; (setf (s-v '%thread) (spawn #'(lambda () (run self)) ;; :name (format nil "Remote unit server ~A:~A" ;; (s-v 'host) (s-v 'port)))) ;; t) ;; (defmethod stop ((self remote-unit-server)) ;; (let ((stream (s-v '%stream)) ;; (thread (s-v '%thread))) ;; (setf (s-v '%stream) nil ;; (s-v '%thread) nil) ;; (close-stream stream) ;; (kill-thread thread))) ;; (defmethod status ((self remote-unit-server)) ;; (and (s-v '%thread) (thread-alive-p (s-v '%thread)) (s-v '%stream))) ;; (defmethod run ((self remote-unit-server)) ;; (loop (when (s-v '%stream)) ;; (multiple-value-bind (type k-id args) (deserialize-unit-message (s-v '%stream)) ;; (cond ;; ((eq 'unit-call type) ;; (handle-unit-call self k-id args)) ;; ((eq 'unit-answer type) ;; (handle-unit-answer self k-id args)) ;; (t ;; (format t "Got unknown message:~A" type)))))) ;; (defmethod handle-unit-call ((self remote-unit-server) k-id args) ;; (let ((method-name (car args)) ;; (unit (find-unit (s-v '%local-unit-server) (cadr args))) ;; (method-args (caddr args))) ;; (send-message unit ;; #'(lambda (unit) ;; (when (slot-value self '%stream) ;; (write-stream (slot-value self '%stream) ;; (serialize-unit-message ;; (list 'unit-answer k-id ;; (multiple-value-list (apply method-name unit method-args)))))))))) ;; (defmethod handle-unit-answer ((self remote-unit-server) k-id args) ;; (let ((unit (find-unit self (car args))) ;; (retval (cadr args))) ;; (send-message unit ;; #'(lambda (unit) ;; (let ((k (find-continuation unit k-id))) ;; (funcall k retval)))))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; STANDARD UNIT ;; ;;;----------------------------------------------------------------------------- ;; (defclass standard-unit (unit) ;; ((%pid :reader get-pid :initarg :pid :initform -1) ;; (%server :initarg :server :initform nil) ;; (%continuations :initform (make-hash-table :test #'equal) ;; :documentation "Captured continuations."))) ;; (defmethod register-continuation ((self standard-unit) lambda &optional (k-id (current-thread))) ;; (setf (gethash k-id (s-v '%continuations)) lambda)) ;; (defmethod unregister-continuation ((self standard-unit) &optional (k-id (current-thread))) ;; (remhash k-id (s-v '%continuations))) ;; (defmethod find-continuation ((self standard-unit) k-id) ;; (gethash k-id (s-v '%continuations))) ;; (defmethod run ((self standard-unit)) ;; (flet ((control-loop-error (condition) ;; (if *debug-on-error* ;; (swank:swank-debugger-hook condition nil) ;; (invoke-restart 'ignore-error))) ;; (l00p () ;; (let ((message (receive-message self))) ;; (cond ;; ((eq message 'shutdown) ;; (format t "Shutting down unit:~A~%" self) ;; (return-from run (values))) ;; ((functionp message) ;; (funcall message self)) ;; (t ;; (format t "Got unknown message:~A~%" message)))))) ;; (loop ;; (handler-bind ((error #'control-loop-error)) ;; (restart-case ;; (l00p) ;; (ignore-error () ;; :report "Ignore the error and continue processing.")))))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; LOCAL UNITS a.k.a. THREADS ;; ;;;----------------------------------------------------------------------------- ;; (defclass local-unit (standard-unit) ;; ((%thread :initform nil ;; :documentation "Local thread that this unit runs."))) ;; (defmethod send-message ((self local-unit) message) ;; (thread-send (s-v '%thread) message)) ;; (defmethod receive-message ((self local-unit)) ;; (thread-receive)) ;; (defmethod start ((self local-unit)) ;; (if (not (status self)) ;; (prog1 t ;; (setf (s-v '%thread) ;; (swank-backend:spawn (curry #'run self) :name "Local Unit"))) ;; nil)) ;; (defmethod stop ((self local-unit)) ;; (if (status self) (send-message self 'shutdown)) ;; t) ;; (defmethod status ((self local-unit)) ;; (and (threadp (s-v '%thread)) (thread-alive-p (s-v '%thread)))) ;; (defmethod sync-method-call ((self local-unit) method-name &rest args) ;; (flet ((k (val) ;; (return-from sync-method-call (apply 'values val))) ;; (me (current-thread))) ;; (send-message self ;; #'(lambda (unit) ;; (let ((result (apply method-name unit args))) ;; (thread-send me ;; #'(lambda (unit) ;; (funcall k result))))))) ;; (run self)) ;; (defclass remote-unit (standard-unit) ;; ()) ;; (defmethod start ((self remote-unit)) t) ;; (defmethod stop ((self remote-unit)) t) ;; (defmethod status ((self remote-unit)) t) ;; (defmethod sync-method-call ((self remote-unit) method-name &rest args) ;; (flet ((k (val) ;; (return-from sync-method-call (apply 'values val)))) ;; (let ((k-id (random-string))) ;; (register-continuation self #'k k-id) ;; (when (slot-value (slot-value self '%server) '%stream) ;; (write-stream (slot-value (slot-value self '%server) '%stream) ;; (serialize-unit-message ;; (list 'unit-call k-id (list method-name (s-v '%pid) args))))))) ;; (run self)) ;; (defmacro defmethod/unit (name &rest args) ;; (let* ((method-name (intern (format nil "%~:@(~A~)" name))) ;; (method-keyword (if (keywordp (car args)) ;; (prog1 (car args) ;; (setf args (cdr args))))) ;; (method-body (cdr args)) ;; (method-args (car args)) ;; (arg-names (extract-argument-names args :allow-specializers t)) ;; (self (car arg-names))) ;; (cond ;; ((eq method-keyword :async) ;; `(progn ;; (defmethod ,method-name ,method-args ;; ,@method-body) ;; (defmethod ,name ,method-args ;; (if (me-p self) ;; (,method-name ,arg-names) ;; (async-method-call ,self ',method-name ,@(rest arg-names)))))) ;; ((or (null method-keyword) (eq method-keyword :sync)) ;; `(progn ;; (defmethod ,method-name ,method-args ;; ,@method-body) ;; (defmethod ,name ,method-args ;; (if (me-p self) ;; (,method-name ,arg-names) ;; (sync-method-call ,self ',method-name ,@(rest arg-names)))))) ;; (t ;; `(defmethod ,method-name ,method-keyword ,method-args ;; ,@method-body))))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; UNIT CACHE ;; ;;;----------------------------------------------------------------------------- ;; (defvar *unit-cache* (make-hash-table :test #'equal)) ;; (defun current-unit (&optional (cache *unit-cache*)) ;; (gethash (current-thread) cache)) ;; (defmethod run :around ((self standard-unit)) ;; (if (equal (s-v '%thread) (current-thread)) ;; (setf (gethash (current-thread) *unit-cache*) self)) ;; (prog1 (call-next-method) ;; (remhash (current-thread) *unit-cache*))) ;; (defmethod/unit t1 :around ((self local-unit)) ;; (list "abuzer" "mabuzer"))
27,674
Common Lisp
.lisp
648
40.658951
99
0.580759
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
120b8b740f51e2248cc21eb48fddf3c511d6e1a6b37e2e41c437ca0ff0497589
8,267
[ -1 ]
8,268
command.lisp
evrim_core-server/src/class+/command.lisp
(in-package :core-server) ;; +---------------------------------------------------------------------------- ;; | Command Framework ;; +---------------------------------------------------------------------------- (defclass command+ (class+) () (:documentation "Metaclass of Command Framework")) (defmethod class+.ctor ((class command+)) (let ((name (class+.name class))) (aif (class+.%ctor class) `(progn (defun ,name ,@it (run (make-instance ',name ,@(class+.ctor-arguments class it)))) (defun ,(intern (format nil "~AM" name) (symbol-package name)) ,@it (make-instance ',name ,@(class+.ctor-arguments class (car it))))) `(progn (defun ,name (&key ,@(class+.ctor-lambda-list class)) (run (make-instance ',name ,@(class+.ctor-arguments class)))) (defun ,(intern (format nil "~AM" name) (symbol-package name)) (&key ,@(class+.ctor-lambda-list class)) (make-instance ',name ,@(class+.ctor-arguments class))))))) (defmethod class+.ctor-lambda-list ((self command+) &optional (include-supplied-p nil)) (reduce0 (lambda (acc slot) (with-slotdef (initarg initform supplied-p) slot (if initarg (let ((symbol (intern (symbol-name initarg)))) (if include-supplied-p (cons (list symbol initform supplied-p) acc) (cons (list symbol initform) acc))) acc))) (reverse (class+.local-slots self)))) (defmethod class+.ctor-arguments ((self command+) &optional lambda-list) (reduce0 (lambda (acc slot) (with-slotdef (initarg) slot (if initarg (cons initarg (cons (intern (symbol-name initarg)) acc)) acc))) (aif (extract-argument-names lambda-list) (filter (lambda (slot) (with-slotdef (name) slot (member name it :test #'string=))) (class+.slots self)) (class+.local-slots self)))) ;; ---------------------------------------------------------------------------- ;; defcommand Macro ;; ---------------------------------------------------------------------------- (defmacro defcommand (name supers slots &rest rest) `(defclass+ ,name (,@supers command) ,slots ,@(append rest '((:metaclass command+))))) ;; ---------------------------------------------------------------------------- ;; Command Base Class ;; ---------------------------------------------------------------------------- (defvar +verbose+ t "make command executions verbose during installation.") (defclass command () ((input-stream :accessor command.input-stream :initarg :input-stream) (output-stream :accessor command.output-stream :initarg :output-stream :initform nil) (verbose :accessor command.verbose :initarg :verbose :initform +verbose+) (verbose-stream :accessor command.verbose-stream :initarg :verbose-stream :initform *standard-output*)) (:metaclass command+)) ;; ---------------------------------------------------------------------------- ;; Protocol ;; ---------------------------------------------------------------------------- (defgeneric run (command) (:documentation "Run this command with given args.")) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>
3,824
Common Lisp
.lisp
80
44.075
87
0.579399
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
88d3576d038773c029009ff8bb786d5af79ee9298a76fc63b04a2f9dc9e8e5ad
8,268
[ -1 ]
8,269
lift.lisp
evrim_core-server/src/class+/lift.lisp
(in-package :core-server) ;; +------------------------------------------------------------------------- ;; | Class+ Lifting ;; +------------------------------------------------------------------------- ;; Author: Evrim Ulu <[email protected]> ;; Date: July 2011 ;; ------------------------------------------------------------------------- ;; Permute ;; ------------------------------------------------------------------------- ;; ;; SERVER> (permute '((a b) (c d) (e f))) ;; ((A C E) (A C F) (A D E) (A D F) (B C E) (B C F) (B D E) (B D F)) (eval-when (:compile-toplevel :load-toplevel :execute) (defun permute (list) (flatten1 (mapcar (lambda (atom) (mapcar (curry #'cons atom) (let ((a (permute (cdr list)))) (if (atom a) (list a) a)))) (car list)))) ;; SERVER> (car (%find-method 'foo (list (find-class 'a) (find-class 'a)))) ;; #<STANDARD-METHOD FOO (A A) {100521CF71}> (defun %find-method (method-name specializers) (aif (sb-pcl::find-generic-function method-name nil) (sb-pcl::compute-applicable-methods-using-classes it specializers))) (defun %walk-arguments (args) (mapcar (lambda (arg) (typecase arg (keyword-function-argument-form (if (null (supplied-p-parameter arg)) (setf (supplied-p-parameter arg) (gensym))))) arg) (walk-lambda-list args nil '() :allow-specializers t))) (defun %walk-specializers (walked-args) (mapcar (lambda (arg) (typecase arg (specialized-function-argument-form (find-class (arnesi::specializer arg))) (t (find-class 't)))) walked-args))) ;; +------------------------------------------------------------------------- ;; | Method Lifting ;; +------------------------------------------------------------------------- (defvar +lift-compilation+ nil) (defmacro defmethod/lift (method-name (&rest args) &optional output-method-name) (let* ((walked-args (%walk-arguments args)) (specializers (%walk-specializers walked-args)) (lifts (mapcar (lambda (class) (aif (mapcar (compose #'class+.find (lambda (a) (if (listp a) (cadr a) a)) #'sb-pcl::slot-definition-type) (filter (lambda (slot) (eq (slot-definition-host slot) 'lift)) (class+.slots class))) it (list class))) specializers)) (method (car (any (lambda (specializers) (%find-method method-name specializers)) (permute lifts))))) (if method (let* ((method-lambda-list (mapcar (lambda (arg specializer) (setf (arnesi::specializer arg) (class-name specializer)) arg) (walk-lambda-list (sb-pcl::method-lambda-list method) nil nil :allow-specializers t) (sb-pcl::method-specializers method))) (method-lambda-list (append method-lambda-list (drop (length method-lambda-list) walked-args))) (arguments (mapcar #'cons walked-args method-lambda-list))) (labels ((find-slot (new-class old-class) ;; page/editor template (aif (any (lambda (slot) (aif (member (class+.find old-class) (class+.superclasses (class+.find (let ((slot-type (sb-pcl::slot-definition-type slot))) (if (listp slot-type) (cadr slot-type) slot-type))))) slot)) (filter (lambda (slot) (eq 'lift (slot-definition-host slot))) (class+.slots (find-class new-class)))) (slot-definition-name it) (error "error in find-slot new-class ~A old class ~A" new-class old-class))) (process-argument (atom) (destructuring-bind (new . old) atom (typecase new (specialized-function-argument-form (let ((new-specializer (arnesi::specializer new)) (old-specializer (arnesi::specializer old))) (if (eq new-specializer old-specializer) `(list ,(name new)) `(list (slot-value ,(name new) ',(find-slot new-specializer old-specializer)))))) (keyword-function-argument-form `(if ,(arnesi::supplied-p-parameter new) (list ,(make-keyword (name old)) ,(name new)) nil)) (t `(list ,(name new))))))) `(defmethod ,(or output-method-name method-name) ,(unwalk-lambda-list walked-args) ,(cond ((atom method-name) `(apply ',method-name (append ,@(mapcar #'process-argument arguments)))) (t `(,(car method-name) (,(cadr method-name) ,@(flatten1 (mapcar #'cdr (mapcar #'process-argument (cdr arguments))))) ,(name (caar arguments)))))))) `(defmethod ,(or output-method-name method-name) ,(unwalk-lambda-list walked-args) (if +lift-compilation+ (warn "Can't compile method lift ~A" ',(or output-method-name method-name)) (let ((+lift-compilation+ t)) (warn "Compiling method lift ~A" ',(or output-method-name method-name)) (eval `(defmethod/lift ,',method-name ,',args ,',output-method-name)) ,(cond ((atom method-name) `(apply ',(or output-method-name method-name) ,(extract-apply-arguments args))) (t `(,(car method-name) (,(cadr method-name) ,@(nreverse (reduce (lambda (acc arg) (typecase arg (keyword-function-argument-form (cons (name arg) (cons (make-keyword (name arg)) acc))) (t (cons (name arg) acc)))) (cdr walked-args) :initial-value nil))) ,(car args)))))))))) ;; (defmacro defmethod/lift (method-name (&rest args) ;; &optional output-method-name) ;; `(progn ;; (eval-when (:compile-toplevel :load-toplevel) ;; (%defmethod/lift ,method-name ,args ,output-method-name)) ;; (eval-when (:execute) ;; (%defmethod/lift ,method-name ,args ,output-method-name)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun class+-find-slot-in-classes (slot supers) (any (lambda (class) (aif (class+.find-slot class slot) (let ((subclass (class+-find-slot-in-classes slot (remove class (class+.superclasses class))))) (if (null subclass) class subclass)))) supers)) (defmethod class+-lifted-slots (name supers slots) (let ((lifted-slots (filter (lambda (slot) (eq (getf (cdr slot) :host) 'lift)) slots))) (mapcar (lambda (class) (let ((keyword (make-keyword (class-name class)))) `(,(class-name class) :host lift :initarg ,keyword :initform (error ,(format nil "Provide :~A" keyword)) :type ,(class-name class)))) (uniq (mapcar (lambda (slot) (aif (class+-find-slot-in-classes (car slot) (mapcar #'class+.find supers)) it (error "Can't find slot ~A to lift in superclasses" (car slot)))) (filter (lambda (slot) (if (any (lambda (class) (class+.find-slot class (car slot))) (mapcar (lambda (slot) (find-class (getf (cdr slot) :type))) lifted-slots)) nil t)) (filter (lambda (slot) (getf (cdr slot) :lift)) slots)))))))) (defmethod class+.find-lifted-slot ((self class+) slot-to-find) (any (lambda (slot) (if (class+.find-slot (class+.find (let ((a (sb-pcl::slot-definition-type slot))) (if (listp a) (cadr a) a))) slot-to-find) (slot-definition-name slot))) (filter (lambda (slot) (eq 'lift (slot-definition-host slot))) (class+.slots self)))) (defmethod copy-lifted-slot ((self class+-instance) (slot standard-slot-definition) value) value) (defmethod shared-initialize :after ((self class+-instance) slots &key &allow-other-keys) (mapcar (lambda (slot) (let* ((name (slot-definition-name slot)) (lifted-slot (class+.find-lifted-slot (class-of self) name))) (setf (slot-value self name) (copy-lifted-slot self slot (slot-value (slot-value self lifted-slot) name))))) (filter (lambda (slot) (and (slot-definition-lift slot) (or (eq (slot-definition-host slot) 'remote) (eq (slot-definition-host slot) 'both)))) (class+.slots (class-of self)))) self) (defmacro defclass+-slot-lifts (class-name) (let ((class (class+.find class-name))) (flet ((find-lifted-slot (slot-to-find) (any (lambda (slot) (aif (class+.find-slot (let ((slot-type (sb-pcl::slot-definition-type slot))) (find-class (if (listp slot-type) (cadr slot-type) slot-type))) slot-to-find) it)) (filter (lambda (slot) (eq 'lift (slot-definition-host slot))) (class+.slots class))))) `(progn ,@(mapcar (lambda (slot) (with-slotdef (name reader writer) slot (let ((lifted-slot (find-lifted-slot name))) (let ((reader1 reader) (writer1 writer)) (declare (ignore reader1 writer1)) (assert (not (null lifted-slot)) nil "Cant find slot ~A to lift" name) (with-slotdef (reader writer) lifted-slot `(progn ,(if reader `(defmethod/lift ,reader ((self ,class-name)) ;; ,reader1 )) ,(if writer `(defmethod/lift ,writer (value (self ,class-name)) ;; ,writer1 )))))))) (filter (lambda (slot) (and (eq 'local (slot-definition-host slot)) (slot-definition-lift slot))) (class+.slots class))))))) ;; ------------------------------------------------------------------------- ;; Lift Usage ;; ------------------------------------------------------------------------- ;; (defclass+ a () ;; ((slot1 :host local :initform "slot1-of-a") ;; (slot2 :host remote :initform "slot2-of-a"))) ;; (defclass+ c () ;; ((slot3 :host local :initform "slot3-of-c"))) ;; (defclass+ b (a c) ;; ((slot1 :lift t) ;; (slot2 :host remote :lift t) ;; (slot3 :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Method Lifting ;; ------------------------------------------------------------------------- ;; (defmethod lifted-method ((a1 a) (a2 a) x &key (y 'default-y y-supplied-p)) ;; (describe (list a1 a2 y y-supplied-p)) ;; (list 'lifted-slot2-first-a (a.slot2 a1) ;; 'lifted-slot2-second-a (a.slot2 a2) ;; 'x x 'y y)) ;; (defmethod (setf lifted-setf-method) (value (a1 a) (a2 a)) ;; (list value a1 a2)) ;; (defmethod lifted-method ((b1 b) (b2 b) x &key y) ;; (call-next-method (slot-value b1 'a) ;; (slot-value b2 'a))) ;; (defmethod/lift lifted-method ((first-b b) (second-b b) x1 &key (y1 nil supplied-p))) ;; ;; (PROGN ;; ;; (EVAL-WHEN (:EXECUTE) ;; ;; (DEFMETHOD LIFTED-METHOD ((FIRST-B B) (SECOND-B B) X1 &KEY Y1) ;; ;; (LIFTED-METHOD (SLOT-VALUE FIRST-B 'A) (SLOT-VALUE SECOND-B 'A) ;; ;; X1 :Y Y1)))) ;; (defmethod/lift (setf lifted-setf-method) (value (a1 b) (a2 b))) ;; ;; (PROGN ;; ;; (EVAL-WHEN (:EXECUTE) ;; ;; (DEFMETHOD (SETF LIFTED-SETF-METHOD) (VALUE (A1 B) (A2 B)) ;; ;; (SETF (LIFTED-SETF-METHOD (SLOT-VALUE A1 'A) (SLOT-VALUE A2 'A)) ;; ;; VALUE)))) ;; ------------------------------------------------------------------------- ;; Slot Lifting ;; ------------------------------------------------------------------------- ;; SERVER> (let* ((a (a)) ;; (b (b :a a :c (c)))) ;; (setf (b.slot1 b) "foo-bar") ;; (describe b) ;; (describe a)) ;; #<B {1002A09C91}> ;; [standard-object] ;; Slots with :INSTANCE allocation: ;; SLOT3 = "slot3-of-c" ;; SLOT1 = NIL ;; SLOT2 = "slot2-of-a" ;; A = #<A {1002A09771}> ;; C = #<C {1002A09A31}> ;; #<A {1002A09771}> ;; [standard-object] ;; Slots with :INSTANCE allocation: ;; SLOT1 = "foo-bar" ;; SLOT2 = "slot2-of-a" ;; ; No value ;; SERVER>
11,847
Common Lisp
.lisp
339
29.495575
90
0.543895
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
80492553ae60bdd276b3ee3c44eda06866ab5a08deac50ba10f36177b5806e8e
8,269
[ -1 ]
8,270
protocol.lisp
evrim_core-server/src/class+/protocol.lisp
(in-package :core-server) ;; +---------------------------------------------------------------------------- ;; | Class+ Protocol ;; +---------------------------------------------------------------------------- (defun find-class+ (class+) "Returns the instance of class+ associated with the symbol named 'class+'." (etypecase class+ (symbol (find-class class+ nil)) (class+ class+))) (defun class+.find (class+) (find-class+ class+)) (defgeneric class+.name (class+) (:documentation "Name of this class+")) (defgeneric class+.direct-superclasses (class+) (:documentation "Returns direct super classes+ of this class+") (:method ((self t)) nil)) (defgeneric class+.superclasses (class+) (:documentation "Returns super classes+ of this class+") (:method ((self t)) nil)) (defgeneric class+.direct-subclasses (class+) (:documentation "Returns direct sub classes+ of this class+") (:method ((self t)) nil)) (defgeneric class+.subclasses (class+) (:documentation "Returns sub classes+ of this class+") (:method ((self t)) nil)) (defgeneric class+.slots (class+) (:documentation "Returns all slots of this class+") (:method ((self t)) nil)) (defgeneric class+.rest (class+) (:method ((self t)) nil)) (defgeneric class+.methods (class+) (:documentation "Returns list of all method-names and associated lambda lists") (:method ((self t)) nil)) ;; ---------------------------------------------------------------------------- ;; Extra Definitions ;; ---------------------------------------------------------------------------- (defgeneric class+.slot-search (class+ match-p) (:documentation "Returns all slots that satisfies match-p lambda") (:method ((self t) match-p) nil)) ;; (defgeneric class+.search (class+ goal-p &optional successors combiner) ;; (:documentation "Convenient search method that by default applies goal-p lambda to ;; all superclasses of this class+ until goal-p returns a value other than nil")) (defgeneric class+.local-slots (class+) (:documentation "Returns an assoc list of local-slots with corresponding default values") (:method ((self t)) nil)) (defgeneric class+.remote-slots (class+) (:documentation "Returns an assoc list of remote-slots with corresponding default values") (:method ((self t)) nil)) (defgeneric class+.local-methods (class+) (:documentation "Returns list of local method-names and associated lambda lists") (:method ((self t)) nil)) (defgeneric class+.remote-methods (class+) (:documentation "Returns list of remote method-names and associated lambda lists ") (:method ((self t)) nil)) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>
3,345
Common Lisp
.lisp
66
48.424242
92
0.664518
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6a238e54fbaa157a1f30bcb6ff1574f26390d239cdb0f30b347a6bdadd725142
8,270
[ -1 ]
8,271
model.lisp
evrim_core-server/src/manager/src/model.lisp
;; +------------------------------------------------------------------------- ;; | Manager Application Model ;; +------------------------------------------------------------------------- (in-package :manager) ;; ------------------------------------------------------------------------- ;; Server OAuth Credentials ;; ------------------------------------------------------------------------- (defclass+ facebook-credentials () ((app-id :host both) (app-secret :host both)) (:ctor make-facebook-credentials)) (defclass+ google-credentials () ((client-id :host both) (client-secret :host both)) (:ctor make-google-credentials)) (defclass+ twitter-credentials () ((consumer-key :host both) (consumer-secret :host both)) (:ctor make-twitter-credentials)) (defclass+ yahoo-credentials () ((consumer-key :host both) (consumer-secret :host both)) (:ctor make-yahoo-credentials)) ;; +------------------------------------------------------------------------- ;; | Administrator Definition (Manager Application Users) ;; +------------------------------------------------------------------------- (defclass+ admin (secure-object simple-user) ((username :host local :print t :index t :documentation "Admin Username") (password :host local :documentation "Admin Password") (creation-timestamp :host local :type integer :initform (get-universal-time))) (:ctor make-admin) (:default-initargs :permissions '((owner . 0) (group . 0) (other . 0) (unauthorized . -1)) :levels '(admin/authorized))) ;; ------------------------------------------------------------------------- ;; Account Definition ;; ------------------------------------------------------------------------- (defclass+ account (object-with-id) ((user :host local :type user :relation accounts :documentation "Associated User") (provider :initform (error "Provide :provider")) (last-update :host local :documentation "Last update time of this account") (name :host local :documentation "Name of this person")) (:ctor %make-account)) ;; ------------------------------------------------------------------------- ;; Local Account Definition ;; ------------------------------------------------------------------------- (defclass+ local-account (account) ((email :host local :print t :index t :documentation "Email address") (password :host local :documentation "Password")) (:ctor make-local-account) (:default-initargs :provider 'coretal)) ;; ------------------------------------------------------------------------- ;; External Account Definition ;; ------------------------------------------------------------------------- (defclass+ external-account (account) ((account-id :host local :print t :index t :documentation "Account ID" :accessor account.account-id) (token :host local :documentation "Token associated with this account")) (:ctor %make-external-account)) ;; ------------------------------------------------------------------------- ;; Facebook Account Definition ;; ------------------------------------------------------------------------- ;; #<JOBJECT {100D4774D3}> [standard-object] ;; Slots with :INSTANCE allocation: ;; ATTRIBUTES = (:METADATA #<JOBJECT {100D4760F3}> :UPDATED_TIME ;; "2012-06-25T18:36:31+0000" :VERIFIED TRUE :LOCALE "en_US" :TIMEZONE 3 ;; :EMAIL "[email protected]" :GENDER "male" :FAVORITE_ATHLETES ;; (#<JOBJECT {100CFD0A13}>) :LOCATION #<JOBJECT {100CFC86E3}> :USERNAME ;; "eevrimulu" :LINK "http://www.facebook.com/eevrimulu" :LAST_NAME "Ulu" ;; :FIRST_NAME "Evrim" :NAME "Evrim Ulu" :ID "700518347") (defclass+ facebook-account (external-account) ((username :host local) (first-name :host local) (last-name :host local) (email :host local) (verified :host local) (timezone :host local) (locale :host local) (location :host local) (gender :host local) (link :host local)) (:ctor make-facebook-account) (:default-initargs :provider 'facebook)) ;; ------------------------------------------------------------------------- ;; Google Account ;; ------------------------------------------------------------------------- (defclass+ google-account (external-account) ((locale :host local) (gender :host local) (picture :host local) (link :host local) (last-name :host local) (first-name :host local) (verified :host local) (email :host local) (last-update :host local)) (:ctor make-google-account) (:default-initargs :provider 'google)) ;; ------------------------------------------------------------------------- ;; Twitter Account ;; ------------------------------------------------------------------------- (defclass+ twitter-account (external-account) ((lang :host local) (verified :host local) (geo-enabled :host local) (time-zone :host local) (utc-offset :host local) (created-at :host local) (protected :host local) (description :host local) (url :host local) (location :host local) (screen-name :host local)) (:ctor make-twitter-account) (:default-initargs :provider 'twitter)) ;; ------------------------------------------------------------------------- ;; Yahoo Account ;; ------------------------------------------------------------------------- (defclass+ yahoo-account (external-account) ((nickname :host local) (first-name :host local) (last-name :host local)) (:ctor make-yahoo-account) (:default-initargs :provider 'yahoo)) ;; ------------------------------------------------------------------------- ;; User Definition ;; ------------------------------------------------------------------------- (defclass+ user (object-with-id simple-user) ((accounts :host local :type account* :relation user :documentation "Associated accounts" :leaf t) (default-account :host local :type account :documentation "Default Account of this user") (associations :host local :type account-associations :relation user)) (:ctor make-user)) (defmethod user.default-account ((self user)) (with-slots (accounts default-account) self (or default-account (car accounts)))) ;; ------------------------------------------------------------------------- ;; Account Association ;; ------------------------------------------------------------------------- (defclass+ account-association (object-with-id) ((account :host local :type account) (realm :host local :type realm :relation associations))) ;; +------------------------------------------------------------------------- ;; | Realm Definition ;; +------------------------------------------------------------------------- (defclass+ realm (secure-object object-with-id) ((fqdn :host local :index t :print t :documentation "FQDN" :type string) (creation-timestamp :host both :type integer :documentation "Creation timestamp" :initform (get-universal-time)) (associations :host local :type account-association* :relation realm)) (:ctor make-realm) (:default-initargs :permissions '((owner . 0) (group . 0) (other . 0) (unauthorized . -1)) :levels '(realm/authorized))) ;; ------------------------------------------------------------------------- ;; Crud Definitions ;; ------------------------------------------------------------------------- (defcrud admin) (defcrud user) (defcrud account) (defcrud local-account) (defcrud external-account) (defcrud facebook-account) (defcrud google-account) (defcrud twitter-account) (defcrud account-association) (defcrud realm) ;; ------------------------------------------------------------------------- ;; Access Token ;; ------------------------------------------------------------------------- (defvar +token-lifetime+ (* 12 3600)) (defclass+ access-token () ((timestamp :host local :initform (get-universal-time) :accessor access-token.timestamp) (token :host local :initform (random-string 8) :accessor access-token.token) (association :host local :initform (error "Provide :association") :accessor access-token.association) (session-id :host local :initform (error "Provide :session-id") :accessor access-token.session-id)) (:ctor make-access-token)) (defmethod access-token.expired-p ((self access-token)) (with-slots (timestamp) self (if (> (get-universal-time) (+ timestamp +token-lifetime+)) t))) ;; (deftransaction user.update-from-facebook ((self database) (user user) ;; (data jobject)) ;; (with-attributes (id) data ;; (let ((account (any (lambda (account) ;; (and (typep account 'facebook-account) ;; (equal (account.account-id account) id) ;; account)) ;; (user.accounts user)))) ;; (if (null account) ;; (error "No Facebook account found for ~A, Data: ~A" user data)) ;; (prog1 user (facebook-account.update-from-jobject self account data))))) ;; ;; ------------------------------------------------------------------------- ;; ;; Manager Users ;; ;; ------------------------------------------------------------------------- ;; (defcomponent manager-user (simple-user remote-reference) ;; ((username :host both :print t :index t :accessor manager-user.username ;; :documentation "Manager Username") ;; (password :host local :export nil :accessor manager-user.password ;; :documentation "Manager Password") ;; (creation-timestamp :host both :type integer :initform (get-universal-time) ;; :documentation "Creation timestamp")) ;; (:ctor make-manager-user)) ;; (defcrud manager-user) ;; ;; ------------------------------------------------------------------------- ;; ;; Site Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent site (object-with-id) ;; ((fqdn :host both :print t :documentation "FQDN of remote site" :index t ;; :type string) ;; (owner :host both :type manager-user :initform (error "Provide :owner") ;; :documentation "Owner of this site") ;; (creation-timestamp :host both :type integer :initform (get-universal-time) ;; :documentation "Creation timestamp of this site")) ;; (:ctor make-site)) ;; (defmethod/remote init ((self site)) ;; (setf (owner self) (make-component (owner self)))) ;; ;; ------------------------------------------------------------------------- ;; ;; Account Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent account (object-with-id) ;; ((user :host local :type user :relation accounts :export nil ;; :documentation "Associated coretal4-user to this account")) ;; (:ctor make-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; Local Account Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent local-account (account) ;; ((email :host local :print t :index t ;; :documentation "Email address of the local account") ;; (password :host local :print t ;; :documentation "Password of the local account")) ;; (:ctor make-local-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; External Account Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent external-account (account) ;; ((username :host local :print t :index t ;; :documentation "Username associated to account") ;; (token :host local :export nil ;; :documentation "Token associated to this account")) ;; (:ctor make-external-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; Facebook Account Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent fb-account (external-account) ;; () ;; (:ctor make-fb-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; Google Account ;; ;; ------------------------------------------------------------------------- ;; (defcomponent google-account (external-account) ;; () ;; (:ctor make-google-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; Twitter Account ;; ;; ------------------------------------------------------------------------- ;; (defcomponent twitter-account (external-account) ;; () ;; (:ctor make-twitter-account)) ;; ;; ------------------------------------------------------------------------- ;; ;; User Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent user (object-with-id) ;; ((accounts :host both :type account* :relation user ;; :documentation "Associated accounts to this user") ;; (profiles :host both :type profile* :relation account ;; :documentation "Associated profiles to this account") ;; (default-profile :host both :type profile ;; :documentation "Default profile of this account") ;; (associations :host both :type profile-association* :relation user ;; :documentation "Profile associations")) ;; (:ctor make-user)) ;; ;; ------------------------------------------------------------------------- ;; ;; Profile Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent profile (object-with-id) ;; ((email :host both :print t :index t :documentation "User Profile Email") ;; (name :host both :print t :documentation "Name of this profile (ie Google)") ;; (visible-name :host both :documentation "Visible name") ;; (avatar :host both :documentation "Avatar URL of this profile") ;; (account :host both :type account :relation profiles ;; :documentation "Associated account to this profile")) ;; (:ctor make-profile)) ;; ;; ------------------------------------------------------------------------- ;; ;; Profile Association Definition ;; ;; ------------------------------------------------------------------------- ;; (defcomponent profile-association (object-with-id) ;; ((site :host both :print t :type site ;; :documentation "Site that this profile is associated with") ;; (profile :host both :print t :type profile ;; :documentation "Profile that this association points to") ;; (user :host both :print t :type user :relation associations ;; :documentation "Owner account of this association")) ;; (:ctor make-profile-association)) ;; ;; ------------------------------------------------------------------------- ;; ;; CRUD Definitions ;; ;; ------------------------------------------------------------------------- ;; (defcrud site) ;; (defcrud account) ;; (defcrud fb-account) ;; (defcrud google-account) ;; (defcrud twitter-account) ;; (defcrud profile) ;; (defcrud profile-association) ;; (defcrud user)
14,745
Common Lisp
.lisp
312
45.134615
83
0.501946
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e51caa2b65ac0ce66d5fda401b8018ee3298863faaac2ea1e410e6b790374594
8,271
[ -1 ]
8,272
dynamic.lisp
evrim_core-server/src/manager/src/dynamic.lisp
(in-package :manager) (defclass+ dynamic-application+ (dynamic-class+ http-application+) ()) ;; ------------------------------------------------------------------------- ;; Applications Generated by Manager ;; ------------------------------------------------------------------------- (defclass+ dynamic-application (web-application persistent-application) () (:metaclass dynamic-application+) (:default-initargs :database-directory nil)) (defprint-object (self dynamic-application :identity t) (format t "~A" (web-application.fqdn self))) (defparameter +superclasses+ '(http-application database-server)) (defmethod dynamic-application.superclasses ((self dynamic-application)) (reduce0 (lambda (acc atom) (if (member (class-name atom) +superclasses+) (cons (symbol->js (class-name atom)) acc) acc)) (reverse (class+.superclasses (class-of self))))) (defmethod core-server::database.directory ((application dynamic-application)) (ensure-directories-exist (merge-pathnames (make-pathname :directory (list :relative "var" (web-application.fqdn application) "db")) (bootstrap::home)))) (defcrud dynamic-application) (defmethod dynamic-application.find-class ((self persistent-server) class) (find-class (find class +superclasses+ :key #'symbol->js :test #'equal))) (deftransaction dynamic-application.change-class ((self persistent-server) (instance dynamic-application) new-superclasses) (let* ((supers (cons (find-class 'dynamic-application) (mapcar (curry #'dynamic-application.find-class self) new-superclasses))) ;; (args (reduce0 (lambda (acc slot) ;; (core-server::with-slotdef (initarg name) slot ;; (cons initarg ;; (cons (slot-value instance name) acc)))) ;; (reverse (class+.local-slots (class-of instance))))) (metaclass (find-class 'dynamic-application+))) (unregister self instance) (stop instance) (change-class instance (make-instance metaclass :name 'dynamic-application :direct-superclasses supers)) (start instance) (register self instance)))
2,121
Common Lisp
.lisp
47
41.042553
78
0.664248
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5cb81632e6a80f5d597dc106ae8f52d3cf3cf2d316de13370ee03bc10933f490
8,272
[ -1 ]
8,273
auth.lisp
evrim_core-server/src/manager/src/auth.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Authentication Controller ;; ------------------------------------------------------------------------- (defmethod/cc make-auth-controller/anonymous ((self manager-application) &key (page "login") error-message) (<core:simple-controller :default-page page (<core:simple-page :name "login" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Would you like to have a new account?" (<:a :class "pad5" :href "#page:register" "Sign Up")))) (<core:simple-widget-map :selector "middle" :widget (<manager:login)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "register" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Already have an account?" (<:a :class "pad5" :href "#page:login" "Sign In")))) (<core:simple-widget-map :selector "middle" :widget (<manager:registration)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "error" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Would you like to have a new account?" (<:a :class "pad5" :href "#page:register" "Sign Up")))) (<core:simple-widget-map :selector "middle" :widget (<manager:authentication-error :message error-message))))) (defmethod/cc make-auth-controller/user ((self manager-application) (account account) (realm realm)) (<core:simple-controller :default-page "accounts" (<core:simple-page :name "accounts" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "You are about to login to " (realm.fqdn realm) "."))) (<core:simple-widget-map :selector "middle" :widget (<manager:accounts :default-account account)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))))) (defmethod make-oauth-answer-uri ((self manager-application) (provider symbol)) (let ((url (manager.oauth-uri self))) (setf (uri.queries url) `(("action" . "answer") ("provider" . ,(symbol->js provider)))) url)) ;; http://node1.coretal.net:8080/auth.core?mode=return&type=facebook&code=CODE#_=_ ;; http://localhost:8080/auth.core?action=login&return-to=http%3A%2F%2Fnode1.coretal.net%3A8080%2Fauthentication%2Fauth.core (defmethod make-oauth-uri ((self manager-application) (provider symbol) (state string)) (let ((credentials (database.get self (make-keyword provider)))) (when credentials (case provider (facebook (with-slots (app-id) credentials (<fb:oauth-uri :client-id app-id :redirect-uri (make-oauth-answer-uri self provider) :state state))) (google (with-slots (client-id client-secret) credentials (<google:oauth-uri :client-id client-id :redirect-uri (make-oauth-answer-uri self provider) :state state))) (twitter (with-slots (consumer-key consumer-secret) credentials (let ((callback (make-oauth-answer-uri self provider))) (uri.add-query callback "state" state) (let ((token (<twitter:get-request-token :callback callback :consumer-key consumer-key :consumer-secret consumer-secret))) (setf (gethash (<oauth1:request-token.token token) (manager.request-token-cache self)) token) (<twitter:authorize-url :token token))))))))) (defmethod find-oauth1-account ((self manager-application) (provider symbol) (token string) (verifier string)) (case provider (twitter (let ((credentials (database.get self (make-keyword provider)))) (with-slots (consumer-key consumer-secret) credentials (let ((req-token (gethash token (manager.request-token-cache self)))) (cond ((null req-token) (error "Twitter request token not found: ~A, verifier: ~A" token verifier)) (t (let* ((access-token (<twitter:get-access-token :verifier verifier :consumer-key consumer-key :consumer-secret consumer-secret :request-token req-token)) (twitter-id (<twitter:access-token.user-id access-token)) (screen-name (<twitter:access-token.screen-name access-token)) (twitter-user (<twitter:secure-get-user :token access-token :consumer-key consumer-key :consumer-secret consumer-secret :screen-name screen-name)) (account (twitter-account.find self :account-id twitter-id))) (remhash token (manager.request-token-cache self)) (if account account (multiple-value-bind (user account) (user.add-from-twitter self twitter-user) (declare (ignore user)) account))))))))))) (defmethod manager.get-oauth2-user ((self manager-application) (provider (eql 'facebook)) (code string)) (with-slots (app-id app-secret) (database.get self :facebook) (<fb:me :token (<fb:get-access-token :client-id app-id :client-secret app-secret :code code :redirect-uri (make-oauth-answer-uri self 'facebook))))) (defmethod manager.get-oauth2-user ((self manager-application) (provider (eql 'google)) (code string)) (with-slots (client-id client-secret) (database.get self :google) (<google:userinfo :token (<google:get-access-token :client-id client-id :client-secret client-secret :code code :redirect-uri (make-oauth-answer-uri self 'google))))) (defmethod manager.get-oauth1-user ((self manager-application) (provider (eql 'twitter)) (req-token <oauth1:request-token) (token string) (verifier string)) (with-slots (consumer-key consumer-secret) (database.get self :twitter) (let* ((access-token (<twitter:get-access-token :verifier verifier :consumer-key consumer-key :consumer-secret consumer-secret :request-token req-token)) (twitter-id (<twitter:access-token.user-id access-token))) (<twitter:secure-get-user :token access-token :consumer-key consumer-key :consumer-secret consumer-secret :user-id twitter-id)))) (defmethod manager.create-oauth2-account ((self manager-application) (provider symbol) (code string)) (let ((credentials (database.get self (make-keyword provider)))) (case provider (facebook (with-slots (app-id app-secret) credentials (let* ((url (make-oauth-answer-uri self 'facebook)) (token (<fb:get-access-token :client-id app-id :client-secret app-secret :code code :redirect-uri url)) (fb-user (<fb:me :token token)) (facebook-id (get-attribute fb-user :id)) (account (facebook-account.find self :account-id facebook-id))) (aif account account (multiple-value-bind (user account) (user.add-from-facebook self fb-user) (declare (ignore user)) account))))) (google (with-slots (client-id client-secret) credentials (let* ((url (make-oauth-answer-uri self 'google)) (token (<google:get-access-token :client-id client-id :client-secret client-secret :code code :redirect-uri url)) (google-user (<google:userinfo :token token)) (google-id (get-attribute google-user :id)) (account (google-account.find self :account-id google-id))) (aif (google-account.find self :account-id google-id) account (multiple-value-bind (user account) (user.add-from-google self google-user) (declare (ignore user)) account)))))))) (defmethod manager.add-oauth2-account ((self manager-application) (provider symbol) (code string)) (let ((credentials (database.get self (make-keyword provider)))) (case provider (facebook (with-slots (app-id app-secret) credentials (let* ((url (make-oauth-answer-uri self 'facebook)) (token (<fb:get-access-token :client-id app-id :client-secret app-secret :code code :redirect-uri url)) (fb-user (<fb:me :token token)) (facebook-id (get-attribute fb-user :id)) (account (facebook-account.find self :account-id facebook-id))) (aif account account (multiple-value-bind (user account) (user.add-from-facebook self fb-user) (declare (ignore user)) account))))) (google (with-slots (client-id client-secret) credentials (let* ((url (make-oauth-answer-uri self 'google)) (token (<google:get-access-token :client-id client-id :client-secret client-secret :code code :redirect-uri url)) (google-user (<google:userinfo :token token)) (google-id (get-attribute google-user :id)) (account (google-account.find self :account-id google-id))) (aif (google-account.find self :account-id google-id) account (multiple-value-bind (user account) (user.add-from-google self google-user) (declare (ignore user)) account)))))))) ;; ------------------------------------------------------------------------- ;; Authentication Controller ;; ------------------------------------------------------------------------- (defhandler "auth\.core" ((self manager-application)) (flet ((find-realm (return-to) (let ((url (uri? (make-core-stream return-to)))) (if url (realm.find self :fqdn (uri.server url)))))) (let* ((request (context.request +context+)) (referer (or (http-request.header request 'referer) (make-uri))) (action (or (uri.query referer "action") "login")) (return-to (uri.query referer "return-to")) (realm (find-realm return-to))) (labels ((handle-action (component action &rest args) (declare (ignore component)) (case action (:login (destructuring-bind (provider) args (case provider ((facebook google) (let ((k-url (action/hash ((code "code")) (send/user (setf (query-session :account) (find-oauth2-account self provider code)))))) (continue/js (make-oauth-uri self provider k-url)))) ((yahoo twitter) (let ((k-url (action/hash ((token "oauth_token") (verifier "oauth_verifier")) (send/user (setf (query-session :account) (find-oauth1-account self provider token verifier)))))) (continue/js (make-oauth-uri self provider k-url)))) (t (send/anonymous "error" (format nil "Unknown provider ~A (3)" provider)))))) (:use (destructuring-bind (account) args (let* ((session-id (session.id (context.session +context+))) (access-token (or (query-session :token) (setf (query-session :token) (manager.create-token self realm account session-id))))) (with-slots (token) access-token (continue/js (jambda (self) (setf (slot-value window 'location) (+ return-to "?token=" token)))))))))) (send/user (account) (apply #'handle-action (javascript/suspend (lambda (stream) (let* ((kontroller (make-auth-controller/user self account realm)) (kontroller (authorize self (account.user account) kontroller))) (rebinding-js/cc (kontroller) stream (setf (slot-value window 'controller) (kontroller nil)))))))) (send/anonymous (page &optional error) (apply #'handle-action (javascript/suspend (lambda (stream) (let* ((kontroller (make-auth-controller/anonymous self :page page :error-message error)) (kontroller (authorize self (make-anonymous-user) kontroller))) (rebinding-js/cc (kontroller) stream (setf (slot-value window 'controller) (kontroller nil))))))))) (cond ((equal action "answer") ;; Redirect to exact continuation + avoid CSRF (let ((state (uri.query referer "state")) (url (http-request.uri request))) (uri.add-query url +continuation-query-name+ state) (mapcar (lambda (param) (aif (uri.query referer param) (uri.add-query url param it))) '("code" "provider" "oauth_token" "oauth_verifier")) (send/redirect (uri->string url)))) ((null realm) (send/anonymous "error" "Sorry, realm not found. (3)")) ((null return-to) ;; Show Error Message (send/anonymous "error" "Sorry, return-to is missing. (1)")) ((query-session :account) (send/user (query-session :account))) (t (send/anonymous action nil))))))) ;; http://node1.coretal.net:8080/auth.core?action=answer&provider=facebook&return-to=http%3A%2F%2Flocalhost%3A8080%2Fauthentication%2Fauth.core&code=AQBbuPsNJLwAvLrd7VgD-zpPlthxpIf4is3VsgBd-VHC6dIGQ8J7Fw9o3-zjrYmTpI9XgKZO62oFkhrK_CYQQajN14mzrfaotncX_KLBhykz3kMe_VpnWbrDcou0c0c9Ew4MWN4E-pHyCBz9fT_ysspl032fsY8oR-UFYYym_1nE4gcIrcZQjF6bNss5UDI9_4A#_=_ ;; https://www.facebook.com/dialog/oauth?client_id=162577700491917&response-type=token&display=popup&scope=email&redirect_uri=http%3A%2F%2Fnode1%2Ecoretal%2Enet%3A8080%2Fauth%2Ecore%3Faction%3Danswer%26provider%3Dfacebook%26return%2Dto%3Dhttp%253A%252F%252Flocalhost%253A8080%252Fauthentication%252Fauth%252Ecore ;; (let ((account ;; (javascript/suspend ;; (lambda (stream) ;; (let* ((k-url ;; (action/hash ((provider "provider") (code "code") ;; (token "oauth_token") ;; (verifier "oauth_verifier")) ;; (let* ((provider (find-provider-symbol provider)) ;; (account ;; (case provider ;; ((or facebook google) ;; (find-oauth2-account self provider code)) ;; (twitter ;; (find-oauth1-account self provider ;; token verifier))))) ;; (answer ;; (or account ;; (send/anonymous "error" ;; "Sorry, user not found. (2)")))))) ;; (kontroller ;; (make-auth-controller/anonymous self :page page :state k-url ;; :error-message error)) ;; (kontroller ;; (authorize self (make-anonymous-user) kontroller))) ;; (rebinding-js/cc (kontroller) stream ;; (setf (slot-value window 'controller) (kontroller nil)))))))) ;; (setf (query-session :user) (account.user account)) ;; (send/user account))
14,566
Common Lisp
.lisp
325
38.772308
348
0.643656
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
31ac8d290f836f46dabc99eafcdd53a896546fd3764af4d7fe39cfb14f986d6b
8,273
[ -1 ]
8,274
application.lisp
evrim_core-server/src/manager/src/application.lisp
;; ------------------------------------------------------------------------- ;; Manager Application ;; ------------------------------------------------------------------------- (in-package :manager) (defapplication manager-application (root-web-application-mixin http-application database-server logger-server serializable-web-application) ((token-cache :accessor manager.token-cache :initform (make-hash-table :test #'equal :synchronized t))) (:default-initargs :database-directory (merge-pathnames (make-pathname :directory '(:relative "var" "localhost" "db")) (tr.gen.core.server.bootstrap:home)) :db-auto-start t :fqdn "localhost" :admin-email "root@localhost" :project-name "manager" :project-pathname #p"/home/aycan/core-server/projects/manager/" :htdocs-pathname (make-project-path "manager" "wwwroot"))) (defmethod web-application.password-of ((self manager-application) (user string)) (aif (admin.find self :username user) (admin.password it))) (defmethod web-application.find-user ((self manager-application) (user string)) (admin.find self :username user)) (defmethod manager.oauth-uri ((self manager-application)) (let ((server (application.server self))) (make-uri :scheme "http" :server (web-application.fqdn self) :port (core-server::socket-server.port server) :paths '(("oauth.html"))))) (defmethod manager.api-uri ((self manager-application)) (let ((server (application.server self))) (make-uri :scheme "http" :server (web-application.fqdn self) :port (core-server::socket-server.port server) :paths '(("api"))))) ;; ------------------------------------------------------------------------- ;; Access Token Interface ;; ------------------------------------------------------------------------- (defmethod manager.remove-token ((self manager-application) (token access-token)) (remhash (access-token.token token) (manager.token-cache self))) (defmethod manager.gc-tokens ((self manager-application)) (let ((cache (manager.token-cache self))) (prog1 cache (maphash (lambda (key access-token) (if (access-token.expired-p access-token) (remhash key cache))) (manager.token-cache self))))) (defmethod manager.create-token ((self manager-application) (realm realm) (account account) (session-id string)) ;; Garbage Collect First (when (> (random 100) 40) (manager.gc-tokens self)) ;; Create Access Token (let ((association (or (account-association.find self :realm realm :account account) (account-association.add self :realm realm :account account)))) (let ((access-token (make-access-token :association association :session-id session-id))) (with-slots (token) access-token (setf (gethash token (manager.token-cache self)) access-token) access-token)))) (deftransaction facebook-account.update-from-jobject ((self database) (account facebook-account) (data jobject)) (with-attributes (updated_time verified locale timezone email location gender link first_name last_name name username) data (facebook-account.update self account :name name :username username :first-name first_name :last-name last_name :email email :verified verified :last-update updated_time :timezone timezone :locale locale :location location :gender gender :link link))) (deftransaction facebook-account.add-from-jobject ((self database) (data jobject)) (with-attributes (id) data (let ((account (facebook-account.add self :account-id id))) (facebook-account.update-from-jobject self account data)))) (deftransaction twitter-account.update-from-jobject ((self database) (account twitter-account) (data jobject)) (with-attributes (lang verified geo_enabled time_zone utc_offset created_at protected description url location screen_name name) data (twitter-account.update self account :lang lang :verified verified :geo-enabled geo_enabled :time-zone time_zone :utc-offset utc_offset :created-at created_at :protected protected :description description :url url :location location :screen-name screen_name :name name :last-update (get-universal-time)))) (deftransaction twitter-account.add-from-jobject ((self database) (data jobject)) (with-attributes (id_str) data (let ((account (twitter-account.add self :account-id id_str))) (twitter-account.update-from-jobject self account data)))) (deftransaction google-account.update-from-jobject ((self database) (account google-account) (data jobject)) (with-attributes (locale gender picture link family_name given_name name verified_email email last-update) data (google-account.update self account :locale locale :gender gender :picture picture :link link :last-name family_name :first-name given_name :name name :verified verified_email :email email :last-update last-update))) (deftransaction google-account.add-from-jobject ((self database) (data jobject)) (with-attributes (id) data (let ((account (google-account.add self :account-id id))) (google-account.update-from-jobject self account data)))) (deftransaction user.register ((self database) &key name email password (timestamp (get-universal-time))) (let ((local-account (local-account.add self :password password :name name :email email :last-update timestamp))) (values (user.add self :accounts (list local-account) :group (simple-group.find self :name "user")) local-account))) ;; ------------------------------------------------------------------------- ;; Sendmail ;; ------------------------------------------------------------------------- (defmethod manager.sendmail ((self manager-application) to subject body) (sendmail (application.server self) (format nil "no-reply@~A" (web-application.fqdn self)) to (format nil "[Core-serveR] ~A" subject) (<:html (<:head (<:meta :http--equiv "content-type" :content "text/html; charset=utf-8") (<:title "[Core serveR] - " subject)) (<:body (<:h1 "[Core Server]") (<:h2 subject) (<:p "Dear Sir/Madam,") body (<:p :class "footer" "--" (<:br) "Kind regards," (<:br) "Core Server Team " (let ((email (format nil "info@~A" (web-application.fqdn self)))) (<:a :href (concatenate 'string "mailto:" email) (concatenate 'string "&lt;" email "&gt;")))))) nil nil "[Core-serveR]")) (defmethod manager.send-password-recovery-email ((self manager-application) email url) (manager.sendmail self email "Password Recovery" (list (<:p "You declared that you have just lost your password. " "To recover your password please click the link below.") (<:p (<:a :href (typecase url (uri (uri->string url)) (string url)) "Recover Password"))))) ;; ------------------------------------------------------------------------- ;; Init Database ;; ------------------------------------------------------------------------- (defmethod init-database ((self manager-application)) (assert (null (database.get self 'initialized))) (setf (database.get self 'api-secret) (random-string)) (let ((group (simple-group.add self :name "admin"))) (admin.add self :name "Root User" :username "root" :password "core-server" :owner nil :group group)) (simple-group.add self :name "user") (setf (database.get self 'initialized) t) self) ;; ------------------------------------------------------------------------- ;; Server API Hook ;; ------------------------------------------------------------------------- (defmethod start ((self manager-application)) (if (not (database.get self 'initialized)) (prog1 t (init-database self)) nil)) (defun hostname () #+sbcl (sb-unix:unix-gethostname) #-sbcl "N/A") (defun core-server-version () (slot-value (asdf::find-system "core-server") 'asdf::version)) ;; (deftransaction user.add-from-twitter ((self database) (data jobject)) ;; (with-attributes (id_str) data ;; (aif (twitter-account.find self :account-id id_str) ;; (error "User already exists ~A, Data: ~A" it data)) ;; (let ((account (twitter-account.add-from-jobject self data))) ;; (values (user.add self ;; :accounts (list account) ;; :group (simple-group.find self :name "user")) ;; account)))) ;; (deftransaction user.add-from-google ((self database) (data jobject)) ;; (with-attributes (id) data ;; (aif (google-account.find self :account-id id) ;; (error "Google account already exists ~A, Data: ~A" it data)) ;; (let ((account (google-account.add-from-jobject self data))) ;; (values (user.add self ;; :accounts (list account) ;; :group (simple-group.find self :name "user")) ;; account)))) ;; (deftransaction user.add-from-facebook ((self database) (data jobject)) ;; (with-attributes (id) data ;; (aif (facebook-account.find self :account-id id) ;; (error "User already exists ~A, Data: ~A" it data)) ;; (let ((account (facebook-account.add-from-jobject self data))) ;; (values (user.add self ;; :accounts (list account) ;; :group (simple-group.find self :name "user")) ;; account))))
9,522
Common Lisp
.lisp
219
38.625571
86
0.623207
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5ddd20d5b033468762e9d6456ab3b654926d61f030f883f101270d5341bda9e4
8,274
[ -1 ]
8,275
packages.lisp
evrim_core-server/src/manager/src/packages.lisp
(in-package :cl-user) (defpackage :tr.gen.core.manager (:nicknames :manager) (:import-from #:core-server #:host #:port #:peers-max #:peer-class #:protocol #:username #:password #:mail-port #+ssl #:ssl #:server) (:use :common-lisp :core-server :arnesi) (:export #:manager-web-application-mixin #:web-application.oauth-uri #:web-application.oauth-handler-uri #:web-application.api-uri #:dynamic-application+ #:dynamic-application)) (defpackage :tr.gen.core.manager.widget (:nicknames :<manager) (:export #:controller ;; Info #:server-info/crud #:server-info ;; Server #:server #:server/crud ;; Socket #:socket-server/crud #:socket-server ;; Database #:database-server/crud #:database-server ;; Mail Sender #:mail-sender/crud #:mail-sender ;; Applications #:application/table #:web-application/crud #:applications #:application-crud #:dynamic-application-crud ;; Sites #:sites #:site/table #:site/crud ;; Administrators #:admin/table #:admin/crud #:administrators ;; Settings #:settings ;; Auth #:login #:registration #:authentication-error #:recover-password #:forgot-password ;; Login Link #:login-link #:login-link/anonymous #:login-link/registered ;; Account #:accounts #:accounts/anonymous #:accounts/registered ;; Plugin #:authentication-plugin #:authentication-plugin/anonymous #:authentication-plugin/user ;; API Client #:realm.list #:realm.add #:realm.update #:realm.delete )) ;; ------------------------------------------------------------------------- ;; A Namespace for API Calls ;; ------------------------------------------------------------------------- (defpackage :<core-server (:nicknames :tr.gen.core.server.markup :core-server.markup) (:use :core-server) (:export #:markup #:markup+ #:response #:error #:login #:logout #:authentication #:user ))
2,048
Common Lisp
.lisp
77
21.896104
76
0.608651
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3c76f88f211e5adb60fb239ba9965e170528c288e0d6faf553c94311fcbdbe6e
8,275
[ -1 ]
8,276
init.lisp
evrim_core-server/src/manager/src/init.lisp
(in-package :manager) ;; +------------------------------------------------------------------------- ;; | Manager Instance ;; +------------------------------------------------------------------------- (defun register-me (&optional (server *server*)) (if (null (status *app*)) (start *app*)) (register server *app*)) (defun unregister-me (&optional (server *server*)) (unregister server *app*)) (defvar *app* (make-instance 'manager-application))
455
Common Lisp
.lisp
10
43.5
77
0.455782
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7c3feec904281d95db1dc8a2016f3a23d09468255082da4251ce5d1996c35934
8,276
[ -1 ]
8,277
server.lisp
evrim_core-server/src/manager/src/ui/server.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Server Crud ;; ------------------------------------------------------------------------- (defwebcrud <manager:server/crud () ((name :label "Server Name") (hostname :label "Hostname") (memory :label "Memory Usage") (date :label "Server Timestamp" :remote-type timestamp) (auto-start :label "Autostart?" :remote-type checkbox) (debug :label "In debug mode?" :remote-type checkbox)) (:default-intiargs :title "Server Info" :editable-p nil :deletable-p nil)) ;; ------------------------------------------------------------------------- ;; Info Component ;; ------------------------------------------------------------------------- (defcomponent <manager:server (<widget:simple) ((crud :host remote :initform (<manager:server/crud)) (_tab :host remote :initform (<core:tab)))) (defmethod/local get-server-info ((self <manager:server)) (let ((server (application.server application))) (with-slots (name auto-start debug) server (jobject :name name :hostname (hostname) :memory (format nil "~10:D MB" (sb-kernel::dynamic-usage)) :date (get-universal-time) :auto-start auto-start :debug debug)))) (defmethod/cc get-server-tab ((self <manager:server) class) (let ((server (application.server (component.application self)))) (case class (socket-server (let ((_server (<manager:socket-server :server server))) (list "Socket Server" (<manager:socket-server/crud :instance _server)))) (database-server (let ((_server (<manager:database-server :server server))) (list "Database Server" (<manager:database-server/crud :instance _server)))) (mail-sender (let ((_server (<manager:mail-sender :server server))) (list "Mail Gateway" (<manager:mail-sender/crud :instance _server))))))) (defmethod/local get-server-tabs ((self <manager:server)) (let ((server (application.server application))) (remove-if #'null (mapcar (lambda (class) (get-server-tab self class)) (mapcar #'class-name (class+.superclasses (class-of server))))))) (defmethod/remote init ((self <manager:server)) (call-next-method self) (append self (make-component (crud self) :instance (get-server-info self))) (append self (make-component (_tab self) :tabs (mapcar-cc (lambda (c) (destructuring-bind (a b) c (list a (make-component b)))) (get-server-tabs self)) :tab-title "Capabilities")))
2,582
Common Lisp
.lisp
57
40.070175
77
0.585385
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fc17ee06721351a128e9e22b87ef8398ca2f770f89ad6013e51c3bf8cd8caebe
8,277
[ -1 ]
8,278
old.lisp
evrim_core-server/src/manager/src/ui/old.lisp
;; (defun make-css (css-list) ;; (apply #'concatenate 'string (mapcar #'dom2string css-list))) ;; ;; generate a css string compile time ;; (defparameter *css* ;; (make-css ;; (list (css "body" :font-family "verdana, sans-serif") ;; (css "#footer" :font-size "80%" :margin "2em auto" :width "60em") ;; (css ".chapter" :margin-left "auto" ;; :margin-right "auto" :width "50em") ;; (css "code, pre" :font-family "monospace" :font-weight "normal") ;; (css ".path" :color "#448844") ;; (css "div.sysinfo" ;; :background "#FFFFC9 none repeat scroll 0 0" ;; :padding "1em" ;; :border "1px solid #B4BAEA")))) ;; (defvar *cslink* (<:a :href "http://labs.core.gen.tr" "Core Server")) ;; (defvar *examples* ;; (<:code :class "path" (format nil "~A" (bootstrap:in-home #P"examples/")))) ;; (defvar *header* (<:div :id "header")) ;; (defvar *footer* ;; (<:div :id "footer" ;; (<:hr) ;; (<:p (<:a :href "http://labs.core.gen.tr" (format nil "Core Server ~A" (core-server-version))) ;; " | " ;; (format nil "~A ~A" (lisp-implementation-type) ;; (lisp-implementation-version))))) ;; (defun box (summary body) ;; (<:div :class "box" ;; (<:table :border "0" :summary summary ;; (<:tbody ;; (<:tr ;; (<:td :align "center" :width "25" :valign "top" :rowspan "2" ;; (<:img :src "images/note.png" :alt "info icon")) ;; (<:th :align "left" summary)) ;; (<:tr ;; (<:td :align "left" :valign "top" ;; body)))))) ;; (defun/cc page (body) ;; (<:html ;; (<:head ;; (<:title "Core Server Manager") ;; (<:meta :http--equiv "Content-Type" :content "text/html; charset=utf-8") ;; (<:style :type "text/css" *css*)) ;; (<:body ;; *header* ;; (<:div :class "chapter" ;; body) ;; *footer*))) ;; (defun/cc main () ;; (page ;; (<:div :id "content" ;; (<:div :id "introduction" ;; (<:h1 "Core Server Manager") ;; (<:p *cslink* " is an application server written in Common Lisp. You can find sample applications at " *examples* ".")) ;; (<:div :class "sysinfo" ;; (box "System Information" (<:p (format nil "Hostname: ~A" (hostname)))))))) ;; (defhandler "manager" ((self manager-application)) ;; (main))
2,275
Common Lisp
.lisp
58
38.12069
129
0.555405
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fd87184d7d9818ebbc523609e2b43c6a09febf334ed43f9dac67e24b98c6ea32
8,278
[ -1 ]
8,279
info.lisp
evrim_core-server/src/manager/src/ui/info.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Server Crud ;; ------------------------------------------------------------------------- (defwebcrud <manager:server-info/crud () ((name :label "Server Name") (hostname :label "Hostname") (memory :label "Memory Usage") (date :label "Server Timestamp" :remote-type timestamp) (apps :label "# of applications" :remote-type number) (auto-start :label "Autostart?" :remote-type checkbox) (debug :label "In debug mode?" :remote-type checkbox)) (:default-intiargs :title "Server Info" :editable-p nil :deletable-p nil)) ;; ------------------------------------------------------------------------- ;; Info Component ;; ------------------------------------------------------------------------- (defcomponent <manager:server-info (<widget:simple) ((crud :host remote :initform (<manager:server-info/crud)))) (defmethod/local get-server-info ((self <manager:server-info)) (let ((server (application.server application))) (with-slots (name auto-start debug) server (jobject :name name :hostname (hostname) :memory (format nil "~10:D MB" (sb-kernel::dynamic-usage)) :date (get-universal-time) :auto-start auto-start :debug debug :apps (length (server.applications server)))))) (defmethod/remote init ((self <manager:server-info)) (call-next-method self) (append self (make-component (crud self) :instance (get-server-info self))))
1,514
Common Lisp
.lisp
31
44.83871
78
0.553451
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0397036603833bb8d775def40cfe006ff0157bf646536600a85110bd296c20e6
8,279
[ -1 ]
8,280
settings.lisp
evrim_core-server/src/manager/src/ui/settings.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Crud's ;; ------------------------------------------------------------------------- (defwebcrud facebook-app-crud () ((app-id :label "Application ID") (app-secret :label "Application Secret")) (:default-initargs :title "Facebook Application Configuration")) (defwebcrud google-app-crud () ((client-id :label "Client ID") (client-secret :label "Client Secret")) (:default-initargs :title "Google API Configuration")) (defwebcrud twitter-app-crud () ((consumer-key :label "Consumer Key") (consumer-secret :label "Consumer Secret")) (:default-initargs :title "Twitter API Configuration")) (defwebcrud yahoo-app-crud () ((consumer-key :label "Consumer Key") (consumer-secret :label "Consumer Secret")) (:default-initargs :title "Yahoo API Configuration")) ;; ------------------------------------------------------------------------- ;; Settings Component ;; ------------------------------------------------------------------------- (defcomponent <manager:settings (<widget:tab) ((_facebook-crud :host remote :initform (facebook-app-crud)) (_google-crud :host remote :initform (google-app-crud)) (_twitter-crud :host remote :initform (twitter-app-crud)) (_yahoo-crud :host remote :initform (yahoo-app-crud))) (:default-initargs :tab-title "Server Settings" :tabs '("Facebook API" "Google API" "Twitter API" "Yahoo API"))) (defmethod/local get-config ((self <manager:settings) tab) (or (cond ((equal tab "Facebook API") (database.get application :facebook)) ((equal tab "Google API") (database.get application :google)) ((equal tab "Twitter API") (database.get application :twitter)) ((equal tab "Yahoo API") (database.get application :yahoo))) (jobject))) (defmethod/local save-config ((self <manager:settings) tab args) (cond ((equal tab "Facebook API") (setf (database.get application :facebook) (apply #'make-facebook-credentials (jobject.attributes args)))) ((equal tab "Google API") (setf (database.get application :google) (apply #'make-google-credentials (jobject.attributes args)))) ((equal tab "Twitter API") (setf (database.get application :twitter) (apply #'make-twitter-credentials (jobject.attributes args)))) ((equal tab "Yahoo API") (setf (database.get application :yahoo) (apply #'make-yahoo-credentials (jobject.attributes args)))))) (defmethod/local delete-config ((self <manager:settings) tab) (cond ((equal tab "Facebook API") (setf (database.get application :facebook) nil)) ((equal tab "Google API") (setf (database.get application :google) nil)) ((equal tab "Twitter API") (setf (database.get application :twitter) nil)) ((equal tab "Yahoo API") (setf (database.get application :yahoo) nil)))) (defmethod/remote core-server::make-tab ((self <manager:settings) tab) (let* ((_config (get-config self tab)) (_crud (cond ((eq tab "Facebook API") (make-component (_facebook-crud self) :instance _config)) ((eq tab "Google API") (make-component (_google-crud self) :instance _config)) ((eq tab "Twitter API") (make-component (_twitter-crud self) :instance _config)) ((eq tab "Yahoo API") (make-component (_yahoo-crud self) :instance _config))))) (make-web-thread (lambda () (destructuring-bind (action args) (call-component _crud) (cond ((eq action "update") (save-config self tab args)) ((eq action "delete") (delete-config self tab))) (show-tab self tab)))) _crud)) (defmethod/remote show-tab ((self <manager:settings) tab) (call-next-method self tab) ;; (let ((_tab (make-tab self tab))) ;; (with-slots (_content) self ;; (replace-node _content (setf (_content self) _tab)) ;; (call-next-method self tab))) ) (defmethod/remote init ((self <manager:settings)) (call-next-method self))
3,982
Common Lisp
.lisp
92
39.336957
76
0.631511
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
85efe6ee8ec4c7e1727eb4238cde3fdfdcb6626ed4117e3f0f6b16dff125d005
8,280
[ -1 ]
8,281
admin.lisp
evrim_core-server/src/manager/src/ui/admin.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Admin/Authorized ;; ------------------------------------------------------------------------- (defcomponent admin/authorized (secure-object/authorized admin remote-reference) ((secure-object :host lift :type admin) (username :lift t :host remote) (password :lift t :host remote) (name :lift t :host remote) (creation-timestamp :lift t :host remote))) (defcrud/lift admin/authorized admin) ;; ------------------------------------------------------------------------- ;; Admin Table ;; ------------------------------------------------------------------------- (deftable <manager:admin/table () ((name :label "Name") (username :label "Username") (creation-timestamp :label "Creation Timestamp" :remote-type timestamp))) ;; ------------------------------------------------------------------------- ;; Manager Users Crud ;; ------------------------------------------------------------------------- (defwebcrud <manager:admin/crud () ((name :label "Name") (username :label "Username" :read-only t) (password :label "Password" :remote-type password) (creation-timestamp :label "Creation Timestamp" :remote-type date :read-only t)) (:default-initargs :title "Administrative Account" :editable-p t :deletable-p t)) ;; ------------------------------------------------------------------------- ;; Sites Component ;; ------------------------------------------------------------------------- (defcomponent <manager:administrators (<core:table-with-crud <widget:simple) () (:default-initargs :table-title "Administrators" :table (<manager:admin/table) :crud (<manager:admin/crud) :input-element (<core:required-value-input :default-value "Enter username (ie root)"))) (defmethod/local get-instances ((self <manager:administrators)) (admin.list application)) (defmethod/local add-instance ((self <manager:administrators) username) (aif (admin.find application :username username) (make-web-error 'error "User %1 already exists." username) (admin.add application :username username :name username :group (simple-group.find application :name "admin") :owner (admin.find application :name "root")))) (defmethod/local delete-instance ((self <manager:administrators) (user admin)) (prog1 t (admin.delete application user))) (defmethod/local update-instance ((self <manager:administrators) (user admin) updates) (prog1 updates (apply #'admin.update application (cons user (jobject.attributes updates)))))
2,618
Common Lisp
.lisp
55
44.2
76
0.555817
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5f4c9db4f0ebb7bd75cfff66708520c14cc191347b77d23c9e5f40cd83f453d9
8,281
[ -1 ]
8,282
sites.lisp
evrim_core-server/src/manager/src/ui/sites.lisp
(in-package :manager) (defcomponent site/authorized (secure-object/authorized site remote-reference) ((secure-object :host lift :type site) (fqdn :host remote :lift t) (owner :host remote :lift t) (creation-timestamp :host remote :lift t))) (defcrud/lift site/authorized site) ;; ------------------------------------------------------------------------- ;; Sites Table ;; ------------------------------------------------------------------------- (deftable <manager:site/table () ((fqdn :label "FQDN") (owner :label "Owner" :reader (jambda (a) (slot-value (slot-value a 'owner) 'name))) (timestamp :label "Timestamp" :remote-type timestamp))) ;; ------------------------------------------------------------------------- ;; Site Crud ;; ------------------------------------------------------------------------- (defwebcrud <manager:site/crud () ((fqdn :label "FQDN") (api-key :label "API Key") (api-password :label "API Password") (owner :label "Owner" :reader (jambda (a) (let ((owner (slot-value a 'owner))) (with-slots (name username) owner (+ name " (" username ")"))))) (timestamp :label "Creation Timestamp" :remote-type timestamp)) (:default-initargs :title "Site" :editable-p nil :deletable-p t)) ;; ------------------------------------------------------------------------- ;; Sites Component ;; ------------------------------------------------------------------------- (defcomponent <manager:sites (<core:table-with-crud <widget:simple) () (:default-initargs :table-title "Sites" :table (<manager:site/table) :crud (<manager:site/crud) :input-element (<core:default-value-input :default-value "Enter site name (ie www.core.gen.tr)"))) (defmethod/local get-instances ((self <manager:sites)) (site.list application)) (defmethod/local add-instance ((self <manager:sites) fqdn) (site.add application :fqdn fqdn)) (defmethod/local delete-instance ((self <manager:sites) fqdn) (aif (site.find application :fqdn fqdn) (prog1 t (site.delete application it))))
2,081
Common Lisp
.lisp
48
39.8125
76
0.533333
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
5c58bc3231d1767032b4ac17402af10c424ae0429a59a9b0c3adbb9d357f7b84
8,282
[ -1 ]
8,283
controller.lisp
evrim_core-server/src/manager/src/ui/controller.lisp
;; +------------------------------------------------------------------------- ;; | Manager Application UI Main ;; +------------------------------------------------------------------------- (in-package :manager) ;; ------------------------------------------------------------------------- ;; Index Loop ;; ------------------------------------------------------------------------- (defmethod make-index-controller ((self manager-application)) (authorize self (make-anonymous-user) (<core:simple-controller :default-page "index" (<core:simple-page :name "index" (<core:simple-widget-map :selector "login" :widget (<core:login)) (<core:simple-widget-map :selector "clock" :widget (<core:simple-clock)))))) (defhandler "index\.core" ((self manager-application)) (destructuring-bind (username password) (javascript/suspend (lambda (stream) (let ((kontroller (make-index-controller self))) (rebinding-js/cc (kontroller) stream (kontroller nil))))) (continue/js (let ((admin (admin.find self :username username))) (cond ((and admin (equal (admin.password admin) password)) (prog1 (jambda (self) (setf (slot-value window 'location) "manager.html")) (update-session :user admin))) (t (jambda (self k) (k nil)))))))) ;; ------------------------------------------------------------------------- ;; Page & Widget Definitions ;; ------------------------------------------------------------------------- (defparameter +pages+ (list (list "info" "Info" "Information regarding to the current instance" (cons "content" (<manager:server-info))) (list "server" "Server" "Manage current core server instance" (cons "content" (<manager:server))) (list "apps" "Applications" "Applications currently deployed on this server" (cons "content" (<manager:applications))) ;; (list "aanda" "A & A" "Authentication & Authorization" ;; (cons "content" (<manager:sites))) (list "users" "Administrators" "Administrative accounts that manage this server instance" (cons "content" (<manager:administrators))) (list "settings" "Settings" "Settings related to the current server instance" (cons "content" (<manager:settings)))) "Simple Page & Widget Definitions") ;; ------------------------------------------------------------------------- ;; Make Page ;; ------------------------------------------------------------------------- (defmethod %make-page ((self manager-application) name title description &rest widgets) (<core:simple-page :name name (cons (<core:simple-widget-map :selector "title" :widget (<widget:simple-content (<:h1 title) (<:h2 description))) (mapcar (lambda (widget) (destructuring-bind (selector . widget) widget (<core:simple-widget-map :selector selector :widget widget))) widgets)))) (defmethod make-pages ((self manager-application) &optional (pages +pages+)) (mapcar (curry #'apply #'%make-page) (mapcar (curry #'cons self) pages))) ;; ------------------------------------------------------------------------- ;; Make Menu ;; ------------------------------------------------------------------------- (defun make-menu (&optional (pages +pages+)) (<core:simple-widget-map :selector "menu" :widget (<widget:simple-menu (mapcar (lambda (page) (jobject :name (car page) :title (cadr page))) pages)))) ;; ------------------------------------------------------------------------- ;; Make Clock ;; ------------------------------------------------------------------------- (defun make-clock () (<core:simple-widget-map :selector "clock" :widget (<core:simple-clock))) ;; ------------------------------------------------------------------------- ;; Manager Controller ;; ------------------------------------------------------------------------- (defcomponent <manager:controller (<core:simple-controller) () (:default-initargs :default-page "info")) ;; ------------------------------------------------------------------------- ;; Make Controller ;; ------------------------------------------------------------------------- (defmethod make-controller ((self manager-application) (user admin)) (authorize self user (<manager:controller :constants (list (make-menu +pages+) (make-clock)) (make-pages self +pages+)))) ;; ------------------------------------------------------------------------- ;; Main Manager Loop ;; ------------------------------------------------------------------------- (defhandler "manager\.core" ((self manager-application)) (javascript/suspend (lambda (stream) (aif (query-session :user) (let ((manager (if (application.debug self) (make-controller self it) (or (query-session :manager) (update-session :manager (make-controller self it)))))) (rebinding-js/cc (manager) stream (manager nil))) (with-js () stream ;; Unauthorized (setf window.location "index.html"))))))
5,077
Common Lisp
.lisp
112
40.758929
77
0.482027
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
71d50911200a256230bd33412104619aa7b0ddb578fd4edb2e31342c0db62267
8,283
[ -1 ]
8,284
application.lisp
evrim_core-server/src/manager/src/ui/application.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Application Table ;; ------------------------------------------------------------------------- (deftable <manager:application/table () ((fqdn :label "FQDN") (application-class :label "Application Class"))) ;; ------------------------------------------------------------------------- ;; Applications Component ;; ------------------------------------------------------------------------- (defcomponent <manager:applications (<core:table-with-crud <widget:simple) () (:default-initargs :table-title "Applications" :table (<manager:application/table) :crud (list (<manager:web-application/crud) (<manager:dynamic-application-crud)) :input-element (<core:fqdn-input))) (defmethod/local start-stop-app ((self <manager:applications) (app web-application/view)) (break (list 'start app))) (defmethod/local register-unregister-app ((self <manager:applications) (app web-application/view)) (break (list 'register app))) (defmethod/remote handle-crud ((self <manager:applications) instance action args) (if (eq action "start/stop") (start-stop-app self instance) (if (eq action "register/unregister") (register-unregister-app self instance) (call-next-method self instance action args)))) (defmethod/cc make-view ((self <manager:applications) (app dynamic-application)) (make-dynamic-application/view :application app)) (defmethod/cc make-view ((self <manager:applications) (app web-application)) (make-web-application/view :application app)) (defmethod/remote core-server::_make-crud-component ((self <manager:applications) instance) (make-component (if (slot-value instance 'type-name) (car (cdr (core-server::crud self))) (car (core-server::crud self))) :instance instance)) (defmethod/local get-instances ((self <manager:applications)) (mapcar (lambda (app) (make-view self app)) (server.applications (application.server application)))) (defmethod/local add-instance ((self <manager:applications) fqdn) (aif (find-application (application.server application) fqdn) (make-web-error 'error "FQDN %1 already exists." fqdn) (let ((new-application (make-instance 'dynamic-application :fqdn fqdn :admin-email "root@localhost"))) (register (application.server application) new-application) (make-view self new-application)))) (defmethod/local delete-instance ((self <manager:applications) (instance web-application/view)) (prog1 t (unregister (application.server application) (slot-value instance '%web-application)))) (defmethod/local update-instance ((self <manager:applications) (instance web-application/view) args) (jobject)) (defmethod/local update-instance ((self <manager:applications) (instance dynamic-application/view) args) (let* ((attributes (core-server::plist-to-alist (jobject.attributes args))) (supers (cdr (find 'application-superclasses attributes :key #'car :test #'string=))) (attributes (core-server::alist-to-plist (remove 'application-superclasses attributes :key #'car :test #'string=)))) (dynamic-application.change-class (application.server application) instance supers) (make-view self (apply #'dynamic-application.update (application.server application) (cons instance attributes))))) ;; (defmethod/local get-tabs ((self <manager:applications) ;; (instance web-application/view)) ;; nil) ;; (defmethod/local get-tabs ((self <manager:applications) ;; (instance dynamic-application/view)) ;; (let ((app (%web-application instance))) ;; (reduce0 (lambda (acc tab) ;; (cond ;; ((equal tab "httpApplication") ;; (cons (cons tab ;; (make-http-application/view ;; :http-application (%%web-application instance))) ;; acc)) ;; ((equal tab "databaseServer") ;; (cons (cons tab ;; (make-database-server/view ;; :database-server (%%web-application instance))) ;; acc)) ;; (t acc))) ;; (dynamic-application.superclasses instance)))) ;; (defmethod/remote core-server::_make-crud-component ((self <manager:applications) ;; instance) ;; (let* ((_crud (if (slot-value instance 'type-name) ;; (car (cdr (core-server::crud self))) ;; (car (core-server::crud self)))) ;; (_crud (make-component _crud :instance instance)) ;; (_tabs (get-tabs self instance))) ;; (when _tabs ;; (let ((_tab (make-component (_tab self) ;; :tabs (mapcar-cc ;; (lambda (tab) ;; (destructuring-bind (name c) tab ;; (cons name (make-component c)))) ;; _tabs) ;; :tab-title "Configuration"))) ;; (add-class _tab "pad5") ;; (append _crud _tab))) ;; _crud))
4,871
Common Lisp
.lisp
109
41.302752
84
0.637168
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f3b899da24a041074def6add27d24701d169d46586733bfb7dcf49dbbc90c8e5
8,284
[ -1 ]
8,285
http.lisp
evrim_core-server/src/manager/src/ui/applications/http.lisp
(in-package :manager) (deftable http-application-handlers-table () ((url :label "URL Regular Expression") (method :label "CLOS Method"))) (deftable http-application-security-handlers-table () ((url :label "URL Regular Expression") (method :label "CLOS Method") (authentication-type :label "Auth Type"))) ;; ------------------------------------------------------------------------- ;; HTTP Application / View ;; ------------------------------------------------------------------------- (defcomponent http-application/view (<core:tab) ((%http-application :host lift :type http-application :reader %%http-application :initarg :http-application) (handlers :host remote) (security-handlers :host remote) (_table :host remote :initform (http-application-handlers-table)) (_security-table :host remote :initform (http-application-security-handlers-table))) (:ctor %make-http-application/view) (:default-initargs :nav-alignment "right" :tab-title "HTTP Application")) (defun make-http-application/view (&key application) (flet ((to-symbols1 (handlers) (mapcar (lambda (a) (jobject :method (format nil "~A:~A" (package-name (symbol-package (car a))) (symbol-name (car a))) :url (cadr a))) handlers)) (to-symbols2 (handlers) (mapcar (lambda (a) (jobject :method (format nil "~A:~A" (package-name (symbol-package (car a))) (symbol-name (car a))) :url (cadr a) :authentication-type (symbol->js (car (reverse a))))) handlers))) (let ((handlers (http-application+.handlers (class-of application))) (s-handlers (core-server::http-application+.security-handlers (class-of application)))) (%make-http-application/view :http-application application :security-handlers (to-symbols2 s-handlers) :handlers (to-symbols1 handlers))))) (defmethod/remote init ((self http-application/view)) (setf (core-server::tabs self) (list (cons "handlers" (make-component (_table self) :instances (handlers self))) (cons "securityHandlers" (make-component (_security-table self) :instances (security-handlers self))))) (call-next-method self))
2,264
Common Lisp
.lisp
55
35.509091
76
0.621315
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1f5a1b8356b11c888312a3d3435b160054c30b60b05e15c2f7b2ac8f6bc16e72
8,285
[ -1 ]
8,286
dynamic.lisp
evrim_core-server/src/manager/src/ui/applications/dynamic.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Manager Created Application Crud ;; ------------------------------------------------------------------------- (defwebcrud <manager::%dynamic-application-crud (<manager:web-application/crud) ((fqdn :label "Domain Name") (application-class :label "Application Class" :read-only t) (application-superclasses :label "Superclasses" :remote-type core-server::multiple-checkbox :options (mapcar #'core-server::symbol-to-js +superclasses+)) (is-running :label "Is running?" :remote-type checkbox :read-only t) (is-registered :label "Is registered?" :remote-type checkbox :read-only t)) (:default-initargs :title "Application" :editable-p t :deletable-p t)) (defcomponent <manager:dynamic-application-crud (singleton-component-mixin <manager::%dynamic-application-crud) ()) ;; ------------------------------------------------------------------------- ;; Manager Created Application View ;; ------------------------------------------------------------------------- (defcomponent dynamic-application/view (web-application/view) ((%application :host lift :type dynamic-application :reader %application :initarg :application) (application-superclasses :host remote) (type-name :host remote :initform "dynamic-application")) (:ctor %make-dynamic-application/view)) (defcrud/lift dynamic-application/view dynamic-application) (defmethod/lift dynamic-application.change-class ((self persistent-server) (instance dynamic-application/view) new-superclasses)) (defmethod/lift dynamic-application.superclasses ((self dynamic-application/view))) (defun make-dynamic-application/view (&key application) (let ((class (symbol->js (class-name (class-of application)))) (registered-p (if (application.server application) t)) (supers (mapcar #'class-name (class+.superclasses (class-of application))))) (%make-dynamic-application/view :application application :application-class class :application-superclasses (dynamic-application.superclasses application) :is-running (status application) :is-registered registered-p :tabs (reduce0 (lambda (acc super) (aif (make-application-tab application super) (cons it acc) acc)) supers))))
2,364
Common Lisp
.lisp
48
44.958333
83
0.642579
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e463e50386d885794b942571fd0a08e1f1b3c1148a7d11fdf5106ebadf92d4a3
8,286
[ -1 ]
8,287
web.lisp
evrim_core-server/src/manager/src/ui/applications/web.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Web Application CRUD ;; ------------------------------------------------------------------------- (defcomponent web-application-crud-mixin () ((tab :host remote :initform (<core:tab)))) (defwebcrud <manager:web-application/crud (web-application-crud-mixin) ((fqdn :label "Domain Name") (application-class :label "Application Class" :read-only t) (is-running :label "Is running?" :remote-type checkbox :read-only t) (is-registered :label "Is registered?" :remote-type checkbox :read-only t)) (:default-initargs :title "Application" :editable-p nil :deletable-p nil)) (defmethod/remote register-button ((self <manager:web-application/crud)) (with-slots (instance) self (with-slots (is-registered) instance (<:input :type "button" :value (if is-registered (_"Unregister") (_"Register")) :title (if is-registered (_"Unregister this application from server") (_"Register this application to the server")) :onclick (lifte (answer-component self (list "register/unregister" instance))))))) (defmethod/remote start-button ((self <manager:web-application/crud)) (with-slots (instance) self (with-slots (is-running) instance (<:input :type "button" :value (if is-running (_"Stop") (_"Start")) :title (if is-running (_"Stop this application") (_"Start this application")) :onclick (lifte (answer-component self (list "start/stop" instance))))))) (defmethod/remote view-buttons ((self <manager:web-application/crud)) (append (call-next-method self) (list (start-button self) (register-button self)))) (defmethod/remote destroy ((self <manager:web-application/crud)) (if (typep (slot-value (tab self) 'destroy) 'function) (destroy (tab self))) (call-next-method self)) (defmethod/remote init ((self <manager:web-application/crud)) (call-next-method self) (with-slots (instance) self (with-slots (tabs) instance (when tabs (let ((tabs (mapcar-cc (lambda (tab) (destructuring-bind (name c) tab (cons name (make-component c)))) tabs))) (append self (setf (tab self) (make-component (tab self) :tabs tabs :tab-title "Capabilities")))))))) ;; ------------------------------------------------------------------------- ;; Web Application View ;; ------------------------------------------------------------------------- (defcomponent web-application/view (remote-reference) ((%application :host lift :type web-application :reader %application :initarg :application) (fqdn :lift t :host remote) (application-class :host remote) (is-running :host remote) (is-registered :host remote) (tabs :host remote)) (:ctor %make-web-application/view)) (defun make-application-tab (application superclass) (case superclass (http-application (list "HTTP Application" (make-http-application/view :application application))) (database-server (list "Database Server" (<manager:database-server/crud :instance (<manager:database-server :server application)))))) (defun make-web-application/view (&key application) (let ((class (symbol->js (class-name (class-of application)))) (registered-p (if (application.server application) t)) (supers (mapcar #'class-name (class+.superclasses (class-of application))))) (%make-web-application/view :application application :application-class class :is-running (status application) :is-registered registered-p :tabs (reduce0 (lambda (acc super) (aif (make-application-tab application super) (cons it acc) acc)) supers))))
3,766
Common Lisp
.lisp
91
36.604396
78
0.631378
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
18fc4ea5a1ec0e621491a0f0d958e289dcfcfdf421c42ec1aab19cddde2554b1
8,287
[ -1 ]
8,288
database.lisp
evrim_core-server/src/manager/src/ui/servers/database.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Database Server ;; ------------------------------------------------------------------------- (defwebcrud <manager:database-server/crud () ((database-directory :label "Database Directory") (log-pathname :label "Transaciton Log") (snapshot-pathname :label "Snapshot")) (:default-initargs :editable-p nil :deletable-p nil :title nil)) (defcomponent <manager:database-server () ((database-directory :host remote) (log-pathname :host remote) (snapshot-pathname :host remote)) (:ctor %make-database-server)) (defun <manager:database-server (&key server) (%make-database-server :database-directory (namestring (database.directory server)) :log-pathname (namestring (database.transaction-log-pathname server)) :snapshot-pathname (namestring (database.snapshot-pathname server))))
919
Common Lisp
.lisp
21
40.619048
76
0.621229
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
6246484a87901eb99792a9829556c53e570e0063c5361e2ea0e5443b7fc3db74
8,288
[ -1 ]
8,289
socket.lisp
evrim_core-server/src/manager/src/ui/servers/socket.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Socket Server ;; ------------------------------------------------------------------------- (defwebcrud <manager:socket-server/crud () ((host-port :label "Bind Address") (protocol :label "Protocol") (peers-max :label "# of Peers" :remote-type number) (peer-class :label "Peer Class")) (:default-initargs :title nil :editable-p nil :deletable-p nil)) ;; ------------------------------------------------------------------------- ;; Socket Component ;; ------------------------------------------------------------------------- (defcomponent <manager:socket-server () ((_server :host lift :type core-server::socket-server) (host-port :host remote) (protocol :host remote) (peers-max :host remote :lift t) (peer-class :host remote)) (:ctor %make-socket-server)) (defun <manager:socket-server (&key server) (with-slots (host port peers-max peer-class protocol) server (%make-socket-server :_server server :host-port (format nil "~A:~A" host port) :protocol (symbol->js protocol) :peer-class (symbol->js (car peer-class)))))
1,171
Common Lisp
.lisp
26
42.076923
76
0.513585
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
428a24afd9f3681e6ba9bcbfd572cbdde59164934b27b714c42f5ef2223c9694
8,289
[ -1 ]
8,290
mail-sender.lisp
evrim_core-server/src/manager/src/ui/servers/mail-sender.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Mail Sender ;; ------------------------------------------------------------------------- (defwebcrud <manager:mail-sender/crud () ((server :label "Mail Server") (port :label "SMTP Port" :remote-type number) (ssl :label "Enable TLS?" :remote-type checkbox) (username :label "Username") (password :label "Password" :remote-type password)) (:default-initargs :title nil :editable-p nil :deletable-p nil)) (defcomponent <manager:mail-sender () ((username :host remote) (password :host remote) (port :host remote) (ssl :host remote) (server :host remote :accessor mail-sender.server)) (:ctor %make-mail-sender)) (defun <manager:mail-sender (&key server) (with-slots (username password mail-port server ssl) server (%make-mail-sender :username username :password password :port mail-port :ssl ssl :server server)))
997
Common Lisp
.lisp
25
35.44
76
0.576883
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7198c71ea80c6a3608377b1a0a2fe1b34fa9991e82eda5f8d9ce40512f72277c
8,290
[ -1 ]
8,291
markup.lisp
evrim_core-server/src/manager/src/api/markup.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Data Definitions ;; ------------------------------------------------------------------------- ;; +xml-namespaces-table+ (eval-when (:compile-toplevel :load-toplevel :execute) (defclass <core-server:markup+ (xml+) () (:default-initargs :namespace "coreServer" :schema "http://labs.core.gen.tr/2012/API/"))) (defclass+ <core-server:markup (xml) () (:metaclass <core-server:markup+)) ;; +------------------------------------------------------------------------ ;; | Core-Server Markup Definition: defcore-server-tag ;; +------------------------------------------------------------------------ (defmacro defapi-tag (name &rest attributes) `(progn (defclass+ ,name (<core-server:markup) (,@(mapcar (lambda (attr) (list attr :print nil :host 'remote)) attributes)) (:metaclass <core-server:markup+) (:tag ,@(string-downcase (symbol-name name))) (:attributes ,@attributes)) (find-class+ ',name))) (defapi-tag <core-server:response) (defapi-tag <core-server:authentication status) (defapi-tag <core-server:user name id last-update) (defapi-tag <core-server:error code)
1,235
Common Lisp
.lisp
29
39.103448
76
0.513716
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
abe80f6767af7cc3232bf1b03d0c3c029892f0ee1c41d12211311012564631e5
8,291
[ -1 ]
8,292
api.lisp
evrim_core-server/src/manager/src/api/api.lisp
;; +------------------------------------------------------------------------- ;; | Core Server API ;; +------------------------------------------------------------------------- (in-package :manager) ;; ------------------------------------------------------------------------- ;; API Call Definition Macro ;; ------------------------------------------------------------------------- (defmacro defapi-call (name (&rest args) &body body) (let ((url (format nil "^/api/~A\\.*" name))) `(progn (defauth ,url manager-application) (defhandler ,url ((application manager-application) (output "output") ,@args) (flet ((output () ,@body)) (cond ((equal output "json") (json-serialize (output))) (t (output)))))))) ;; ------------------------------------------------------------------------- ;; Login API CAll ;; ------------------------------------------------------------------------- (defapi-call "login" ((token "token")) (let* ((request (context.request +context+)) (user (core-server::http-request.authenticated-user request)) (access-token (gethash token (manager.token-cache application))) (association (and access-token (access-token.association access-token)))) ;; (describe ;; (list 'login ;; token access-token association user ;; (and association (secure.owner (account-association.realm association))) ;; (and user (admin.find application :username user)))) (cond ((null access-token) ;; return error (<core-server:response (<core-server:error :code 401 "Invalid token."))) ((not (eq (secure.owner (account-association.realm association)) (admin.find application :username user))) ;; No access (<core-server:response (<core-server:error :code 402 "You are not the realm owner."))) (t (with-slots (account) association (<core-server:response (<core-server:authentication :status "TRUE" (<core-server:user :id (get-database-id (account.user account)) :name (account.name account) :last-update (account.last-update account))))))))) ;; ------------------------------------------------------------------------- ;; Login Client ;; ------------------------------------------------------------------------- (defcommand <core-server:login (http) ((token :host local :initform (error "Provide :token")))) (defmethod http.setup-uri ((self <core-server:login)) (prog1 (call-next-method self) (http.add-query self "token" (slot-value self 'token)))) (defmethod http.evaluate ((self <core-server:login) result response) (let* ((response result) (authentication (car (xml.children response))) (user (and authentication (car (xml.children authentication))))) (if (and authentication (equal (authentication.status authentication) "TRUE")) user (error "Authentication failed.")))) ;; ------------------------------------------------------------------------- ;; Logout API Call ;; ------------------------------------------------------------------------- (defapi-call "logout" ((token "token")) (let* ((request (context.request +context+)) (user (core-server::http-request.authenticated-user request)) (access-token (gethash token (manager.token-cache application))) (association (and access-token (access-token.association access-token)))) ;; (describe (list 'logout ;; token access-token association user ;; (secure.owner (account-association.realm association)) ;; (admin.find application :username user))) (cond ((null access-token) ;; return error (<core-server:response (<core-server:error :code 401 "Invalid token."))) ((not (eq (secure.owner (account-association.realm association)) (admin.find application :username user))) ;; No access (<core-server:response (<core-server:error :code 402 "You are not the realm owner."))) (t (with-slots (account) association (with-slots (session-id) access-token (remhash session-id (http-application.sessions application)) (remhash token (manager.token-cache application)) (<core-server:response (<core-server:authentication :status "FALSE")))))))) ;; ------------------------------------------------------------------------- ;; Login Client ;; ------------------------------------------------------------------------- (defcommand <core-server:logout (http) ((token :host local :initform (error "Provide :token")))) (defmethod http.setup-uri ((self <core-server:logout)) (prog1 (call-next-method self) ;; (describe (slot-value self 'token)) (http.add-query self "token" (slot-value self 'token)))) (defmethod http.evaluate ((self <core-server:logout) result response) (let* ((response result) (authentication (car (xml.children response)))) (if (and authentication (equal (authentication.status authentication) "FALSE")) t (error "Authentication failed.")))) ;; ------------------------------------------------------------------------- ;; Manager Application API a.k.a. Core Server API ;; ------------------------------------------------------------------------- (defrest realm-rest () () (:url "api\\/realm") (:class realm) (:authenticate t)) (defrest-client "http://localhost:8080/api/realm" realm <manager) ;; (defrest site-rest () ;; () ;; (:url "api\/site") ;; (:class site) ;; (:authenticate t)) ;; (core-server::defrest-crud/lift site-rest/anonymous site-rest) ;; (defrest site-rest-5 () ;; () ;; (:url "tite") ;; (:class site) ;; (:authenticate t)) ;; (DEFMETHOD/LOCAL SITE-REST.LIST ((IT.BESE.ARNESI::SELF SITE-REST)) ;; (SITE.LIST TR.GEN.CORE.SERVER::CRUD-LIST ;; (TR.GEN.CORE.SERVER::REST.APPLICATION ;; IT.BESE.ARNESI::SELF))) ;; ;; ------------------------------------------------------------------------- ;; ;; Sites API ;; ;; ------------------------------------------------------------------------- ;; (defmethod authenticate-sites-api ((self manager-application) username password) ;; (and (site.find self :username username :password password) t)) ;; (defvar +unauthorized-message+ ;; (<:html (<:body (<:h1 "Unauthorized") ;; (<:h2 "Core Server - " ;; (<:a :href "http://labs.core.gen.tr/" ;; "http://labs.core.gen.tr/"))))) ;; (defmacro with-sites-api ((manager username password) &body body) ;; `(cond ;; ((authenticate-sites-api ,manager ,username ,password) ,@body) ;; (t ;; (setf (http-response.status-code (context.response +context+)) ;; (core-server::make-status-code 403)) ;; +unauthorized-message+))) ;; (defmacro defsites-api (name (&rest args) &body body) ;; `(defhandler ,(format nil "^/api/~A\\.*" name) ;; ((application manager-application) (username "api-key") ;; (password "api-password") (output "output") ,@args) ;; (flet ((output () ;; (with-sites-api (application username password) ;; ,@body))) ;; (cond ;; ((equal output "json") ;; (json-serialize (output))) ;; (t ;; (output)))))) ;; ;; ------------------------------------------------------------------------- ;; ;; Authentication - Server Side ;; ;; ------------------------------------------------------------------------- ;; (defclass+ authentication-token () ;; ((token) ;; (user :type user) ;; (manager-session-id :type string))) ;; (defmethod authenticate-token ((self manager-application) token) ;; (let ((tokens (or (database.get self 'tokens) ;; (setf (database.get self 'tokens) ;; (make-hash-table :test #'equal :synchronized t))))) ;; (gethash token tokens))) ;; (defmethod unauthenticate-token ((self manager-application) token) ;; (let* ((tokens (or (database.get self 'tokens) ;; (setf (database.get self 'tokens) ;; (make-hash-table :test #'equal :synchronized t)))) ;; (authentication-token (gethash token tokens))) ;; (when authentication-token ;; (remhash (authentication-token.manager-session-id authentication-token) ;; (http-application.sessions self)) ;; (remhash token tokens)))) ;; (defsites-api "authenticate" ((token "token")) ;; (aif (authenticate-token application token) ;; (<core-server:response ;; (<core-server:authentication :status "TRUE" ;; (<core-server:user :email (user.email it) :name (user.name it)))) ;; (<core-server:response ;; (<core-server:authentication :status "FALSE")))) ;; (defsites-api "unauthenticate" ((token "token")) ;; (<core-server:response ;; (<core-server:authentication ;; :status (if (unauthenticate-token application token) "TRUE" "FALSE"))))
8,628
Common Lisp
.lisp
192
42.109375
83
0.554418
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
4b5753d807971093bcf2624a37fa1d255d3efa6fcd005c5071079fff3e5eabb0
8,292
[ -1 ]
8,293
manager-user.lisp
evrim_core-server/src/manager/src/api/manager-user.lisp
(in-package :manager) (defrest site-rest () () (:url "site") (:class site) (:authenticate t)) ;; (core-server::defrest-crud/lift site-rest/anonymous site-rest) ;; (defrest site-rest-5 () ;; () ;; (:url "tite") ;; (:class site) ;; (:authenticate t)) ;; (DEFMETHOD/LOCAL SITE-REST.LIST ((IT.BESE.ARNESI::SELF SITE-REST)) ;; (SITE.LIST TR.GEN.CORE.SERVER::CRUD-LIST ;; (TR.GEN.CORE.SERVER::REST.APPLICATION ;; IT.BESE.ARNESI::SELF))) ;; ------------------------------------------------------------------------- ;; Manager Users API ;; ------------------------------------------------------------------------- (defmethod authenticate-manager-api ((self manager-application) username password) (and (user.find self :username username :password password) t)) (defmacro with-manager-api ((manager username password) &body body) `(cond ((authenticate-manager-api ,manager ,username ,password) ,@body) (t (setf (http-response.status-code (context.response +context+)) (core-server::make-status-code 403)) +unauthorized-message+))) (defmacro defmanager-api (name (&rest args) &body body) `(defhandler ,(format nil "^/api/~A\\.*" name) ((application manager-application) (username "username") (password "password") (output "output") ,@args) (flet ((output () (with-manager-api (application username password) ,@body))) (cond ((equal output "json") (json-serialize (output))) (t (output)))))) (defmanager-api "add" ((site "site")) (let ((site (or (site.find application :fqdn site) (site.add application :fqdn site)))) (<core-server:response (<core-server:site :fqdn (site.fqdn site) :api-key (site.api-key site) :api-password (site.api-password site))))) (defmanager-api "delete" ((site site)) (let ((site (site.find application :fqdn site))) (<core-server:response (if site (prog1 t (site.delete application site)) nil)))) (defmanager-api "query" ((site site)) (let ((site (site.find application :fqdn site))) (<core-server:response (if site (<core-server:site :fqdn (site.fqdn site) :api-key (site.api-key site) :api-password (site.api-password site)) nil))))
2,229
Common Lisp
.lisp
61
33
82
0.616311
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
9a29a734fbf1867519c3fa48fd850c913c90552cfb8d110d921971279e1e663c
8,293
[ -1 ]
8,294
user.lisp
evrim_core-server/src/manager/src/auth/user.lisp
(in-package :manager) (defcomponent account-crud-mixin () ()) (defmethod/remote view-buttons ((self account-crud-mixin)) (list (<:input :type "button" :value "Use this account" :title "Use this account" :onclick (lifte (answer-component self (list "use" (slot-value self 'instance))))))) ;; ------------------------------------------------------------------------- ;; Facebook Account CRUD ;; ------------------------------------------------------------------------- (defwebcrud facebook-account/crud (account-crud-mixin) ((first-name :label "First Name") (last-name :label "Last Name") (email :label "E-mail")) (:default-initargs :title nil)) (defcomponent facebook-account/view (remote-reference) ((account :host lift :type facebook-account) (first-name :host remote :lift t) (last-name :host remote :lift t) (email :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Twitter Account CRUD ;; ------------------------------------------------------------------------- (defwebcrud twitter-account/crud (account-crud-mixin) ((name :label "Name") (screen-name :label "Screen Name") (description :label "Description")) (:default-initargs :title nil)) (defcomponent twitter-account/view (remote-reference) ((account :host lift :type twitter-account) (name :host remote :lift t) (screen-name :host remote :lift t) (description :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Google Account CRUD ;; ------------------------------------------------------------------------- (defwebcrud google-account/crud (account-crud-mixin) ((first-name :label "First Name") (last-name :label "Last Name") (email :label "E-mail")) (:default-initargs :title nil)) (defcomponent google-account/view (remote-reference) ((account :host lift :type google-account) (first-name :host remote :lift t) (last-name :host remote :lift t) (email :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Yahoo Account CRUD ;; ------------------------------------------------------------------------- (defwebcrud yahoo-account/crud (account-crud-mixin) ((first-name :label "First Name") (last-name :label "Last Name") (nickname :label "Nickname")) (:default-initargs :title nil)) (defcomponent yahoo-account/view (remote-reference) ((account :host lift :type yahoo-account) (first-name :host remote :lift t) (last-name :host remote :lift t) (nickname :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Local Account CRUD ;; ------------------------------------------------------------------------- (defwebcrud local-account/crud (account-crud-mixin) ((name :label "Name") (email :label "E-mail")) (:default-initargs :title nil)) (defcomponent local-account/view (remote-reference) ((account :host lift :type local-account) (name :host remote :lift t) (email :host remote :lift t))) ;; ------------------------------------------------------------------------- ;; Account Widget ;; ------------------------------------------------------------------------- (defcomponent <manager:accounts (secure-object <widget:simple) ((default-account :host local)) (:default-initargs :levels '(<manager:accounts/registered) :permissions '((owner . 0) (group . 0) (other . 0) (anonymous . -1) (unauthorized . -1)) :owner (make-user :name "root") :group (make-simple-group :name "users"))) (defmethod authorize ((self manager-application) (user user) (accounts <manager:accounts)) (apply (core-server::%secure-constructor accounts user) (list :secure-object accounts :user user :current-application self :owner (secure.owner accounts) :group (secure.group accounts) :default-tab (aif (default-account accounts) (format nil "~@(~A~)" (account.provider it)) "Coretal")))) (defparameter +account-cruds+ (list (cons "Facebook" (facebook-account/crud)) (cons "Twitter" (twitter-account/crud)) (cons "Google" (google-account/crud)) (cons "Google" (yahoo-account/crud)) (cons "Coretal" (local-account/crud)))) (defcomponent <manager:accounts/registered (secure-object/authorized <widget:tab) ((secure-object :host lift :type <manager:accounts) (accounts :host local :export nil) (default-account :host remote :lift t) (account-cruds :host remote :initform +account-cruds+)) (:default-initargs :tab-title "Accounts" :tabs (list "Coretal" "Facebook" "Google" "Twitter" "Yahoo"))) (defmethod/local get-account ((self <manager:accounts/registered) name) (let ((accounts (user.accounts (secure.user self)))) (acond ((and (equal "Coretal" name) (any (make-type-matcher 'local-account) accounts)) (local-account/view :account it)) ((and (equal "Facebook" name) (any (make-type-matcher 'facebook-account) accounts)) (facebook-account/view :account it)) ((and (equal "Google" name) (any (make-type-matcher 'google-account) accounts)) (google-account/view :account it)) ((and (equal "Twitter" name) (any (make-type-matcher 'twitter-account) accounts)) (twitter-account/view :account it)) ((and (equal "Yahoo" name) (any (make-type-matcher 'yahoo-account) accounts)) (yahoo-account/view :account it))))) (defmethod/local do-use1 ((self <manager:accounts/registered) account) (answer-component self (list self :use (slot-value account 'account)))) (defmethod/local external-login-url ((self <manager:accounts/registered) provider) (let ((provider (find (string-upcase provider) '(facebook yahoo google twitter) :test #'string=))) (answer-component self (list self :login provider)))) (defmethod/remote do-external-login ((self <manager:accounts/registered) provider) (setf window.location (external-login-url self provider))) (defmethod/remote core-server::make-tab ((self <manager:accounts/registered) tab) (let ((account (get-account self tab))) (cond (account (let* ((_crud (find-cc (lambda (a) (equal (car a) tab)) (account-cruds self))) (_crud (make-component (car (cdr _crud)) :instance account))) (make-web-thread (lambda () (destructuring-bind (action account) (call-component _crud) (cond ((equal action "use") (do-use1 self account)) (t (throw (new (*error (+ "unhandled action:" action ",args:" args))))))))) _crud)) ((equal tab "Facebook") (<:div :class "auth-buttons center text-center" (<:p (<:a :class "btn-auth btn-facebook" :onclick (lifte (do-external-login self "facebook")) (_ "Add My") (<:b " Facebook ") (_ "Account"))))) ((equal tab "Google") (<:div :class "auth-buttons center text-center" (<:p (<:a :class "btn-auth btn-google" :onclick (lifte (do-external-login self "google")) (_ "Add My") (<:b " Google ") (_ "Account"))))) ((equal tab "Twitter") (<:div :class "auth-buttons center text-center" (<:p (<:a :class "btn-auth btn-twitter" :onclick (lifte (do-external-login self "twitter")) (_ "Add My") (<:b " Twitter ") (_ "Account"))))) ((equal tab "Yahoo") (<:div :class "auth-buttons center text-center" (<:p (<:a :class "btn-auth btn-yahoo" :onclick (lifte (do-external-login self "yahoo")) (_ "Add My") (<:b " Yahoo ") (_ "Account"))))))))
7,539
Common Lisp
.lisp
173
39.514451
85
0.591169
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
925b6986cc823acedbe36759c318ef7fe0dcfbcd621e74e990107a5bba3bf174
8,294
[ -1 ]
8,295
interface.lisp
evrim_core-server/src/manager/src/auth/interface.lisp
;; ------------------------------------------------------------------------- ;; OAuth Application Interface ;; ------------------------------------------------------------------------- (in-package :manager) (defmethod oauth.make-answer-uri ((self manager-application) (provider symbol)) (let ((url (manager.oauth-uri self))) (setf (uri.queries url) `(("action" . "answer") ("provider" . ,(symbol->js provider)))) url)) ;; http://node1.coretal.net:8080/auth.core?mode=return&type=facebook&code=CODE#_=_ ;; http://localhost:8080/auth.core?action=login&return-to=http%3A%2F%2Fnode1.coretal.net%3A8080%2Fauthentication%2Fauth.core (defmethod oauth.make-uri ((self manager-application) (provider symbol) (state string)) (let ((credentials (database.get self (make-keyword provider)))) (when credentials (case provider (facebook (with-slots (app-id) credentials (<fb:oauth-uri :client-id app-id :redirect-uri (oauth.make-answer-uri self provider) :state state))) (google (with-slots (client-id client-secret) credentials (<google:oauth-uri :client-id client-id :redirect-uri (oauth.make-answer-uri self provider) :state state))) (twitter (with-slots (consumer-key consumer-secret) credentials (let ((callback (oauth.make-answer-uri self provider))) (uri.add-query callback "state" state) (let ((token (<twitter:get-request-token :callback callback :consumer-key consumer-key :consumer-secret consumer-secret))) (values (<twitter:authorize-url :token token) token))))))))) (defmethod oauth.get-user-v2 ((self manager-application) (provider (eql 'facebook)) (code string)) (with-slots (app-id app-secret) (database.get self :facebook) (<fb:me :token (<fb:get-access-token :client-id app-id :client-secret app-secret :code code :redirect-uri (oauth.make-answer-uri self 'facebook))))) (defmethod oauth.get-user-v2 ((self manager-application) (provider (eql 'google)) (code string)) (with-slots (client-id client-secret) (database.get self :google) (<google:userinfo :token (<google:get-access-token :client-id client-id :client-secret client-secret :code code :redirect-uri (oauth.make-answer-uri self 'google))))) (defmethod oauth.get-user-v1 ((self manager-application) (provider (eql 'twitter)) (req-token <oauth1:request-token) (token string) (verifier string)) (with-slots (consumer-key consumer-secret) (database.get self :twitter) (let* ((access-token (<twitter:get-access-token :verifier verifier :consumer-key consumer-key :consumer-secret consumer-secret :request-token req-token)) (twitter-id (<twitter:access-token.user-id access-token))) (<twitter:secure-get-user :token access-token :consumer-key consumer-key :consumer-secret consumer-secret :user-id twitter-id)))) ;; ------------------------------------------------------------------------- ;; OAuth Handle ;; ------------------------------------------------------------------------- (defmethod oauth.handle ((self manager-application) (provider symbol) (third-party jobject) &optional current-account) (let* ((account-id (get-attribute third-party (case provider (facebook :id) (google :id) (twitter :id_str)))) (account (external-account.find self :account-id account-id))) (cond ((and account current-account ;; Merge accounts (not (eq (account.user account) (account.user current-account)))) (let* ((old-user (account.user account)) (old-accounts (user.accounts old-user)) (new-user (account.user current-account))) (mapcar (lambda (account) (account.update self account :user new-user)) old-accounts) (user.delete self old-user) account)) (account account) ;; Already exists, return it ((and current-account (null account)) ;; Previous accounts, adding a new one. (let ((new-account (funcall (case provider (facebook #'facebook-account.add-from-jobject) (google #'google-account.add-from-jobject) (twitter #'twitter-account.add-from-jobject)) self third-party)) (user (account.user current-account))) (user.update self user :accounts (cons new-account (user.accounts user))) new-account)) ((and (null current-account) (null account)) ;; No previous accounts, new user, new account. (let ((new-account (funcall (case provider (facebook #'facebook-account.add-from-jobject) (google #'google-account.add-from-jobject) (twitter #'twitter-account.add-from-jobject)) self third-party))) (user.add self :group (simple-group.find self :name "user") :accounts (list new-account)) new-account))))) (defmethod oauth.handle-v2 ((self manager-application) (provider symbol) (code string) &optional current-account) (oauth.handle self provider (oauth.get-user-v2 self provider code) current-account)) (defmethod oauth.handle-v1 ((self manager-application) (provider symbol) (request-token <oauth1:request-token) (token string) (verifier string) &optional current-account) (oauth.handle self provider (oauth.get-user-v1 self provider request-token token verifier) current-account)) ;; (defmethod oauth.create-account-v1 ((self manager-application) (provider symbol) ;; (code string)) ;; (let ((user (oauth.get-user-v2 self provider code))) ;; (case provider ;; (facebook ;; (aif (facebook-account.find )))))) ;; (defmethod oauth.add-account-v1 ((self manager-application) (user user) ;; (provider symbol) (code string)) ;; ) ;; (defmethod oauth.find-account-v1 ((self manager-application) (provider symbol) ;; (token string) (verifier string)) ;; (case provider ;; (twitter ;; (let ((credentials (database.get self (make-keyword provider)))) ;; (with-slots (consumer-key consumer-secret) credentials ;; (let ((req-token (gethash token (manager.request-token-cache self)))) ;; (cond ;; ((null req-token) ;; (error "Twitter request token not found: ~A, verifier: ~A" ;; token verifier)) ;; (t ;; (let* ((access-token ;; (<twitter:get-access-token :verifier verifier ;; :consumer-key consumer-key ;; :consumer-secret consumer-secret ;; :request-token req-token)) ;; (twitter-id (<twitter:access-token.user-id access-token)) ;; (screen-name (<twitter:access-token.screen-name access-token)) ;; (twitter-user ;; (<twitter:secure-get-user :token access-token ;; :consumer-key consumer-key ;; :consumer-secret consumer-secret ;; :screen-name screen-name)) ;; (account ;; (twitter-account.find self :account-id twitter-id))) ;; (remhash token (manager.request-token-cache self)) ;; (if account ;; account ;; (multiple-value-bind (user account) (user.add-from-twitter self twitter-user) ;; (declare (ignore user)) ;; account))))))))))) ;; (defmethod manager.create-oauth2-account ((self manager-application) (provider symbol) ;; (code string)) ;; (let ((credentials (database.get self (make-keyword provider)))) ;; (case provider ;; (facebook ;; (with-slots (app-id app-secret) credentials ;; (let* ((url (make-oauth-answer-uri self 'facebook)) ;; (token (<fb:get-access-token :client-id app-id ;; :client-secret app-secret ;; :code code :redirect-uri url)) ;; (fb-user (<fb:me :token token)) ;; (facebook-id (get-attribute fb-user :id)) ;; (account (facebook-account.find self :account-id facebook-id))) ;; (aif account ;; account ;; (multiple-value-bind (user account) (user.add-from-facebook self fb-user) ;; (declare (ignore user)) ;; account))))) ;; (google ;; (with-slots (client-id client-secret) credentials ;; (let* ((url (make-oauth-answer-uri self 'google)) ;; (token (<google:get-access-token :client-id client-id ;; :client-secret client-secret ;; :code code :redirect-uri url)) ;; (google-user (<google:userinfo :token token)) ;; (google-id (get-attribute google-user :id)) ;; (account (google-account.find self :account-id google-id))) ;; (aif (google-account.find self :account-id google-id) ;; account ;; (multiple-value-bind (user account) (user.add-from-google self google-user) ;; (declare (ignore user)) ;; account)))))))) ;; (defmethod manager.add-oauth2-account ((self manager-application) (provider symbol) ;; (code string)) ;; (let ((credentials (database.get self (make-keyword provider)))) ;; (case provider ;; (facebook ;; (with-slots (app-id app-secret) credentials ;; (let* ((url (make-oauth-answer-uri self 'facebook)) ;; (token (<fb:get-access-token :client-id app-id ;; :client-secret app-secret ;; :code code :redirect-uri url)) ;; (fb-user (<fb:me :token token)) ;; (facebook-id (get-attribute fb-user :id)) ;; (account (facebook-account.find self :account-id facebook-id))) ;; (aif account ;; account ;; (multiple-value-bind (user account) (user.add-from-facebook self fb-user) ;; (declare (ignore user)) ;; account))))) ;; (google ;; (with-slots (client-id client-secret) credentials ;; (let* ((url (make-oauth-answer-uri self 'google)) ;; (token (<google:get-access-token :client-id client-id ;; :client-secret client-secret ;; :code code :redirect-uri url)) ;; (google-user (<google:userinfo :token token)) ;; (google-id (get-attribute google-user :id)) ;; (account (google-account.find self :account-id google-id))) ;; (aif (google-account.find self :account-id google-id) ;; account ;; (multiple-value-bind (user account) (user.add-from-google self google-user) ;; (declare (ignore user)) ;; account)))))))) ;; (defmethod manager.find-account-v2 ((self manager-application) (provider symbol) (code string)) ;; (case provider ;; (facebook ;; (let ((fb-user (oauth.get-user-v2 self provider code))) ;; (facebook-account.find self :account-id (get-attribute fb-user :id)))))) ;; (defmethod manager.new-account-v2 ((self manager-application) ;; (account account) (provider symbol) (code string)) ;; (case provider ;; (facebook ;; )))
10,537
Common Lisp
.lisp
230
42.234783
124
0.640506
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
12239bbb6e9cf81a2828b284d1b20e161a60b217cc2b53f7700b2f308f328995
8,295
[ -1 ]
8,296
controller.lisp
evrim_core-server/src/manager/src/auth/controller.lisp
;; ------------------------------------------------------------------------- ;; OAuth Controller ;; ------------------------------------------------------------------------- (in-package :manager) ;; ------------------------------------------------------------------------- ;; Authentication Controller ;; ------------------------------------------------------------------------- (defmethod/cc make-auth-controller/anonymous ((self manager-application) &key (page "login") error-message) (<core:simple-controller :default-page page (<core:simple-page :name "login" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Would you like to have a new account?" (<:a :class "pad5" :href "#page:register" "Sign Up")))) (<core:simple-widget-map :selector "middle" :widget (<manager:login)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "register" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Already have an account?" (<:a :class "pad5" :href "#page:login" "Sign In")))) (<core:simple-widget-map :selector "middle" :widget (<manager:registration)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "forgot" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Already have an account?" (<:a :class "pad5" :href "#page:login" "Sign In")))) (<core:simple-widget-map :selector "middle" :widget (<manager:forgot-password)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "recover" (<core:simple-widget-map :selector "middle" :widget (<manager:recover-password)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))) (<core:simple-page :name "error" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "Would you like to have a new account?" (<:a :class "pad5" :href "#page:register" "Sign Up")))) (<core:simple-widget-map :selector "middle" :widget (<manager:authentication-error :message error-message))))) (defmethod/cc make-auth-controller/user ((self manager-application) (account account) (realm realm)) (<core:simple-controller :default-page "accounts" (<core:simple-page :name "accounts" (<core:simple-widget-map :selector "top-right" :widget (<widget:simple-content (<:p "You are about to login to " (realm.fqdn realm) "."))) (<core:simple-widget-map :selector "middle" :widget (<manager:accounts :default-account account)) (<core:simple-widget-map :selector "bottom" :widget (<widget:simple-content "Our services in other languages: " (<:a :href "#" "English") " | " (<:a :href "#" "Turkce")))))) ;; ------------------------------------------------------------------------- ;; Authentication Controller ;; ------------------------------------------------------------------------- (defhandler "auth\.core" ((self manager-application)) (flet ((find-realm (return-to) (let ((url (uri? (make-core-stream return-to)))) (if url (realm.find self :fqdn (uri.server url)))))) (let* ((request (context.request +context+)) (referer (or (http-request.header request 'referer) (make-uri))) (action (or (uri.query referer "action") "login")) (return-to (uri.query referer "return-to")) (realm (find-realm return-to))) (labels ((handle-oauth2 (provider code) (send/user (setf (query-session :account) (oauth.handle-v2 self provider code (query-session :account))))) (handle-oauth1 (provider request-token token verifier) (send/user (setf (query-session :account) (oauth.handle-v1 self provider request-token token verifier (query-session :account))))) (handle-local (email password) (let ((account (local-account.find self :email email))) (if (and account (equal (local-account.password account) password)) (apply #'handle-action (continue/js (controller/user (setf (query-session :account) account)))) (continue/js (make-web-error 'error "Sorry, cannot validate credentials."))))) (handle-registration (name email password) (let ((account (local-account.find self :email email))) (if account (continue/js (make-web-error 'error "Sorry, this account already exists.")) (multiple-value-bind (user account) (user.register self :name name :email email :password password) (declare (ignore user)) (apply #'handle-action (continue/js (controller/user (setf (query-session :account) account)))))))) (handle-forgot-password (email) (let ((account (local-account.find self :email email))) (cond (account (let* ((k-url (action/hash () (let ((k-url (core-server::http-request.query (context.request +context+) +continuation-query-name+))) (destructuring-bind (component action &rest args) (javascript/suspend (lambda (stream) (let ((kontroller (controller/anonymous "recover"))) (rebinding-js/cc (kontroller) stream (setf (slot-value window 'controller) (kontroller nil)))))) (case action (:recover (destructuring-bind (password) args (local-account.update self account :password password) (setf (query-session :account) account) (context.remove-action +context+ k-url) (continue/js t))) (t (handle-action component action args))))))) (url (manager.oauth-uri self))) (setf (uri.queries url) `(("action" . "recover") ("state" . ,k-url) ("return-to" . ,return-to))) (manager.send-password-recovery-email self email (uri->string url)) (continue/js "An email has been sent to your adress."))) (t (continue/js (make-web-error 'error "Sorry, this email is not registered.")))))) (handle-action (component action &rest args) (declare (ignore component)) (case action (:login (destructuring-bind (provider &rest args) args (case provider ((facebook google) (let ((k-url (action/hash ((code "code")) (handle-oauth2 provider code)))) (continue/js (oauth.make-uri self provider k-url)))) ((yahoo twitter) (let ((+action-hash-override+ (format nil "act-~A" (make-unique-random-string 8)))) (multiple-value-bind (url request-token) (oauth.make-uri self provider +action-hash-override+) (let ((k-url (action/hash ((token "oauth_token") (verifier "oauth_verifier")) (handle-oauth1 provider request-token token verifier)))) (assert (equal k-url +action-hash-override+)) (continue/js url))))) (local (destructuring-bind (email password) args (handle-local email password))) (t (send/anonymous "error" (format nil "Unknown provider ~A (2)" provider)))))) (:forgot (destructuring-bind (email) args (handle-forgot-password email))) (:register (destructuring-bind (name email password) args (handle-registration name email password))) (:use (destructuring-bind (account) args (let* ((session-id (session.id (context.session +context+))) (access-token (or (query-session :token) (setf (query-session :token) (manager.create-token self realm account session-id))))) (with-slots (token) access-token (continue/js (jambda (self) (setf (slot-value window 'location) (+ return-to "?token=" token)))))))))) (controller/user (account) (let* ((kontroller (make-auth-controller/user self account realm))) (authorize self (account.user account) kontroller))) (controller/anonymous (page &optional error) (let ((kontroller (make-auth-controller/anonymous self :page page :error-message error))) (authorize self (make-anonymous-user) kontroller))) (send/user (account) (apply #'handle-action (javascript/suspend (lambda (stream) (let ((kontroller (controller/user account))) (rebinding-js/cc (kontroller) stream (setf (slot-value window 'controller) (kontroller nil)))))))) (send/anonymous (page &optional error) (apply #'handle-action (javascript/suspend (lambda (stream) (let ((kontroller (controller/anonymous page error))) (rebinding-js/cc (kontroller) stream (setf (slot-value window 'controller) (kontroller nil))))))))) (cond ((equal action "recover") (let ((state (uri.query referer "state")) (return-to (uri.query referer "return-to")) (url (http-request.uri request))) (uri.add-query url +continuation-query-name+ state) (if return-to (uri.add-query url "return-to" return-to)) (send/redirect (uri->string url)))) ((equal action "answer") ;; Redirect to exact continuation + avoid CSRF (let ((state (uri.query referer "state")) (url (http-request.uri request))) (uri.add-query url +continuation-query-name+ state) (mapcar (lambda (param) (aif (uri.query referer param) (uri.add-query url param it))) '("code" "provider" "oauth_token" "oauth_verifier")) (send/redirect (uri->string url)))) ((null realm) (send/anonymous "error" "Sorry, realm not found. (3)")) ((null return-to) ;; Show Error Message (send/anonymous "error" "Sorry, return-to is missing. (1)")) ((query-session :account) (send/user (query-session :account))) (t (send/anonymous action nil)))))))
10,548
Common Lisp
.lisp
246
35.626016
80
0.592736
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a47eadddb481a1c9356df0acf57ae215be52469836dd4927edc0b89cfab7c50e
8,296
[ -1 ]
8,297
anonymous.lisp
evrim_core-server/src/manager/src/auth/anonymous.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; Login Widget ;; ------------------------------------------------------------------------- (defcomponent <manager:login (<widget:simple <core:login) ((title :host remote :initform "Sign In") (subtitle :host remote :initform "Provide your credentials to log-in.")) (:default-initargs :_username-input (<core:email-input :default-value "Email" :name "email" :size "35"))) (defmethod/local external-login-url ((self <manager:login) provider) (let ((provider (find (string-upcase provider) '(facebook yahoo google twitter) :test #'string=))) (answer-component self (list self :login provider)))) (defmethod/remote do-external-login ((self <manager:login) provider) (setf window.location (external-login-url self provider))) (defmethod/local core-server::login-with-credentials ((self <manager:login) username password) (answer-component self (list self :login 'local username password))) (defmethod/remote core-server::do-login-with-credentials ((self <manager:login) username password) (let ((ctor (core-server::login-with-credentials self username password)) (kontroller (controller (widget-map self)))) (destroy kontroller) (set-parameter "page" nil) (call/cc ctor kontroller))) (defmethod/remote core-server::buttons ((self <manager:login)) (<:p (<:input :type "submit" :class "button" :value "login" :disabled t) (<:a :href "#page:forgot" :class "pad10" "Forgot password?"))) (defmethod/remote template ((self <manager:login)) (let ((form (call-next-method self))) (<:div (<:h1 (title self)) (<:h2 (subtitle self)) (<:div :class "left core" form) (<:div :class "right oauth-buttons" (<:p (<:a :class "btn-auth btn-facebook" :onclick (lifte (do-external-login self "facebook")) (_"Sign In with ") (<:b "Facebook"))) (<:p (<:a :class "btn-auth btn-twitter" :onclick (lifte (do-external-login self "twitter")) (_"Sign In with ") (<:b "Twitter"))) (<:p (<:a :class "btn-auth btn-google" :onclick (lifte (do-external-login self "google")) (_"Sign In with ") (<:b "Google"))) (<:p (<:a :class "btn-auth btn-yahoo" :onclick (lifte (do-external-login self "yahoo")) (_"Sign In with ") (<:b "Yahoo"))))))) (defmethod/remote destroy ((self <manager:login)) (remove-class self "core-auth-widget") (call-next-method self)) (defmethod/remote init ((self <manager:login)) (call-next-method self) (add-class self "core-auth-widget")) ;; ------------------------------------------------------------------------- ;; Forgot Password ;; ------------------------------------------------------------------------- (defcomponent <manager:forgot-password (<:div <widget:simple) ((title :host remote :initform "Recover Password") (subtitle :host remote :initform "Please enter your email to recover your password") (_username-input :host remote :initform(<core:email-input :default-value "Email" :name "email" :size "35")))) (defmethod/local forgot-password ((self <manager:forgot-password) email) (answer-component self (list self :forgot email))) (defmethod/remote do-forgot-password ((self <manager:forgot-password) email) (alert (_ (forgot-password self email))) (window.close)) (defmethod/remote template ((self <manager:forgot-password)) (let ((_input (make-component (_username-input self) :validation-span-id "username-validation"))) (<:div :class "core" (<:h1 (_ (title self))) (<:h2 (_ (subtitle self))) (<:form :onsubmit (lifte (do-forgot-password self (get-input-value _input))) (with-field _input (<:span :class "validation" :id "username-validation" "Enter your username")) (with-field "" (<:input :type "submit" :class "button" :value "Recover" :disabled t)))))) (defmethod/remote destroy ((self <manager:forgot-password)) (remove-class self "core-auth-widget") (call-next-method self)) (defmethod/remote init ((self <manager:forgot-password)) (call-next-method self) (add-class self "core-auth-widget") (append self (template self))) ;; ------------------------------------------------------------------------- ;; Registration Widget ;; ------------------------------------------------------------------------- (defcomponent <manager:registration (<:div <widget:simple) ((_required-input :host remote :initform (<core:required-value-input)) (_email-input :host remote :initform (<core:email-input)) (_password-input :host remote :initform (<core:password-input)) (_h1-text :host remote :initform "Registration") (_h2-text :host remote :initform "Sign-up to use Coretal.net Services")) (:default-initargs :id "registrationBox")) (defmethod/remote make-elements ((self <manager:registration)) (let ((_username (make-component (_required-input self) :default-value (_ "Name") :validation-span-id "XX-username-validation" :size "35")) (_email (make-component (_email-input self) :default-value (_ "Email") :validation-span-id "XX-email-validation" :size "35")) (_password1 (make-component (_password-input self) :default-value (_ "Enter Password") :validation-span-id "XX-password-validation1")) (_password2 (make-component (_password-input self) :default-value (_ "Re-enter Password") :validation-span-id "XX-password-validation2")) (_agreement (call/cc (_required-input self) (extend (jobject :validation-span-id "XX-agreement-validation") (<:input :type "checkbox"))))) (add-class _agreement "pad5") (list _username _email _password1 _password2 _agreement))) (defmethod/local register-with-credentials ((self <manager:registration) name email password) (answer-component self (list self :register name email password))) (defmethod/remote do-register-with-credentials ((self <manager:registration) name email password) (let ((ctor (register-with-credentials self name email password)) (kontroller (controller (widget-map self)))) (destroy kontroller) (set-parameter "page" nil) (call/cc ctor kontroller))) (defmethod/remote template ((self <manager:registration)) (destructuring-bind (_username _email _password1 _password2 _agreement) (make-elements self) (<:form :onsubmit (lifte (do-register-with-credentials self (get-input-value _username) (get-input-value _email) (get-input-value _password1))) (<:h1 (_ (_h1-text self))) (<:h2 (_ (_h2-text self))) (<:div :class "left width-50p" (with-field _username (<:span :class "validation" :id "XX-username-validation" (_ "Enter your full name")))) (<:div (with-field _email (<:span :class "validation" :id "XX-email-validation" (_ "Enter your email address")))) (<:div :class "clear left width-50p" (with-field _password1 (<:span :class "validation" :id "XX-password-validation1" (_ "Enter your password")))) (<:div (with-field _password2 (<:span :class "validation" :id "XX-password2-validation2" (_ "Re-enter your password")))) (<:div :class "left width-50p" (with-field (<:p :class "agreement" (<:label :for (slot-value _agreement 'id) _agreement (if (eq "tr" +default-language+) (<:span :class "pad5" " " (<:a :href "/agreement.html" :target "_blank" (_ "agreement")) " " (_ "I accept the terms in the")) (<:span :class "pad5" " " (_ "I accept the terms in the") " " (<:a :href "/agreement.html" :target "_blank" (_ "agreement") "."))))) "")) (<:div (with-field "" (<:input :type "submit" :value (_ "Register") :disabled t)))))) (defmethod/remote destroy ((self <manager:registration)) (remove-class self "core") (remove-class self "core-auth-widget") (call-next-method self)) (defmethod/remote init ((self <manager:registration)) (call-next-method self) (add-class self "core-auth-widget") (add-class self "core") (append self (template self))) ;; ------------------------------------------------------------------------- ;; Recover Password ;; ------------------------------------------------------------------------- (defcomponent <manager:recover-password (<:div <widget:simple) ((title :host remote :initform "Recover Password") (subtitle :host remote :initform "Please enter a new password") (_password-input :host remote :initform (<core:password-input)))) (defmethod/local recover-password ((self <manager:recover-password) password) (answer-component self (list self :recover password))) (defmethod/remote do-recover-password ((self <manager:recover-password) password) (recover-password self password) (alert (+ (_ "Your password has been updated.") (_ "Thank you."))) (window.close)) (defmethod/remote template ((self <manager:recover-password)) (let ((_input1 (make-component (_password-input self) :validation-span-id "passwd1-validation")) (_input2 (make-component (_password-input self)))) (<:div :class "core" (<:h1 (_ (title self))) (<:h2 (_ (subtitle self))) (<:form :onsubmit (lifte (do-recover-password self (get-input-value _input1))) (with-field _input1 (<:span :id "passwd1-validation" :class "validation")) (with-field _input2 (<:span :id "passwd2-validation" :class "validation")) (<:p (<:input :type "submit" :class "button" :value (_"Reset Password") :disabled t)))))) (defmethod/remote destroy ((self <manager:recover-password)) (remove-class self "core-auth-widget") (call-next-method self)) (defmethod/remote init ((self <manager:recover-password)) (call-next-method self) (add-class self "core-auth-widget") (append self (template self))) ;; ------------------------------------------------------------------------- ;; Error Content ;; ------------------------------------------------------------------------- (defcomponent <manager:authentication-error (<widget:simple-content) ((message :host remote :initform "Sorry, an error occured."))) (defmethod/remote destroy ((self <manager:authentication-error)) (remove-class self "core-auth-widget") (call-next-method self)) (defmethod/remote init ((self <manager:authentication-error)) (setf (core-server::content self) (list (<:h1 (_ "Authentication Error")) (<:h2 (_ (or (get-parameter "message") (message self) "Sorry, and error occured."))))) (add-class self "core-auth-widget") (call-next-method self))
10,619
Common Lisp
.lisp
237
40.472574
94
0.624988
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
20b04d7573a61b117fee85b5bdcb3cb6f02423324a415cbf11cdb3b861ad09af
8,297
[ -1 ]
8,298
plugin.lisp
evrim_core-server/src/manager/src/mixin/plugin.lisp
;; ------------------------------------------------------------------------- ;; Manager Plugin ;; ------------------------------------------------------------------------- (in-package :manager) (defcomponent <manager:authentication-plugin (secure-object) () (:default-initargs :levels '(<manager:authentication-plugin/anonymous <manager:authentication-plugin/user) :permissions '((OWNER . 1) (GROUP . 1) (OTHER . 1) (ANONYMOUS . 0) (UNAUTHORIZED . -1)) :group (make-simple-group :name "admin") :owner (make-simple-user :name "root"))) ;; ------------------------------------------------------------------------- ;; Anonymous Plugin ;; ------------------------------------------------------------------------- (defplugin <manager:authentication-plugin/anonymous (secure-object/authorized) ()) (defmethod/local login-with-token ((self <manager:authentication-plugin/anonymous) token) (with-slots (oauth-key oauth-secret) application (describe (list 'trying-to-get-user token)) (let ((user (<core-server:login :token token :debug-p t ;; :cache-p nil :url (web-application.api-uri application "login") :username oauth-key :password oauth-secret))) (describe (list 'just-got-user token)) (setf (query-session :token) token) (answer-component self (list self :login user))))) (defmethod/remote do-login ((self <manager:authentication-plugin/anonymous) token) (let ((ctor (login-with-token self token))) (destroy self) ;; Destroy current controller (call/cc ctor self))) ;; Make new controller instance ;; ------------------------------------------------------------------------- ;; User Plugin ;; ------------------------------------------------------------------------- (defplugin <manager:authentication-plugin/user (secure-object/authorized) ()) (defmethod/local logout ((self <manager:authentication-plugin/user)) (with-slots (oauth-key oauth-secret) application (let* ((token (query-session :token)) (response (<core-server:logout :token token :url (web-application.api-uri application "logout") :username oauth-key :password oauth-secret))) (answer-component self (list self :logout response))))) (defmethod/remote do-logout ((self <manager:authentication-plugin/user)) (let ((ctor (logout self))) (destroy self) ;; Destroy current controller (call/cc ctor self))) ;; Make new controller instance
2,455
Common Lisp
.lisp
50
44.94
90
0.573394
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
a4df59a349f653a1d7a7538fe6c1b03b87c4d462b3d47a27a618ca8bc3010d1f
8,298
[ -1 ]
8,299
widget.lisp
evrim_core-server/src/manager/src/mixin/widget.lisp
(in-package :manager) ;; ------------------------------------------------------------------------- ;; <manager:login-link - Simple Anchor that invokes Manager App Login Process ;; ------------------------------------------------------------------------- (defcomponent <manager:login-link (<:a secure-object) ((auth-uri :host remote :initform (error "Provide :auth-uri")) (return-uri :host remote :initform (error "Provide :return-uri")) (login-text :host remote :initform "Login") (logout-text :host remote :initform "Logout")) (:default-initargs :levels '(<manager:login-link/anonymous <manager:login-link/registered) :permissions '((OWNER . 1) (GROUP . 1) (OTHER . 1) (ANONYMOUS . 0) (UNAUTHORIZED . -1)) :owner (make-simple-user :name "Admin") :group (make-simple-group :name "users"))) (defcomponent <manager:login-link/anonymous (<:a secure-object/authorized) ((secure-object :host lift :type <manager:login-link) (auth-uri :host remote :lift t) (return-uri :host remote :lift t) (login-text :host remote :lift t))) (defmethod/remote init ((self <manager:login-link/anonymous)) (with-slots (protocol host pathname) (slot-value window 'location) (let* ((paths (reverse (cdr (.split pathname "/")))) (paths (if (eq "" (car paths)) (.join (reverse (cons (return-uri self) (cdr paths))) "/") (.join (reverse (cons (return-uri self) paths) "/")))) (return-uri (+ protocol "//" host "/" paths)) (url (+ (auth-uri self) "?action=login&return-to=" (encode-u-r-i-component return-uri)))) (_debug (list "url" url)) (setf (slot-value self 'inner-h-t-m-l) (_ (login-text self)) (slot-value self 'onclick) (lifte (pop-up url "Login" 600 350)))))) (defcomponent <manager:login-link/registered (<:a <widget:simple secure-object/authorized) ((secure-object :host lift :type <manager:login-link) (logout-text :host remote :lift t))) (defmethod/remote init ((self <manager:login-link/registered)) (setf (slot-value self 'inner-h-t-m-l) (_ (logout-text self)) (slot-value self 'onclick) (lifte (do-logout (controller (widget-map self)))))) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2012 Metin Evrim Ulu ;; 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/>.
2,868
Common Lisp
.lisp
51
52.901961
90
0.661917
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
dc46b1c10a646c934951843c9e8e5062c130972d242614bda48ae1e17d2cd6ae
8,299
[ -1 ]
8,300
application.lisp
evrim_core-server/src/manager/src/mixin/application.lisp
(in-package :manager) (defmethod server.manager ((self server)) (aif (any (lambda (app) (and (typep app 'manager-application) app)) (server.applications self)) it (error "Couldn't find manager application in ~A" self))) ;; ------------------------------------------------------------------------- ;; Manager Web Application Mixin ;; ------------------------------------------------------------------------- (defapplication manager-web-application-mixin () ((oauth-handler-uri :host local :initform nil :accessor web-application.oauth-handler-uri) (oauth-key :host local :initform nil :accessor web-application.oauth-key) (oauth-secret :host local :initform nil :accessor web-application.oauth-secret) ;; (oauth-api-uri :host remote :initform (error "Provide :api-uri") ;; ;; "http://localhost:8080/api/oauth.core" ;; :accessor web-application.api-uri) )) (defmethod web-application.oauth-handler-uri ((self manager-web-application-mixin)) (or (slot-value self 'oauth-handler-uri) "auth.core")) (defmethod web-application.oauth-uri ((self manager-web-application-mixin)) (manager.oauth-uri (server.manager (application.server self)))) (defmethod web-application.api-uri ((self manager-web-application-mixin) method-name) (let ((url (manager.api-uri (server.manager (application.server self))))) (prog1 url (setf (uri.paths url) (append (uri.paths url) (list (list method-name))))))) ;; Tell compiler to treat doLogin properly in mixin/plugin.lisp (EVAL-WHEN (:LOAD-TOPLEVEL :COMPILE-TOPLEVEL :EXECUTE) (SETF (GETHASH 'DO-LOGIN TR.GEN.CORE.SERVER::+JAVASCRIPT-CPS-FUNCTIONS+) T (GETHASH '.DO-LOGIN TR.GEN.CORE.SERVER::+JAVASCRIPT-CPS-FUNCTIONS+) T) (DEFJSMACRO DO-LOGIN (&REST TR.GEN.CORE.SERVER::ARGS) `(.DO-LOGIN ,@TR.GEN.CORE.SERVER::ARGS))) (defhandler "auth\.core" ((self manager-web-application-mixin) (token "token") (hash "__hash")) (<:html (<:head (<:script :type "text/javascript" :src "library.core") (<:script :type "text/javascript" (lambda (stream) (rebinding-js/cc (hash token) stream (let ((opener window.opener)) (cond ((null opener) (alert "An error ocurred. window.opener is null. -Coretal.net") (window.close)) ((null token) (window.close)) ((and hash (slot-value opener hash)) (call/cc (slot-value opener hash) token) (window.close)) (t (let ((controller (slot-value opener 'controller))) (do-login controller token) (window.close))))))))) (<:body)))
2,577
Common Lisp
.lisp
54
43.074074
85
0.643482
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
bdb8f41883ebd653c5adc356db06bab6351ceb8431fee39ec4479223a2968f4b
8,300
[ -1 ]
8,301
class.lisp
evrim_core-server/src/security/class.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Abstract Security Classes ;; ------------------------------------------------------------------------- ;; ------------------------------------------------------------------------- ;; Abstract Group ;; ------------------------------------------------------------------------- (defclass+ abstract-group () ((name :accessor group.name :initform (error "Provide :name") :initarg :name :host local :index t :export t :print t) (users :host local :export nil :accessor group.users :relation groups :type abstract-user*)) (:ctor %make-abstract-group)) ;; ------------------------------------------------------------------------- ;; Abstract User ;; ------------------------------------------------------------------------- (defclass+ abstract-user () ((name :accessor user.name :initform nil :initarg :name :host both :index t :print t) (group :accessor user.group :initform nil :initarg :group :host both :print t) (groups :accessor user.groups :host local :type abstract-group* :relation users :export nil)) (:ctor %make-abtract-user)) (defmethod user.has-group ((user abstract-user) (group abstract-group)) (find group (cons (user.group user) (user.groups user)))) (defmethod user.has-group ((user abstract-user) (group string)) (find group (cons (user.group user) (user.groups user)) :key #'group.name :test #'equal)) ;; ------------------------------------------------------------------------- ;; Anonymous Group ;; ------------------------------------------------------------------------- (defclass+ anonymous-group (abstract-group) () (:ctor make-anonymous-group) (:default-initargs :name "Anonymous Group")) ;; ------------------------------------------------------------------------- ;; Anonymous User ;; ------------------------------------------------------------------------- (defclass+ anonymous-user (abstract-user) () (:ctor make-anonymous-user) (:default-initargs :name "Anonymous User" :group (make-anonymous-group)))
2,090
Common Lisp
.lisp
43
46.302326
76
0.454144
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fd581fd3f41085468cf411cbdb57a9e6c94971f57213f470c2979572f3860f33
8,301
[ -1 ]
8,302
authorize.lisp
evrim_core-server/src/security/authorize.lisp
;; ------------------------------------------------------------------------- ;; Authorization ;; ------------------------------------------------------------------------- ;; Author: Evrim Ulu <[email protected]> ;; Date: 11/3/2012 (in-package :core-server) ;; ------------------------------------------------------------------------- ;; Secure Object ;; ------------------------------------------------------------------------- (defparameter +umask+ '((owner . 1) (group . 0) (other . 0) (anonymous . 0) (unauthorized . -1))) (defclass+ secure-object () ((owner :host local :type abstract-user :export nil :reader secure.owner :initarg :owner :initform (error "Provide :owner")) (group :host local :type abstract-group :export nil :reader secure.group :initarg :group :initform (error "Provide :group")) (levels :host local :export nil :reader secure.levels :initform '(secure-object/unauthorized secure-object/authorized)) (permissions :host local :export nil :reader secure.permissions :initform +umask+)) (:ctor make-secure-object)) (defclass+ secure-object/authorized () ((secure-object :host lift :type secure-object :reader secure-object) (owner :lift t :host local :export nil :type abstract-user :reader secure.owner) (group :lift t :host local :export nil :type abstract-group :reader secure.group) (user :host local :export nil :initform (error "Provide :user") :type abstract-user :reader secure.user) (current-application :host local :export nil :initform (error "Provide :current-application") :type application :reader secure.application))) (defmethod component.application ((self secure-object/authorized)) (secure.application self)) (defclass+ secure-object/unauthorized () ((secure-object :host lift :type secure-object) (current-application :host local :export nil :initform (error "Provide :current-application") :type application :reader secure.application))) (defmethod component.application ((self secure-object/unauthorized)) (current-application self)) ;; ------------------------------------------------------------------------- ;; Authorization Helpers ;; ------------------------------------------------------------------------- (defmethod level->constructor ((self secure-object) (level integer) &optional levels) (let ((levels (or levels (secure.levels self)))) (cond ((>= level (length levels)) (car (reverse levels))) ((< level 0) (car levels)) (t (nth level levels))))) (defmethod %secure-constructor ((self secure-object) (user anonymous-user) &optional levels) (let ((level (or (cdr (assoc 'anonymous (secure.permissions self))) (cdr (assoc 'unauthorized (secure.permissions self))) -1))) (level->constructor self level levels))) (defmethod %secure-constructor ((self secure-object) (user abstract-user) &optional levels) (let* ((levels (or levels (secure.levels self))) (level (cond ;; Grant Maximum Permission ((or (user.has-group user "editor") (user.has-group user "admin")) (- (length (secure.permissions self)) 1)) ;; Owner Match ((eq user (secure.owner self)) (cdr (assoc 'owner (secure.permissions self)))) ;; Group Match ((find (group.name (secure.group self)) (user.groups user) :key #'group.name :test #'equal) (cdr (assoc 'group (secure.permissions self)))) ;; Default Permission (t (cdr (assoc 'other (secure.permissions self))))))) (level->constructor self level))) ;; ------------------------------------------------------------------------- ;; Authorization Protocol ;; ------------------------------------------------------------------------- (defmethod copy-lifted-slot ((self secure-object/authorized) (slot standard-slot-definition) value) (if (slot-definition-authorize slot) (authorize (secure.application self) (secure.user self) value) value)) (defmethod copy-lifted-slot ((self secure-object/unauthorized) (slot standard-slot-definition) value) (if (slot-definition-authorize slot) (authorize (secure.application self) (make-anonymous-user) value) value)) (defmethod authorize ((application application) (user abstract-user) (object t)) object) (defmethod authorize ((application application) (user abstract-user) (object list)) (mapcar (curry #'authorize application user) object)) (defmethod authorize ((application application) (user abstract-user) (object secure-object/authorized)) object) (defmethod authorize ((application application) (user abstract-user) (object secure-object/unauthorized)) object) (defmethod authorize ((application application) (user abstract-user) (object secure-object)) (apply (%secure-constructor object user) (list :secure-object object :user user :current-application application :owner (secure.owner object) :group (secure.group object))))
4,955
Common Lisp
.lisp
107
42.317757
85
0.624793
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
3b3a6e773c8de302de98a85b74d6ff3688aefa62c552c5c360de203b3e0525b5
8,302
[ -1 ]
8,303
authenticate.lisp
evrim_core-server/src/security/authenticate.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Authentication ;; ------------------------------------------------------------------------- ;; Author: Evrim Ulu <[email protected]> ;; Date: 11/03/2012 ;; ------------------------------------------------------------------------- ;; Simple Group ;; ------------------------------------------------------------------------- (defclass+ simple-group (abstract-group) () (:ctor make-simple-group)) ;; ------------------------------------------------------------------------- ;; Simple User ;; ------------------------------------------------------------------------- (defclass+ simple-user (abstract-user) () (:ctor make-simple-user)) (defcrud simple-group) (defcrud simple-user) (deftransaction init-authentication ((self database)) (let* ((admins (simple-group.add self :name "admin")) (editors (simple-group.add self :name "editor")) (admin (simple-user.add self :name "admin" :groups (list admins editors)))) (list admin admins editors))) (defvar +system-group+ (make-simple-group :name "admin")) (defvar +system+ (make-simple-user :name "admin" :group +system-group+))
1,204
Common Lisp
.lisp
28
41
76
0.436379
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8c1ec7c8c163171ca8b6f09a2ed81f3f185a2a992ea0ecde8380eded89523005
8,303
[ -1 ]
8,304
util.lisp
evrim_core-server/src/streams/util.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| Stream DSL Utilities ;;+---------------------------------------------------------------------------- (defun operator-search (operator goal-p &optional (successor #'operator-successor) (combiner #'append)) (core-search (list operator) goal-p successor combiner)) (defun operator-search-type (operator types) (let (lst) (operator-search operator (lambda (o) (if (atom types) (if (typep o types) (push o lst)) (if (any (lambda (a) (typep o a)) types) (push o lst))) nil)) lst))
1,429
Common Lisp
.lisp
30
43.066667
82
0.618705
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7cdf8ea77d8de3cf51bd0d43c18517b2d74c7ac4e5a8ef6ffabf561f1b371ae0
8,304
[ -1 ]
8,305
grammar.lisp
evrim_core-server/src/streams/grammar.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| A DSL For Stream Processing ;;| Author: Evrim Ulu <[email protected]> ;;| Date: 03/2008 ;;+---------------------------------------------------------------------------- ;; ;; This is the refactor of our old vector stream parser. It is generalized ;; to handle more streams and more operators. ;; ;;----------------------------------------------------------------------------- ;; About Stream DSL: ;;----------------------------------------------------------------------------- ;; i) Every operator starts with ':' to avoid symbol/package name conflicts ;; ii) walk-grammar walks DSL forms ;; ii) Every argument is walked ;; iii) To escape to lisp use (:do ..) operator ;; (eval-when (:load-toplevel :compile-toplevel :execute) (defun make-operator-symbol (name) (intern (format nil "~A-OPERATOR" name) (find-package :core-server))) (defun operator-ctor (operator) (symbol-function (make-operator-symbol operator))) (defun walk-grammar (lst) "Walker for Stream Grammar" (cond ((and (listp lst) (listp (car lst)) (keywordp (caar lst))) (apply (operator-ctor 'bind) (list (intern (symbol-name (caar lst))) :arguments (mapcar #'walk-grammar (cdar lst)) :binds (mapcar #'walk-grammar (cdr lst))))) ((and (listp lst) (keywordp (car lst))) (if (find-class (make-operator-symbol (symbol-name (car lst))) nil) (apply (operator-ctor (symbol-name (car lst))) (mapcar #'walk-grammar (cdr lst))) (apply (operator-ctor 'bind) (list (intern (symbol-name (car lst))) :arguments (mapcar #'walk-grammar (cdr lst)))))) (t lst)))) (defclass operator () () (:documentation "Base class for Grammar AST")) (defgeneric operator-successor (operator) (:documentation "Returns successors of this operator")) (defmethod operator-successor ((operator t)) nil) (defmethod operator-successor :around ((operator t)) (nreverse (flatten (call-next-method)))) (defmacro defoperator (name supers lambda-list) "Define a stream operator" `(prog1 (defclass ,(make-operator-symbol name) (,@(mapcar #'make-operator-symbol supers) operator) ,(mapcar (lambda (slot) (list slot :accessor slot :initarg (make-keyword slot))) (flatten (extract-argument-names lambda-list)))) (defun ,(make-operator-symbol name) ,lambda-list (make-instance ',(make-operator-symbol name) ,@(reduce (lambda (acc slot) (cons (make-keyword slot) (cons slot acc))) (flatten (extract-argument-names lambda-list)) :initial-value nil))) (defmethod operator-successor ((operator ,(make-operator-symbol name))) (append ,@(mapcar (lambda (arg) (list 'ensure-list `(,arg operator))) (extract-argument-names lambda-list)))))) ;;----------------------------------------------------------------------------- ;; Classification of Stream Operators ;;----------------------------------------------------------------------------- ;;----------------------------------------------------------------------------- ;; Stream Operators ;;----------------------------------------------------------------------------- ;; - Bind - Binds the result of the funciton to variables (m-v-b) ;; - Checkpoint - Checkpoints current stream while executing its body ;; - Commit - Commits current stream and returns from checkpoint block ;; - Rewind - Rewinds current stream and returns from checkpoint block ;; - Rewind-Return - Rewinds current stream, returns from checkpoint ;; block with the 'value'. ;;----------------------------------------------------------------------------- (defoperator bind () (func &key arguments binds)) (defoperator checkpoint () (&rest args)) (defoperator commit () ()) (defoperator rewind% () ()) (defoperator rewind () ()) (defoperator rewind-return () (value)) ;;----------------------------------------------------------------------------- ;; Control Flow Operators ;;----------------------------------------------------------------------------- ;; - And - Executes body in a sequence ;; - Or - Executes body until it finds a value other than nil ;; - Not - Inversion operator ;; - Return - Returns from current function ;; - Zero-or-more - Loops until body fails to match something ;; - Zom - Same as zero-or-more ;; - One-or-more - matches for the first time and loops the rest ;; - Oom - Same as one-or-more ;; - Cond - Usual condition operator ;; - If - Usual if operator ;; - Do - Escape operator, use to escape to lisp2 ;;----------------------------------------------------------------------------- (defoperator and () (&rest args)) (defoperator or () (&rest args)) (defoperator not () (&rest args)) (defoperator return () (value)) (defoperator zero-or-more () (&rest children)) (defoperator zom (zero-or-more) (&rest children)) (defoperator one-or-more () (&rest children)) (defoperator oom (one-or-more) (&rest children)) (defoperator if () (consequent then &optional else)) (defoperator cond () (&rest conditions)) (defoperator do () (&rest children)) (defoperator map () (target-list &rest body)) (defoperator sep () (seperator children)) (defoperator any (map) ()) (defoperator all (map) ()) (defoperator optional () (&rest children)) ;;----------------------------------------------------------------------------- ;; Debugging Operators ;;----------------------------------------------------------------------------- ;; - Debug - Prints the current peeked element ;; - Current - Describes stream object ;;----------------------------------------------------------------------------- (defoperator debug () ()) (defoperator current () ()) ;;----------------------------------------------------------------------------- ;; Vector Stream Operators ;;----------------------------------------------------------------------------- ;; - Type - Checks whether the peeked element is a type of type-name ;; - Sequence-case-sensitive - matches a sequence of characters (ie. String) ;; - Scs - Same as sequence-case-sensitive ;; - Sequence-case-insensitive - matches a sequence of characters case ;; insensitively. ;; - Sci - Same as sequeence-case-insensitive ;; - Collect - Collect source into target, used to make temporary arrays ;;----------------------------------------------------------------------------- (defoperator type () (type-name &optional target)) (defoperator sequence-case-sensitive () (value)) (defoperator scs (sequence-case-sensitive) (value)) (defoperator seq (sequence-case-sensitive) (value)) (defoperator sequence-case-insensitive () (value)) (defoperator sci (sequence-case-insensitive) (value)) (defoperator collect () (source target)) (defoperator indent () (&optional how-many)) (defoperator deindent () (&optional how-many)) ;;----------------------------------------------------------------------------- ;; Object Stream Operators ;;----------------------------------------------------------------------------- ;; - class? - Binds class of the current object stream ;; - class! - Sets the class of the current object stream ;;----------------------------------------------------------------------------- (defoperator class? () (klass)) (defoperator class! () (klass)) (defoperator slot! () (slot-name value)) (defoperator slot? () (slot-name &optional bind)) (defoperator oneof () (vals &optional target)) (defoperator noneof () (vals &optional target)) (defoperator satisfy () (slambda &optional target)) ;;----------------------------------------------------------------------------- ;; Stream DSL Operator Compilers ;;----------------------------------------------------------------------------- ;; ;; All stream DSL forms are compiled to lisp2 forms in order to be executable. ;; (eval-when (:load-toplevel :compile-toplevel :execute) (defgeneric expand-grammar (form expander stream-symbol &optional continue checkpoint) (:documentation "Compile grammar body")) (defmethod expand-grammar ((form t) (expander function) (stream symbol) &optional (continue nil) (checkpoint nil)) (declare (ignorable continue checkpoint)) (error "Please implement appropriate method for expand-grammar"))) (defmacro defgrammar-expander (name (form expander stream continue checkpoint) &body body) "Define a stream operator to lisp2 compiler" `(defmethod expand-grammar ((,form ,(make-operator-symbol name)) (,expander function) (,stream symbol) &optional (,continue nil) (,checkpoint nil)) (declare (ignorable ,continue ,checkpoint)) ,@body)) (defgrammar-expander bind (form expander stream continue checkpoint) (if (not (fboundp (func form))) (setf (func form) (intern (symbol-name (func form)) :core-server))) (if (< (length (arguments form)) 1) `(,(func form) ,stream) `(multiple-value-setq ,(arguments form) (,(func form) ,stream)))) ;;----------------------------------------------------------------------------- ;; Stream Operator Compilers ;;----------------------------------------------------------------------------- (defgrammar-expander checkpoint (form expander stream continue checkpoint) (with-unique-names (checkpoint) `(block ,checkpoint (checkpoint-stream ,stream) ,(funcall expander (apply (operator-ctor 'and) (args form)) expander stream continue checkpoint) (rewind-stream ,stream) ,continue))) (defgrammar-expander commit (form expander stream continue checkpoint) `(progn (commit-stream ,stream) (return-from ,checkpoint ,continue))) (defgrammar-expander rewind% (form expander stream continue checkpoint) `(prog1 ,continue (rewind-stream ,stream))) (defgrammar-expander rewind (form expander stream continue checkpoint) `(progn ,(funcall expander (walk-grammar `(:rewind%)) expander stream continue checkpoint) (return-from ,checkpoint ,continue))) (defgrammar-expander rewind-return (form expander stream continue checkpoint) (funcall expander (walk-grammar `(:and (:rewind%) (:return ,(value form)))) expander stream continue checkpoint)) ;;----------------------------------------------------------------------------- ;; Control Operator Compilers ;;----------------------------------------------------------------------------- (defgrammar-expander and (form expander stream continue checkpoint) (cond ((= 0 (length (args form))) nil) ((= 1 (length (args form))) (funcall expander (car (args form)) expander stream continue checkpoint)) (t `(and ,@(mapcar (rcurry expander expander stream t checkpoint) (args form)))))) (defgrammar-expander or (form expander stream continue checkpoint) `(or ,@(mapcar (rcurry expander expander stream nil checkpoint) (args form)))) (defgrammar-expander not (form expander stream continue checkpoint) `(not ,@(mapcar (rcurry expander expander stream continue checkpoint) (args form)))) (defgrammar-expander return (form expander stream continue checkpoint) `(progn (if (< (current-checkpoint ,stream) cp) (error "This parser rule is not functional")) (do ((i (current-checkpoint ,stream) (current-checkpoint ,stream))) ((= (the fixnum i) (the fixnum cp)) nil) (commit-stream ,stream)) (return-from rule-block ,(value form)))) (defgrammar-expander zero-or-more (form expander stream continue checkpoint) `(not (do () ((not ,(funcall expander (apply (operator-ctor 'and) (children form)) expander stream continue checkpoint)))))) (defgrammar-expander one-or-more (form expander stream continue checkpoint) (funcall expander (apply (operator-ctor 'and) (append (children form) (list (apply (operator-ctor 'zom) (children form))))) expander stream continue checkpoint)) (defgrammar-expander if (form expander stream continue checkpoint) `(if ,(consequent form) ,(funcall expander (then form) expander stream continue checkpoint) ,(if (arnesi::else form) (funcall expander (arnesi::else form) expander stream continue checkpoint) continue))) (defgrammar-expander cond (form expander stream continue checkpoint) `(prog1 ,continue (cond ,@(mapcar #'(lambda (atom) (list (car atom) (funcall expander (apply (operator-ctor 'and) (mapcar #'walk-grammar (cdr atom))) expander stream continue checkpoint))) (conditions form))))) (defgrammar-expander do (form expander stream continue checkpoint) `(prog1 ,continue ,@(children form))) (defgrammar-expander map (form expander stream continue checkpoint) `(prog1 ,continue (mapcar (lambda (it) ,@(mapcar (rcurry expander expander stream continue checkpoint) (body form))) ,(target-list form)))) (defgrammar-expander any (form expander stream continue checkpoint) `(any (lambda (it) ,@(mapcar (rcurry expander expander stream continue checkpoint) (body form))) ,(target-list form))) (defgrammar-expander all (form expander stream continue checkpoint) `(all (lambda (it) ,@(mapcar (rcurry expander expander stream continue checkpoint) (body form))) ,(target-list form))) ;;----------------------------------------------------------------------------- ;; Debug Operator Compilers ;;----------------------------------------------------------------------------- (defgrammar-expander debug (form expander stream continue checkpoint) `(prog1 ,continue (format t "current:~A~%" (peek-stream ,stream)))) (defgrammar-expander current (form expander stream continue checkpoint) `(prog1 ,continue (describe ,stream))) ;;----------------------------------------------------------------------------- ;; Vector Operator Compilers ;;----------------------------------------------------------------------------- (defgrammar-expander type (form expander stream continue checkpoint) `(if (typep (peek-stream ,stream) ',(type-name form)) ,(if (target form) `(setq ,(target form) (read-stream ,stream)) `(read-stream ,stream)))) (defgrammar-expander sequence-case-sensitive (form expander stream continue checkpoint) (with-unique-names (str len count match element) `(let* ((,str ,(if (stringp (value form)) (string-to-octets (value form) :utf-8) `(string-to-octets ,(value form) :utf-8))) (,len (length ,str))) (checkpoint-stream ,stream) (do ((,element (peek-stream ,stream) (peek-stream ,stream)) (,count 0 (+ ,count 1)) (,match t (eq ,element (aref ,str ,count)))) ((or (null ,match) (>= ,count ,len)) (if ,match (prog1 t (commit-stream ,stream)) (prog1 nil (rewind-stream ,stream)))) (read-stream ,stream))))) (defgrammar-expander sequence-case-insensitive (form expander stream continue checkpoint) (with-unique-names (str-upcase str-downcase len count match element) `(let* ((,str-upcase ,(if (stringp (value form)) (string-to-octets (string-upcase (value form)) :utf-8) `(string-to-octets (string-upcase ,(value form)) :utf-8))) (,str-downcase ,(if (stringp (value form)) (string-to-octets (string-downcase (value form)) :utf-8) `(string-to-octets (string-downcase ,(value form)) :utf-8))) (,len (length ,str-upcase))) (checkpoint-stream ,stream) (do ((,element (peek-stream ,stream) (peek-stream ,stream)) (,count 0 (+ ,count 1)) (,match t (or (eq ,element (aref ,str-upcase ,count)) (eq ,element (aref ,str-downcase ,count))))) ((or (null ,match) (>= ,count ,len)) (if ,match (prog1 t (commit-stream ,stream)) (prog1 nil (rewind-stream ,stream)))) (read-stream ,stream))))) (defgrammar-expander collect (form expander stream continue checkpoint) `(or (push-atom ,(source form) ,(target form)) t)) (defgrammar-expander oneof (form expander stream continue checkpoint) (cond ((listp (vals form)) (error 'notimplementedyet)) ((stringp (vals form)) (funcall expander (walk-grammar `(:or ,@(mapcar #'(lambda (x) `(:and ,x (:do ,(if (target form) `(setq ,(target form) ,x))))) (nreverse (reduce #'(lambda (acc item) (cons item acc)) (vals form) :initial-value nil))))) expander stream continue checkpoint)) ((numberp (vals form)) (error 'notimplementedyet)))) (defgrammar-expander noneof (form expander stream continue checkpoint) (let ((peeq (gensym))) (cond ((stringp (vals form)) `(let ((,peeq (peek-stream ,stream))) (if (not (or ,@(mapcar #'(lambda (x) `(= ,peeq ,(char-code x))) (nreverse (reduce #'(lambda (acc item) (cons item acc)) (vals form) :initial-value nil))))) (prog1 t (setq ,(target form) (read-stream ,stream))))))))) (defgrammar-expander satisfy (form expander stream continue checkpoint) `(if (funcall ,(slambda form) (peek-stream ,stream)) ,(if (target form) `(prog1 ,continue (setq ,(target form) (read-stream ,stream))) continue) ,(not continue))) (defgrammar-expander optional (form expander stream continue checkpoint) (funcall expander (walk-grammar `(:checkpoint ,@(children form) (:commit))) expander stream continue checkpoint)) (defoperator type2 () (type-name &optional target)) (defgrammar-expander type2 (form expander stream continue checkpoint) (if (target form) `(setq ,(target form) (read-stream2 ,stream ',(type-name form))) `(read-stream2 ,stream ',(type-name form)))) (defoperator type3 () (type-name &optional target)) (defgrammar-expander type3 (form expander stream continue checkpoint) (if (target form) `(if (,(type-name form) (peek-stream ,stream)) (setq ,(target form) (read-stream ,stream))) `(if (,(type-name form) (peek-stream ,stream)) (read-stream ,stream)))) ;;----------------------------------------------------------------------------- ;; Object Stream Operator Compilers ;;----------------------------------------------------------------------------- (defgrammar-expander class? (form expander stream continue checkpoint) `(setq ,(klass form) (slot-value ,stream '%clazz))) (defgrammar-expander class! (form expander stream continue checkpoint) `(setf (clazz ,stream) ,(klass form))) (defgrammar-expander slot! (form expander stream continue checkpoint) `(write-stream ,stream (cons ,(slot-name form) ,(value form)))) (defgrammar-expander slot? (form expander stream continue checkpoint) `(when (eq (car (peek-stream ,stream)) ,(slot-name form)) ,(if (bind form) `(setq ,(bind form) (cdr (read-stream ,stream))) `(read-stream ,stream)))) ;; (defparser crlf? () ;; (:or (:checkpoint #\Return #\Newline (:commit)) #\Newline) ;; (:return t)) ;; (defrender crlf! () ;; #\Return #\Newline) ;; (defrender hex-value! (hex) ;; (:byte! (aref +hex-alphabet+ (floor (/ hex 16)))) ;; (:byte! (aref +hex-alphabet+ (rem hex 16)))) ;; (defrender gee! () ;; "gee") ;; (defparser lwsp? () ;; (:zom (:type (or space? tab? carriage-return? linefeed?))) ;; (:return t)) ;; (defparser hex-value? (a b) ;; (:or (:and (:type digit? a) ;; (:do (setq a (- (the (unsigned-byte 8) a) 48)))) ;; (:and (:type hex-upchar? a) ;; (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 65))))) ;; (:and (:type hex-lochar? a) ;; (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 97)))))) ;; (:or (:and (:type digit? b) ;; (:do (setq b (- (the (unsigned-byte 8) b) 48)))) ;; (:and (:type hex-upchar? b) ;; (:do (setq b (+ 10 (- (the (unsigned-byte 8) b) 65))))) ;; (:and (:type hex-lochar? b) ;; (:do (setq b (+ 10 (- (the (unsigned-byte 8) b) 97)))))) ;; (:return (+ (* (the (unsigned-byte 8) a) 16) (the (unsigned-byte 8) b)))) ;; (defparser escaped? (hex) ;; (:and #\% (:hex-value? hex) (:return hex))) ;; (defparser quoted? ((value (make-accumulator :byte)) c b) ;; (:or ;; (:and ;; #\" ;; (:zom (:or ;; (:checkpoint ;; (:and #\\ #\" ;; (:do (push-atom #\" value)) ;; (:commit))) ;; (:and #\" (:return (octets-to-string value :utf-8))) ;; (:and (:or ;; (:and (:utf-escaped? b c) (:collect b value)) ;; (:escaped? c) ;; (:type (or visible-char? space?) c)) ;; (:collect c value))))) ;; (:and (:zom (:or ;; (:and (:utf-escaped? b c) (:collect b value)) ;; (:escaped? c) ;; (:type (or visible-char? space?) c)) ;; (:collect c value)) ;; (:return (octets-to-string value :utf-8))))) ;; (defvector->lisp rule-1 (a b c &aux def) ;; (:zom (:or (:and (:seq "Username:") ;; (:zom (:type visible-char? c) (:collect c username))) ;; (:type octet?))) ;; (:return username)) ;; (deflisp->vector rule-2 (a b c &aux gee) ;; (:char! a) (:byte! b) (:char! c)) ;; (defvector->vector utf-8?! () ;; (:zom (:type octet? c) ;; (:if (> c 127) ;; (:and ;; (:checkpoint ;; (read-until-utf8 acc)) ;; (:char! (octets-to-string acc :utf-8))))))
21,935
Common Lisp
.lisp
508
39.700787
104
0.588081
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7cb33747298b559fd5ab158ce1a4215cfacfe0d883827f0d88cbee0a48c8f6a8
8,305
[ -1 ]
8,306
parser.lisp
evrim_core-server/src/streams/parser.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;(declaim (optimize (speed 3) (space 2) (safety 0) (debug 0) (compilation-speed 0))) ;;;----------------------------------------------------------------------------- ;;; HENRY G. BAKER PARSER GENERATOR WITH EXTENDED GRAMMAR ;;; http://linux.rice.edu/~rahul/hbaker/Prag-Parse.html ;;;----------------------------------------------------------------------------- ;;;----------------------------------------------------------------------------- ;;; Simple Type Definitions - Kludge macros since CL doesn't have Mr. Curry. ;;;----------------------------------------------------------------------------- (defmacro defatom (name args &rest body) "Match definition macro that provides a common lexical environment for matchers." `(progn (declaim (inline ,name)) (defun ,name ,(if args (list 'c '&aux args) '(c)) (if c (let ((c (if (characterp c) (char-code c) c))) (declare (type (unsigned-byte 8) c)) ,@body))) (export ',name) (deftype ,name () `(satisfies ,',name)))) ;;; http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2 (defatom bit? () (or (= c 0) (= c 1))) (defatom octet? () (and (> c -1) (< c 256))) (defatom char? () (and (> c -1) (< c 128))) (defatom upalpha? () (and (> c 64) (< c 91))) (defatom loalpha? () (and (> c 96) (< c 123))) (defatom alpha? () (or (loalpha? c) (upalpha? c))) (defatom digit? () (and (> c 47) (< c 58))) (defatom alphanum? () (or (alpha? c) (digit? c))) (defatom control? () (or (= c 127) (and (> c -1) (< c 32)))) (defatom carriage-return? () (= c 13)) (defatom linefeed? () (= c 10)) (defatom space? () (= c 32)) (defatom tab? () (= c 9)) (defatom no-break-space? () (= c 160)) (defatom double-quote? () (= c 34)) (defatom return? () (= c 13)) (defatom white-space? () (or (space? c) (tab? c) (no-break-space? c))) (defatom visible-char? () (and (> c 32) (< c 127))) (defatom hex-upchar? () (and (> c 64) (< c 71))) (defatom hex-lochar? () (and (> c 96) (< c 103))) (defatom hex-char? () (or (hex-upchar? c) (hex-lochar? c))) (defatom hex? () (or (digit? c) (hex-char? c))) (defatom upper-case? () (and (> c 64) (< c 91))) (defatom lower-case? () (and (> c 96) (< c 123))) ;;;--------------------------------------------------------------------------- ;;; Parser ;;;--------------------------------------------------------------------------- (eval-when (:compile-toplevel :execute :load-toplevel) (defgeneric expand-parser (form expander stream &optional continue checkpoint) (:documentation "special dsl for parsing")) (defmethod expand-parser ((form t) (expander function) (stream symbol) &optional (continue nil) (checkpoint nil)) (declare (ignore continue checkpoint)) `(when (eq (peek-stream ,stream) ,(if (characterp form) (char-code form) form)) (read-stream ,stream))) (defmethod expand-parser ((form operator) (expander function) (stream symbol) &optional (continue nil) (checkpoint nil)) (expand-grammar form expander stream continue checkpoint))) (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro defparser (name args &rest body) "Parser rule defining macro that provides a common lexical environment for rules." (with-unique-names (stream) (flet ((rule-args () (if args (list* stream '&aux args) (list stream)))) `(defun ,name ,(rule-args) (block rule-block (let ((cp (current-checkpoint ,stream))) (declare (ignorable cp)) ,(expand-parser (walk-grammar `(:checkpoint ,@body)) #'expand-parser stream) nil))))))) (defmacalias defparser defrule) (defparser crlf? () (:or (:checkpoint #\Return #\Newline (:commit)) #\Newline) (:return t)) (defparser lwsp? () (:zom (:type (or space? tab? carriage-return? linefeed?))) (:return t)) (defparser hex-value? (a b) (:or (:and (:type digit? a) (:do (setq a (- (the (unsigned-byte 8) a) 48)))) (:and (:type hex-upchar? a) (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 65))))) (:and (:type hex-lochar? a) (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 97)))))) (:or (:and (:type digit? b) (:do (setq b (- (the (unsigned-byte 8) b) 48)))) (:and (:type hex-upchar? b) (:do (setq b (+ 10 (- (the (unsigned-byte 8) b) 65))))) (:and (:type hex-lochar? b) (:do (setq b (+ 10 (- (the (unsigned-byte 8) b) 97)))))) (:return (+ (* (the (unsigned-byte 8) a) 16) (the (unsigned-byte 8) b)))) (defparser hex-value*? (a acc) (:zom (:or (:and (:type digit? a) (:do (setq a (- (the (unsigned-byte 8) a) 48)))) (:and (:type hex-upchar? a) (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 65))))) (:and (:type hex-lochar? a) (:do (setq a (+ 10 (- (the (unsigned-byte 8) a) 97)))))) (:do (push a acc))) (:return (reduce (lambda (acc a) (+ (ash acc 4) a)) (reverse acc) :initial-value 0))) ;; escaped = "%" hex hex (eval-when (:load-toplevel :compile-toplevel :execute) (defparser escaped? (hex) #\% (:hex-value? hex) (:return hex))) (defparser digit-value? (d) (:type digit? d) (:return (- (the (unsigned-byte 8) d) 48))) (eval-when (:load-toplevel :compile-toplevel :execute) (defparser fixnum? ((acc (make-accumulator)) c) (:type digit? c) (:collect c acc) (:zom (:type digit? c) (:collect c acc)) (:return (parse-integer acc)))) (defparser string? (c (acc (make-accumulator))) (:zom (:type visible-char? c) (:collect c acc)) (:return acc)) (defparser float? ((acc (make-accumulator)) c) (:and (:zom (:type digit? c) (:collect c acc)) (:and #\. (:collect #\. acc)) (:oom (:type digit? c) (:collect c acc))) (:return acc)) (eval-when (:load-toplevel :compile-toplevel :execute) (defparser version? (version d) (:fixnum? d) (:do (push d version)) (:zom #\. (:fixnum? d) (:do (push d version))) (:return (nreverse version)))) (eval-when (:load-toplevel :compile-toplevel :execute) (defparser utf-escaped? (f1 f2 f3 f4) (:sci "%u") (:type hex? f1) (:type hex? f2) (:type hex? f3) (:type hex? f4) ;; (:do (describe (list f1 f2 f3 f4))) (:return ;;(+ (- f1 48) (* 8 (- f2 48)) (* 16 (- f3 48)) (* 32 (- f4 48))) (with-input-from-string (s (format nil "#x~C~C~C~C" (code-char f1) (code-char f2) (code-char f3) (code-char f4))) (read s))))) ;; ie. \u0040 -> @ symbol ;; used in javascript (defparser utf-escaped2? (f1 f2 f3 f4) (:seq "\\u") (:type hex? f1) (:type hex? f2) (:type hex? f3) (:type hex? f4) ;; (:do (describe (list f1 f2 f3 f4))) (:return ;;(+ (- f1 48) (* 8 (- f2 48)) (* 16 (- f3 48)) (* 32 (- f4 48))) (with-input-from-string (s (format nil "#x~C~C~C~C" (code-char f1) (code-char f2) (code-char f3) (code-char f4))) (read s)))) (defparser escaped-string? (c (acc (make-accumulator :byte))) (:oom (:or (:utf-escaped2? c) (:escaped? c) (:type octet? c)) (:collect c acc)) (:return (if (> (length acc) 0) (octets-to-string acc :utf-8) acc))) (defparser quoted? (c acc identifier) (:or (:and #\' (:do (setq identifier #.(char-code #\')))) (:and #\" (:do (setq identifier #.(char-code #\"))))) (:or (:and (:if (eq identifier #.(char-code #\')) #\' #\") (:return "")) (:and (:do (setq acc (make-accumulator :byte))) (:oom (:if (eq identifier #.(char-code #\')) (:not #\') (:not #\")) (:or (:utf-escaped2? c) (:escaped? c) (:and #\\ (:type octet? c)) (:type octet? c)) (:collect c acc)) (:return (octets-to-string acc :utf-8)))) ;; (defparser quoted? (c (acc (make-accumulator :byte))) ;; (:or (:and #\' ;; (:zom (:or (:and (:seq "\\\'") (:do (setq c #.(char-code #\')))) ;; (:and (:not #\') ;; (:or (:escaped? c) ;; (:type octet? c)))) ;; (:collect c acc)) ;; (:return (octets-to-string acc :utf-8))) ;; (:and #\" ;; (:zom ;; (:or ;; (:and (:seq "\\\"") (:do (setq c #.(char-code #\")))) ;; (:and (:not #\") ;; (:or (:escaped? c) ;; (:type octet? c)))) ;; (:collect c acc)) ;; (:return (octets-to-string acc :utf-8))))) (defparser parse-line? (c (acc (make-accumulator))) (:zom (:or (:and #\Newline (:return acc)) (:and (:type octet? c) (:collect c acc)))) (:return acc))) (defparser lines? (c (acc (make-accumulator)) lst) (:oom (:or (:and #\Newline (:do (push acc lst) (setq acc (make-accumulator)))) (:and (:type octet? c) (:collect c acc)))) (:return (nreverse (if (> (length acc) 0) (cons acc lst) lst)))) (defparser words? (c (acc (make-accumulator)) lst) (:lwsp?) (:zom (:or (:and #\Space (:do (push acc lst) (setq acc (make-accumulator)))) (:and (:type octet? c) (:collect c acc)))) (:do (if (> (length acc) 0 ) (push acc lst))) (:return (reverse lst))) ;; (declaim (inline match-atom)) ;; (defun match-atom (stream atom) ;; (let ((c (peek-stream stream))) ;; (cond ;; ((and (characterp atom) (> (char-code atom) 127)) ;;utf-8 ;; (prog1 t ;; (checkpoint-stream stream) ;; (prog1 t ;; (reduce #'(lambda (acc atom) ;; (declare (ignore acc)) ;; (if (eq (the (unsigned-byte 8) atom) (the (unsigned-byte 8) c)) ;; (progn ;; (read-stream c) (setq c (peek-stream stream))) ;; (progn ;; (rewind-stream stream) ;; (return-from match-atom nil))) ;; nil) ;; (string-to-octets (string atom) :utf-8) :initial-value nil)) ;; (commit-stream stream))) ;; ((characterp atom) (eq c (char-code atom))) ;; (t (eq atom c))))) ;; (defmacro match/stream (stream atom) ;; `(when (match-atom ,stream ,atom) ;; (read-stream ,stream))) ;; (defmacro match-type/stream (stream type var) ;; `(when (typep (peek-stream ,stream) ',type) ;; ,(if (null var) ;; `(read-stream ,stream) ;; `(setq ,var (read-stream ,stream))))) ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (defvar +parser-rules+ (make-hash-table :test #'equal)) ;; Rule or not ;; (defvar +checkpoint+ nil)) ;; used for backtracking ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (defun compile-parser-grammar (stream-var form ;; &optional (match-func 'match/stream) ;; (match-type-func 'match-type/stream)) ;; (labels ;; ((compile1 (form &optional (continue nil)) ;; (cond ;; ((and (consp form) (keywordp (car form))) ;; (case (car form) ;; ((:and) ;; `(and ,@(compiled-subexprs form t))) ;; ((:or) ;; `(or ,@(compiled-subexprs form nil))) ;; ((:not) ;; `(not ,@(compiled-subexprs form continue))) ;; ((:checkpoint) ;; (with-unique-names (checkpoint) ;; (let ((+checkpoint+ checkpoint)) ;; `(block ,checkpoint ;; (checkpoint-stream ,stream-var) ;; ,(compile1 `(:and ,@(cdr form))) ;; (rewind-stream ,stream-var) ;; ,continue)))) ;; ((:commit) ;; `(progn ;; (commit-stream ,stream-var) ;; (return-from ,+checkpoint+ ,continue))) ;; ((:rewind) ;; `(progn ;; (rewind-stream ,stream-var) ;; (return-from ,+checkpoint+ ,continue))) ;; ((:return) ;; `(let ((retval (multiple-value-list ,(cadr form)))) ;; (cond ;; ((= (the fixnum (current-checkpoint ,stream-var)) (the fixnum cp)) nil) ;; ((< (the fixnum (current-checkpoint ,stream-var)) (the fixnum cp)) ;; (error "This parser rule is not functional!")) ;; (t (do ((i (current-checkpoint ,stream-var) ;; (current-checkpoint ,stream-var))) ;; ((= (the fixnum i) (the fixnum cp)) nil) ;; (commit-stream ,stream-var)))) ;; (return-from rule-block (apply #'values retval)))) ;; ((:rewind-return) ;; `(progn (rewind-stream ,stream-var) ;; ,(compile1 `(:return ,(cadr form))))) ;; ((:zero-or-more :zom) ;; `(not (do () ((not ,(compile1 `(:and ,@(cdr form)) continue)))))) ;; ((:one-or-more :oom) ;; (compile1 `(:and ,@(cdr form) (:zom ,@(cdr form))) continue)) ;; ((:if) ;; `(prog1 ,continue ;; (if ,(cadr form) ;; ,(compile1 (caddr form)) ;; ,(if (cadddr form) ;; (compile1 (cadddr form)))))) ;; ((:cond) ;; `(prog1 ,continue ;; (cond ;; ,@(mapcar #'(lambda (atom) ;; (list (car atom) ;; (compile1 `(:and ,@(cdr atom))))) ;; (cdr form))))) ;; ((:sequence-case-sensitive :scs :sequence :seq) ;; (if (stringp (cadr form)) ;; (compile1 ;; `(:checkpoint ;; ,@(nreverse ;; (reduce #'(lambda (acc atom) ;; (cons atom acc)) ;; (cadr form) :initial-value nil)) ;; (:commit))) ;; (compile1 ;; `(:checkpoint ;; (:do ;; (reduce #'(lambda (acc atom) ;; (declare (ignore acc)) ;; (when (not (,match-func ,stream-var atom)) ;; (rewind-stream ,stream-var) ;; (return-from ,+checkpoint+ nil))) ;; ,(cadr form) :initial-value nil)) ;; (:commit))))) ;; ((:sequence-case-insensitive :sci) ;; (if (stringp (cadr form)) ;; (compile1 ;; `(:checkpoint ;; ,@(nreverse ;; (reduce #'(lambda (acc atom) ;; (let ((upcase (char-upcase atom)) ;; (downcase (char-downcase atom))) ;; (if (eq upcase downcase) ;; (cons atom acc) ;; (cons (list ':or upcase downcase) ;; acc)))) ;; (cadr form) :initial-value nil)) ;; (:commit))) ;; (compile1 ;; `(:checkpoint ;; (:do ;; (reduce #'(lambda (acc atom) ;; (declare (ignore acc)) ;; (when (not (or (,match-func ,stream-var (char-upcase atom)) ;; (,match-func ,stream-var (char-downcase atom)))) ;; (rewind-stream ,stream-var) ;; (return-from ,+checkpoint+ nil))) ;; ,(cadr form) :initial-value nil)) ;; (:commit))))) ;; ((:empty) t) ;; ((:type) ;; (assert (null (cdddr form))) ;; `(,match-type-func ,stream-var ,(cadr form) ,(caddr form))) ;; ((:do) ;; (assert (not (null (cdr form)))) ;; `(progn ,@(cdr form) ;; ,continue)) ;; ((:collect) ;; (assert (null (cdddr form))) ;; `(or (push-atom ,(cadr form) ,(caddr form)) t)) ;; ((:debug) ;; `(or (format t "current char-code:~D~%" (let ((c (peek-stream ,stream-var))) ;; (if (characterp c) ;; (char-code c) ;; c))) ;; ,continue)) ;; ((:current) ;; `(progn (describe ,stream-var) ,continue)) ;; (t ;; (if (< (length (cdr form)) 1) ;; `(,(intern (symbol-name (car form))) ,stream-var) ;; `(multiple-value-setq ,(cdr form) ;; (,(intern (symbol-name (car form))) ,stream-var)))))) ;; ;; (if (gethash (car form) +parser-rules+) ;; ;; (if (< (length (cdr form)) 1) ;; ;; `(,(gethash (car form) +parser-rules+) ,stream-var) ;; ;; `(multiple-value-setq ,(cdr form) (,(gethash (car form) +parser-rules+) ,stream-var))) ;; ;; (error "No rule associated with:~A" (car form)))))) ;; (t ;; `(,match-func ,stream-var ,form)))) ;; (compiled-subexprs (form &optional (continue t)) ;; (mapcar #'(lambda (f) (compile1 f continue)) (cdr form)))) ;; (compile1 form)))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; Rules ;; ;;;----------------------------------------------------------------------------- ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (defmacro defrule (name args &rest body) ;; "Rule definition macro that provides a common lexical environment for rules." ;; (with-unique-names (stream) ;; (flet ((rule-args () ;; (if args ;; (list* stream '&aux args) ;; (list stream)))) ;; (setf (gethash (make-keyword name) +parser-rules+) name) ;; `(defun ,name ,(rule-args) ;; (block rule-block ;; (let ((cp (current-checkpoint ,stream))) ;; (declare (ignorable cp)) ;; ,(compile-parser-grammar stream `(:checkpoint ,@body)) ;; nil))))))) ;; ;;;----------------------------------------------------------------------------- ;; ;;; Rules ;; ;;;----------------------------------------------------------------------------- ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (defmacro defrule (name args &rest body) ;; "Rule definition macro that provides a common lexical environment for rules." ;; (with-unique-names (stream) ;; (flet ((rule-args () ;; (if args ;; (list* stream '&aux args) ;; (list stream)))) ;; (setf (gethash (make-keyword name) +parser-rules+) name) ;; `(defun ,name ,(rule-args) ;; (block rule-block ;; (let ((cp (current-checkpoint ,stream))) ;; (declare (ignorable cp)) ;; ,(compile-parser-grammar stream `(:checkpoint ,@body)) ;; nil))))))) ;; (defmacro defvector-render (name args &body body) ;; `(defmethod ,name ((stream core-vector-io-stream) ,@args) ;; ,@body ;; stream)) ;; (defvector-render null! () ;; (string! stream "NIL")) ;; (defvector-render t! () ;; (string! stream "T")) ;; (defvector-render boolean! (boolean) ;; (if boolean ;; (t! stream) ;; (null! stream))) ;; (defvector-render symbol! ((symbol symbol)) ;; (let ((package (symbol-package symbol)) ;; (name (prin1-to-string symbol))) ;; (cond ((eq package (find-package 'common-lisp)) (string! stream "CL:")) ;; ((eq package (find-package 'keyword)) (string! stream #\:)) ;; (t (string! stream (package-name package)) ;; (string! stream "::"))) ;; (if (char= (char name (1- (length name))) #\|) ;; (string! stream (subseq name (position #\| name))) ;; (string! stream (subseq name (1+ (or (position #\: name :from-end t) -1))))))) ;; (defvector-render sequence! ((sequence sequence)) ;; (flet ((proper-sequence (length) ;; (let ((id (set-known-object serialization-state object))) ;; (string! stream "(:SEQUENCE ") ;; (fixnum! stream id) ;; (string! stream " :CLASS ") ;; (symbol! stream (etypecase object (list 'list) (vector 'vector))) ;; (string! stream " :SIZE ") ;; (fixnum! stream length) ;; (unless (zerop length) ;; (string! stream " :ELEMENTS (") ;; (map nil ;; #'(lambda (element) ;; (char! stream #\Space) ;; (funcall (type-of element) stream serialization-state)) ;; object)) ;; (string! stream " ) )"))) ;; (improper-list () ;; (let ((id (set-known-object serialization-state object))) ;; (string! stream "(:CONS ") ;; (fixnum! stream id) ;; (char! stream #\Space) ;; (serialize-sexp-internal (car object) stream serialization-state) ;; (char! stream #\Space) ;; (serialize-sexp-internal (cdr object) stream serialization-state) ;; (string! stream " ) ")))) ;; (let ((id (known-object-id serialization-state object))) ;; (if id ;; (progn ;; (string! stream "(:REF . ") ;; (fixnum! stream id) ;; (string! stream ")")) ;; (multiple-value-bind (seq-type length) (sequence-type-and-length object) ;; (ecase seq-type ;; ((:proper-sequence :proper-list) (proper-sequence length)) ;; ((:dotted-list :circular-list) (improper-list)))))))) ;; (defvector-render hash-table! ((hash-table hash-table)) ;; (let ((id (known-object-id serialization-state object))) ;; (if id ;; (progn ;; (string! stream "(:REF . ") ;; (fixnum! stream id) ;; (string! stream ")")) ;; (let ((count (hash-table-count object))) ;; (setf id (set-known-object serialization-state object)) ;; (string! stream "(:HASH-TABLE ") ;; (fixnum! stream id) ;; (string! stream " :TEST ") ;; (symbol! stream (hash-table-test object)) ;; (string! stream " :SIZE ") ;; (fixnum! stream (hash-table-size object)) ;; (string! stream " :REHASH-SIZE ") ;; (fixnum! stream (hash-table-rehash-size object)) ;; (string! stream " :REHASH-THRESHOLD ") ;; (prin1 (hash-table-rehash-threshold object) stream) ;; (unless (zerop count) ;; (write-string " :ENTRIES (" stream) ;; (maphash #'(lambda (key value) ;; (write-string " (" stream) ;; (serialize-sexp-internal key stream serialization-state) ;; (write-string " . " stream) ;; (serialize-sexp-internal value stream serialization-state) ;; (princ ")" stream)) ;; object)) ;; (write-string " ) )" stream))))) ;; (defmethod structure-object! ((stream core-vector-io-stream) ;; (structure-object structure-object)) ;; (let ((id (known-object-id serialization-state object))) ;; (if id ;; (progn ;; (write-string "(:REF . " stream) ;; (prin1 id stream) ;; (write-string ")" stream)) ;; (let ((serializable-slots (get-serializable-slots serialization-state object))) ;; (setf id (set-known-object serialization-state object)) ;; (write-string "(:STRUCT " stream) ;; (prin1 id stream) ;; (write-string " :CLASS " stream) ;; (print-symbol (class-name (class-of object)) stream) ;; (when serializable-slots ;; (write-string " :SLOTS (" stream) ;; (mapc #'(lambda (slot) ;; (write-string " (" stream) ;; (print-symbol slot stream) ;; (write-string " . " stream) ;; (serialize-sexp-internal (slot-value object slot) stream serialization-state) ;; (write-string ")" stream)) ;; serializable-slots)) ;; (write-string " ) )" stream))))) ;; (defmethod standard-object ((stream core-vector-io-stream) ;; (standard-object standard-object)) ;; (let ((id (known-object-id serialization-state object))) ;; (if id ;; (progn ;; (write-string "(:REF . " stream) ;; (prin1 id stream) ;; (write-string ")" stream)) ;; (let ((serializable-slots (get-serializable-slots serialization-state object))) ;; (setf id (set-known-object serialization-state object)) ;; (write-string "(:OBJECT " stream) ;; (prin1 id stream) ;; (write-string " :CLASS " stream) ;; (print-symbol (class-name (class-of object)) stream) ;; (when serializable-slots ;; (princ " :SLOTS (" stream) ;; (loop :for slot :in serializable-slots ;; :do (when (slot-boundp object slot) ;; (write-string " (" stream) ;; (print-symbol slot stream) ;; (write-string " . " stream) ;; (serialize-sexp-internal (slot-value object slot) stream serialization-state) ;; (write-string ")" stream)))) ;; (write-string " ) )" stream))))) ;; (defrule abc? (header abc) ;; (:cond ;; ((string= "abc" header) ;; (:zom (:type visible-char?)) ;; (:do (setq abc 1))) ;; (t ;; (:return 1)))) ;; (defrule abc? () ;; #\1 #\2 #\6 ;; (:return (list 1 2))) ;;(defparameter *gee (format nil "TEXTEE~CTEXTBB~C" #\Newline #\Newline)) ;;(defparameter *gee (format nil "~C~C~C~Ca" #\Return #\Linefeed #\Space #\Tab)) ;;(defparameter *gee (format nil "~C~C" #\Space #\Tab)) ;;(defparameter *gee (format nil "A7")) ;; (defrule text-newline (c (text (make-accumulator)) (text2 (make-accumulator))) ;; (:and (:zom (:type alpha? c) ;; (:collect c text)) ;; (:type linefeed?)) ;; (:debug) ;; (:and (:zom (:type alpha? c) ;; (:collect c text2)) ;; (:type linefeed?)) ;; (:return (values text text2))) ;; (defmacro match (&rest matchers) ;; "Attempts to match the next input character with one of the supplied matchers." ;; `(and ;; (or ,@(loop for m in matchers ;; collect `(match-atom ,m s))) ;; ;; cheat here a little bit - eat entire char entity instead ;; ;; of peeked char ;; (eat))) ;; (defmacro match-seq (&rest sequence) ;; "Tries to match the supplied matchers in sequence with characters in the input stream." ;; `(and ,@(loop for s in sequence ;; collect `(match ,s)))) ;; (defmacro match* (&rest sequence) ;; "Matches any occurances of any of the supplied matchers." ;; `(loop with data = (make-accumulator (stream-type s)) ;; for c = (match ,@sequence) ;; while c ;; do (push-atom c data) ;; finally (return data))) ;; (defmacro peek (&rest matchers) ;; "Looks ahead for an occurance of any of the supplied matchers." ;; `(or ,@(loop for m in matchers ;; collect `(match-atom ,m s)))) ;; (defmacro match+ (&rest sequence) ;; "Matches one or more occurances of any of the supplied matchers." ;; `(and (peek ,@sequence) ;; (match* ,@sequence))) ;; (defmacro must ((error-type &rest error-args) &rest body) ;; "Throws a parse error if the supplied forms do not succeed." ;; `(or (progn ,@body) ;; (error ',error-type ,@error-args)))
25,567
Common Lisp
.lisp
658
36.585106
96
0.555462
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e34b2f2eb52b6e75a42603f951a50d339a327377864c4cc46342f8b3bde45972
8,306
[ -1 ]
8,307
streams.lisp
evrim_core-server/src/streams/streams.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;(declaim (optimize (speed 3) (space 2) (safety 0) (debug 0) (compilation-speed 0))) ;;;------------------------------------------------------------------------- ;;; IMPLEMENTATION OF SEVERAL BOGUS TURING MACHINES (Left is broken) ;;;------------------------------------------------------------------------- ;;;------------------------------------------------------------------------- ;;; Simple Accumulator ;;;-------------------------------------------------------------------------- (defun make-accumulator (&optional (type :character) (size 0)) "Creates an adjustable string with a fill pointer." (declare (type fixnum size)) (make-array size :element-type (cond ((eq type :character) 'character) ((eq type :integer) 'integer) (t '(unsigned-byte 8))) :adjustable t :fill-pointer 0)) (declaim (inline push-atom)) (defun push-atom (atom accumulator) (cond ((and (numberp atom) (> atom 255)) (reduce #'(lambda (acc atom) (declare (ignore acc)) (vector-push-extend atom accumulator)) (string-to-octets (string (code-char atom)) :utf8) :initial-value nil)) ((and (characterp atom) (not (eq 'character (array-element-type accumulator)))) (reduce #'(lambda (acc atom) (declare (ignore acc)) (vector-push-extend atom accumulator) nil) (string-to-octets (string atom) :utf8) :initial-value nil)) ((and (typep atom '(unsigned-byte 8)) (eq 'character (array-element-type accumulator))) (vector-push-extend (code-char atom) accumulator)) (t (vector-push-extend atom accumulator)))) (defun pop-atom (accumulator) (vector-pop accumulator)) ;;;------------------------------------------------------------------------- ;;; Stream Definitions ;;;------------------------------------------------------------------------- (eval-when (:compile-toplevel :execute :load-toplevel) (defclass core-stream () ((%checkpoints :initform '()) ;; checkpoints list as (index #(buffer)) (%current :initform -1 :type fixnum)))) ;; current checkpoint (defgeneric read-stream (core-stream) (:documentation "read byte")) (defgeneric peek-stream (core-stream) (:documentation "peek byte")) (defgeneric checkpoint-stream (core-stream) (:documentation "start tx")) (defgeneric commit-stream (core-stream) (:documentation "commit")) (defgeneric rewind-stream (core-stream) (:documentation "rollback")) (defgeneric write-stream (core-stream atom) (:documentation "write byte")) (defgeneric close-stream (core-stream) (:documentation "close stream, clear buffers")) (defgeneric return-stream (core-stream) (:documentation "stagnate data out of the stream")) (defgeneric transactionalp (core-stream) (:documentation "transactional predicate")) (defgeneric current-checkpoint (core-stream) (:documentation "id for current checkpoint")) (defgeneric core-streamp (core-stream) (:method ((stream core-stream)) t) (:method ((stream t)) nil)) (defmethod transactionalp ((self core-stream)) (> (the fixnum (s-v '%current)) -1)) (defmethod current-checkpoint ((self core-stream)) (if (> (the fixnum (s-v '%current)) -1) (length (s-v '%checkpoints)) -1)) (defmethod rewind-stream :around ((self core-stream)) (if (not (transactionalp self)) -1 (call-next-method self))) (defmethod commit-stream :around ((self core-stream)) (if (not (transactionalp self)) -1 (call-next-method self))) (defmethod close-stream :around ((self core-stream)) (when (transactionalp self) (do ((i (current-checkpoint self) (current-checkpoint self))) ((= -1 i) nil) (commit-stream self))) (call-next-method)) (defmethod write-stream ((self core-stream) (c null)) self) (defmethod write-stream ((self core-stream) (char character)) (let ((code (char-code char))) (if (> code 127) (reduce #'(lambda (stream atom) (write-stream stream atom)) (string-to-octets (string char) :utf-8) :initial-value self) (write-stream self code)))) ;;;-------------------------------------------------------------------------- ;;; Standard Output Workarounds ;;;-------------------------------------------------------------------------- (eval-when (:compile-toplevel :execute :load-toplevel) (defclass core-standard-output (core-stream) ()) (defmethod rewind-stream ((self core-standard-output)) nil) (defmethod checkpoint-stream ((self core-standard-output)) nil) (defmethod commit-stream ((self core-standard-output)) nil) (defmethod write-stream ((self core-standard-output) (vector vector)) (reduce #'write-stream vector :initial-value self)) (defmethod write-stream ((self core-standard-output) atom) (prog1 self (princ (code-char atom) *standard-output*))) (defmethod write-stream ((self core-standard-output) (a character)) (prog1 self (write-stream self (char-code a)))) (defmethod write-stream ((self core-standard-output) (a null)) self) (defmethod close-stream ((self core-standard-output)) self) (defvar *core-output* (make-instance 'core-standard-output))) ;;;----------------------------------------------------------------------------- ;;; Vector Stream ;;;----------------------------------------------------------------------------- (defclass %core-vector-stream (core-stream) ((%octets :initarg :octets :initform nil :type (vector (unsigned-byte 8))) ;; underlying octets (%index :initform 0 :type fixnum) ;; current index (%buffer :initform (make-accumulator :byte) :type (vector (unsigned-byte 8))))) (defmethod close-stream ((self %core-vector-stream)) (setf (s-v '%octets) nil (s-v '%index) 0 (s-v '%buffer) nil (s-v '%checkpoints) '() (s-v '%current) -1) t) (defclass core-vector-io-stream (%core-vector-stream) ()) (defmethod return-stream ((self core-vector-io-stream)) (s-v '%octets)) (defmethod peek-stream ((self core-vector-io-stream)) (if (>= (the fixnum (s-v '%index)) (length (the (vector (unsigned-byte 8)) (s-v '%octets)))) nil (aref (the (vector (unsigned-byte 8)) (s-v '%octets)) (the fixnum (s-v '%index))))) (defmethod read-stream ((self core-vector-io-stream)) (let ((c (peek-stream self))) (when c (if (transactionalp self) (push-atom c (s-v '%buffer))) (incf (the fixnum (s-v '%index))) c))) (defmethod write-stream ((self core-vector-io-stream) (val null)) self) (defmethod write-stream ((self core-vector-io-stream) (val character)) (if (> (char-code val) 127) (write-stream self (string-to-octets (format nil "~A" val) :utf-8)) (write-stream self (char-code val)))) (defmethod write-stream ((self core-vector-io-stream) (vector vector)) (prog1 self (reduce #'write-stream vector :initial-value self))) (defmethod write-stream ((self core-vector-io-stream) atom) (if (transactionalp self) (push-atom atom (s-v '%buffer)) (if (> (length (the vector (s-v '%octets))) (the fixnum (s-v '%index))) (setf (aref (the (vector (unsigned-byte 8)) (s-v '%octets)) (s-v '%index)) atom) (push-atom atom (s-v '%octets)))) (incf (the fixnum (s-v '%index))) ;; paradoxal self) (defmethod checkpoint-stream ((self core-vector-io-stream)) (if (transactionalp self) (push (list (s-v '%current) (s-v '%buffer)) (s-v '%checkpoints))) (setf (s-v '%current) (s-v '%index) (s-v '%buffer) (make-accumulator :byte)) (length (s-v '%checkpoints))) (defmethod commit-stream ((self core-vector-io-stream)) (let ((buffer (s-v '%buffer))) (prog1 (rewind-stream self) (reduce #'(lambda (acc item) (declare (ignore acc)) (write-stream self item) nil) buffer :initial-value nil)))) (defmethod rewind-stream ((self core-vector-io-stream)) (setf (s-v '%index) (s-v '%current)) (prog1 (length (s-v '%checkpoints)) (let ((previous-checkpoint (pop (s-v '%checkpoints)))) (if previous-checkpoint (setf (s-v '%current) (car previous-checkpoint) (s-v '%buffer) (cadr previous-checkpoint)) (setf (s-v '%current) -1 (s-v '%buffer) (make-accumulator :byte)))))) ;;;-------------------------------------------------------------------------- ;;; String Stream ;;;-------------------------------------------------------------------------- (defclass core-string-io-stream (core-vector-io-stream) ((external-format :initarg :external-format :initform :utf-8))) (defmethod shared-initialize :after ((self core-string-io-stream) slot-name &rest initargs &key &allow-other-keys) (declare (ignorable initargs)) (when (getf initargs :string) (let ((octets (string-to-octets (getf initargs :string) (s-v 'external-format)))) (setf (s-v '%octets) (make-array (length (the vector octets)) :fill-pointer (length (the vector octets)) :adjustable t :element-type '(unsigned-byte 8) :displaced-to octets))))) (defmethod return-stream ((self core-string-io-stream)) (octets-to-string (s-v '%octets) (s-v 'external-format))) ;;;-------------------------------------------------------------------------- ;;; Socket Stream ;;;-------------------------------------------------------------------------- (defclass %core-fd-stream (core-stream) ((%stream :initarg :stream :initform nil))) (defmethod close-stream ((self %core-fd-stream)) (close (s-v '%stream)) (setf (s-v '%checkpoints) '() (s-v '%current) -1) t) (defclass core-fd-io-stream (%core-fd-stream) ((%peek :initform -1 :type fixnum) (%read-buffer :initform (make-accumulator :byte) :type (vector (unsigned-byte 8))) (%read-index :initform 0 :type fixnum) (%write-buffer :initform (make-accumulator :byte) :type (vector (unsigned-byte 8))) (%transactional :initform nil :reader transactionalp) (%current-checkpoint :initform -1 :reader current-checkpoint))) ;; (defmethod transactionalp ((self core-fd-io-stream)) ;; (s-v '%transactional)) (declaim (inline stream-using-cache?)) (defun stream-using-cache? (self) (< (the fixnum (s-v '%read-index)) (length (s-v '%read-buffer)))) (defmethod %peek-stream ((self core-fd-io-stream)) (flet ((peek () (let ((peeked (read-byte (s-v '%stream) nil nil))) (setf (s-v '%peek) (or peeked -1)) peeked))) (if (< (the fixnum (s-v '%peek)) 0) (peek) (s-v '%peek)))) (defmethod %read-stream ((self core-fd-io-stream)) (let ((peeked (%peek-stream self))) (if peeked (setf (s-v '%peek) -1)) peeked)) (defmethod peek-stream ((self core-fd-io-stream)) (if (stream-using-cache? self) (aref (s-v '%read-buffer) (the fixnum (s-v '%read-index))) (%peek-stream self))) (defmethod read-stream ((self core-fd-io-stream)) (if (stream-using-cache? self) (prog1 (aref (s-v '%read-buffer) (s-v '%read-index)) (incf (the fixnum (s-v '%read-index))) (when (not (transactionalp self)) (if (= (s-v '%read-index) (length (s-v '%read-buffer))) (setf (s-v '%read-index) 0 (s-v '%read-buffer) (make-accumulator :byte))))) (let ((read (%read-stream self))) (when read (when (transactionalp self) (push-atom read (s-v '%read-buffer)) (incf (the fixnum (s-v '%read-index)))) read)))) (defmethod write-stream ((self core-fd-io-stream) (c (eql nil))) self) (defmethod write-stream ((self core-fd-io-stream) (vector vector)) (prog1 self (if (transactionalp self) (reduce #'write-stream vector :initial-value self) (write-sequence vector (s-v '%stream))))) (defmethod write-stream ((self core-fd-io-stream) atom) (prog1 self (if (transactionalp self) (progn (if (null (s-v '%write-buffer)) (setf (s-v '%write-buffer) (make-accumulator :byte))) (push-atom atom (s-v '%write-buffer))) (write-byte atom (s-v '%stream)) ;; (sb-impl::flush-output-buffer (s-v '%stream)) )) ;; (incf (s-v '%read-index)) ;; paradoxal ) (defmethod write-stream ((self core-fd-io-stream) (val character)) (if (> (char-code val) 127) (write-stream self (string-to-octets (format nil "~A" val) :utf-8)) (write-stream self (char-code val)))) (defmethod checkpoint-stream ((self core-fd-io-stream)) (if (transactionalp self) (progn (push (cons (s-v '%current) (s-v '%write-buffer)) (s-v '%checkpoints)) (incf (slot-value self '%current-checkpoint))) (setf (slot-value self '%current-checkpoint) 0)) (setf (s-v '%current) (s-v '%read-index) (s-v '%write-buffer) nil ;; (make-accumulator :byte) (s-v '%transactional) t) ;; (length (s-v '%checkpoints)) (slot-value self '%current-checkpoint)) (defmethod %rewind-checkpoint ((self core-fd-io-stream)) (prog1 (length (s-v '%checkpoints)) (let ((previous-checkpoint (pop (s-v '%checkpoints)))) (if previous-checkpoint (progn (setf (s-v '%current) (car previous-checkpoint) (s-v '%write-buffer) (cdr previous-checkpoint)) (decf (slot-value self '%current-checkpoint))) (setf (s-v '%current) -1 (s-v '%write-buffer) nil ;; (make-accumulator :byte) (s-v '%transactional) nil (slot-value self '%current-checkpoint) -1))))) (defmethod rewind-stream ((self core-fd-io-stream)) (setf (s-v '%read-index) (s-v '%current)) (%rewind-checkpoint self)) (defmethod commit-stream ((self core-fd-io-stream)) (let ((buffer (s-v '%write-buffer))) (prog1 (%rewind-checkpoint self) (write-stream self buffer) (if (not (transactionalp self)) (finish-output (s-v '%stream)))))) ;;;------------------------------------------------------------------------- ;;; File Stream ;;;------------------------------------------------------------------------- (defclass core-file-io-stream (core-fd-io-stream) ()) (defmethod shared-initialize :after ((self core-file-io-stream) slot-name &rest initargs &key &allow-other-keys) (when (getf initargs :file) (setf (s-v '%stream) (open (getf initargs :file) :direction :io :element-type '(unsigned-byte 8) :if-exists :supersede :if-does-not-exist :create :external-format :utf8)))) (defun make-core-file-io-stream (file) (make-instance 'core-file-io-stream :file file)) (defclass core-file-input-stream (core-fd-io-stream) ()) (defmethod shared-initialize :after ((self core-file-input-stream) slot-names &rest initargs &key &allow-other-keys) (when (getf initargs :file) (setf (s-v '%stream) (open (getf initargs :file) :direction :input :element-type '(unsigned-byte 8) :if-does-not-exist :error :external-format :utf-8)))) (defun make-core-file-input-stream (pathname) (make-instance 'core-file-input-stream :file pathname)) (defclass core-file-output-stream (core-fd-io-stream) ()) (defmethod shared-initialize :after ((self core-file-output-stream) slot-names &rest initargs &key &allow-other-keys) (when (getf initargs :file) (setf (s-v '%stream) (open (getf initargs :file) :direction :output :element-type '(unsigned-byte 8) :if-does-not-exist :create :if-exists :supersede :external-format :utf8)))) (defun make-core-file-output-stream (pathname) (make-instance 'core-file-output-stream :file pathname)) ;;;-------------------------------------------------------------------------- ;;; List Stream ;;;-------------------------------------------------------------------------- (defclass core-list-io-stream (core-stream) ((%list :initarg :list :type list :initform nil) ;; underlying list (%index :initform 0 :type fixnum) ;; current index (%buffer :initform '()))) ;; checkpoint buffer (defmethod return-stream ((self core-list-io-stream)) (nreverse (s-v '%list))) (defmethod close-stream ((self core-list-io-stream)) (setf (s-v '%list) nil (s-v '%index) 0 (s-v '%buffer) 0 (s-v '%checkpoints) '() (s-v '%current) -1) t) (defmethod peek-stream ((self core-list-io-stream)) (if (>= (the fixnum (s-v '%index)) (length (s-v '%list))) nil (nth (the fixnum (s-v '%index)) (s-v '%list)))) (defmethod read-stream ((self core-list-io-stream)) (let ((c (peek-stream self))) (when c (if (transactionalp self) (push c (s-v '%buffer))) (incf (the fixnum (s-v '%index))) c))) (defmethod write-stream ((self core-list-io-stream) (c (eql nil))) self) (defmethod write-stream ((self core-list-io-stream) (list list)) (if (transactionalp self) (setf (s-v '%buffer) (append (s-v '%buffer) (list list))) (if (> (length (s-v '%list)) (s-v '%index)) (setf (nth (the fixnum (s-v '%index)) (s-v '%list)) list) (setf (s-v '%list) (append (s-v '%list) (list list))))) (incf (the fixnum (s-v '%index))) ;; paradoxal self) (defmethod write-stream ((self core-list-io-stream) atom) (if (transactionalp self) (setf (s-v '%buffer) (nreverse (cons atom (nreverse (s-v '%buffer))))) (if (> (length (s-v '%list)) (s-v '%index)) (setf (nth (the fixnum (s-v '%index)) (s-v '%list)) atom) (setf (s-v '%list) (nreverse (cons atom (nreverse (s-v '%list))))))) (incf (the fixnum (s-v '%index))) ;; paradoxal self) (defmethod checkpoint-stream ((self core-list-io-stream)) (if (transactionalp self) (push (list (s-v '%current) (s-v '%buffer)) (s-v '%checkpoints))) (setf (s-v '%current) (s-v '%index) (s-v '%buffer) '()) (length (s-v '%checkpoints))) (defmethod commit-stream ((self core-list-io-stream)) (let ((buffer (s-v '%buffer))) (prog1 (rewind-stream self) (dotimes (i (length buffer)) (write-stream self (nth i buffer)))))) (defmethod rewind-stream ((self core-list-io-stream)) (setf (s-v '%index) (s-v '%current)) (prog1 (length (s-v '%checkpoints)) (let ((previous-checkpoint (pop (s-v '%checkpoints)))) (if previous-checkpoint (setf (s-v '%current) (car previous-checkpoint) (s-v '%buffer) (cadr previous-checkpoint)) (setf (s-v '%current) -1 (s-v '%buffer) '()))))) ;; ------------------------------------------------------------------------- ;; Core List Output Stream (faster version for output) ;; ------------------------------------------------------------------------- (defclass core-list-output-stream (core-list-io-stream) ()) (defmethod peek-stream ((self core-list-output-stream)) (error "Use core-list-io-stream")) (defmethod read-stream ((self core-list-output-stream)) (error "Use core-list-io-stream")) (defmethod return-stream ((self core-list-output-stream)) (nreverse (s-v '%list))) (defmethod write-stream ((self core-list-output-stream) (list list)) (mapcar (curry #'write-stream self) list)) (defmethod increase-indent ((self core-list-output-stream) &optional n) (declare (ignore n)) (write-stream self 'increase-indent-magic)) (defmethod decrease-indent ((self core-list-output-stream) &optional n) (declare (ignore n)) (write-stream self 'decrease-indent-magic)) (defmethod write-stream ((self core-list-output-stream) atom) (if (transactionalp self) (setf (s-v '%buffer) (cons atom (s-v '%buffer))) (setf (s-v '%list) (cons atom (s-v '%list)))) self) (defmethod serialize-to ((self core-list-io-stream) stream) (return-stream (reduce (lambda (stream data) (cond ((eq data 'increase-indent-magic) (increase-indent stream)) ((eq data 'decrease-indent-magic) (decrease-indent stream)) (t (write-stream stream data)))) (return-stream self) :initial-value stream))) (defun make-core-list-output-stream (&optional (initial (list))) (make-instance 'core-list-output-stream :list initial)) ;;;-------------------------------------------------------------------------- ;;; Object Stream ;;;-------------------------------------------------------------------------- (defclass core-object-io-stream (core-list-io-stream) ((%clazz :accessor clazz :initarg :clazz :initform nil))) ;; underlyng object clazz (defmethod close-stream ((self core-object-io-stream)) (setf (s-v '%clazz) nil) (call-next-method)) (declaim (inline object-to-list)) (defun object-to-list (object) (reduce #'(lambda (acc item) (let ((name (mopp::slot-definition-name item))) (if (slot-boundp object name) (append acc (list (cons name (slot-value object name)))) acc))) (mopp:class-slots (class-of object)) :initial-value nil)) (defmethod shared-initialize :after ((self core-object-io-stream) slot-name &rest initargs &key &allow-other-keys) (declare (ignorable initargs)) (let ((o (getf initargs :object))) (when o (setf (s-v '%clazz) (class-name (class-of o)) (s-v '%list) (object-to-list o))))) (declaim (inline list-to-object)) (defun list-to-object (list clazz) (let ((o (make-instance clazz))) (reduce #'(lambda (acc slot) (declare (ignore acc)) (let ((name (mopp:slot-definition-name slot))) (setf (slot-value o name) (cdr (assoc name list)))) nil) (mopp:class-slots (find-class clazz)) :initial-value nil) o)) (defmethod return-stream ((self core-object-io-stream)) (list-to-object (s-v '%list) (s-v '%clazz))) (defun make-core-stream (target) (etypecase target (string (make-instance 'core-string-io-stream :string target)) (pathname (make-instance 'core-file-input-stream :file target)) (array (make-instance 'core-vector-io-stream :octets target)) (sb-sys::fd-stream (make-instance 'core-fd-io-stream :stream target)) #+gzip (gzip-stream::gzip-output-stream (make-instance 'core-fd-io-stream :stream target)) #+ssl (cl+ssl::ssl-stream (make-instance 'core-fd-io-stream :stream target)) (list (make-instance 'core-list-io-stream :list target)) (standard-object (make-instance 'core-object-io-stream :object target)))) ;; HELPERS ;; (with-core-stream (s "abc") ;; (read-stream s)) (defmacro with-core-stream ((var val) &body body) `(let ((,var (make-core-stream ,val))) (unwind-protect (progn ,@body) (close-stream ,var)))) (defmacro with-core-stream/cc ((var val) &body body) `(let ((,var (make-core-stream ,val))) (prog1 (progn ,@body) (close-stream ,var)))) ;; +------------------------------------------------------------------------ ;; | Semi Stream ;; +------------------------------------------------------------------------ (defclass wrapping-stream (core-stream) ((%stream :initform (error "Provide :stream") :initarg :stream))) (defmethod transactionalp ((self wrapping-stream)) (transactionalp (s-v '%stream))) (defmethod current-checkpoint ((self wrapping-stream)) (current-checkpoint (s-v '%stream))) (defmethod close-stream ((stream wrapping-stream)) (close-stream (slot-value stream '%stream))) (defmethod checkpoint-stream ((stream wrapping-stream)) (checkpoint-stream (slot-value stream '%stream))) (defmethod rewind-stream ((stream wrapping-stream)) (rewind-stream (slot-value stream '%stream))) (defmethod commit-stream ((stream wrapping-stream)) (commit-stream (slot-value stream '%stream))) (defmethod read-stream ((stream wrapping-stream)) (error "Could not read from ~A" stream)) (defmethod write-stream ((stream wrapping-stream) object) (error "Could not write ~A to ~A" object stream)) (defmethod write-stream ((stream wrapping-stream) (object function)) (prog1 stream (funcall object (slot-value stream '%stream)))) (defmethod write-stream ((stream wrapping-stream) (object null)) stream) (defmethod return-stream ((stream wrapping-stream)) (return-stream (slot-value stream '%stream))) ;; +------------------------------------------------------------------------- ;; | Gzip Stream (there is another one, see make-core-stream) ;; +------------------------------------------------------------------------- (defclass gzip-stream (wrapping-stream) ((compressor :accessor gzip-stream.compressor))) (defun make-gzip-stream (stream) (let ((stream (make-instance 'gzip-stream :stream stream))) (setf (gzip-stream.compressor stream) (make-instance 'gzip-compressor :callback (lambda (buffer end) (describe buffer) (write-stream (slot-value stream '%stream) (if (< end (length buffer)) (subseq buffer 0 end) buffer))))) stream)) (defmethod write-stream ((self gzip-stream) (object string)) (write-stream self (string-to-octets object :utf-8))) (defmethod write-stream ((self gzip-stream) (object vector)) (with-slots (compressor) self (compress-octet-vector (make-array (length object) :initial-contents object :element-type '(unsigned-byte 8)) compressor) (finish-compression compressor) self)) ;; ------------------------------------------------------------------------- ;; Bounded Stream - A Maximum Read Length Bounded Stream ;; ------------------------------------------------------------------------- (defclass bounded-stream (wrapping-stream) ((%max-read :initarg :max-read :initform 0) (%max-read-checkpoints :initform '()))) (defmethod read-allowed-p ((self bounded-stream)) (and (> (s-v '%max-read) 0) t)) (defmethod peek-stream ((self bounded-stream)) (if (read-allowed-p self) (peek-stream (s-v '%stream)))) (defmethod read-stream ((self bounded-stream)) (if (read-allowed-p self) (prog1 (read-stream (s-v '%stream)) (decf (s-v '%max-read))))) (defmethod checkpoint-stream ((self bounded-stream)) (push (s-v '%max-read) (s-v '%max-read-checkpoints)) (call-next-method self)) (defmethod rewind-stream ((self bounded-stream)) (if (transactionalp self) (setf (s-v '%max-read) (pop (S-v '%max-read-checkpoints)))) (call-next-method self)) (defmethod commit-stream ((self bounded-stream)) (if (transactionalp self) (pop (s-v '%max-read-checkpoints))) (call-next-method self)) (defun make-bounded-stream (stream max-read) (make-instance 'bounded-stream :stream stream :max-read max-read)) ;; +------------------------------------------------------------------------- ;; | Http Chunck Dencoding Stream (Transfer-Encoding: chunked) ;; +------------------------------------------------------------------------- (defclass core-chunked-stream (bounded-stream) () (:default-initargs :max-read 0)) (defmethod chunk-readable-p ((self core-chunked-stream)) (let ((max-read (s-v '%max-read))) (and max-read (> max-read 0) t))) (defmethod chunk-setup ((self core-chunked-stream)) (let* ((s (s-v '%stream)) (max-read (s-v '%max-read))) (setf (s-v '%max-read) nil) (crlf? s) (let ((num (hex-value*? s))) (if (and num (> num 0)) (prog1 t (crlf? s) (setf (s-v '%max-read) num)) (prog1 nil (setf (s-v '%max-read) max-read)))))) (defmethod peek-stream ((self core-chunked-stream)) (if (chunk-readable-p self) (call-next-method self) (if (chunk-setup self) (peek-stream self)))) (defmethod read-stream ((self core-chunked-stream)) (if (chunk-readable-p self) (call-next-method self) (if (chunk-setup self) (read-stream self)))) (defun make-chunked-stream (input) (make-instance 'core-chunked-stream :stream input)) ;; ------------------------------------------------------------------------- ;; Line Based Output Stream ;; ------------------------------------------------------------------------- (defclass line-based-stream (wrapping-stream) ((%max-length :initform 76 :initarg :max-line-length) (%cursor :initform 0) (%cursor-checkpoints :initform '()))) (defmethod checkpoint-stream ((self line-based-stream)) (push (s-v '%cursor) (s-v '%cursor-checkpoints)) (call-next-method self)) (defmethod rewind-stream ((self line-based-stream)) (if (transactionalp self) (setf (s-v '%cursor) (pop (s-v '%cursor-checkpoints)))) (call-next-method self)) (defmethod commit-stream ((self line-based-stream)) (if (transactionalp self) (pop (s-v '%cursor-checkpoints))) (call-next-method self)) (defmethod write-stream ((self line-based-stream) (char character)) (let ((code (char-code char))) (if (> code 127) (reduce #'(lambda (stream atom) (write-stream stream atom)) (string-to-octets (string char) :utf-8) :initial-value self) (write-stream self code)))) (defmethod write-stream ((self line-based-stream) (vector vector)) (reduce #'write-stream vector :initial-value self)) (defmethod %do-crlf ((self line-based-stream)) (write-stream (s-v '%stream) #.(char-code #\Newline)) (setf (s-v '%cursor) 0) self) (defmethod write-stream ((self line-based-stream) atom) (if (>= (s-v '%cursor) (s-v '%max-length)) (prog1 self (%do-crlf self) (write-stream self atom)) (prog1 self (write-stream (s-v '%stream) atom) (incf (s-v '%cursor))))) (defun make-line-based-stream (output &optional (max-line-length 76)) (make-instance 'line-based-stream :stream output :max-line-length max-line-length)) ;; +------------------------------------------------------------------------- ;; | Quoted Printable Stream ;; +------------------------------------------------------------------------- (defclass quoted-printable-stream (line-based-stream) ()) (defmethod %do-crlf ((self quoted-printable-stream)) (setf (s-v '%cursor) 0) (string! (s-v '%stream) "?=") (call-next-method self) ;; (setf (s-v '%cursor) 10) self) (defmethod write-stream ((self quoted-printable-stream) (vector vector)) (reduce #'write-stream vector :initial-value self)) (defmethod write-stream ((self quoted-printable-stream) atom) (flet ((do-write-quoted () (if (safe-char? atom) (call-next-method self atom) (prog1 self (when (> (+ 3 (s-v '%cursor)) (s-v '%max-length)) (%do-crlf self) (string! (s-v '%stream) " =?UTF-8?Q?") (setf (s-v '%cursor) 10)) (write-stream (s-v '%stream) #.(char-code #\=)) (hex-value! (s-v '%stream) atom) (incf (s-v '%cursor) 3))))) (if (= (s-v '%cursor) 0) (prog1 self (string! (s-v '%stream) " =?UTF-8?Q?") (setf (s-v '%cursor) 10) (do-write-quoted)) (do-write-quoted)))) (defmethod close-stream ((self quoted-printable-stream)) (string! (s-v '%stream) "?=") self) (defun make-quoted-printable-stream (output &optional (max-line-length 76)) (assert (and (> max-line-length 15) (evenp max-line-length))) (make-instance 'quoted-printable-stream :stream output :max-line-length max-line-length)) ;; ------------------------------------------------------------------------ ;; Core Pipe Stream ;; ------------------------------------------------------------------------ (defclass pipe-stream (core-stream) ((%input :accessor pipe-stream.input :initarg :input :type core-stream :initform (error "Provide :input stream")) (%output :accessor pipe-stream.output :initarg :output :type core-stream :initform (error "Provide :output stream ")))) (defmethod transactionalp ((self pipe-stream)) (transactionalp (s-v '%input))) (defmethod current-checkpoint ((self pipe-stream)) (current-checkpoint (s-v '%input))) (defmethod peek-stream ((self pipe-stream)) (peek-stream (s-v '%input))) (defmethod read-stream ((self pipe-stream)) (read-stream (s-v '%input))) (defmethod write-stream ((self pipe-stream) c) (write-stream (s-v '%output) c)) (defmethod checkpoint-stream ((self pipe-stream)) (if (transactionalp self) (push (s-v '%current) (s-v '%checkpoints))) (checkpoint-stream (s-v '%input)) (checkpoint-stream (s-v '%output)) (setf (s-v '%current) (length (s-v '%checkpoints))) (length (s-v '%checkpoints))) (defmethod rewind-stream ((self pipe-stream)) (prog1 (length (s-v '%checkpoints)) (setf (s-v '%current) (or (pop (s-v '%checkpoints)) -1)) (rewind-stream (s-v '%input)) (rewind-stream (s-v '%output)))) (defmethod commit-stream ((self pipe-stream)) (prog1 (length (s-v '%checkpoints)) (setf (s-v '%current) (or (pop (s-v '%checkpoints)) -1)) (commit-stream (s-v '%input)) (commit-stream (s-v '%output)))) (defmethod close-stream ((self pipe-stream)) (close-stream (s-v '%output)) (close-stream (s-v '%input))) (defmethod return-stream ((self pipe-stream)) (return-stream (s-v '%output))) ;; Object IO Extenstions (defmethod clazz ((self pipe-stream)) (clazz (s-v '%ouput))) (defmethod (setf clazz) (value (self pipe-stream)) (setf (clazz (s-v '%output)) value)) (defun make-pipe-stream (input output) (make-instance 'pipe-stream :input input :output output)) ;; ----------------------------------------------------------------------- ;; Core Transformer Stream ;; ----------------------------------------------------------------------- ;; ;; Only output transforming is tested. ;; (defclass core-transformer-stream (core-stream) ((%output :initform (error "Please specify output stream") :initarg :output :type (or null core-stream)) (%encoder :initarg :encoder :initform (error "Please specify encoder lambda")))) ;; (defmethod peek-stream ((self core-transformer-stream)) ;; (peek-stream (s-v '%input))) ;; (defmethod read-stream ((self core-transformer-stream)) ;; (read-stream (s-v '%input))) ;; (defmethod write-stream ((self core-transformer-stream) c) ;; (write-stream (s-v '%output) c)) (defmethod checkpoint-stream ((self core-transformer-stream)) (if (transactionalp self) (push (s-v '%current) (s-v '%checkpoints))) ;; (checkpoint-stream (s-v '%input)) (checkpoint-stream (s-v '%output)) (setf (s-v '%current) (length (s-v '%checkpoints))) (length (s-v '%checkpoints))) (defmethod rewind-stream ((self core-transformer-stream)) (prog1 (length (s-v '%checkpoints)) (setf (s-v '%current) (or (pop (s-v '%checkpoints)) -1)) ;; (rewind-stream (s-v '%input)) (rewind-stream (s-v '%output)))) (defmethod commit-stream ((self core-transformer-stream)) (prog1 (length (s-v '%checkpoints)) (setf (s-v '%current) (or (pop (s-v '%checkpoints)) -1)) ;; (commit-stream (s-v '%input)) (commit-stream (s-v '%output)))) (defmethod close-stream ((self core-transformer-stream)) (close-stream (s-v '%output)) ;; (close-stream (s-v '%input)) ) (defmethod return-stream ((self core-transformer-stream)) (return-stream (s-v '%output))) (defmethod write-stream ((self core-transformer-stream) (vector vector)) (prog1 self (reduce #'write-stream vector :initial-value self))) (defmethod write-stream ((self core-transformer-stream) atom) (prog1 self (if (s-v '%encoder) (funcall (s-v '%encoder) (s-v '%output) atom) (call-next-method)))) (defun make-output-transformer (output encoder) (make-instance 'core-transformer-stream :output output :encoder encoder)) ;; ------------------------------------------------------------------------ ;; Core Indented Stream ;; ------------------------------------------------------------------------ ;; This is used to indent outputs like javascript render. Writes ;; %indent spaces after a #\Newline is written. (defclass core-indented-stream (core-transformer-stream) ((%indent :initform 0 :initarg :indent) (%indent-saved :initform 0) (%increment :initform 2 :initarg :increment))) (defmethod increase-indent ((self core-stream) &optional n) (declare (ignore n)) ;; (warn "(increase-indent ~A) not implemented" self) self) (defmethod increase-indent ((self core-indented-stream) &optional (n nil)) (let ((n (or n (s-v '%increment)))) (aif (< (incf (s-v '%indent) n) 0) (setf (s-v '%indent) 0) it) self)) (defmethod decrease-indent ((self core-stream) &optional n) (declare (ignore n)) ;; (warn "(decrease-indent ~A) not implemented" self) self) (defmethod decrease-indent ((self core-indented-stream) &optional (n nil)) (let ((n (or n (s-v '%increment)))) (aif (< (decf (s-v '%indent) n) 0) (setf (s-v '%indent) 0) it) self)) (defmethod current-indent ((self core-stream)) 0) (defmethod current-indent ((self core-indented-stream)) (s-v '%indent)) (defmethod enable-indentation ((self core-stream)) 0) (defmethod enable-indentation ((self core-indented-stream)) (setf (s-v '%indent) (s-v '%indent-saved))) (defmethod disable-indentation ((self core-stream)) 0) (defmethod disable-indentation ((self core-indented-stream)) (setf (s-v '%indent-saved) (s-v '%indent) (s-v '%indent) 0)) (defmethod write-stream ((self core-indented-stream) (vector vector)) (prog1 self (reduce #'write-stream vector :initial-value self))) (defmethod write-stream ((self core-indented-stream) atom) (prog1 self (funcall (s-v '%encoder) (s-v '%output) atom (s-v '%indent)))) (defun make-indented-stream (output &optional (increment 2) (initial 0)) (make-instance 'core-indented-stream :output output :increment increment :indent initial :encoder #'(lambda (stream atom indent) (write-stream stream atom) (if (or (eq #.(char-code #\Newline) atom) (eq #\Newline atom)) (dotimes (i indent) (write-stream stream #.(char-code #\Space))))))) ;; ------------------------------------------------------------------------ ;; Core Compressed Stream ;; ------------------------------------------------------------------------ ;; This is used to compressed outputs like javascript render. Eats ;; all #\Newline (defclass core-compressed-stream (core-transformer-stream) ()) (defun make-compressed-stream (output) (make-instance 'core-compressed-stream :output output :encoder #'(lambda (stream atom) (if (or (eq #.(char-code #\Newline) atom) (eq #\Newline atom)) stream (write-stream stream atom))))) ;;;------------------------------------------------------------------------- ;;; Core CPS Stream ;;;------------------------------------------------------------------------- (defclass core-cps-stream (core-stream) ((%stack :initarg :stack :initform (error "Stack should not be nil")))) (defmethod read-stream ((self core-cps-stream)) (pop (s-v '%stack))) (defmethod write-stream ((self core-cps-stream) value) (push value (s-v '%stack))) (defmethod checkpoint-stream2 ((self core-cps-stream) name) (push (cons name (s-v '%stack)) (s-v '%checkpoints)) (setf (s-v '%stack) nil) name) (defmethod rewind-stream2 ((self core-cps-stream) name) (do ((checkpoint (pop (s-v '%checkpoints)) (pop (s-v '%checkpoints)))) ((null checkpoint) name) (setf (s-v '%stack) (cdr checkpoint)) (cond ((null (symbol-package name)) (if (string= name (car checkpoint)) (return-from rewind-stream2 name))) (t (if (equal name (car checkpoint)) (return-from rewind-stream2 name))))) name) (defmethod commit-stream2 ((self core-cps-stream) name) (rewind-stream2 self name)) (defmethod run ((self core-cps-stream)) (let ((count 1000000)) (catch 'done ;; (let ((values '(nil)) ;; (+stream+ self)) ;; (declare (special +stream+)) ;; (do ((k (read-stream self) (read-stream self))) ;; ((null k) (apply #'values values)) ;; (setq values (multiple-value-list (apply k (or values (list nil))))) ;; ;; (describe values) ;; (decf count) ;; (if (zerop count) ;; (progn ;; (warn "Executing limit exceeded.") ;; (throw 'done (apply #'values values)))))) (let ((value nil) (+stream+ self)) (declare (special +stream+)) (do ((k (read-stream self) (read-stream self))) ((null k) value) (setq value (funcall k value)))) ))) (defclass core-dummy-cps-stream (core-stream) ()) (defmethod read-stream ((self core-dummy-cps-stream)) (error "Please call inside with-call/cc2")) (defmethod write-stream ((self core-dummy-cps-stream) value) (error "Please call inside with-call/cc2")) (defmethod checkpoint-stream2 ((self core-dummy-cps-stream) name) (error "Please call inside with-call/cc2")) (defmethod commit-stream2 ((self core-dummy-cps-stream) name) (error "Please call-inside with-call/cc2")) (defvar +stream+ (make-instance 'core-dummy-cps-stream) "Dummy CPS Stream") ;;;-------------------------------------------------------------------------- ;;; Core FD NIO Stream ;;;-------------------------------------------------------------------------- (defclass core-fd-nio-stream (core-fd-io-stream) ((unit :initarg :unit :initform nil :accessor unit) (%buffer-size :initarg :buffer-size :initform 4096) (%read-buffer :initform #()))) ;; (defclass core-fd-io-stream (%core-fd-stream) ;; ((%peek :initform -1 :type fixnum) ;; (%read-buffer :initform (make-accumulator :byte) :type (vector (unsigned-byte 8))) ;; (%read-index :initform 0 :type fixnum) ;; (%write-buffer :initform (make-accumulator :byte) :type (vector (unsigned-byte 8))))) (defun zoo () (let ((s (core-ffi::connect "localhost" 7000))) (make-instance 'core-fd-nio-stream :stream s))) ;; burda connect sbclninkini kullanio ondan scio herhalde (defmethod shared-initialize :after ((self core-fd-nio-stream) slots &key &allow-other-keys) (core-ffi::set-nonblock (s-v '%stream)) self) (defmethod/cc1 fill-read-buffer ((self core-fd-nio-stream)) (let/cc1 k (let ((kont (lambda (&rest values) (declare (ignore values)) (funcall k (fill-read-buffer self))))) (with-foreign-object (buffer :uint8 (s-v '%buffer-size)) (core-ffi::bzero buffer (s-v '%buffer-size)) (let* ((ret (core-ffi::%read (s-v '%stream) buffer (s-v '%buffer-size))) (errno (core-ffi::errno))) (cond ((and (s-v 'unit) (eq -1 ret) (eq 11 errno)) (format *standard-output* "Got failed to read: EAGAIN") ;; save k (add-fd (s-v 'unit) (s-v '%stream) (list core-ffi::epollin #.(ash 1 31)) kont) ;; escape (funcall +k+ nil)) ((and (eq -1 ret) (not (eq 11 errno))) (warn "Read returned err:~D, fd: ~D" errno (s-v '%stream)) (core-ffi::%close (s-v '%stream))) ((not (transactionalp self)) (setf (s-v '%read-buffer) (cffi::foreign-array-to-lisp buffer (list :array :uint8 ret)) (s-v '%read-index) 0)) (t (let ((current-length (length (s-v '%read-buffer)))) (let ((array (cffi::foreign-array-to-lisp buffer (list :array :uint8 ret))) (new-array (adjust-array (s-v '%read-buffer) (+ ret current-length)))) (reduce (lambda (len atom) (setf (aref new-array len) atom) (1+ len)) array :initial-value current-length) (setf (s-v '%read-buffer) new-array))))))))) self) (defmethod/cc1 peek-stream ((self core-fd-nio-stream)) (if (stream-using-cache? self) (if (or (null (s-v '%max-read)) (> (s-v '%max-read) 0)) (aref (s-v '%read-buffer) (s-v '%read-index)) nil) (progn (fill-read-buffer self) (peek-stream self)))) (defmethod/cc1 read-stream ((self core-fd-nio-stream)) (let ((peek (peek-stream self))) (when peek (when (s-v '%max-read) (decf (s-v '%max-read))) (incf (s-v '%read-index))) peek)) (defmethod/cc1 write-stream :around ((stream core-fd-nio-stream) (atom null)) stream) (defmethod/cc1 write-stream ((stream core-fd-nio-stream) (atom (eql 'nil))) stream) (defmethod/cc1 write-stream :around ((stream core-fd-nio-stream) (list list)) (cond ((transactionalp stream) (setf (slot-value stream '%write-buffer) (append list (slot-value stream '%write-buffer))) stream) (t (write-stream stream (car list)) (if (cdr list) (write-stream stream (cdr list)) stream)))) (defmethod/cc1 write-stream :around ((stream core-fd-nio-stream) atom) (if (transactionalp stream) (prog1 stream (setf (slot-value stream '%write-buffer) (cons atom (slot-value stream '%write-buffer)))) (call-next-method))) ;; (defmethod/cc1 write-stream ((self core-fd-nio-stream) (atom character)) ;; (write-stream self (char-code atom))) (defmethod/cc1 write-stream ((self core-fd-nio-stream) (string string)) (write-stream self (string-to-octets string :utf-8))) (defmethod/cc1 write-stream ((self core-fd-nio-stream) atom) (prog1 self (let/cc1 k (let ((kont (lambda (&rest values) (declare (ignore values)) (funcall k (write-stream self atom))))) (unwind-protect (cffi::with-foreign-array (buffer (make-array 1 :initial-element atom) (list :array :uint8 1)) (let* ((ret (core-ffi::%write (s-v '%stream) buffer 1)) (errno (core-ffi::errno))) (cond ((and (eq ret -1) (eq 11 errno)) (funcall +k+ kont)) ((eq ret -1) (warn "%write failed with errcode:~A, fd:~D, atom:~A" errno (s-v '%stream) atom) (core-ffi::%close (s-v '%stream))) (t self))))))))) (defparameter *static-5k* (foreign-alloc :string :count 5192)) ;; (lisp-string-to-foreign *5k* *static-5k* 5192) (defmethod/cc1 write-content ((self core-fd-nio-stream)) (prog1 self (let/cc1 k (let ((kont (lambda (&rest values) (declare (ignore values)) (funcall k (write-content self))))) (unwind-protect (let* ((ret (core-ffi::%write (s-v '%stream) *static-5k* 5192)) (errno (core-ffi::errno))) (cond ((and (s-v 'unit) (eq ret -1) (eq 11 errno)) ;; save kont (add-fd (s-v 'unit) (s-v '%stream) (list core-ffi::epollout #.(ash 1 31)) kont) ;; escape (funcall +k+ nil)) ((eq ret -1) (warn "%write failed with errcode:~A, fd:~D, in write-content" errno (s-v '%stream)) (core-ffi::%close (s-v '%stream))) (t self)))))))) (defmethod/cc1 write-stream ((self core-fd-nio-stream) (vector vector)) (prog1 self (let/cc1 k (let ((kont (lambda (&rest values) (declare (ignore values)) (funcall k (write-stream self vector))))) (unwind-protect (cffi::with-foreign-array (buffer vector (list :array :uint8 (length vector))) (let* ((ret (core-ffi::%write (s-v '%stream) buffer (length vector))) (errno (core-ffi::errno))) (cond ((and (s-v 'unit) (eq ret -1) (eq 11 errno)) ;; save kont (add-fd (s-v 'unit) (s-v '%stream) (list core-ffi::epollout #.(ash 1 31)) kont) ;; escape (funcall +k+ nil)) ((eq ret -1) (warn "%write failed with errcode:~A, fd:~D, length vector:~D" errno (s-v '%stream) (length vector)) (core-ffi::%close (s-v '%stream))) (t self))))))))) (defmethod/cc1 checkpoint-stream ((self core-fd-nio-stream)) (if (transactionalp self) (push (list (s-v '%current) (s-v '%write-buffer)) (s-v '%checkpoints))) (setf (s-v '%current) (s-v '%read-index) (s-v '%write-buffer) nil) (length (s-v '%checkpoints))) (defmethod/cc1 %rewind-stream ((self core-fd-nio-stream)) (prog1 (length (s-v '%checkpoints)) (let ((previous-checkpoint (pop (s-v '%checkpoints)))) (if previous-checkpoint (setf (s-v '%current) (car previous-checkpoint) (s-v '%write-buffer) (cadr previous-checkpoint)) (setf (s-v '%current) -1 (s-v '%write-buffer) nil))))) (defmethod/cc1 rewind-stream ((self core-fd-nio-stream)) (setf (s-v '%read-index) (s-v '%current)) (%rewind-stream self)) (defmethod/cc1 commit-stream ((self core-fd-nio-stream)) (let ((buffer (s-v '%write-buffer))) (prog1 (%rewind-stream self) (write-stream self (nreverse buffer))))) (defmethod/cc1 close-stream ((self core-fd-nio-stream)) (when (transactionalp self) (do ((i (current-checkpoint self) (current-checkpoint self))) ((< i 0) nil) (commit-stream self))) (when (s-v 'unit) (del-fd (s-v 'unit) (s-v '%stream))) (core-ffi::%close (s-v '%stream)) self) (deftrace streams '(read-stream write-stream close-stream)) ;;current-checkpoint (deftrace streams-tx '(peek-stream checkpoint-stream rewind-stream commit-stream close-stream current-checkpoint)) ;;string, null, symbol ;; (defmethod write-stream ((self core-fd-nio-stream) (c (eql nil))) ;; self) ;; (defmethod write-stream ((self core-fd-io-stream) (vector vector)) ;; (prog1 self ;; (if (transactionalp self) ;; (reduce #'write-stream vector :initial-value self) ;; (write-sequence vector (s-v '%stream))))) ;; (defmethod checkpoint-stream ((self core-fd-io-stream)) ;; (if (transactionalp self) ;; (push (list (s-v '%current) (s-v '%write-buffer)) ;; (s-v '%checkpoints))) ;; (setf (s-v '%current) (s-v '%read-index) ;; (s-v '%write-buffer) (make-accumulator :byte)) ;; (length (s-v '%checkpoints))) ;; (defmethod %rewind-checkpoint ((self core-fd-io-stream)) ;; (prog1 (length (s-v '%checkpoints)) ;; (let ((previous-checkpoint (pop (s-v '%checkpoints)))) ;; (if previous-checkpoint ;; (setf (s-v '%current) (car previous-checkpoint) ;; (s-v '%write-buffer) (cadr previous-checkpoint)) ;; (setf (s-v '%current) -1 ;; (s-v '%write-buffer) (make-accumulator :byte)))))) ;; (defmethod rewind-stream ((self core-fd-io-stream)) ;; (setf (s-v '%read-index) (s-v '%current)) ;; (%rewind-checkpoint self)) ;; (defmethod commit-stream ((self core-fd-io-stream)) ;; (let ((buffer (s-v '%write-buffer))) ;; (prog1 (%rewind-checkpoint self) ;; (write-stream self buffer) ;; (if (not (transactionalp self)) ;; (finish-output (s-v '%stream)))))) ;; (defmethod/cc read-stream ((self core-fd-nio-stream)) ;; ;; (let/cc k ;; ;; (handler-bind ((kernel-error (lambda (c) ;; ;; (if (eagain? c) ;; ;; (queue-stream (worker self) 'read-only))))) ;; ;; (call-next-method))) ;; 3 ;; ) ;; (defclass core-cps-stream (core-stream) ;; ((%k :initform nil))) ;;; This is used to compressed outputs like javascript render. ;;; ;; (defclass core-cps0-stream (core-stream) ;; ((%k :initform nil) ;; (%continuations :initform '()))) ;; (defmethod copy-core-stream ((self core-cps0-stream)) ;; (let ((s (make-instance 'core-cps-stream))) ;; (setf (slot-value s '%k) (s-v '%k) ;; (slot-value s '%continuations) (copy-list (s-v '%continuations))) ;; s)) ;; (defmethod transactionalp ((self core-cps0-stream)) ;; (not (null (s-v '%k)))) ;; (defmethod current-k ((self core-cps0-stream)) ;; (s-v '%k)) ;; (defmethod/cc checkpoint-stream/cc ((self core-cps0-stream) k) ;; (if (transactionalp self) ;; (push (s-v '%k) (s-v '%continuations))) ;; (setf (s-v '%k) (lambda (&optional values) ;; (setf (s-v '%k) (pop (s-v '%continuations))) ;; (kall k values))) ;; (format t "checkpoint:~D~%" (length (s-v '%continuations))) ;; (length (s-v '%continuations))) ;; (defmethod/cc rewind-stream/cc ((self core-cps0-stream) &optional values) ;; (if (not (transactionalp self)) ;; -1 ;; (apply (s-v '%k) (ensure-list values)))) ;; ;; (defmethod/cc rewind-stream/cc ((self core-cps-stream) &optional values) ;; ;; (break "rewinding~%") ;; ;; (setf *konts* (s-v '%continuations)) ;; ;; (if (not (transactionalp self)) ;; ;; -1 ;; ;; (progn ;; ;; (format t "rewind:~D~%" (1- (length (s-v '%continuations)))) ;; ;; (acond ;; ;; ((pop (s-v '%continuations)) ;; ;; (let ((current (s-v '%k))) ;; ;; (setf (s-v '%k) it) ;; ;; (format t "kalling:~A, k is :~A" current (s-v '%k)) ;; ;; (apply #'kall current values))) ;; ;; ((s-v '%k) ;; ;; (setf (s-v '%k) nil) ;; ;; (format t "K is :~A" (s-v '%k)) ;; ;; (apply #'kall it values)) ;; ;; (t ; ;; (break "y00")) ;; ;; )) ;; ;; )) ;; (defun escape (&rest values) ;; (funcall (apply (arnesi::toplevel-k) values)) ;; (break "You should not see this, call/cc must be escaped already.")) ;; (defmethod/cc commit-stream/cc ((self core-cps0-stream) &optional value) ;; (describe self) ;; (if (not (transactionalp self)) ;; -1 ;; (progn ;; (format t "commit:~D~%" (length (s-v '%continuations))) ;; ;; (setf (s-v '%k) (pop (s-v '%continuations))) ;; (escape value)))) ;; (defclass core-cps0-io-stream (core-cps0-stream core-vector-io-stream) ;; ()) ;; ;; (defmethod/cc checkpoint-stream/cc ((self core-cps-stream)) ;; ;; (let/cc k ;; ;; (if (transactionalp self) ;; ;; (push k (s-v '%continuations))) ;; ;; (setf (s-v '%k) k) ;; ;; (kall k (checkpoint-stream self)))) ;; ;; (defmethod/cc rewind-stream/cc ((self core-cps-stream)) ;; ;; (if (not (transactionalp self)) ;; ;; -1 ;; ;; (progn ;; ;; (acond ;; ;; ((pop (s-v '%continuations)) ;; ;; (setf (s-v '%k) it) ;; ;; (kall it (rewind-stream self))) ;; ;; ((s-v '%k) ;; ;; (setf (s-v '%k) nil) ;; ;; (kall it (rewind-stream self))))))) ;; ;; (defmethod/cc commit-stream/cc ((self core-cps-stream)) ;; ;; (if (not (transactionalp self)) ;; ;; -1 ;; ;; (prog1 (commit-stream self) ;; ;; (setf (s-v '%k) (pop (s-v '%continuations)))))) ;; (defclass core-cps-string-io-stream (core-string-io-stream core-cps0-stream) ;; ()) ;; (defclass core-cps-fd-io-stream (core-cps0-stream core-fd-io-stream) ;; ()) ;; (defclass core-cps-file-io-stream (core-cps0-stream core-file-io-stream) ;; ()) ;; (defclass core-cps-list-io-stream (core-cps0-stream core-list-io-stream) ;; ()) ;; (defclass core-cps-object-io-stream (core-cps0-stream core-object-io-stream) ;; ()) ;; (defun make-core-cps-stream (target) ;; (etypecase target ;; (string (make-instance 'core-cps-string-io-stream :string target)) ;; (pathname (make-instance 'core-cps-file-io-stream :file target)) ;; (array (make-instance 'core-cps-vector-io-stream :octets target)) ;; (sb-sys::fd-stream (make-instance 'core-cps-fd-io-stream :stream target)) ;; (list (make-instance 'core-cps-list-io-stream :list target)) ;; (standard-object (make-instance 'core-cps-object-io-stream :object target))))
54,235
Common Lisp
.lisp
1,301
38.09608
106
0.611557
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
03249a80b95d5594fd31ab6f99b39624aad3c89067fb713628553185b647dbd9
8,307
[ -1 ]
8,308
render.lisp
evrim_core-server/src/streams/render.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;;----------------------------------------------------------------------------- ;;; Render ;;;----------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defgeneric expand-render (form expander stream &optional continue checkpoint) (:documentation "Special dsl for rendering.")) (defmethod expand-render ((form operator) expander (stream symbol) &optional continue checkpoint) (expand-grammar form #'expand-render stream continue checkpoint)) (defmethod expand-render ((form t) expander (stream symbol) &optional continue checkpoint) (declare (ignorable continue checkpoint)) `(write-stream ,stream ,form)) (defmethod expand-render ((form bind-operator) expander (stream symbol) &optional continue checkpoint) (declare (ignorable continue checkpoint)) (if (not (fboundp (func form))) (setf (func form) (intern (symbol-name (func form)) :core-server))) `(,(func form) ,stream ,@(arguments form))) (defmethod expand-render ((form sep-operator) expander (stream symbol) &optional continue checkpoint) (if (symbolp (children form)) `(prog1 ,continue ,(funcall expander (walk-grammar `(car ,(children form))) expander stream continue checkpoint) (mapcar (lambda (atom) ,(funcall expander (walk-grammar `(:and ,(seperator form) atom)) expander stream continue checkpoint)) (cdr ,(children form)))) (error ":sep does not support quoted lists, please use macro."))) (defmethod expand-render ((form indent-operator) expander (stream symbol) &optional continue checkpoint) (declare (ignorable checkpoint expander)) `(prog1 ,continue (increase-indent ,stream ,(how-many form)))) (defmethod expand-render ((form deindent-operator) expander (stream symbol) &optional continue checkpoint) (declare (ignorable checkpoint expander)) `(prog1 ,continue (decrease-indent ,stream ,(how-many form))))) (eval-when (:load-toplevel :compile-toplevel :execute) (defun optimize-render-1 (form) "Optimizes forms and elimiates unnessary class dispatch. SERVER> (describe (optimize-render-1 (walk-grammar `(:and \"abc\" \"def\" (:and #\Newline \"zee\"))))) #<AND-OPERATOR {1003713BE1}> is an instance of class #<STANDARD-CLASS AND-OPERATOR>. The following slots have :INSTANCE allocation: ARGS (\"abcdef zee\")" (let ((ands (operator-search-type form 'and-operator))) (labels ((concat-args (and) (setf (args and) (nreverse (reduce (lambda (acc arg) (cond ((and (or (stringp (car acc)) (characterp (car acc))) (or (stringp arg) (characterp arg))) (cons (format nil "~A~A" (car acc) arg) (cdr acc))) (t (cons arg acc)))) (cdr (args and)) :initial-value (list (car (args and)))))) and) (flatten-args (and) (setf (args and) (nreverse (reduce (lambda (acc arg) (cond ((typep arg 'and-operator) (append (nreverse (args arg)) acc)) ((null arg) acc) (t (cons arg acc)))) (args and) :initial-value nil))) and)) (mapc #'concat-args (mapcar #'flatten-args ands)) form)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro defrender (name args &rest body) "Rule definition macro that provides a common lexical environment for rules." (with-unique-names (stream) `(defun ,name ,(cons stream args) (block rule-block (let ((cp (current-checkpoint ,stream))) (declare (ignorable cp)) ,(expand-render (optimize-render-1 (walk-grammar `(:checkpoint ,@body (:commit)))) #'expand-render stream) ,stream)))))) (defun/cc2 byte! (stream byte) ;; (error "cant writ ebyte") (write-stream stream byte) ) (defun/cc2 char! (stream char) (let ((code (char-code char))) (if (> code 127) (reduce #'(lambda (acc atom) (declare (ignore acc)) (byte! stream atom) nil) (string-to-octets (string char) :utf-8) :initial-value nil) (byte! stream code)))) (defun/cc2 string! (stream string) (if (null string) stream (write-stream stream (string-to-octets string :utf-8)))) ;; (defmethod string! ((stream wrapping-stream) (string null)) ;; stream) ;; (defmethod string! ((stream wrapping-stream) (string string)) ;; (write-stream stream (string-to-octets string :utf-8))) ;; (defun version! (stream version) ;; (fixnum! stream (car version)) ;; (reduce #'(lambda (acc atom) ;; (declare (ignore acc)) ;; (char! stream #\.) ;; (fixnum! stream atom) ;; nil) ;; (cdr version) :initial-value nil)) (defrender version! (version) (:fixnum! (car version)) (:map (cdr version) (:char! #\.) (:fixnum! it))) (defun/cc2 symbol! (stream symbol) (string! stream (string-downcase (symbol-name symbol)))) (defun/cc2 symbol-with-package! (stream symbol) (let ((package (symbol-package symbol))) (when package (string! stream (package-name package)) (string! stream "::")) (string! stream (symbol-name symbol)))) (defun/cc2 fixnum! (stream number) (string! stream (format nil "~D" number))) (defun/cc2 quoted! (stream string &optional (quote #\")) (char! stream quote) (reduce #'(lambda (stream atom) (prog1 stream (cond ((or (char= quote atom) (char= #\\ atom)) (char! stream #\\) (char! stream atom)) ((or (char= #\Return atom) (char= #\Newline atom) (char= #\Linefeed atom)) ) (t (char! stream atom))))) string :initial-value stream) (char! stream quote)) (defun/cc2 quoted-fixnum! (stream number) (quoted! stream (format nil "~D" number))) (defvar +hex-alphabet+ #.(reduce #'(lambda (acc atom) (push-atom (char-code atom) acc) acc) "0123456789ABCDEF" :initial-value (make-accumulator :byte))) (defun/cc2 hex-value! (stream hex) (byte! stream (aref +hex-alphabet+ (floor (/ hex 16)))) (byte! stream (aref +hex-alphabet+ (rem hex 16)))) (defrender hex-value (hex) (:byte! (aref +hex-alphabet+ (floor (/ hex 16)))) (:byte! (aref +hex-alphabet+ (rem hex 16)))) ;;; sugars (defmacro with-separator ((var lst sep stream) &body body) `(let ((,var (car ,lst))) ,@body (reduce #'(lambda (acc ,var) (declare (ignore acc)) (char! ,stream ,sep) (char! ,stream #\ ) ,@body) (cdr ,lst) :initial-value nil)))
7,165
Common Lisp
.lisp
173
37.196532
108
0.653487
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
37f9b32ea7ee5c3b0646e4e70517701c077953c8337fb5bdc94e395436f0041c
8,308
[ -1 ]
8,309
faster.lisp
evrim_core-server/src/streams/faster.lisp
(in-package :core-server) ;; +---------------------------------------------------------------------------- ;; | v2 - Core File IO Streams ;; +---------------------------------------------------------------------------- (defclass core-fd-io-stream-v2 (core-fd-io-stream) ((%write-buffer :initform nil :type (or null list)))) (defmethod write-stream :around ((stream core-fd-io-stream-v2) (atom null)) stream) (defmethod write-stream :around ((stream core-fd-io-stream-v2) atom) (if (transactionalp stream) (prog1 stream (setf (slot-value stream '%write-buffer) (cons atom (slot-value stream '%write-buffer)))) (call-next-method))) (defmethod write-stream ((self core-fd-io-stream-v2) (atom character)) (write-stream self (char-code atom))) (defmethod write-stream ((self core-fd-io-stream-v2) (list list)) (reduce #'write-stream list :initial-value self)) (defmethod write-stream ((self core-fd-io-stream-v2) (string string)) (write-stream self (string-to-octets string :utf-8))) (defmethod checkpoint-stream ((self core-fd-io-stream-v2)) (if (transactionalp self) (push (list (s-v '%current) (s-v '%write-buffer)) (s-v '%checkpoints))) (setf (s-v '%current) (s-v '%read-index) (s-v '%write-buffer) nil) (length (s-v '%checkpoints))) (defmethod %rewind-checkpoint ((self core-fd-io-stream-v2)) (prog1 (length (s-v '%checkpoints)) (let ((previous-checkpoint (pop (s-v '%checkpoints)))) (if previous-checkpoint (setf (s-v '%current) (car previous-checkpoint) (s-v '%write-buffer) (cadr previous-checkpoint)) (setf (s-v '%current) -1 (s-v '%write-buffer) nil))))) (defmethod commit-stream ((self core-fd-io-stream-v2)) (let ((buffer (s-v '%write-buffer))) (prog1 (%rewind-checkpoint self) (write-stream self (nreverse buffer)) (if (not (transactionalp self)) (finish-output (s-v '%stream)))))) (defclass core-character-io-stream-v2 (core-fd-io-stream-v2) ()) (defmethod %peek-stream ((self core-character-io-stream-v2)) (flet ((peek () (let ((peeked (char-code (read-char (s-v '%stream) nil nil)))) (setf (s-v '%peek) (or peeked -1)) peeked))) (if (< (the fixnum (s-v '%peek)) 0) (cond ((and (s-v '%max-read) (> (the fixnum (s-v '%max-read)) 0)) (prog1 (peek) (decf (s-v '%max-read)))) ((s-v '%max-read) nil) (t (peek))) (s-v '%peek)))) (defmethod write-stream ((self core-character-io-stream-v2) (string string)) (write-sequence string (s-v '%stream)) self) (defmethod write-stream ((self core-character-io-stream-v2) (list list)) (reduce #'write-stream list :initial-value self)) (defmethod write-stream ((self core-character-io-stream-v2) (char character)) (write-char char (s-v '%stream)) self) (defmethod write-stream ((self core-character-io-stream-v2) (char integer)) (write-stream self (code-char char))) (defmethod write-stream ((self core-character-io-stream-v2) (char t)) (write-char char (s-v '%stream)) self) (defun make-core-stream-v2 (source &rest args) (apply #'make-instance (typecase source (sb-sys:fd-stream (list 'core-fd-io-stream-v2 :stream source))))) (defun fd-test () (let ((path1 (tmpnam nil)) (path2 (tmpnam nil)) (path3 (tmpnam nil))) (labels ((get-fd1 () (open path1 :direction :output :if-does-not-exist :create :if-exists :overwrite :element-type '(unsigned-byte 8) :external-format :utf8)) (get-fd2 () (open path2 :direction :output :if-does-not-exist :create :if-exists :overwrite :element-type ;; '(unsigned-byte 8) 'character :external-format :utf8)) (fd1 () (let ((s (make-instance 'core-fd-io-stream :stream (get-fd1)))) (checkpoint-stream s) (core-library! (make-compressed-stream s)) (commit-stream s) (close-stream s) s)) (fd2 () (let ((s (make-instance 'core-fd-io-stream-v2 :stream (get-fd1)))) (checkpoint-stream s) (core-library! s) (commit-stream s) (close-stream s) s)) (fd3 () (let ((s (make-instance 'core-character-io-stream-v2 :stream (get-fd2)))) (checkpoint-stream s) (core-library! s) (commit-stream s) (close-stream s) s))) (time (dotimes (i 5000) (fd1))) (time (dotimes (i 5000) (fd2))) (time (dotimes (i 5000) (fd3))) (list path1 path2)))) (defclass server-unit (local-unit) ()) (defmethod/unit handle-stream1 :async ((unit server-unit) stream) (let ((s (make-instance 'core-fd-io-stream :stream stream))) (checkpoint-stream s) (core-library! (make-compressed-stream s)) (commit-stream s) (close-stream s) s)) (defmethod/unit handle-stream2 ((unit server-unit) stream) (let ((s (make-instance 'core-fd-io-stream-v2 :stream stream))) (checkpoint-stream s) (core-library! s) (commit-stream s) (close-stream s) s)) (defmethod/unit handle-stream3 ((unit server-unit) stream) (let ((s (make-instance 'core-character-io-stream-v2 :stream stream))) (checkpoint-stream s) (core-library! s) (commit-stream s) (close-stream s) s)) ;; (defparameter *units* ;; (mapcar (lambda (seq) ;; (let ((unit (make-instance 'server-unit))) ;; (start unit) ;; unit)) ;; (seq 5))) ;; (defparameter *paths* ;; (mapcar (lambda (unit) ;; (tmpnam nil)) ;; (seq 100))) ;; (defun get-fd1 (path) ;; (open path ;; :direction :output ;; :if-does-not-exist :create ;; :if-exists :overwrite ;; :element-type '(unsigned-byte 8) ;; :external-format :utf8)) ;; (defun run-units () ;; (time ;; (progn ;; (mapcar (lambda (unit) ;; (mapcar (lambda (path) ;; (handle-stream1 unit (get-fd1 path))) ;; *paths*)) ;; *units*) ;; (funcall (handle-stream1 (car (reverse *units*)) (get-fd1 (car *paths*))))))) ;; (defapplication test-application (http-application) ;; ()) ;; (defparameter *5k* ;; (let ((acc (make-accumulator))) ;; (loop for i from 1 upto 5192 ;; do (push-atom #\A acc)) ;; acc)) ;; (defhandler "test1.core" ((app test-application)) ;; (write-stream (http-response.stream (context.response +context+)) *5k*)) ;; (defhandler "test2.core" ((app test-application)) ;; (core-library! (http-response.stream (context.response +context+))) ;; nil) ;; (defhandler "test3.core" ((app test-application)) ;; (core-library! (http-response.stream (context.response +context+))) ;; (core-library! (http-response.stream (context.response +context+))) ;; (core-library! (http-response.stream (context.response +context+))) ;; (core-library! (http-response.stream (context.response +context+))) ;; (core-library! (http-response.stream (context.response +context+))) ;; (core-library! (http-response.stream (context.response +context+))) ;; nil) ;; (defvar *app* (make-instance 'test-application :fqdn "zoo.com" :admin-email "test@core")) ;; (register *server* *app*) ;; sh-3.2$ siege -c100 -t20S http://localhost:3001/zoo.com/test1.core ;; ** SIEGE 2.66 ;; ** Preparing 100 concurrent users for battle. ;; The server is now under siege... ;; Lifting the server siege.. done. Transactions: 16212 hits ;; Availability: 100.00 % ;; Elapsed time: 19.99 secs ;; Data transferred: 80.27 MB ;; Response time: 0.10 secs ;; Transaction rate: 811.01 trans/sec ;; Throughput: 4.02 MB/sec ;; Concurrency: 83.51 ;; Successful transactions: 16212 ;; Failed transactions: 0 ;; Longest transaction: 9.81 ;; Shortest transaction: 0.00 ;; sh-3.2$ siege -c100 -t20S http://localhost:3001/zoo.com/test2.core ;; ** SIEGE 2.66 ;; ** Preparing 100 concurrent users for battle. ;; The server is now under siege... ;; Lifting the server siege.. done. Transactions: 9493 hits ;; Availability: 100.00 % ;; Elapsed time: 19.68 secs ;; Data transferred: 47.86 MB ;; Response time: 0.14 secs ;; Transaction rate: 482.37 trans/sec ;; Throughput: 2.43 MB/sec ;; Concurrency: 66.12 ;; Successful transactions: 9493 ;; Failed transactions: 0 ;; Longest transaction: 15.59 ;; Shortest transaction: 0.00 ;; sh-3.2$ siege -c100 -t20S http://localhost:3001/zoo.com/test3.core ;; ** SIEGE 2.66 ;; ** Preparing 100 concurrent users for battle. ;; The server is now under siege... ;; Lifting the server siege.. done. Transactions: 6550 hits ;; Availability: 100.00 % ;; Elapsed time: 20.25 secs ;; Data transferred: 198.12 MB ;; Response time: 0.25 secs ;; Transaction rate: 323.46 trans/sec ;; Throughput: 9.78 MB/sec ;; Concurrency: 81.03 ;; Successful transactions: 6550 ;; Failed transactions: 0 ;; Longest transaction: 13.39 ;; Shortest transaction: 0.00
9,957
Common Lisp
.lisp
239
38.271967
320
0.558252
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
66d5a481cd3a9425825ef338254f05e39add75be2e6169eb3cb58792cf5c0308
8,309
[ -1 ]
8,310
whois.lisp
evrim_core-server/src/services/whois.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| Whois Service ;;+---------------------------------------------------------------------------- ;; ;; This file implements whois service ;; ;;----------------------------------------------------------------------------- ;; Whois Service Specific Variables ;;----------------------------------------------------------------------------- (defparameter *default-whois-port* 43 "Remote whois server port") (defparameter *whois-servers* '(("com" . "whois.internic.net") ("net" . "whois.internic.net") ("org" . "whois.internic.net") ("edu" . "whois.internic.net") ("uk.com" . "whois.uk.com") ("eu.org" . "whois.eu.org") ("ac" . "whois.nic.ac") ("al" . "whois.ripe.net") ("am" . "whois.amnic.net") ("am" . "whois.amnic.net") ("as" . "whois.nic.as") ("at" . "whois.nic.at") ("au" . "whois.aunic.net") ("az" . "whois.ripe.net") ("ba" . "whois.ripe.net") ("be" . "whois.dns.be") ("bg" . "whois.ripe.net") ;; ("bm" . "rwhois.ibl.bm:4321") ("biz" . "whois.biz") ("br" . "whois.nic.br") ("by" . "whois.ripe.net") ("ca" . "whois.cira.ca") ("cc" . "whois.nic.cc") ("ch" . "whois.nic.ch") ("cl" . "whois.nic.cl") ("edu.cn" . "whois.edu.cn") ("cn" . "whois.cnnic.cn") ("cx" . "whois.nic.cx") ("cy" . "whois.ripe.net") ("cz" . "whois.ripe.net") ("de" . "whois.ripe.net") ("dk" . "whois.ripe.net") ("dz" . "whois.ripe.net") ("ee" . "whois.ripe.net") ("eg" . "whois.ripe.net") ("es" . "whois.ripe.net") ("fi" . "whois.ripe.net") ("fo" . "whois.ripe.net") ("fr" . "whois.nic.fr") ("gov" . "whois.nic.gov") ("gr" . "whois.ripe.net") ("gs" . "whois.adamsnames.tc") ("hk" . "whois.hknic.net.hk") ("hm" . "webhost1.capital.hm") ("hr" . "whois.ripe.net") ("hu" . "whois.ripe.net") ("ie" . "whois.domainregistry.ie") ("il" . "whois.ripe.net") ("in" . "whois.ncst.ernet.in") ("info" . "whois.afilias.net") ("int" . "whois.isi.edu") ("is" . "whois.isnet.is") ("it" . "whois.nic.it") ("jp" . "whois.nic.ad.jp") ("kr" . "whois.krnic.net") ("kz" . "whois.domain.kz") ("li" . "whois.nic.li") ("lk" . "whois.nic.lk") ("lt" . "whois.ripe.net") ("lu" . "whois.ripe.net") ("lv" . "whois.ripe.net") ("ma" . "whois.ripe.net") ("md" . "whois.ripe.net") ("mil" . "whois.nic.mil") ("mk" . "whois.ripe.net") ("mm" . "whois.nic.mm") ("mobi" . "whois.dotmobiregistry.net") ("ms" . "whois.adamsnames.tc") ("mt" . "whois.ripe.net") ("mx" . "whois.nic.mx") ("my" . "whois.mynic.net") ("nl" . "whois.domain-registry.nl") ("no" . "whois.norid.no") ("nu" . "whois.nic.nu") ("pe" . "whois.rcp.net.pe") ("pk" . "whois.pknic.net.pk") ("pl" . "whois.ripe.net") ("pt" . "whois.dns.pt") ("ro" . "whois.ripe.net") ("ru" . "whois.ripn.net") ("se" . "whois.nic-se.se") ("sg" . "whois.nic.net.sg") ("sh" . "whois.nic.sh") ("si" . "whois.ripe.net") ("sk" . "whois.ripe.net") ("sm" . "whois.ripe.net") ("st" . "whois.nic.st") ("su" . "whois.ripe.net") ("tc" . "whois.adamsnames.tc") ("tf" . "whois.adamsnames.tc") ("th" . "whois.thnic.net") ("tj" . "whois.nic.tj") ("tm" . "whois.nic.tm") ("tn" . "whois.ripe.net") ("to" . "whois.tonic.to") ("tr" . "whois.metu.edu.tr") ("tw" . "whois.twnic.net") ("tv" . "tvwhois.verisign-grs.com") ("ua" . "whois.ripe.net") ("ac.uk" . "whois.ja.net") ("gov.uk" . "whois.ja.net") ("uk" . "whois.nic.uk") ("us" . "whois.isi.edu") ("va" . "whois.ripe.net") ("vg" . "whois.adamsnames.tc") ("yu" . "whois.ripe.net") ("gb.com" . "whois.nomination.net") ("gb.net" . "whois.nomination.net") ("za" . "whois.co.za")) "Addresses of whois servers around around the world") ;; com, net, org, edu -> type1 ;; info -> type2 ;; tv -> type1 ;; mobi -> type2 ;; biz -> type3 (defun render-type1 (fqdn) (format nil "=~a~c~c" fqdn #\return #\linefeed)) (defun render-type2 (fqdn) (format nil "~a~c~c" fqdn #\return #\linefeed)) (defun render-type3 (fqdn) (format nil "~a~c~c" fqdn #\return #\linefeed)) (defun parser-type1 (text) (search "No match for" text)) (defun parser-type2 (text) (search "NOT FOUND" text)) (defun parser-type3 (text) (search "Not found:" text)) (defparameter +whois-map+ (list (cons '("com" "net" "org" "edu" "tv") '(render-type1 . parser-type1)) (cons '("info" "mobi") '(render-type2 . parser-type2)) (cons '("biz") '(render-type3 . parser-type3)))) (defun whois-map-lookup (dpart) (reduce (lambda (i a) (if (null i) a i)) (mapcar (lambda (l) (if (member dpart (car l) :test #'string=) (cdr l))) +whois-map+))) (defun root-domain-part (fqdn) (awhen (position #\. fqdn :from-end t) (subseq fqdn (1+ it)))) (defun whois-server (fqdn &optional (server-list *whois-servers*)) "Returns whois server associated to 'fqdn'" (flet ((resolve (addr) (sb-bsd-sockets:host-ent-address (sb-bsd-sockets:get-host-by-name addr)))) (awhen (root-domain-part fqdn) (let ((s (assoc it server-list :test #'equal))) (aif (and s (cdr s) (position #\: (cdr s))) (values (resolve (subseq (cdr s) 0 it)) (or (parse-integer (subseq (cdr s) (1+ it)) :junk-allowed t) *default-whois-port*) (subseq (cdr s) 0 it)) (values (resolve (cdr s)) *default-whois-port* (cdr s))))))) ;; look for this top level domains: com info net org tv mobi biz ;; domain-availablep :: string -> bool (defun domain-availablep (fqdn) "Returns t if domain is available" (let ((res (whois fqdn))) (if (funcall (car res) (cdr res)) t nil))) (defun whois (fqdn) "Executes whois query on 'fqdn'" (handler-bind ((error (lambda (condition) (restart-case (swank::swank-debugger-hook condition nil) (ignore-error () :report "ignore error" (return-from whois nil)))))) (multiple-value-bind (server port) (whois-server fqdn) (let ((s (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol 6)) (out "") (whois-map (whois-map-lookup (root-domain-part fqdn)))) (sb-bsd-sockets:socket-connect s server port) (with-open-stream (s (sb-bsd-sockets:socket-make-stream s :input t :output t :buffering :none :external-format :iso-8859-9 :element-type 'character)) (format s (funcall (car whois-map) fqdn)) (force-output s) ;; no need to read all output, just search every line (do ((line (read-line s nil :eof) (read-line s nil :eof))) ((eq line :eof)) (setf out (concatenate 'string out (format nil "~A~%" line)))) (format t "~A" out) (cons (cdr whois-map) out))))))
7,625
Common Lisp
.lisp
211
31.843602
94
0.562348
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
2f872a0c7217fe33dcf5fed587caeead98273109602c8788fb8f837abbbb32d0
8,310
[ -1 ]
8,311
mail.lisp
evrim_core-server/src/services/mail.lisp
;;+-------------------------------------------------------------------------- ;;| Mail Service ;;+-------------------------------------------------------------------------- (in-package :tr.gen.core.server) ;; Usage: ;; (defparameter *s (make-instance 'mail-sender ;; :username "[email protected]" ;; :password "l00kman0h4ndz" ;; :server "mail.core.gen.tr" ;; :port 25)) ;; (start *s) ;; (sendmail *s envelope) ;; We define a class for the main service object called ;; "mail-sender". This object has mandatory slots like username and ;; password used to connect to a mail server. mail server hostname and ;; port also required. (defclass+ mail-sender (logger-server) ((username :accessor mail-sender.username :initarg :mail-username :initform nil :documentation "Username for connecting to mail server") (password :accessor mail-sender.password :initarg :mail-password :initform nil :documentation "Password for connecting to mail server") (server :accessor mail-sender.server :initarg :mail-server :initform (error "mail-sender server must be defined.") :documentation "mail server hostname") (mail-port :accessor mail-sender.port :initarg :mail-port :initform 25 :documentation "mail server port") #+ssl (ssl :accessor mail-sender.ssl :initarg :mail-ssl :initform nil :documentation "enabled ssl/tls")) (:default-initargs :name "mail sender")) ;; we're also inheriting logger-server. So here we define a logging ;; function with a default tag 'smtp. (defmethod log-me ((self mail-sender) tag text) (call-next-method self tag (format nil "~A: ~A" (unit.name self) text))) (defmethod %log-me ((self mail-sender) text) (log-me self 'smtp text)) ;; when queue has envelopes, process the queue (defmethod/unit sendmail! ((self mail-sender) envelope) (%log-me self (format nil "Connecting ~A:~D." (mail-sender.server self) (mail-sender.port self))) (labels ((envelope! (stream envelope) (%log-me self (format nil "Sending message: ~A" envelope)) (smtp-send :envelope envelope :stream stream)) #+ssl (do-ssl () (aif (connect (mail-sender.server self) (mail-sender.port self)) (progn (%log-me self "Connected to SMTP Server.") ;; 220 node2.core.gen.tr ESMTP (smtp? it) ;; should be < 400 (%log-me self "Service ready. Starting TLS") (smtp! it "STARTTLS") (smtp? it) (let ((it (make-core-stream (cl+ssl:make-ssl-client-stream (slot-value it '%stream))))) (%log-me self "TLS started.") ;; Say hello (smtp-ehlo :stream it) ;; should be < 400 (%log-me self (format nil "Got HELO from ~A." (mail-sender.server self))) ;; 235 2.0.0 OK Authenticated (if (mail-sender.password self) (smtp-auth-plain :username (mail-sender.username self) :password (mail-sender.password self) :stream it)) ;; shoudl be < 400 (envelope! it envelope) (smtp-quit :stream it) ;; close conn (close-stream it) (%log-me self "Connection closed.") (close-stream it))))) (do-plain () (aif (connect (mail-sender.server self) (mail-sender.port self)) (progn (%log-me self "Connected to SMTP Server.") ;; 220 node2.core.gen.tr ESMTP (smtp? it) ;; should be < 400 (%log-me self "Service ready.") ;; Say hello (smtp-ehlo :stream it) ;; should be < 400 (%log-me self (format nil "Got HELO from ~A." (mail-sender.server self))) ;; 235 2.0.0 OK Authenticated (if (mail-sender.password self) (smtp-auth-plain :username (mail-sender.username self) :password (mail-sender.password self) :stream it)) ;; shoudl be < 400 (envelope! it envelope) (smtp-quit :stream it) ;; close conn (close-stream it) (%log-me self "Connection closed.")) (close-stream it)))) #+ssl (if (mail-sender.ssl self) (do-ssl) (do-plain)) #-ssl (do-plain))) ;; main interface to other programs (defmethod/unit sendmail :async-no-return ((self mail-sender) from to subject text &optional cc reply-to display-name) (sendmail! self (make-instance 'envelope :from from :to (ensure-list to) :subject subject :text text :cc (ensure-list cc) :reply-to reply-to :display-name display-name))) ;; (defparameter *test-mails* ;; (list ;; (make-instance 'envelope ;; :from "[email protected]" ;; :to '("[email protected]") ;; :subject "first mail (1)" ;; :text (with-core-stream (s "") ;; (with-html-output s ;; (<:html ;; (<:head (<:title "taytl")) ;; (<:body ;; (<:h1 "Heading 1") ;; (<:p "Lorem ipsum okuzum malim.")))))) ;; (make-instance 'envelope ;; :from "[email protected]" ;; :to '("[email protected]") ;; :subject "second mail (2)" ;; :text "number two (2)") ;; (make-instance 'envelope ;; :from "[email protected]" ;; :to '("[email protected]") ;; :subject "third mail (3)" ;; :text "number three (3)"))) ;;; sample mail conversation ;;; ;;; aycan.irican@node2 ~ $ nc mail.core.gen.tr 25 ;;; 220 node2.core.gen.tr ESMTP ;;; HELO core.gen.tr ;;; 250 node2.core.gen.tr ;;; mail from: [email protected] ;;; 250 2.1.0 Ok ;;; rcpt to: [email protected] ;;; 250 2.1.5 Ok ;;; data ;;; 354 End data with <CR><LF>.<CR><LF> ;;; deneme evrimcim deneme ;;; . ;;; 250 2.0.0 Ok: queued as 62E6818ABA ;; (let ((c (connect "mail.core.gen.tr" 25))) ;; (smtp? c) ;; (smtp! c "STARTTLS") ;; (describe (smtp? c)) ;; (let ((c (make-core-stream ;; (cl+ssl:make-ssl-client-stream (slot-value c '%stream))))) ;; ;; (describe (smtp? c)) ;; (smtp-ehlo :stream c) ;; (smtp-auth-plain :username "" ;; :password "" ;; :stream c) ;; (smtp-send :envelope (make-instance ;; 'envelope ;; :from "[email protected]" ;; :to (list "[email protected]") ;; :subject "subject" :text "text") ;; :stream c) ;; (smtp? c))) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>.
6,827
Common Lisp
.lisp
180
34.188889
78
0.622963
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c2236e76b2aaec10216f06022ed9ab902ec5bcba7084a8f5761cdae4983754e7
8,311
[ -1 ]
8,312
filesystem.lisp
evrim_core-server/src/services/filesystem.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;; Filesystem abstraction as a service ;;+---------------------------------------------------------------------------- ;; ;; Usage: create a filesystem service, ;; ;; (defparameter *fs* ;; (make-instance 'filesystem :root *project-docs-root* :label *project-name*)) ;; ;; Second parameter must be a relative pathname, ;; ;; (writefile *fs* #P"staff/introduction.txt" "Here we go...") ;; (readfile *fs* #P"staff/introduction.txt") ;; (list-directory *fs* #P"pictures/" :recursive t) ;; http://www.emmett.ca/~sabetts/slurp.html (defun slurp-stream5 (stream) (let ((seq (make-array (file-length stream) :element-type 'character :fill-pointer t))) (setf (fill-pointer seq) (read-sequence seq stream)) seq)) (defclass filesystem (local-unit) ((label :accessor filesystem.label :initarg :label :initform "") (root :accessor filesystem.root :initarg :root :initform (error "Filesystem root must be set!")))) ;; security & validator layer (defmacro with-guard ((fs filepath) &body body) (let* ((errors (gensym))) `(let ((,errors (list #'(lambda () (error "Filesystem null!")) #'(lambda () (error "You must use relative paths!")))) (ret (cond ((null ,fs) (function car)) ((and (pathname-directory ,filepath) (not (eq :RELATIVE (car (pathname-directory ,filepath))))) (function cadr)) (t (let ((res (progn ,@body))) #'(lambda (x) (declare (ignore x)) #'(lambda () res))))))) (funcall (funcall ret ,errors))))) ;; filesystem -> pathname -> IO String (defmethod/unit readfile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (with-open-file (s (merge-pathnames filepath (filesystem.root self))) (slurp-stream5 s)))) ;; filesystem -> pathname -> data -> IO String (defmethod/unit writefile :async-no-return ((self filesystem) filepath data) (with-guard (self filepath) (with-output-to-file (s (merge-pathnames filepath (filesystem.root self))) :if-exists :overwrite :if-does-not-exist :create (write-sequence data s)))) ;; filesystem -> pathname -> IO Bool (defmethod/unit deletefile :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (delete-file (merge-pathnames filepath (filesystem.root self))))) ;; filesystem -> pathname -> pathname -> IO Bool (defmethod/unit movefile :async-no-return ((self filesystem) src dst) (error "Not implemented yet.")) ;; filesystem -> pathname -> IO [pathname] (defmethod/unit ls :async-no-return ((self filesystem) filepath) (with-guard (self filepath) (cl-fad::list-directory (merge-pathnames filepath (filesystem.root self))))) (defmethod/unit fold-directory :async-no-return ((self filesystem) filepath fun) (with-guard (self filepath) (cl-fad:walk-directory (merge-pathnames filepath (filesystem.root self)) fun :directories t :if-does-not-exist :error)))
3,756
Common Lisp
.lisp
78
45.012821
101
0.673854
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
89755eb64e9021103966b3ab5640a38c9f94749677c01ce212ed4d2ef7f5c7e0
8,312
[ -1 ]
8,313
mime-types.lisp
evrim_core-server/src/rfc/mime-types.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. ;; thanks to edi weitz for this huge list... (in-package :tr.gen.core.server) (defparameter *mime-type-list* '(("application/andrew-inset" "ez") ("application/cu-seeme" "cu") ("application/dsptype" "tsp") ("application/futuresplash" "spl") ("application/hta" "hta") ("application/java-archive" "jar") ("application/java-serialized-object" "ser") ("application/java-vm" "class") ("application/mac-binhex40" "hqx") ("application/mac-compactpro" "cpt") ("application/mathematica" "nb") ("application/msaccess" "mdb") ("application/msword" "doc" "dot") ("application/octet-stream" "bin") ("application/oda" "oda") ("application/ogg" "ogg") ("application/pdf" "pdf") ("application/pgp-keys" "key") ("application/pgp-signature" "pgp") ("application/pics-rules" "prf") ("application/postscript" "ps" "ai" "eps") ("application/rar" "rar") ("application/rdf+xml" "rdf") ("application/rss+xml" "rss") ("application/smil" "smi" "smil") ("application/wordperfect" "wpd") ("application/wordperfect5.1" "wp5") ("application/xhtml+xml" "xhtml" "xht") ("application/xml" "fo" "xml" "xsl") ("application/zip" "zip") ("application/vnd.cinderella" "cdy") ("application/vnd.mozilla.xul+xml" "xul") ("application/vnd.ms-excel" "xls" "xlb" "xlt") ("application/vnd.ms-pki.seccat" "cat") ("application/vnd.ms-pki.stl" "stl") ("application/vnd.ms-powerpoint" "ppt" "pps") ("application/vnd.oasis.opendocument.chart" "odc") ("application/vnd.oasis.opendocument.database" "odb") ("application/vnd.oasis.opendocument.formula" "odf") ("application/vnd.oasis.opendocument.graphics" "odg") ("application/vnd.oasis.opendocument.graphics-template" "otg") ("application/vnd.oasis.opendocument.image" "odi") ("application/vnd.oasis.opendocument.presentation" "odp") ("application/vnd.oasis.opendocument.presentation-template" "otp") ("application/vnd.oasis.opendocument.spreadsheet" "ods") ("application/vnd.oasis.opendocument.spreadsheet-template" "ots") ("application/vnd.oasis.opendocument.text" "odt") ("application/vnd.oasis.opendocument.text-master" "odm") ("application/vnd.oasis.opendocument.text-template" "ott") ("application/vnd.oasis.opendocument.text-web" "oth") ("application/vnd.rim.cod" "cod") ("application/vnd.smaf" "mmf") ("application/vnd.stardivision.calc" "sdc") ("application/vnd.stardivision.draw" "sda") ("application/vnd.stardivision.impress" "sdd" "sdp") ("application/vnd.stardivision.math" "smf") ("application/vnd.stardivision.writer" "sdw" "vor") ("application/vnd.stardivision.writer-global" "sgl") ("application/vnd.sun.xml.calc" "sxc") ("application/vnd.sun.xml.calc.template" "stc") ("application/vnd.sun.xml.draw" "sxd") ("application/vnd.sun.xml.draw.template" "std") ("application/vnd.sun.xml.impress" "sxi") ("application/vnd.sun.xml.impress.template" "sti") ("application/vnd.sun.xml.math" "sxm") ("application/vnd.sun.xml.writer" "sxw") ("application/vnd.sun.xml.writer.global" "sxg") ("application/vnd.sun.xml.writer.template" "stw") ("application/vnd.symbian.install" "sis") ("application/vnd.visio" "vsd") ("application/vnd.wap.wbxml" "wbxml") ("application/vnd.wap.wmlc" "wmlc") ("application/vnd.wap.wmlscriptc" "wmlsc") ("application/x-123" "wk") ("application/x-abiword" "abw") ("application/x-apple-diskimage" "dmg") ("application/x-bcpio" "bcpio") ("application/x-bittorrent" "torrent") ("application/x-cdf" "cdf") ("application/x-cdlink" "vcd") ("application/x-chess-pgn" "pgn") ("application/x-cpio" "cpio") ("application/x-csh" "csh") ("application/x-debian-package" "deb" "udeb") ("application/x-director" "dcr" "dir" "dxr") ("application/x-dms" "dms") ("application/x-doom" "wad") ("application/x-dvi" "dvi") ("application/x-flac" "flac") ("application/x-font" "pfa" "pfb" "gsf" "pcf") ("application/x-freemind" "mm") ("application/x-futuresplash" "spl") ("application/x-gnumeric" "gnumeric") ("application/x-go-sgf" "sgf") ("application/x-graphing-calculator" "gcf") ("application/x-gtar" "gtar" "tgz" "taz") ("application/x-hdf" "hdf") ("application/x-httpd-php" "phtml" "pht" "php") ("application/x-httpd-php-source" "phps") ("application/x-httpd-php3" "php3") ("application/x-httpd-php3-preprocessed" "php3p") ("application/x-httpd-php4" "php4") ("application/x-ica" "ica") ("application/x-internet-signup" "ins" "isp") ("application/x-iphone" "iii") ("application/x-iso9660-image" "iso") ("application/x-java-jnlp-file" "jnlp") ("application/x-javascript" "js") ("application/x-jmol" "jmz") ("application/x-kchart" "chrt") ("application/x-killustrator" "kil") ("application/x-koan" "skp" "skd" "skt" "skm") ("application/x-kpresenter" "kpr" "kpt") ("application/x-kspread" "ksp") ("application/x-kword" "kwd" "kwt") ("application/x-latex" "latex") ("application/x-lha" "lha") ("application/x-lzh" "lzh") ("application/x-lzx" "lzx") ("application/x-maker" "frm" "maker" "frame" "fm" "fb" "book" "fbdoc") ("application/x-mif" "mif") ("application/x-ms-wmd" "wmd") ("application/x-ms-wmz" "wmz") ("application/x-msdos-program" "com" "exe" "bat" "dll") ("application/x-msi" "msi") ("application/x-netcdf" "nc") ("application/x-ns-proxy-autoconfig" "pac") ("application/x-nwc" "nwc") ("application/x-object" "o") ("application/x-oz-application" "oza") ("application/x-pkcs7-certreqresp" "p7r") ("application/x-pkcs7-crl" "crl") ("application/x-python-code" "pyc" "pyo") ("application/x-quicktimeplayer" "qtl") ("application/x-redhat-package-manager" "rpm") ("application/x-sh" "sh") ("application/x-shar" "shar") ("application/x-shockwave-flash" "swf" "swfl") ("application/x-stuffit" "sit") ("application/x-sv4cpio" "sv4cpio") ("application/x-sv4crc" "sv4crc") ("application/x-tar" "tar") ("application/x-tcl" "tcl") ("application/x-tex-gf" "gf") ("application/x-tex-pk" "pk") ("application/x-texinfo" "texinfo" "texi") ("application/x-trash" "~%" "" "bak" "old" "sik") ("application/x-troff" "tt" "r" "roff") ("application/x-troff-man" "man") ("application/x-troff-me" "me") ("application/x-troff-ms" "ms") ("application/x-ustar" "ustar") ("application/x-wais-source" "src") ("application/x-wingz" "wz") ("application/x-x509-ca-cert" "crt") ("application/x-xcf" "xcf") ("application/x-xfig" "fig") ("application/x-xpinstall" "xpi") ("audio/basic" "au" "snd") ("audio/midi" "mid" "midi" "kar") ("audio/mpeg" "mpga" "mpega" "mp2" "mp3" "m4a") ("audio/mpegurl" "m3u") ("audio/prs.sid" "sid") ("audio/x-aiff" "aif" "aiff" "aifc") ("audio/x-gsm" "gsm") ("audio/x-mpegurl" "m3u") ("audio/x-ms-wma" "wma") ("audio/x-ms-wax" "wax") ("audio/x-pn-realaudio" "ra" "rm" "ram") ("audio/x-realaudio" "ra") ("audio/x-scpls" "pls") ("audio/x-sd2" "sd2") ("audio/x-wav" "wav") ("chemical/x-alchemy" "alc") ("chemical/x-cache" "cac" "cache") ("chemical/x-cache-csf" "csf") ("chemical/x-cactvs-binary" "cbin" "cascii" "ctab") ("chemical/x-cdx" "cdx") ("chemical/x-cerius" "cer") ("chemical/x-chem3d" "c3d") ("chemical/x-chemdraw" "chm") ("chemical/x-cif" "cif") ("chemical/x-cmdf" "cmdf") ("chemical/x-cml" "cml") ("chemical/x-compass" "cpa") ("chemical/x-crossfire" "bsd") ("chemical/x-csml" "csml" "csm") ("chemical/x-ctx" "ctx") ("chemical/x-cxf" "cxf" "cef") ("chemical/x-embl-dl-nucleotide" "emb" "embl") ("chemical/x-galactic-spc" "spc") ("chemical/x-gamess-input" "inp" "gam" "gamin") ("chemical/x-gaussian-checkpoint" "fch" "fchk") ("chemical/x-gaussian-cube" "cub") ("chemical/x-gaussian-input" "gau" "gjc" "gjf") ("chemical/x-gaussian-log" "gal") ("chemical/x-gcg8-sequence" "gcg") ("chemical/x-genbank" "gen") ("chemical/x-hin" "hin") ("chemical/x-isostar" "istr" "ist") ("chemical/x-jcamp-dx" "jdx" "dx") ("chemical/x-kinemage" "kin") ("chemical/x-macmolecule" "mcm") ("chemical/x-macromodel-input" "mmd" "mmod") ("chemical/x-mdl-molfile" "mol") ("chemical/x-mdl-rdfile" "rd") ("chemical/x-mdl-rxnfile" "rxn") ("chemical/x-mdl-sdfile" "sd" "sdf") ("chemical/x-mdl-tgf" "tgf") ("chemical/x-mmcif" "mcif") ("chemical/x-mol2" "mol2") ("chemical/x-molconn-Z" "b") ("chemical/x-mopac-graph" "gpt") ("chemical/x-mopac-input" "mop" "mopcrt" "mpc" "dat" "zmt") ("chemical/x-mopac-out" "moo") ("chemical/x-mopac-vib" "mvb") ("chemical/x-ncbi-asn1" "asn") ("chemical/x-ncbi-asn1-ascii" "prt" "ent") ("chemical/x-ncbi-asn1-binary" "val" "aso") ("chemical/x-ncbi-asn1-spec" "asn") ("chemical/x-pdb" "pdb" "ent") ("chemical/x-rosdal" "ros") ("chemical/x-swissprot" "sw") ("chemical/x-vamas-iso14976" "vms") ("chemical/x-vmd" "vmd") ("chemical/x-xtel" "xtel") ("chemical/x-xyz" "xyz") ("image/gif" "gif") ("image/ief" "ief") ("image/jpeg" "jpeg" "jpg" "jpe") ("image/pcx" "pcx") ("image/png" "png") ("image/svg+xml" "svg" "svgz") ("image/tiff" "tiff" "tif") ("image/vnd.djvu" "djvu" "djv") ("image/vnd.wap.wbmp" "wbmp") ("image/x-cmu-raster" "ras") ("image/x-coreldraw" "cdr") ("image/x-coreldrawpattern" "pat") ("image/x-coreldrawtemplate" "cdt") ("image/x-corelphotopaint" "cpt") ("image/x-icon" "ico") ("image/x-jg" "art") ("image/x-jng" "jng") ("image/x-ms-bmp" "bmp") ("image/x-photoshop" "psd") ("image/x-portable-anymap" "pnm") ("image/x-portable-bitmap" "pbm") ("image/x-portable-graymap" "pgm") ("image/x-portable-pixmap" "ppm") ("image/x-rgb" "rgb") ("image/x-xbitmap" "xbm") ("image/x-xpixmap" "xpm") ("image/x-xwindowdump" "xwd") ("model/iges" "igs" "iges") ("model/mesh" "msh" "mesh" "silo") ("model/vrml" "wrl" "vrml") ("text/calendar" "ics" "icz") ("text/comma-separated-values" "csv") ("text/css" "css") ("text/h323" "323") ("text/html" "html" "htm" "shtml") ("text/iuls" "uls") ("text/mathml" "mml") ("text/plain" "asc" "txt" "text" "diff" "pot") ("text/richtext" "rtx") ("text/rtf" "rtf") ("text/scriptlet" "sct" "wsc") ("text/texmacs" "tm" "ts") ("text/tab-separated-values" "tsv") ("text/vnd.sun.j2me.app-descriptor" "jad") ("text/vnd.wap.wml" "wml") ("text/vnd.wap.wmlscript" "wmls") ("text/x-bibtex" "bib") ("text/x-boo" "boo") ("text/x-c++hdr" "h++" "hpp" "hxx" "hh") ("text/x-c++src" "c++" "cpp" "cxx" "cc") ("text/x-chdr" "h") ("text/x-component" "htc") ("text/x-csh" "csh") ("text/x-csrc" "c") ("text/x-dsrc" "d") ("text/x-haskell" "hs") ("text/x-java" "java") ("text/x-literate-haskell" "lhs") ("text/x-moc" "moc") ("text/x-pascal" "pp" "as") ("text/x-pcs-gcd" "gcd") ("text/x-perl" "pl" "pm") ("text/x-python" "py") ("text/x-setext" "etx") ("text/x-sh" "sh") ("text/x-tcl" "tcl" "tk") ("text/x-tex" "tex" "ltx" "sty" "cls") ("text/x-vcalendar" "vcs") ("text/x-vcard" "vcf") ("video/dl" "dl") ("video/dv" "dif" "dv") ("video/fli" "fli") ("video/gl" "gl") ("video/mpeg" "mpeg" "mpg" "mpe") ("video/mp4" "mp4") ("video/quicktime" "qt" "mov") ("video/vnd.mpegurl" "mxu") ("video/x-la-asf" "lsf" "lsx") ("video/x-mng" "mng") ("video/x-ms-asf" "asf" "asx") ("video/x-ms-wm" "wm") ("video/x-ms-wmv" "wmv") ("video/x-ms-wmx" "wmx") ("video/x-ms-wvx" "wvx") ("video/x-msvideo" "avi") ("video/x-sgi-movie" "movie") ("x-conference/x-cooltalk" "ice") ("x-world/x-vrml" "vrm" "vrml" "wrl")) "An alist where the cars are MIME types and the cdrs are list of file suffixes for the corresponding type.") (defparameter *mime-type-hash* (let ((hash (make-hash-table :test #'equalp))) (loop for (type . suffixes) in *mime-type-list* do (loop for suffix in suffixes do (setf (gethash suffix hash) type))) hash) "A hash table which maps file suffixes to MIME types.") (defun mime-type (pathspec) "Given a pathname designator PATHSPEC returns the MIME type \(as a string) corresponding to the suffix of the file denoted by PATHSPEC \(or NIL)." (gethash (pathname-type pathspec) *mime-type-hash*))
13,450
Common Lisp
.lisp
344
34.293605
74
0.621192
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
61b4c4c7427179257487eefa7e9cc1befe8e970d542a4c9a0c172edf4af2c137
8,313
[ -1 ]
8,314
2109.lisp
evrim_core-server/src/rfc/2109.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;;----------------------------------------------------------------------------- ;;; RFC 2109 - HTTP State Management Mechanism (aka Cookies) ;;; http://www.ietf.org/rfc/rfc2109.txt ;;;----------------------------------------------------------------------------- (defclass cookie () ((name :accessor cookie.name :initarg :name :initform nil) (value :accessor cookie.value :initarg :value :initform nil) (version :accessor cookie.version :initarg :version :initform nil :type integer) (comment :accessor cookie.comment :initarg :comment :initform nil) (domain :accessor cookie.domain :initarg :domain :initform nil) (max-age :accessor cookie.max-age :initarg :max-age :initform nil :type integer) (expires :accessor cookie.expires :initarg :expires :initform nil :type integer) (path :accessor cookie.path :initarg :path :initform nil) (secure :accessor cookie.secure :initarg :secure :initform nil :type boolean))) (defprint-object (self cookie) (format t "~A:~A" (slot-value self 'name) (slot-value self 'value))) (defgeneric cookiep (cookie) (:method ((cookie cookie)) t) (:method ((cookie t)) nil)) (defun make-cookie (name value &key (version 1) (comment nil) (domain nil) (max-age nil) (path nil) (secure nil) (expires nil)) (make-instance 'cookie :name name :value value :version version :comment comment :domain domain :max-age max-age :path path :expires expires :secure secure)) ;; Set-Cookie: Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo" (defmethod cookie! ((stream core-stream) (cookie cookie)) (with-slots (name value version comment domain max-age path secure) cookie (when name (string! stream (cookie.name cookie)) (char! stream #\=) (quoted! stream value) (when version (string! stream "; Version=") (fixnum! stream version)) (when comment (string! stream "; Comment=") (quoted! stream comment)) (when domain (string! stream "; Domain=") (string! stream domain)) (when max-age (string! stream "; Max-age=") (fixnum! stream max-age)) (when path (string! stream "; Path=") (string! stream path)) (when secure (string! stream "; Secure"))))) (defatom rfc2109-cookie-header? () (and (visible-char? c) (not (eq #.(char-code #\=) c)))) (defatom rfc2109-cookie-value? () (and (visible-char? c) (not (eq #.(char-code #\;) c)) (not (eq #.(char-code #\,) c)))) (defrule rfc2109-quoted-value? ((value (make-accumulator)) c) (:or (:and #\" (:zom (:or (:checkpoint (:and #\\ #\" (:do (push-atom #\" value)) (:commit))) (:and #\" (:return value)) (:and (:type (or visible-char? space?) c) (:collect c value))))) (:and (:zom (:type rfc2109-cookie-value? c) (:collect c value)) (:return value)))) ;; Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"; $Domain=".core.gen.tr" (defrule cookie? ((key (make-accumulator)) value version path domain c max-age comment expires secure) (:optional (:sci "$Version=") (:rfc2109-quoted-value? version) (:or #\; #\,) (:do (setq version (parse-integer version)))) (:oom (:type rfc2109-cookie-header? c) (:collect c key)) #\= (:rfc2109-quoted-value? value) (:zom #\; ;; (:not (or #\Return #\Newline)) (:lwsp?) (:or (:and (:sci "path=") (:rfc2109-quoted-value? path)) (:and (:sci "domain=") (:rfc2109-quoted-value? domain)) (:and (:sci "expires=") (:http-date? expires)) (:and (:sci "max-age=") (:rfc2109-quoted-value? max-age)) (:and (:sci "version=") (:rfc2109-quoted-value? version)) (:and (:sci "comment=") (:rfc2109-quoted-value? comment)) (:and (:sci "secure=") (:rfc2109-quoted-value? secure))) (:lwsp?)) (:return (make-cookie key value :version version :domain domain :path path :max-age max-age :comment comment :expires expires :secure secure))) (defrule cookies? (cookie acc) (:oom (:cookie? cookie) (:do (push cookie acc))) (:return (nreverse acc))) #| (defparameter *c (make-cookie "neym" "valyu" :version 2 :comment "coment" :domain "domeyn" :max-age 0 :path "/acme" :secure t)) (cookiep *c) (describe *c) (defparameter *s (make-core-stream "")) (time (cookie! *s *c)) (octets-to-string (slot-value *s '%octets) :utf-8) => "neym=\"valyu\"; Version=\"2\"; Comment=\"coment\"; Domain=\"domeyn\"; Max-age=\"0\"; Path=\"/acme\"; Secure" SERVER> (cookie? (make-core-stream "$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; $Domain=\"gee\"; Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; Shipping=\"FedEx\"; $Path=/acme;")) (#<COOKIE {BA88419}> #<COOKIE {BA89B09}> #<COOKIE {BA8A669}>) SERVER> (mapcar #'describe *) #<COOKIE {BA88419}> is an instance of class #<STANDARD-CLASS COOKIE>. The following slots have :INSTANCE allocation: NAME "Customer" VALUE "WILE_E_COYOTE" VERSION 1 COMMENT NIL DOMAIN "gee" MAX-AGE NIL PATH "/acme" SECURE NIL #<COOKIE {BA89B09}> is an instance of class #<STANDARD-CLASS COOKIE>. The following slots have :INSTANCE allocation: NAME "Part_Number" VALUE "Rocket_Launcher_0001" VERSION NIL COMMENT NIL DOMAIN NIL MAX-AGE NIL PATH "/acme" SECURE NIL #<COOKIE {BA8A669}> is an instance of class #<STANDARD-CLASS COOKIE>. The following slots have :INSTANCE allocation: NAME "Shipping" VALUE "FedEx" VERSION NIL COMMENT NIL DOMAIN NIL MAX-AGE NIL PATH "/acme" SECURE NIL (NIL NIL NIL) |#
6,460
Common Lisp
.lisp
172
33.761628
112
0.633971
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d44625ea634a284f162264ab02ad3e9f8dffd746d3fa7c953d4f5ebd997572d7
8,314
[ -1 ]
8,315
2616.lisp
evrim_core-server/src/rfc/2616.lisp
;;;--------------------------------------------------------------------------- ;;; RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1 ;;;--------------------------------------------------------------------------- (in-package :tr.gen.core.server) ;;;--------------------------------------------------------------------------- ;;; HTTP METHOD/PROTOCOL ;;;--------------------------------------------------------------------------- (defparser http-protocol? (version) (:seq "HTTP/") (:version? version) (:return (list 'HTTP version))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar +http-request-methods+ '(options get head post put delete trace connect))) (defparser http-method? (c (val (make-accumulator))) (:zom (:type alpha? c) (:collect c val)) (:return (car (member (string-upcase val) +http-request-methods+ :test #'string=)))) (defrender http-method! (method) (:symbol! method)) ;;;--------------------------------------------------------------------------- ;;; HTTP HEADER TYPES ;;;--------------------------------------------------------------------------- (defatom http-header-name? () (and (visible-char? c) (not (eq c #.(char-code #\:))))) (defatom http-header-value? () (or (visible-char? c) (space? c))) (defatom separator? () (if (member c '#.(cons 9 (mapcar #'char-code '(#\( #\) #\< #\> #\@ #\, #\; #\: #\\ #\" #\/ #\[ #\] #\? #\= #\{ #\} #\ )))) t)) (defatom tokenatom? () (and (not (separator? c)) (not (control? c)))) (defparser token? (c (acc (make-accumulator))) (:type tokenatom? c) (:collect c acc) (:zom (:type tokenatom? c) (:collect c acc)) (:return acc)) (defparser http-field-name? (c) (:token? c) (:return c)) ;; Ex: ;asd=asd or ;asd="asd" ;; header-parameter? :: stream -> (attr . val) (defparser header-parameter? (attr val) (:and #\; (:lwsp?) (:token? attr) #\= (:or (:token? val) (:quoted? val))) (:return (cons attr val))) (defrender header-parameter! (hp) #\; (car hp) #\= (:quoted! (cdr hp))) ;; 3.8 product tokens ;; product = token [ "/" product-version] ;; product-version = token (defparser product-version? (c) (:token? c) (:return c)) (defparser product? (prod ver) (:token? prod) (:zom #\/ (:product-version? ver)) (:return (cons prod ver))) ;;;--------------------------------------------------------------------------- ;;; 4.5 HTTP GENERAL HEADERS ;;;--------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defvar +http-general-headers+ '(CACHE-CONTROL CONNECTION DATE PRAGMA TRAILER TRANSFER-ENCODING UPGRADE VIA WARNING))) ;; len=9 ;; 14.9 Cache-Control ;; Cache-Control = "Cache-Control" ":" 1#cache-directive ;; cache-directive = cache-request-directive | cache-response-directive ;; cache-request-directive = ;; "no-cache" ; Section 14.9.1 ;; | "no-store" ; Section 14.9.2 ;; | "max-age" "=" delta-seconds ; Section 14.9.3, 14.9.4 ;; | "max-stale" [ "=" delta-seconds ] ; Section 14.9.3 ;; | "min-fresh" "=" delta-seconds ; Section 14.9.3 ;; | "no-transform" ; Section 14.9.5 ;; | "only-if-cached" ; Section 14.9.4 ;; | cache-extension ; Section 14.9.6 ;; cache-response-directive = ;; "public" ; Section 14.9.1 ;; | "private" [ "=" <"> 1#field-name <"> ] ; Section 14.9.1 ;; | "no-cache" [ "=" <"> 1#field-name <"> ]; Section 14.9.1 ;; | "no-store" ; Section 14.9.2 ;; | "no-transform" ; Section 14.9.5 ;; | "must-revalidate" ; Section 14.9.4 ;; | "proxy-revalidate" ; Section 14.9.4 ;; | "max-age" "=" delta-seconds ; Section 14.9.3 ;; | "s-maxage" "=" delta-seconds ; Section 14.9.3 ;; | cache-extension ; Section 14.9.6 ;; cache-extension = token [ "=" ( token | quoted-string ) ] ;; FIXmE: Implement cache-extension (defvar +http-cache-request-directives+ '(no-cache no-store max-age max-stale min-fresh no-transform only-if-cached)) (defparser http-cache-control? (result val) (:oom (:or (:and (:seq "no-cache") (:do (push (cons 'no-cache nil) result))) (:and (:seq "no-store") (:do (push (cons 'no-store nil) result))) (:and (:seq "max-age") #\= (:fixnum? val) (:do (push (cons 'max-age val) result))) (:and (:seq "pre-check") #\= (:fixnum? val) (:do (push (cons 'pre-check val) result))) (:and (:seq "post-check") #\= (:fixnum? val) (:do (push (cons 'post-check val) result))) (:and (:seq "max-stale") #\= (:fixnum? val) (:do (push (cons 'max-stale val) result))) (:and (:seq "min-fresh") #\= (:fixnum? val) (:do (push (cons 'min-fresh val) result))) (:and (:seq "no-transform") (:do (push (cons 'no-transform nil) result))) (:and (:seq "only-if-cached") (:do (push (cons 'only-if-cached nil) result))) (:and (:seq "must-revalidate") (:do (push (cons 'must-revalidate nil) result)))) (:zom (:type (or tab? space?))) (:optional #\,) (:zom (:type (or tab? space?)))) (:return (nreverse result))) (defvar +http-cache-response-directives+ '(public private no-cache no-store no-transform must-revalidate proxy-revalidate max-age s-maxage)) (defrender %http-cache-control! (cache-control-cons) (:cond ((atom cache-control-cons) cache-control-cons) ((typep (cdr cache-control-cons) 'fixnum) (car cache-control-cons) #\= (cdr cache-control-cons)) ((typep (cdr cache-control-cons) 'cons) (car cache-control-cons) #\, (cadr cache-control-cons) #\= (cddr cache-control-cons)) ((typep (cdr cache-control-cons) 'string) (car cache-control-cons) #\= (:quoted! (cdr cache-control-cons))) (t (:do (error "Invalid Cache-Control declaration."))))) (defun http-cache-control! (stream cache-controls) (let ((cache-controls (ensure-list cache-controls))) (flet ((cache-control! (cache-control-cons) (if (atom cache-control-cons) (typecase cache-control-cons (null t) (symbol (symbol! stream cache-control-cons)) (string (string! stream cache-control-cons))) (typecase (cdr cache-control-cons) (fixnum (symbol! stream (car cache-control-cons)) (char! stream #\=) (fixnum! stream (cdr cache-control-cons))) (cons (symbol! stream (car cache-control-cons)) (char! stream #\,) (string! stream (cadr cache-control-cons)) (char! stream #\=) (quoted! stream (cddr cache-control-cons))) (string (symbol! stream (car cache-control-cons)) (char! stream #\=) (quoted! stream (cdr cache-control-cons))) (t (error "Invalid Cache-Control declaration!")))))) (cache-control! (car cache-controls)) (mapcar (lambda (cache-control-cons) (string! stream ", ") (cache-control! cache-control-cons)) (cdr cache-controls))))) ;; 14.10 Connection ;; Connection = "Connection" ":" 1#(connection-token) ;; connection-token = token (defparser http-connection? (tokens c) (:token? c) (:do (push c tokens)) (:zom #\, (:lwsp?) (:token? c) (:do (push c tokens))) (:return tokens)) (defun/cc2 http-connection! (stream connection) (typecase connection (symbol (symbol! stream connection)) (string (string! stream connection)))) ;; 14.18 Date ;; Date = "Date" ":" HTTP-date ;;;--------------------------------------------------------------------------- ;;; DATE TImE FORmATS (see 3.3.1) ;;;--------------------------------------------------------------------------- ;; ;; Sun, 06 Nov 1994 08:49:37 GmT ; RFC 822, updated by RFC 1123 ;; Sunday, 06-Nov-94 08:49:37 GmT ; RFC 850, obsoleted by RFC 1036 ;; Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format ;; ;; HTTP-date = rfc1123-date | rfc850-date | asctime-date ;; rfc1123-date = wkday "," SP date1 SP time SP "GMT" ;; rfc850-date = weekday "," SP date2 SP time SP "GMT" ;; asctime-date = wkday SP date3 SP time SP 4DIGIT ;; date1 = 2DIGIT SP month SP 4DIGIT ;; ; day month year (e.g., 02 Jun 1982) ;; date2 = 2DIGIT "-" month "-" 2DIGIT ;; ; day-month-year (e.g., 02-Jun-82) ;; date3 = month SP ( 2DIGIT | ( SP 1DIGIT )) ;; ; month day (e.g., Jun 2) ;; time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ;; ; 00:00:00 - 23:59:59 ;; wkday = "Mon" | "Tue" | "Wed" ;; | "Thu" | "Fri" | "Sat" | "Sun" ;; weekday = "Monday" | "Tuesday" | "Wednesday" ;; | "Thursday" | "Friday" | "Saturday" | "Sunday" ;; month = "Jan" | "Feb" | "Mar" | "Apr" ;; | "May" | "Jun" | "Jul" | "Aug" ;; | "Sep" | "Oct" | "Nov" | "Dec" (defun find-rfc1123-month (str) (aif (position (string-downcase str) '("jan" "feb" "mar" "apr" "may" "jun" "jul" "aug" "sep" "oct" "nov" "dec") :test #'equal) (1+ it))) (eval-when (:load-toplevel :compile-toplevel :execute) (defvar +rfc1123-day-names+ '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")) (defvar +rfc1123-month-names+ '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))) ;; Sun, 06 Nov 1994 08:49:37 GmT ; RFC 822, updated by RFC 1123 (defparser rfc1123-date? ((acc (make-accumulator)) c day month year hour minute second gmt) (:zom (:type visible-char?)) (:lwsp?) (:fixnum? day) (:lwsp?) (:zom (:type alpha? c) (:collect c acc)) (:do (setq month (find-rfc1123-month acc))) (:lwsp?) (:fixnum? year) (:lwsp?) (:fixnum? hour) #\: (:fixnum? minute) #\: (:fixnum? second) (:lwsp?) (:or (:and (:seq "GMT") (:do (setq gmt 0))) (:and #\+ (:fixnum? gmt)) (:and #\- (:fixnum? gmt) (:do (setq gmt (* gmt -1))))) (:return (encode-universal-time second minute hour day month year gmt))) ;; Sunday, 06-Nov-94 08:49:37 GmT ; RFC 850, obsoleted by RFC 1036 (defparser rfc850-date? (day month year hour minute second (acc (make-accumulator)) c (gmt 0)) (:zom (:type visible-char?)) (:lwsp?) (:fixnum? day) #\- (:zom (:type alpha? c) (:collect c acc)) (:do (setq month (find-rfc1123-month acc))) #\- (:fixnum? year) (:do (setq year (+ 1900 year))) (:lwsp?) (:fixnum? hour) #\: (:fixnum? minute) #\: (:fixnum? second) (:lwsp?) (:or (:and (:seq "GMT") (:do (setq gmt 0))) (:and #\+ (:fixnum? gmt)) (:and #\- (:fixnum? gmt) (:do (setq gmt (* gmt -1))))) (:return (encode-universal-time second minute hour day month year gmt))) ;; Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format (defparser asctime-date? ((acc (make-accumulator)) c day month year hour minute second) (:zom (:type visible-char?)) (:lwsp?) (:zom (:type alpha? c) (:collect c acc)) (:do (setq month (find-rfc1123-month acc))) (:lwsp?) (:fixnum? day) (:lwsp?) (:fixnum? hour) #\: (:fixnum? minute) #\: (:fixnum? second) (:lwsp?) (:fixnum? year) (:return (encode-universal-time second minute hour day month year 0))) (defparser http-date? (timestamp) (:or (:rfc1123-date? timestamp) (:rfc850-date? timestamp) (:asctime-date? timestamp)) (:return timestamp)) ;;Sun, 06 Nov 1994 08:49:37 GmT (defun/cc2 http-date! (stream timestamp) (multiple-value-bind (second minute hour day month year day-of-week) (decode-universal-time timestamp 0) (string! stream (format nil "~a, ~2,'0d ~a ~d ~2,'0d:~2,'0d:~2,'0d GMT" (nth day-of-week +rfc1123-day-names+) day (nth (1- month) +rfc1123-month-names+) year hour minute second)))) ;; 14.32 Pragma ;; ;; Pragma = "Pragma" ":" 1#pragma-directive ;; pragma-directive = "no-cache" | extension-pragma ;; extension-pragma = token [ "=" ( token | quoted-string ) ] (defparser extension-pragma? ((attr (make-accumulator)) val) (:lwsp?) (:http-field-name? attr) #\= (:quoted? val) (:return (cons attr val))) (defparser http-pragma? (pragma) (:or (:and (:seq "no-cache") (:do (setq pragma (cons 'no-cache nil)))) (:extension-pragma? pragma)) (:return pragma)) (defun http-pragma! (stream pragma-cons) (if (atom pragma-cons) (symbol! stream pragma-cons) (typecase (car pragma-cons) (symbol (symbol! stream (car pragma-cons))) (string (string! stream (car pragma-cons)) (char! stream #\=) (string! stream (cdr pragma-cons)))))) ;; 14.40 Trailer ;; ;; Trailer = "Trailer" ":" 1#field-name (defparser http-trailer? (fields c) (:http-field-name? c) (:do (push c fields)) (:zom #\, (:lwsp?) (:http-field-name? c) (:do (push c fields))) (:return fields)) (defun http-trailer! (stream fields) (if (car fields) (progn (string! stream (car fields)) (reduce #'(lambda (acc item) (declare (ignore acc)) (char! stream #\,) (string! stream item)) (cdr fields) :initial-value nil)))) ;; 14.41 Transfer-Encoding ;; ;; Transfer-Encoding = "Transfer-Encoding" ":" 1#transfer-coding ;; Transfer-Encoding: chunked (see 3.6) (eval-when (:compile-toplevel :load-toplevel :execute) (defparser http-transfer-extension? (tok param params) (:token? tok) (:zom (:header-parameter? param) (:do (push param params))) (:return (cons tok params)))) (defun http-transfer-extension! (stream te) (typecase (car te) (string (string! stream (car te))) (symbol (symbol! stream (car te)))) (when (cdr te) (reduce #'(lambda (acc item) (declare (ignore acc)) (header-parameter! stream item)) (cdr te) :initial-value nil))) ;; http-transfer-encoding? :: stream -> (token . (attr . val)) (defparser http-transfer-encoding? (encs c) (:http-transfer-extension? c) (:do (push c encs)) (:zom #\, (:lwsp?) (:http-transfer-extension? c) (:do (push c encs))) (:return encs)) ;; http-transfer-encoding! :: stream -> ((token . (attr . val)) ...) -> nil (defun http-transfer-encoding! (stream encodings) (with-separator (i encodings #\, stream) (http-transfer-extension! stream i))) ;; 14.42 Upgrade ;; Upgrade = "Upgrade" ":" 1#product ;; Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 (defparser http-upgrade? (c products) (:product? c) (:do (push c products)) (:zom #\, (:lwsp?) (:product? c) (:do (push c products))) (:return products)) (defun http-upgrade! (stream products) (with-separator (i products #\, stream) (string! stream (car i)) (char! stream #\/) (string! stream (cdr i)))) ;; 14.45 Via ;; Via = "Via" ":" 1#( received-protocol received-by [ comment ] ) ;; received-protocol = [ protocol-name "/" ] protocol-version ;; protocol-name = token ;; protocol-version = token ;; received-by = ( host [ ":" port ] ) | pseudonym ;; pseudonym = token ;; Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) ;; Via: 1.0 ricky, 1.1 ethel, 1.1 fred, 1.0 lucy ;; Via: 1.0 ricky, 1.1 mertz, 1.0 lucy (defparser via-received-by? (c) (:or (:hostport? c) (:token? c)) (:return c)) (defparser via-received-protocol? (pname pver) (:token? pname) (:or (:and #\/ (:token? pver) (:return (cons pname pver))) (:return (cons nil pname)))) ;; ex: (("HTTP" . "1.1") ("core.gen.tr" . 80) "core server site") (defparser http-via? (prot by comment vias) (:via-received-protocol? prot) (:lwsp?) (:via-received-by? by) (:lwsp?) (:optional (:comment? comment)) (:do (push (list prot by comment) vias)) (:zom #\, (:lwsp?) (:via-received-protocol? prot) (:lwsp?) (:via-received-by? by) (:lwsp?) (:optional (:comment? comment)) (:do (push (list prot by comment) vias))) (:return (nreverse vias))) (defun http-via! (stream vias) (with-separator (i vias #\, stream) (when (car i) (if (caar i) (progn (string! stream (caar i)) (char! stream #\/) (string! stream (cdar i))) (string! stream (cdar i)))) (char! stream #\ ) (when (cadr i) (hostport! stream (cadr i))) (char! stream #\ ) (when (caddr i) (comment! stream (caddr i))))) ;; 14.46 Warning ;; Warning = "Warning" ":" 1#warning-value ;; warning-value = warn-code SP warn-agent SP warn-text [SP warn-date] ;; warn-code = 3DIGIT ;; warn-agent = ( host [ ":" port ] ) | pseudonym ;; ; the name or pseudonym of the server adding ;; ; the Warning header, for use in debugging ;; warn-text = quoted-string ;; warn-date = <"> HTTP-date <"> (defparser warn-agent? (agent) (:or (:hostport? agent) (:token? agent)) (:return agent)) (defparser warn-code? (c) (:fixnum? c) (:return c)) (defparser warn-date? (d) #\" (:http-date? d) #\" (:return d)) (defparser warning-value? (code agent text date) (:warn-code? code) (:lwsp?) (:warn-agent? agent) (:lwsp?) (:quoted? text) (:lwsp?) (:warn-date? date) (:return (list code agent text date))) (defparser http-warning? (c acc) (:warning-value? c) (:do (push c acc)) (:zom (:warning-value? c) (:do (push c acc))) (:return acc)) ;; warning :: '((199 ("www.core.gen.tr" . 80) "warn text" 3408142800)) (defun http-warning! (stream warnings) (with-separator (i warnings #\, stream) (fixnum! stream (car i)) (char! stream #\ ) (if (cdr (cadr i)) (hostport! stream (cadr i)) (string! stream (car (cadr i)))) (char! stream #\ ) (quoted! stream (caddr i)) (char! stream #\ ) (char! stream #\") (http-date! stream (cadddr i)) (char! stream #\"))) ;;;--------------------------------------------------------------------------- ;;; 5.3 HTTP REQUEST HEADERS ;;;--------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defvar +http-request-headers+ '(ACCEPT ACCEPT-CHARSET ACCEPT-ENCODING ACCEPT-LANGUAGE AUTHORIZATION EXPECT FROM HOST IF-MATCH IF-MODIFIED-SINCE IF-NONE-MATCH IF-RANGE IF-UNMODIFIED-SINCE MAX-FORWARDS PROXY-AUTHORIZATION RANGE REFERER TE USER-AGENT COOKIE))) ;; len=19 ;; 14.1 Accept ;; Accept = "Accept" ":" ;; #( media-range [ accept-params ] ) ;; media-range = ( "*/*" ;; | ( type "/" "*" ) ;; | ( type "/" subtype ) ;; ) *( ";" parameter ) ;; accept-params = ";" "q" "=" qvalue *( accept-extension ) ;; accept-extension = ";" token [ "=" ( token | quoted-string ) ] ;; text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 (defatom http-media-type? () (and (not (eq c #.(char-code #\,))) (not (eq c #.(char-code #\;))) (not (eq c #.(char-code #\/))) (http-header-name? c))) ;; quality-value? :: stream -> float ;; 3.9 Quality Values ;; qvalue = ( "0" [ "." 0*3DIGIT ]) ;; | ( "1" [ "." 0*3("0") ] ) (defparser quality-value? ((val (make-accumulator)) c) (:or (:and #\0 (:collect #\0 val) (:or (:and #\. (:collect #\. val) (:zom (:type digit? c) (:collect c val))) (:return (float 0)))) (:and #\1 (:collect #\1 val) (:zom (:type digit? c)))) (:return (parse-float val))) ;; quality-parameter? :: stream -> ("q" . float) (defparser quality-parameter? (val) (:and #\; (:lwsp?) #\q #\= (:quality-value? val)) (:return (cons "q" val))) ;; http-media-range? :: stream -> (values type subtype ((attr .val) ...)) (defparser http-media-range? ((type (make-accumulator)) (subtype (make-accumulator)) param params c) (:zom (:type http-media-type? c) (:collect c type)) #\/ (:zom (:type http-media-type? c) (:collect c subtype)) (:zom (:or (:quality-parameter? param) ;; accept-extension (:header-parameter? param)) (:do (push param params))) (:return (values type subtype params))) ;; http-accept? :: stream -> ((type subtype ((attr . val) ...)) ...) (defparser http-accept? (type subtype params accept) (:oom (:and (:http-media-range? type subtype params) (:do (push (list type subtype params) accept)) (:zom (:not #\,) (:type http-header-name?))) (:zom (:type space?))) (:return accept)) (defmethod http-media-range! ((stream core-stream) media) (string! stream (car media)) (char! stream #\/) (string! stream (cdr media))) (defmethod http-accept! ((stream core-stream) http-accept) (reduce (lambda (stream media) (char! stream #\,) (http-media-range! stream media)) (cddr http-accept) :initial-value (prog1 stream (string! stream (car http-accept)) (char! stream #\/) (string! stream (cadr http-accept))))) ;; Http Language (defatom http-language-type? () (and (not (eq c #.(char-code #\,))) (not (eq c #.(char-code #\;))) (visible-char? c))) ;; http-language? :: stream -> (language . quality) (defparser http-language? (c (lang (make-accumulator)) quality) (:type http-language-type? c) (:collect c lang) (:zom (:type http-language-type? c) (:collect c lang)) (:or (:and (:quality-parameter? quality) (:return (cons lang (cdr quality)))) (:return (cons lang 1.0)))) (defmethod http-language! ((stream core-stream) http-language) (string! stream (car http-language)) (when (not (null (cdr http-language))) (string! stream ";q=") (string! stream (format nil "~A" (cdr http-language))))) ;; 14.2 Accept Charset ;; Accept-Charset = "Accept-Charset" ":" 1#( ( charset | "*" )[ ";" "q" "=" qvalue ] ) ;; Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 (defparser http-accept-charset? (e e*) (:zom (:and (:http-language? e) (:do (push e e*)) (:zom (:not #\,) (:type http-header-name?))) (:zom (:type space?))) (:return (nreverse e*))) (defmethod http-accept-charset! ((stream core-stream) accept-charset) (reduce (lambda (stream encoding) (char! stream #\,) (http-language! stream encoding)) (cdr accept-charset) :initial-value (http-language! stream (car accept-charset)))) ;; 14.3 Accept Encoding ;; Accept-Encoding = "Accept-Encoding" ":" 1#( codings [ ";" "q" "=" qvalue ]) ;; codings = ( content-coding | "*" ) (defparser http-accept-encoding? (e e*) (:zom (:and (:http-language? e) (:do (push e e*)) (:zom (:not #\,) (:type http-header-name?))) (:zom (:type space?))) (:return (nreverse e*))) (defmethod http-accept-encoding! ((stream core-stream) accept-encoding) (http-accept-charset! stream accept-encoding)) ;; 14.4 Accept Language ;; Accept-Language = "Accept-Language" ":" 1#( language-range [ ";" "q" "=" qvalue ]) ;; language-range = ( ( 1*8ALPHA * ( "-" 1*8ALPHA)) | "*" ) ;; Accept-Language: da, en-gb;q=0.8, en;q=0.7 (defparser http-accept-language? (langs lang) (:zom (:and (:http-language? lang) (:do (push lang langs)) (:zom (:not #\,) (:type http-header-name?))) (:zom (:type space?))) (:return (nreverse langs))) (defmethod http-accept-language! ((stream core-stream) accept-language) (http-accept-charset! stream accept-language)) ;; 14.8 Authorization ;; Authorization = "Authorization" ":" credentials (defparser http-authorization? (challenge) (:http-challenge? challenge) (:return challenge)) (defmethod http-authorization! ((stream core-stream) challenge) (let ((scheme (car challenge))) ;; (symbol! stream scheme) ;; This is amazing, twitter does not respond to "oauth" -evrim. (if (string= scheme 'oauth) (string! stream "OAuth") (string! stream (format nil "~@(~A~)" scheme))) (char! stream #\ ) (prog1 stream (if (eq 'basic scheme) (string! stream (cdr challenge)) (let ((params (cdr challenge))) (when params (string! stream (caar params)) (char! stream #\=) (quoted! stream (cdar params)) (if (cdr params) (reduce #'(lambda (stream item) (char! stream #\,) ;; (char! stream #\Newline) (string! stream (car item)) (char! stream #\=) (quoted! stream (cdr item))) (cdr params) :initial-value stream)))))))) ;; 14.20 Expect ;; expectation-extension = token [ "=" ( token | quoted-string ) ;; *expect-params ] ;; expect-params = ";" token [ "=" ( token | quoted-string ) ] (defparser expectation-extension? ((attr (make-accumulator)) (val (make-accumulator)) c) (:and (:lwsp?) (:zom (:type alphanum? c) (:collect c attr)) #\= (:zom (:type http-media-type? c) (:collect c val))) (:return (cons attr val))) ;; Expect = "Expect" ":" 1#expectation ;; expectation = "100-continue" | expectation-extension ;; FIXmE: implement extensions. (defparser http-expect? (expectation param params) (:or (:and (:seq "100-continue") (:return '100-continue)) (:and (:expectation-extension? expectation) (:zom (:and (:header-parameter? param) (:do (push param params)))))) (:return (cons expectation params))) (defmethod http-expect! ((stream core-stream) http-expect) (cond ((eq http-expect '100-continue) (string! stream "100-continue")) (t (string! stream (caar http-expect)) (char! stream #\=) (string! stream (cdar http-expect)) (string! stream ";q=") (string! stream (cdadr http-expect))))) ;; 14.22 From ;; From = "From" ":" mailbox (defparser http-from? (mbox) (:mailbox? mbox) (:return mbox)) (defmethod http-from! ((stream core-stream) mbox) (char! stream #\<) (string! stream mbox) (char! stream #\>)) ;; 14.23 Host ;; Host = "Host" ":" host [ ":" port ] ; Section 3.2.2 (defparser http-host? (hp) (:hostport? hp) (:return hp)) (defmethod http-host! ((stream core-stream) hostport) (hostport! stream hostport)) ;; 14.19 Etag ;; ETag = "ETag" ":" entity-tag ;; 3.11 Entity Tags ;; entity-tag = [ weak ] opaque-tag ;; weak = "W/" ;; opaque-tag = quoted-string ;; ;; http-etag? :: stream -> (tagstr . weak?) (eval-when (:compile-toplevel :load-toplevel :execute) (defparser http-etag? (tagstr weak?) (:checkpoint #\W #\/ (:do (setq weak? t)) (:commit)) (:quoted? tagstr) (:return (cons tagstr weak?)))) ;; 14.24 If-Match ;; If-Match = "If-Match" ":" ( "*" | 1#entity-tag ) ;; If-Match: "xyzzy" ;; If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" ;; If-Match: * (defparser http-if-match? (tag (etags '())) (:or (:and #\* (:return (cons '* nil))) (:and (:http-etag? tag) (:do (push tag etags)) (:zom #\, (:lwsp?) (:http-etag? tag) (:do (push tag etags))))) (:return (nreverse etags))) (defmethod http-if-match! ((stream core-stream) if-match) (reduce (lambda (stream if-match) (char! stream #\,) (http-etag! stream if-match)) (cdr if-match) :initial-value (http-etag! stream if-match))) ;; 14.25 If-Modified-Since ;; If-Modified-Since = "If-Modified-Since" ":" HTTP-date ;; If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT (defparser http-if-modified-since? (date) (:http-date? date) (:return date)) (defmethod http-if-modified-since! ((stream core-stream) date) (http-date! stream date)) ;; 14.26 If-None-Match ;; If-None-Match = "If-None-Match" ":" ( "*" | 1#entity-tag ) ;; If-None-Match: "xyzzy" ;; If-None-Match: W/"xyzzy" ;; If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" ;; If-None-Match: W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz" ;; If-None-Match: * (defparser http-if-none-match? (res) (:http-if-match? res) (:return res)) (defmethod http-if-none-match! ((stream core-stream) if-none-match) (http-if-match! stream if-none-match)) ;; 14.27 If-Range ;; If-Range = "If-Range" ":" ( entity-tag | HTTP-date ) ;; FIXmE: Implement me. (defparser http-if-range? (range) (:or (:http-date? range) (:http-etag? range)) (:return range)) (defmethod http-if-range! ((stream core-stream) if-range) (if (numberp if-range) (http-date! stream if-range) (http-etag! stream if-range))) ;; 14.28 If-Unmodified-Since ;; If-Unmodified-Since = "If-Unmodified-Since" ":" HTTP-date ;; If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT (defparser http-if-unmodified-since? (date) (:http-date? date) (:return date)) (defmethod http-if-unmodified-since! ((stream core-stream) date) (http-date! stream date)) ;; 14.31 Max-Forwards ;; Max-Forwards = "Max-Forwards" ":" 1*DIGIT (defparser http-max-forwards? (num) (:fixnum? num) (:return num)) (defmethod http-max-forwards! ((stream core-stream) max-forwards) (fixnum! stream max-forwards)) ;; 14.34 Proxy-Authorization ;; Proxy-Authorization = "Proxy-Authorization" ":" credentials (defparser http-proxy-authorization? (creds) (:http-credentials? creds) (:return creds)) ;; FIXME -evrim. (defmethod http-proxy-authorization! ((self core-stream) credentials) (http-credentials! self credentials)) ;; 14.35 Range ;; 14.35.1 Byte Ranges ;; ranges-specifier = byte-ranges-specifier ;; byte-ranges-specifier = bytes-unit "=" byte-range-set ;; byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec ) ;; byte-range-spec = first-byte-pos \"-\" [last-byte-pos] ;; first-byte-pos = 1*DIGIT ;; last-byte-pos = 1*DIGIT ;; suffix-byte-range-spec = \"-\" suffix-length ;; suffix-length = 1*DIGIT (defparser http-bytes-unit? (c (unit (make-accumulator))) (:zom (:type alpha? c) (:collect c unit)) (:return unit)) (defparser http-byte-range-set? (c l r) (:or (:and #\- (:fixnum? r) (:do (push (cons nil r) c))) (:and (:fixnum? l) #\- (:checkpoint (:fixnum? r) (:commit)) (:do (push (cons l r) c)))) (:zom #\, (:lwsp?) (:or (:and #\- (:fixnum? r) (:do (push (cons nil r) c))) (:and (:fixnum? l) #\- (:checkpoint (:fixnum? r) (:commit)) (:do (push (cons l r) c))))) (:return c)) (defparser http-byte-ranges-specifier? (bytes-unit ranges) (:http-bytes-unit? bytes-unit) #\= (:http-byte-range-set? ranges) (:return (cons bytes-unit ranges))) (defparser http-ranges-specifier? (c) (:http-byte-ranges-specifier? c) (:return c)) ;; 14.35 Range ;; Range = "Range" ":" ranges-specifier ;; ranges-specifier = byte-ranges-specifier ;; byte-ranges-specifier = bytes-unit "=" byte-range-set ;; byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec ) ;; byte-range-spec = first-byte-pos "-" [last-byte-pos] ;; first-byte-pos = 1*DIGIT ;; last-byte-pos = 1*DIGIT ;; suffix-byte-range-spec = "-" suffix-length ;; suffix-length = 1*DIGIT (defparser http-range? (c) (:http-ranges-specifier? c) (:return c)) (defmethod http-byte-range-specifier! ((stream core-stream) range) (if (car range) (fixnum! stream (car range))) (char! stream #\-) (if (cdr range) (fixnum! stream (cdr range))) stream) (defmethod http-range! ((stream core-stream) range) (string! stream "bytes=") (reduce (lambda (stream range) (char! stream #\,) (http-byte-range-specifier! stream range)) (cddr range) :initial-value (http-byte-range-specifier! stream (cadr range)))) ;; 14.36 Referer ;; Referer = "Referer" ":" ( absoluteURI | relativeURI ) ;; Referer: http://www.w3.org/hypertext/DataSources/Overview.html (defparser http-referer? (uri) (:uri? uri) (:return uri)) (defmethod http-referer! ((stream core-stream) referer) (uri! stream referer)) ;; 14.39 TE ;; TE = "TE" ":" #( t-codings ) ;; t-codings = "trailers" | ( transfer-extension [ accept-params ] ) ;; TE: deflate ;; TE: ;; TE: trailers, deflate;q=0.5 (defparser http-te? (te acc) (:http-transfer-extension? te) (:do (push te acc)) (:zom #\, (:lwsp?) (:http-transfer-extension? te) (:do (push te acc))) (:return (nreverse acc))) (defmethod http-te! ((stream core-stream) te) (reduce (lambda (stream te) (char! stream #\,) (http-transfer-extension! stream te)) (cdr te) :initial-value (http-transfer-extension! stream (car te)))) ;; 14.43 User-Agent ;; User-Agent = "User-Agent" ":" 1*( product | comment ) ;; ;; http://en.wikipedia.org/wiki/User_agent ;; Mozilla/MozVer (compatible; MSIE IEVer[; Provider]; Platform[; Extension]*) [Addition] ;; Mozilla/MozVer (Platform; Security; SubPlatform; Language; rv:Revision[; Extension]*) Gecko/GeckVer [Product/ProdVer] (defparser user-agent-token? ((token (make-accumulator)) c) (:zom (:and (:not #\;) (:checkpoint #\) (:if (> (length token) 0) (:rewind-return token) (:rewind-return nil))) (:type http-header-value? c)) (:collect c token)) (:lwsp?) (:if (> (length token) 0) (:return token))) ;; ie: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727) ;; => ((BROWSER . IE) (MOZ-VER (4 0)) (VERSION (6 0)) (OS . "Windows NT 5.1")) (defparser ie-user-agent? (moz-ver version os token) (:seq "Mozilla/") (:version? moz-ver) (:lwsp?) #\( (:checkpoint (:seq "compatible;") (:lwsp?) (:seq "MSIE") (:lwsp?) (:version? version) #\; (:lwsp?) (:user-agent-token? os) (:lwsp?) (:zom (:user-agent-token? token)) #\) (:return (list (cons 'browser 'ie) (list 'moz-ver moz-ver) (list 'version version) (cons 'os os))))) ;; ff: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0 ;; => ((BROWSER . FIREFOX) (MOZ-VER (5 0)) (OS . "Linux i686") (REVISION (1 8 1)) (VERSION (2 0))) ;; sea: Mozilla/5.0 (X11; U; Linux i686; tr-TR; rv:1.8.1.2) Gecko/20070511 SeaMonkey/1.1.1 ;; => ((BROWSER . SEAMONKEY) (MOZ-VER (5 0)) (OS . "Linux i686") (REVISION (1 8 1 2)) (VERSION (1 1 1))) ;; oldmoz: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.13) Gecko/20060522 ;; => ((BROWSER . MOZILLA) (MOZ-VER (5 0)) (OS . "Linux i686") (REVISION (1 7 13))) ;; iceweasel: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.8) Gecko/20071004 Iceweasel/2.0.0.8 (Debian-2.0.0.8-1) ;; => (defparser gecko-user-agent? (moz-ver version os c browser revision) (:seq "Mozilla/") (:version? moz-ver) (:lwsp?) #\( (:checkpoint (:user-agent-token?) (:user-agent-token?) (:do (setq os (make-accumulator))) (:user-agent-token? os) (:user-agent-token?) (:lwsp?) (:seq "rv:") (:version? revision) #\) (:lwsp?) (:zom (:type http-header-name?)) (:or (:checkpoint (:lwsp?) (:do (setq browser (make-accumulator))) (:zom (:not #\/) (:type visible-char? c) (:collect c browser)) (:version? version) (:zom (:type http-header-value?)) ;; eat rest (:return (list (cons 'browser (intern (string-upcase browser))) (list 'moz-ver moz-ver) (cons 'os os) (list 'revision revision) (list 'version version)))) (:and (:zom (:type http-header-value?)) ;; eat rest (:return (list (cons 'browser 'mozilla) (list 'moz-ver moz-ver) (cons 'os os) (list 'revision revision))))))) ;; opera: Opera/9.21 (X11; Linux i686; U; en-us) ;; Opera/9.51 (Windows NT 5.1; U; en) ;; => ((BROWSER . OPERA) (VERSION (9 21)) (OS "X11" "Linux i686") (LANG . "en-us")) (defparser opera-user-agent? (version os lang tok) (:seq "Opera/") (:version? version) (:lwsp?) #\( (:zom (:user-agent-token? tok) (:do (push tok os))) (:do (progn (setf lang (pop os)) (pop os))) ;; remove unused "U;" #\) (:return (list (cons 'browser 'opera) (list 'version version) (cons 'os (reverse os)) (cons 'lang lang)))) (defparser unparsed-user-agent? (c (str (make-accumulator))) (:zom (:or (:type (or visible-char? white-space?) c)) (:collect c str)) (:return (list (cons 'browser 'unknown) (cons 'string str)))) (defparser http-user-agent? (agent) ;; (:or (:ie-user-agent? agent) ;; (:gecko-user-agent? agent) ;; (:opera-user-agent? agent)) ;; (:zom (:not (:crlf?)) (:type octet?)) ;; (:return agent) (:unparsed-user-agent? agent) (:return agent)) (defmethod http-user-agent! ((self core-stream) agent) (string! self (format nil "~A" agent))) ;; RFC 2109 Cookie - rfc/2109.lisp (defparser http-cookie? (cookie) (:cookies? cookie) (:return cookie)) (defmethod http-cookie! ((stream core-stream) cookie) (cookie! stream cookie)) ;;;--------------------------------------------------------------------------- ;;; 5.3 HTTP RESPONSE HEADERS ;;;--------------------------------------------------------------------------- (eval-when (:compile-toplevel :load-toplevel :execute) (defvar +http-response-headers+ '(ACCEPT-RANGES AGE ETAG LOCATION PROXY-AUTHENTICATE RETRY-AFTER SERVER VARY WWW-AUTHENTICATE SET-COOKIE))) ;; len=9 ;; 14.5 Accept Ranges ;; Accept-Ranges = "Accept-Ranges" ":" acceptable-ranges ;; acceptable-ranges = 1#range-unit | "none" (defparser http-accept-ranges? (c acc) (:or (:and (:seq "none") (:return 'none)) (:and (:do (setf acc (make-accumulator))) (:oom (:type (or visible-char? space?) c) (:collect c acc)) (:return acc)))) (defun http-accept-ranges! (stream &optional accept-ranges) (if accept-ranges (string! stream accept-ranges) (string! stream "none"))) ;; 14.6 Age ;; Age = "Age" ":" age-value ;; age-value = delta-seconds (defparser http-age? (c) (:fixnum? c) (:return c)) (defun http-age! (stream age) (fixnum! stream age)) ;; 14.19 ETag ;; ETag = "ETag" ":" entity-tag ;; ETag: "xyzzy" ;; ETag: W/"xyzzy" ;; ETag: "" ;; FIXmE: whats thiz? (defun http-etag! (stream etag) (if (cdr etag) (progn (char! stream #\W) (char! stream #\/) (quoted! stream (car etag))) (quoted! stream (car etag)))) ;; 14.30 Location ;; Location = "Location" ":" absoluteURI ;; Location: http://www.w3.org/pub/WWW/People.html (defparser http-location? (c) (:uri? c) (:return c)) (defun http-location! (stream uri) (uri! stream uri)) ;; 14.33 Proxy Authenticate ;; Proxy-Authenticate = "Proxy-Authenticate" ":" 1#challenge ;; FIXME -evrim. (defparser http-proxy-authenticate? () (:return nil)) (defun http-proxy-authenticate! (stream challenge) (http-challenge! stream challenge)) ;; 14.37 Retry-After ;; Retry-After = "Retry-After" ":" ( HTTP-date | delta-seconds ) ;; Retry-After: Fri, 31 Dec 1999 23:59:59 GMT ;; Retry-After: 120 (defparser http-retry-after? (c) (:or (:fixnum? c) (:http-date? c)) (:return c)) (defun http-retry-after! (stream ra) (if (> ra 1000000000) (http-date! stream ra) (fixnum! stream ra))) ;; 14.38 Server ;; Server = "Server" ":" 1*( product | comment ) ;; Server: CERN/3.0 libwww/2.17 (defparser http-server? (c (acc (make-accumulator))) (:oom (:type (or visible-char? space?) c) (:collect c acc)) (:return acc)) (defun http-server! (stream server) (string! stream server)) ;; 14.44 Vary ;; Vary = "Vary" ":" ( "*" | 1#field-name ) ;; FIXME: -evrim. (defparser http-vary? () (:return nil)) (defun http-vary! (stream vary) (if (> (length vary) 1) (if (car vary) (progn (string! stream (car vary)) (reduce #'(lambda (acc atom) (declare (ignore acc)) (char! stream #\,) (string! stream atom)) (cdr vary) :initial-value nil))) (char! stream #\*))) ;; 14.47 WWW-Authenticate ;; WWW-Authenticate = "WWW-Authenticate" ":" 1#challenge ;; FIXME -evrim. (defparser http-www-authenticate? (scheme param params) (:http-auth-scheme? scheme) (:lwsp?) (:http-auth-param? param) (:do (push param params)) (:zom #\, (:lwsp?) (:http-auth-param? param) (:do (push param params))) (:return (cons scheme (nreverse params)))) (defun http-www-authenticate! (stream challenge) (http-challenge! stream challenge)) ;; RFC 2109 Cookie - rfc/2109.lisp (defparser http-set-cookie? (c) (:cookie? c) (:return c)) (defun http-set-cookie! (stream cookie) (cookie! stream cookie)) ;;;--------------------------------------------------------------------------- ;;; 7.1 HTTP ENTITY HEADERS ;;;--------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defvar +http-entity-headers+ '(ALLOW CONTENT-ENCODING CONTENT-LANGUAGE CONTENT-LENGTH CONTENT-LOCATION CONTENT-MD5 CONTENT-RANGE CONTENT-TYPE EXPIRES LAST-MODIFIED))) ;; len=10 ;; 14.7 Allow ;; Allow = "Allow" ":" #method ;; Allow: GET, HEAD, PUT (defparser http-allow? (method methods) (:zom (:and (:http-method? method) (:do (push method methods)) #\, (:zom (:type space?)))) (:return (nreverse methods))) (defun http-allow! (stream methods) (let ((methods (ensure-list methods))) (symbol! stream (car methods)) (mapc #'(lambda (atom) (string! stream ", ") (symbol! stream atom)) (cdr methods)))) ;; 14.11 Content-Encoding ;; Content-Encoding = "Content-Encoding" ":" 1#content-coding ;; Content-Encoding: gzip (defparser http-content-encoding? ((acc (make-accumulator)) c) (:type http-header-name? c) (:collect c acc) (:zom (:type http-header-name? c) (:collect c acc)) (:return acc)) (defun http-content-encoding! (stream encodings) (let ((encodings (ensure-list encodings))) (symbol! stream (car encodings)) (mapc #'(lambda (atom) (string! stream ", ") (symbol! stream atom)) (cdr encodings)))) ;; 14.12 Content-Language ;; Content-Language = "Content-Language" ":" 1#language-tag ;; Content-Language: mi, en (defparser http-content-language? (c (acc (make-accumulator)) (langs '())) (:zom (:zom (:type alpha? c) (:collect c acc)) (:do (push acc langs) (setq acc (make-accumulator))) #\, (:zom (:type space?))) (:return (nreverse langs))) (defun http-content-language! (stream langs) (let ((langs (ensure-list langs))) (typecase (car langs) (string (string! stream (car langs))) (symbol (symbol! stream (car langs)))) (mapc #'(lambda (atom) (string! stream ", ") (typecase atom (string (string! stream atom)) (symbol (symbol! stream atom)))) (cdr langs)))) ;; 14.13 Content-Length ;; Content-Length = "Content-Length" ":" 1*DIGIT ;; Content-Length: 3495 (defparser http-content-length? (num) (:fixnum? num) (:return num)) (defun/cc2 http-content-length! (stream length) (fixnum! stream length)) ;; 14.14 Content-Location ;; Content-Location = "Content-Location" ":" ( absoluteURI | relativeURI ) (defparser http-content-location? (uri) (:uri? uri) (:return uri)) (defun http-content-location! (stream uri) (uri! stream uri)) ;; 14.15 Content-MD5 ;; Content-MD5 = "Content-MD5" ":" md5-digest ;; md5-digest = <base64 of 128 bit MD5 digest as per RFC 1864> (defparser http-content-md5? (c (acc (make-accumulator))) (:type alpha? c) (:collect c acc) (:zom (:type alpha? c) (:collect c acc)) (:return acc)) (defun http-content-md5! (stream md5) (string! stream md5)) ;; 14.16 Content-Range ;; Content-Range = "Content-Range" ":" content-range-spec ;; content-range-spec = byte-content-range-spec ;; byte-content-range-spec = bytes-unit SP ;; byte-range-resp-spec "/" ;; ( instance-length | "*" ) ;; byte-range-resp-spec = (first-byte-pos "-" last-byte-pos) | "*" ;; instance-length = 1*DIGIT ;; FIXmE: implement me. (defparser http-content-range? (c (acc (make-accumulator))) (:type http-header-value? c) (:collect c acc) (:zom (:type http-header-value? c) (:collect c acc)) (:return acc)) (defun http-content-range! (stream range) (string! stream range)) ;; 14.17 Content-Type ;; Content-Type = "Content-Type" ":" media-type ;; Content-Type: text/html; charset=ISO-8859-4 (defparser http-content-type? (type subtype params) (:http-media-range? type subtype params) (:return (if params (list type subtype params) (list type subtype)))) ;; http-content-type! :: (string string . string) ;; ex: '("text" "html" ("charset" . "UTF-8") ...) ;; or: '("text" "javascript" ("charset" "UTF-8") ..) (defun/cc2 http-content-type! (stream typesubtype-charset-cons) (string! stream (car typesubtype-charset-cons)) (char! stream #\/) (string! stream (cadr typesubtype-charset-cons)) (reduce #'(lambda (acc item) (declare (ignore acc)) (char! stream #\;) (string! stream (car item)) (char! stream #\=) (if (listp (cdr item)) (string! stream (cadr item)) (string! stream (cdr item)))) (cddr typesubtype-charset-cons) :initial-value nil)) ;; 14.21 Expires ;; Expires = "Expires" ":" HTTP-date ;; Expires: Thu, 01 Dec 1994 16:00:00 GMT (defparser http-expires? (date) (:http-date? date) (:return date)) (defun http-expires! (stream timestamp) (http-date! stream timestamp)) ;; 14.29 Last-Modified ;; Last-Modified = "Last-Modified" ":" HTTP-date ;; Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT (defparser http-last-modified? (date) (:http-date? date) (:return date)) (defun http-last-modified! (stream timestamp) (http-date! stream timestamp)) ;;;--------------------------------------------------------------------------- ;;; HTTP mESSAGE ;;;--------------------------------------------------------------------------- (defclass http-message () ((version :accessor http-message.version :initform '(1 1) :initarg :version) (general-headers :accessor http-message.general-headers :initarg :general-headers :initform '()) (unknown-headers :accessor http-message.unknown-headers :initform '() :initarg :unknown-headers) (entities :accessor http-message.entities :initarg :entities :initform '()))) ;;;-------------------------------------------------------------------------- ;;; HTTP REQUEST ;;;-------------------------------------------------------------------------- (defclass http-request (http-message) ((method :accessor http-request.method :initarg :method) (uri :accessor http-request.uri :initarg :uri) (headers :accessor http-request.headers :initform '() :initarg :headers) (entity-headers :accessor http-request.entity-headers :initform '() :initarg :entity-headers) (peer-type :accessor http-request.peer-type :initform 'http) (authenticated-p :accessor http-request.authenticated-p :initform nil) (authenticated-user :accessor http-request.authenticated-user :initform nil) (relative-p :accessor http-request.relative-p :initform nil) (stream :accessor http-request.stream :initform nil :initarg :stream))) (defprint-object (self http-request :identity t) (format t "~A ~A" (s-v 'method) (s-v 'uri))) (defun make-http-request (&rest args) (apply #'make-instance 'http-request args)) (defmethod http-request.content-type ((self http-request)) (aif (assoc 'content-type (http-request.entity-headers self)) (cdr it))) (defmethod http-request.content-length ((self http-request)) (aif (assoc 'content-length (http-request.entity-headers self)) (cdr it))) (defmethod http-request.headers ((self http-request)) (append (slot-value self 'headers) (mapcar (lambda (a) (list (car a) (octets-to-string (cdr a) :utf-8))) (slot-value self 'unknown-headers)))) (defmethod http-request.header ((request http-request) key) (cdr (assoc key (http-request.headers request) :test #'string=))) (defmethod http-request.add-request-header ((self http-request) key val) (setf (slot-value self 'headers) (cons (cons key val) (remove-if #'(lambda (a) (eq a key)) (slot-value self 'headers) :key #'car)))) (defmethod http-request.referrer ((request http-request)) (aif (http-request.header request 'referer) (uri.server it))) (defmethod http-request.cookies ((request http-request)) (http-request.header request 'cookie)) (defmethod http-request.cookie ((request http-request) name) (find name (http-request.cookies request) :key #'cookie.name :test #'string=)) (defmethod http-request.query ((request http-request) query) (uri.query (http-request.uri request) query)) (defmethod http-request-first-line! ((stream core-stream) method uri proto) (string! stream (symbol-name method)) (char! stream #\Space) (relative-uri! stream uri) (string! stream " HTTP/") (string! stream (format nil "~A.~A" (car proto) (cadr proto))) (char! stream #\Newline)) (defmethod http-request! ((stream core-stream) (request http-request)) (with-slots (method uri proto) request (http-request-first-line! stream method uri '(1 1)) (reduce (lambda (stream header) (http-request-header! stream header)) (http-request.headers request) :initial-value stream) (reduce (lambda (stream header) (http-entity-header! stream header)) (http-request.entity-headers request) :initial-value stream) (char! stream #\Newline) ;; (char! stream #\Newline) )) (defparser http-request-first-line? (method uri proto) (:http-method? method) (:lwsp?) (:uri? uri) (:lwsp?) (:http-protocol? proto) (:return (values method uri (cadr proto)))) (defmacro defhttp-header-parser (name format header-list) `(defparser ,name (stub) (:not #\Newline) (:or ,@(nreverse (reduce #'(lambda (acc atom) (cons `(:and (:sci ,(format nil "~A:" (symbol-name atom))) (:zom (:type space?)) (,(intern (format nil format atom) :keyword) stub) (:return (cons ',atom stub))) acc)) (eval header-list) :initial-value nil))))) (defhttp-header-parser http-general-header? "HTTP-~A?" +http-general-headers+) (defhttp-header-parser http-request-header? "HTTP-~A?" +http-request-headers+) (defhttp-header-parser http-entity-header? "HTTP-~A?" +http-entity-headers+) (defatom %%http-header-value? () (and (not (linefeed? c)) (not (carriage-return? c)))) (defparser http-unknown-header? ((key (make-accumulator)) (value (make-accumulator :byte)) c) (:not #\Newline) (:oom (:type http-header-name? c) (:collect c key)) #\: (:zom (:type space?)) (:oom (:type %%http-header-value? c) (:collect c value)) (:return (cons key value))) (defparser rfc2616-request-headers? (c method uri version key value header gh rh eh uh) (:http-request-first-line? method uri version) (:lwsp?) (:zom (:or (:and (:http-general-header? header) (:do (push header gh))) (:and (:http-request-header? header) (:do (push header rh))) (:and (:http-entity-header? header) (:do (push header eh))) (:and (:http-unknown-header? header) (:do (push header uh)))) (:zom (:type %%http-header-value?)) (:crlf?)) (:return (values method uri version (nreverse gh) (nreverse rh) (nreverse eh) (nreverse uh)))) (defparser http-request-headers? (method uri version gh rh eh uh) (:rfc2616-request-headers? method uri version gh rh eh uh) (:return (values 'http method uri version gh rh eh uh))) (defparser x-www-form-urlencoded? (query) (:query? query) (:return query)) ;;;--------------------------------------------------------------------------- ;;; HTTP RESPONSE ;;;--------------------------------------------------------------------------- (defclass http-response (http-message) ((response-headers :accessor http-response.response-headers :initarg :response-headers :initform '()) (status-code :accessor http-response.status-code :initform (make-status-code 200) :initarg :status-code) (entity-headers :accessor http-response.entity-headers :initform '() :initarg :entity-headers) (peer-type :accessor http-response.peer-type :initform 'http :initarg :peer-type) (stream :accessor http-response.stream :initform nil :initarg :stream) (entities :accessor http-response.entities :initform nil :initarg :entities))) (defprint-object (self http-response :identity t) (format *standard-output* "~A" (s-v 'status-code))) (defun make-http-response (&rest args) (apply #'make-instance 'http-response args)) (defmethod http-response.add-entity ((self http-response) entity) (with-slots (entities) self (setf entities (cons entity entities)))) (defmethod http-response.response-header ((self http-response) key) (cdr (assoc key (http-response.response-headers self) :test #'string=))) (defmethod http-response.add-entity-header ((self http-response) key val) (setf (slot-value self 'entity-headers) (cons (cons key val) (remove-if #'(lambda (a) (eq a key)) (slot-value self 'entity-headers) :key #'car)))) (defmethod http-response.add-response-header ((self http-response) key val) (setf (slot-value self 'response-headers) (cons (cons key val) (remove-if #'(lambda (a) (eq a key)) (slot-value self 'response-headers) :key #'car)))) (defmethod http-response.add-general-header ((self http-response) key val) (setf (slot-value self 'general-headers) (cons (cons key val) (remove-if #'(lambda (a) (eq a key)) (slot-value self 'general-headers) :key #'car)))) (defmethod http-response.remove-header ((self http-response) key) (mapcar (lambda (a) (setf (slot-value self a) (remove key (slot-value self a) :key #'car))) '(general-headers response-headers entity-headers))) (defmethod http-response.disable-cache ((self http-response)) (http-response.add-general-header self 'cache-control 'no-cache) (http-response.add-general-header self 'pragma 'no-cache) (http-response.add-entity-header self 'expires 0)) (defmethod http-response.set-content-type ((self http-response) content-type) (http-response.add-entity-header self 'content-type content-type)) (defmethod http-response.get-entity-header ((self http-response) key) (cdr (assoc key (http-response.entity-headers self)))) (defmethod http-response.get-response-header ((self http-response) key) (cdr (assoc key (http-response.response-headers self)))) (defmethod http-response.get-content-type ((self http-response)) (http-response.get-entity-header self 'content-type)) (defmethod http-response.get-content-length ((self http-response)) (http-response.get-entity-header self 'content-length)) (defmethod http-response.add-cookie ((self http-response) (cookie cookie)) (setf (slot-value self 'response-headers) (cons (cons 'set-cookie cookie) (remove-if #'(lambda (a) (and (typep (cdr a) 'cookie) (string= (cookie.name (cdr a)) (cookie.name cookie)))) (slot-value self 'response-headers))))) (defmacro defhttp-header-render (name format header-list) (let ((hname (gensym))) `(defun/cc2 ,name (stream hdr) (let ((,hname (car hdr))) (cond ,@(mapcar #'(lambda (h) `((eql ,hname ',h) (progn (string! stream (symbol-name ',h)) (char! stream #\:) (char! stream #\ ) (,(intern (format nil format h)) stream (cdr hdr))))) (eval header-list)) (t (error (format nil "Unknown header name: ~A" (car hdr)))))) (char! stream #\Newline)))) (defhttp-header-render http-general-header! "HTTP-~A!" +http-general-headers+) (defhttp-header-render http-response-header! "HTTP-~A!" +http-response-headers+) (defhttp-header-render http-request-header! "HTTP-~A!" +http-request-headers+) (defhttp-header-render http-entity-header! "HTTP-~A!" +http-entity-headers+) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *status-codes* '((100 . "Continue") (101 . "Switching Protocols") (200 . "OK") (201 . "Created") (202 . "Accepted") (203 . "Non-Authoritative Information") (204 . "No Content") (205 . "Reset Content") (206 . "Partial Content") (300 . "Multiple Choices") (301 . "Moved Permanently") (302 . "Found") (303 . "See Other") (304 . "Not Modified") (305 . "Use Proxy") (307 . "Temporary Redirect") (400 . "Bad Request") (401 . "Unauthorized") (402 . "Payment Required") (403 . "Forbidden") (404 . "Not Found") (405 . "Method Not Allowed") (406 . "Not Acceptable") (407 . "Proxy Authentication Required") (408 . "Request Time-out") (409 . "Conflict") (410 . "Gone") (411 . "Length Required") (412 . "Precondition Failed") (413 . "Request Entity Too Large") (414 . "Request-URI Too Large") (415 . "Unsupported Media Type") (416 . "Requested range not satisfiable") (417 . "Expectation Failed") (500 . "Internal Server Error") (501 . "Not Implemented") (502 . "Bad Gateway") (503 . "Service Unavailable") (504 . "Gateway Time-out") (505 . "HTTP Version not supported"))) (defun make-status-code (num &optional description) (if description (cons num description) (assoc num *status-codes*)))) ;; HTTP/1.1 404 Not Found (defparser status-code? (version status c message) (:sci "HTTP/") (:version? version) (:lwsp?) (:fixnum? status) (:lwsp?) (:type octet? c) (:do (setq message (make-accumulator))) (:collect c message) (:zom (:or (:type visible-char? c) (:type space? c)) (:collect c message)) (:return (values version status message))) ;; status-code! :: stream -> [Int] -> (Int, String) (defun/cc2 status-code! (stream version status-code) (string! stream "HTTP/") (version! stream version) (char! stream #\ ) (fixnum! stream (car status-code)) (char! stream #\ ) (string! stream (cdr status-code)) (char! stream #\Newline)) (defun/cc2 http-response-headers! (stream response) ;; Status-Line (status-code! stream (http-message.version response) (http-response.status-code response)) ;; general headers (reduce #'(lambda (acc item) (declare (ignorable acc)) (http-general-header! stream item)) (http-message.general-headers response) :initial-value nil) ;; response headers (reduce #'(lambda (acc item) (declare (ignorable acc)) (http-response-header! stream item)) (http-response.response-headers response) :initial-value nil) ;; entity headers (reduce #'(lambda (acc item) (declare (ignorable acc)) (http-entity-header! stream item)) (http-response.entity-headers response) :initial-value nil)) (defhttp-header-parser http-response-header? "HTTP-~A?" +http-response-headers+) (defparser http-response-headers? (header gh eh uh key value c) (:zom (:or (:and (:http-general-header? header) (:do (push header gh))) (:and (:http-response-header? header) (:do (push header gh))) (:and (:http-entity-header? header) (:do (push header eh))) (:and (:http-unknown-header? header) (:do (push header uh)))) (:zom (:type %%http-header-value?)) (:optional (:crlf?))) (:return (values (nreverse gh) (nreverse eh) (nreverse uh)))) (defparser http-response? (version status-code status-message gh eh uh) (:status-code? version status-code status-message) (:lwsp?) (:http-response-headers? gh eh uh) (:optional (:crlf?)) (:return (make-instance 'http-response :status-code status-code :entity-headers eh :response-headers (append gh uh)))) ;; ------------------------------------------------------------------------- ;; Trace Definition ;; ------------------------------------------------------------------------- (deftrace http-headers (append (list 'http-request-first-line? 'rfc2616-request-headers? 'http-unknown-header? 'http-general-header? 'http-request-header? 'http-entity-header? 'http-request! 'http-response? 'http-response-headers? 'http-challenge? 'status-code! 'http-response-headers! 'http-request-first-line!) (flatten1 (mapcar (lambda (header) (list (intern (format nil "HTTP-~A?" header)) (intern (format nil "HTTP-~A!" header)))) (append +http-general-headers+ +http-request-headers+ +http-entity-headers+ +http-response-headers+))))) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. ;; HTTP/1.1 404 Not Found ;; Date: Sat, 02 Jul 2011 16:06:29 GMT ;; Server: Apache/2.2.16 (Debian) ;; Vary: Accept-Encoding ;; Content-Length: 205 ;; Content-Type: text/html; charset=iso-8859-1 ;; <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> ;; <html><head> ;; <title>404 Not Found</title> ;; </head><body> ;; <h1>Not Found</h1> ;; <p>The requested URL /foo.bar was not found on this server.</p> ;; </body></html> ;; (defparameter *response* "HTTP/1.1 404 Not Found ;; Server: Apache/2.2.16 (Debian) ;; Vary: Accept-Encoding ;; Date: Sat, 02 Jul 2011 16:06:29 GMT ;; Content-Length: 205 ;; Content-Type: text/html; charset=iso-8859-1 ;; <!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"> ;; <html><head> ;; <title>404 Not Found</title> ;; </head><body> ;; <h1>Not Found</h1> ;; <p>The requested URL /foo.bar was not found on this server.</p> ;; </body></html>")
61,373
Common Lisp
.lisp
1,555
36.009003
120
0.610781
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1febd5c3c504dd97392184eeedede4ccb7805da0ea1299e7e46c9bce2b02944a
8,315
[ -1 ]
8,316
2617.lisp
evrim_core-server/src/rfc/2617.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;; 1.2 Access Authentication Framework ;; auth-scheme = token ;; auth-param = token "=" ( token | quoted-string ) ;; challenge = auth-scheme 1*SP 1#auth-param ;; realm = "realm" "=" realm-value ;; realm-value = quoted-string ;; credentials = auth-scheme #auth-param ;; http-auth-scheme? :: stream -> string (defatom http-auth-scheme-type? () (and (not (eq c #.(char-code #\,))) (alphanum? c))) (defrule http-auth-scheme? (c (acc (make-accumulator))) (:or (:and (:sci "basic") (:return 'basic)) (:and (:sci "digest") (:return 'digest)) (:and (:type http-auth-scheme-type? c) (:collect c acc) (:zom (:type http-auth-scheme-type? c) (:collect c acc)) (:return acc)))) ;; http-auth-scheme! :: stream -> string -> string (defun http-auth-scheme! (stream scheme) (string! stream scheme)) ;; http-auth-param? :: stream -> (cons string string) (defrule http-auth-param? (attr val) (:http-auth-scheme? attr) #\= (:or (:quoted? val) (:http-auth-scheme? val)) (:return (cons attr val))) (defun http-auth-param! (stream acons) (string! stream (car acons)) (char! stream #\=) (quoted! stream (cdr acons))) ;; http-challenge? :: stream -> (cons string ((attrstr . valstr) ...)) (defrule http-challenge? (scheme params c param) (:http-auth-scheme? scheme) (:lwsp?) (:if (eq scheme 'basic) (:and (:do (setq param (make-accumulator :byte))) (:oom (:type visible-char? c) (:collect c param)) (:return (cons scheme (split ":" (octets-to-string (base64? (make-core-stream param)) :us-ascii))))) (:and (:http-auth-param? param) (:do (push param params)) (:zom #\, (:lwsp?) (:http-auth-param? param) (:do (push param params))) (:return (cons scheme (nreverse params)))))) ;; http-challenge! :: stream (cons string ((attrstr . val) ...)) (defun http-challenge! (stream challenge) (symbol! stream (car challenge)) (char! stream #\ ) (prog1 stream (let ((params (cdr challenge))) (when params (string! stream (caar params)) (char! stream #\=) (quoted! stream (cdar params)) (if (cdr params) (reduce #'(lambda (acc item) (char! stream #\,) ;; (char! stream #\Newline) (string! stream (car item)) (char! stream #\=) (quoted! stream (cdr item))) (cdr params) :initial-value nil)))))) (defrule http-realm-value? (c) (:quoted? c) (:return c)) (defrule http-realm? (realm) (:seq "realm=") (:http-realm-value? realm) (:return realm)) (defrule http-credentials? (scheme param) (:http-auth-scheme? scheme) (:lwsp?) (:http-auth-param? param) (:return (cons scheme param))) (defmethod http-credentials! ((stream core-stream) credentials) (http-auth-scheme! stream (car credentials)) (char! stream #\ ) (if (cdr credentials) (http-auth-param! stream (cdr credentials))) stream)
3,666
Common Lisp
.lisp
96
34.78125
72
0.655318
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e7118fe942209684355dccef7cc68a4860298c0ad9213fee3a4bf456ecb12e1e
8,316
[ -1 ]
8,317
3501.lisp
evrim_core-server/src/rfc/3501.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| RFC 3501 IMAP Protocol ;;+---------------------------------------------------------------------------- ;; ;; This file implement only client side operations ;; ;; Notes: ;; - imap-append need to be tested, timestamp is not working ;; - imap-fetch: parse reponse body ;; - imap-uid: not implemented yet (defparser imap-newline? () #\Return #\Newline (:return t)) (defatom imap-valid-char? () (or (space? c) (visible-char? c))) (defparser imap-eat-until-newline? () (:zom (:type imap-valid-char?)) (:return t)) (defparser imap-greeting? (c (acc (make-accumulator))) (:lwsp?) #\* (:zom (:not (:imap-newline?)) (:type imap-valid-char? c) (:collect c acc)) (:return acc)) (defrender imap! (cont message) (:string! cont) (:char! #\Space) (:string! message) (:char! #\Newline)) (defparser imap-status-line? (cont status) (:string? cont) (:lwsp?) (:or (:and (:seq "OK") (:do (setf status 'OK))) (:and (:seq "BAD") (:do (setf status 'BAD)))) (:zom (:not (:imap-newline?)) (:type octet?)) (:return (values cont status))) (defparser imap? (cont status) (:imap-status-line? cont status) (:return (list cont status))) ;; Imap message flags Parser/Render (defatom imap-flag? () (and (not (eq c #.(char-code #\)))) (visible-char? c))) (defparser imap-flags? (flags c (acc (make-accumulator))) #\( (:zom (:not #\)) (:or (:and (:seq "\\Seen") (:do (push 'seen flags))) (:and (:seq "\\Answered") (:do (push 'answered flags))) (:and (:seq "\\Flagged") (:do (push 'flagged flags))) (:and (:seq "\\Deleted") (:do (push 'deleted flags))) (:and (:seq "\\Draft") (:do (push 'draft flags))) (:and (:seq "\\Recent") (:do (push 'recent flags))) (:and (:seq "\\Noselect") (:do (push 'noselect flags))) (:and (:seq "\\*") (:do (push '* flags))) (:and (:zom (:type imap-flag? c) (:collect c acc)) (:do (push acc flags) (setf acc (make-accumulator))))) (:lwsp?)) (:return (if (null flags) 'non-existent-imap-flag (nreverse flags)))) (defvar +imap-flags+ '((seen "\\Seen") (answered "\\Answered") (flagged "\\Flagged") (deleted "\\Deleted") (draft "\\Draft") (recent "\\Recent") (noselect "\\Noselect") (* "\\*"))) (defrender imap-flags! (flags) #\( (:sep " " flags) #\)) (defun filter-imap-flags (flags) (mapcar (lambda (a) (aif (cdr (assoc a +imap-flags+)) it a)) flags)) (defcommand imap () ((stream :host local :initform (error "Please specify stream")) (message :host local :initform (error "Please specify message")) (continuation :host local :initform (random-string 4)) (parser :initform #'imap?))) (defmethod render ((self imap)) (imap! (imap.stream self) (imap.continuation self) (imap.message self))) (defmethod parser ((self imap)) (funcall (imap.parser self) (imap.stream self))) (defmethod validate-continuation ((self imap) cont) (if (equal cont (imap.continuation self)) t (error "Got response for other cont, current:~A, got:~A" (imap.continuation self) cont))) (defmethod validate-result ((self imap) result) (if (eq result 'OK) t (error "Got BAD response for ~A" self))) (defmethod run ((self imap)) (render self) (let ((result (parser self))) (validate-continuation self (car result)) (validate-result self (cadr result)) (cddr result))) ;; 6.1. Client Commands - Any State ;; 6.1.1. CAPABILITY Command ;; Arguments: none ;; Responses: REQUIRED untagged response: CAPABILITY ;; Result: OK - capability completed ;; BAD - command unknown or arguments invalid (defparser imap-capability? (c (acc (make-accumulator)) params cont status) (:seq "* CAPABILITY ") (:zom (:zom (:type visible-char? c) (:collect c acc)) (:do (push acc params) (setf acc (make-accumulator))) (:type space?)) (:lwsp?) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse params))))) (defcommand imap-capability (imap) () (:default-initargs :message "CAPABILITY" :parser #'imap-capability?)) ;; 6.1.2. NOOP Command ;; Arguments: none ;; Responses: no specific responses for this command (but see below) ;; Result: OK - noop completed ;; BAD - command unknown or arguments invalid (defparser imap-noop? (cont status num value params) (:zom #\* (:fixnum? num) (:string? value) (:do (push (cons num value) params))) (:imap-status-line? cont status) (:return (cons cont (cons status params)))) (defcommand imap-noop (imap) () (:default-initargs :message "NOOP" :parser #'imap-noop?)) ;; 6.1.3. LOGOUT Command ;; Arguments: none ;; Responses: REQUIRED untagged response: BYE ;; Result: OK - logout completed ;; BAD - command unknown or arguments invalid (defparser imap-logout? (cont status) #\* (:lwsp?) (:seq "BYE") (:zom (:not #\Newline) (:type octet?)) (:imap-status-line? cont status) (:return (cons cont (cons status t)))) (defcommand imap-logout (imap) () (:default-initargs :message "LOGOUT" :parser #'imap-logout?)) (defmethod run ((self imap-logout)) (prog1 (call-next-method) (close-stream (imap.stream self)))) ;; 6.2. Client Commands - Not Authenticated State ;; 6.2.1. STARTTLS Command ;; Arguments: none ;; Responses: no specific response for this command ;; Result: OK - starttls completed, begin TLS negotiation ;; BAD - command unknown or arguments invalid (defcommand imap-starttls (imap) () (:default-initargs :message "STARTTLS" :parser #'imap?)) ;; 6.2.2. AUTHENTICATE Command ;; Arguments: authentication mechanism name ;; Responses: continuation data can be requested ;; Result: OK - authenticate completed, now in authenticated state ;; NO - authenticate failure: unsupported authentication ;; mechanism, credentials rejected ;; BAD - command unknown or arguments invalid, ;; authentication exchange cancelled (defcommand imap-authenticate (imap) ((mechanism :accessor imap.mechanism :initarg :mechanism :initform "LOGIN")) (:default-initargs :message "AUTHENTICATE")) ;; 6.2.3. LOGIN Command ;; Arguments: user name ;; password ;; Responses: no specific responses for this command ;; Result: OK - login completed, now in authenticated state ;; NO - login failure: user name or password rejected ;; BAD - command unknown or arguments invalid (defcommand imap-login (imap) ((username :host local :initarg :username :accessor imap.username :initform (error "Please specify username")) (password :host local :initarg :password :accessor imap.password :initform (error "Please specify password"))) (:default-initargs :message "LOGIN")) (defmethod run ((self imap-login)) (prog1 t (setf (imap.message self) (format nil "~A ~A ~A" (imap.message self) (imap.username self) (imap.password self))) (call-next-method))) ;; 6.3. Client Commands - Authenticated State (defcommand imap-mailbox-command (imap) ((mailbox :accessor imap.mailbox :initform (error "Please specify mailbox") :host local))) (defmethod render ((self imap-mailbox-command)) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A" (imap.message self) (imap.mailbox self)))) ;; 6.3.1. SELECT Command ;; Arguments: mailbox name ;; Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT ;; REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS, ;; UIDNEXT, UIDVALIDITY ;; Result: OK - select completed, now in selected state ;; NO - select failure, now in authenticated state: no ;; such mailbox, can't access mailbox ;; BAD - command unknown or arguments invalid (defparser imap-select? (cont status flags exists recent unseen uidvalidity uidnext permanent-flags) (:zom #\* (:lwsp?) (:or (:and (:seq "FLAGS") (:lwsp?) (:imap-flags? flags) (:if (eq flags 'non-existent-imap-flag) (:do (setf flags nil)))) (:checkpoint (:fixnum? exists) (:lwsp?) (:seq "EXISTS") (:commit)) (:checkpoint (:fixnum? recent) (:lwsp?) (:seq "RECENT") (:commit)) (:and (:seq "OK") (:lwsp?) (:or (:and (:seq "[UNSEEN ") (:fixnum? unseen) (:imap-eat-until-newline?)) (:and (:seq "[UIDVALIDITY ") (:fixnum? uidvalidity) (:imap-eat-until-newline?)) (:and (:seq "[UIDNEXT ") (:fixnum? uidnext) (:imap-eat-until-newline?)) (:and (:seq "[PERMANENTFLAGS ") (:imap-flags? permanent-flags) (:if (eq permanent-flags 'non-existent-imap-flag) (:do (setf permanent-flags nil))) (:imap-eat-until-newline?))))) (:lwsp?)) (:imap-status-line? cont status) (:return (cons cont (cons status (list (cons 'exists exists) (cons 'recent recent) (cons 'unseen unseen) (cons 'uidvalidity uidvalidity) (cons 'uidnext uidnext) (cons 'permanent-flags permanent-flags)))))) (defcommand imap-select (imap-mailbox-command) () (:default-initargs :message "SELECT" :parser #'imap-select?)) ;; 6.3.2. EXAMINE Command ;; Arguments: mailbox name ;; Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT ;; REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS, ;; UIDNEXT, UIDVALIDITY ;; Result: OK - examine completed, now in selected state ;; NO - examine failure, now in authenticated state: no ;; such mailbox, can't access mailbox ;; BAD - command unknown or arguments invalid (defcommand imap-examine (imap-select) () (:default-initargs :message "EXAMINE")) ;; 6.3.3. CREATE Command ;; Arguments: mailbox name ;; Responses: no specific responses for this command ;; Result: OK - create completed ;; NO - create failure: can't create mailbox with that name ;; BAD - command unknown or arguments invalid (defcommand imap-create (imap-mailbox-command) () (:default-initargs :message "CREATE")) ;; 6.3.4. DELETE Command ;; Arguments: mailbox name ;; Responses: no specific responses for this command ;; Result: OK - delete completed ;; NO - delete failure: can't delete mailbox with that name ;; BAD - command unknown or arguments invalid (defcommand imap-delete (imap-mailbox-command) () (:default-initargs :message "DELETE")) ;; 6.3.5. RENAME Command ;; Arguments: existing mailbox name ;; new mailbox name ;; Responses: no specific responses for this command ;; Result: OK - rename completed ;; NO - rename failure: can't rename mailbox with that name, ;; can't rename to mailbox with that name ;; BAD - command unknown or arguments invalid (defcommand imap-rename (imap-mailbox-command) ((new-mailbox :accessor imap.new-mailbox :initform (error "Please specify new mailbox") :initarg :new-mailbox :host local)) (:default-initargs :message "RENAME")) (defmethod render ((self imap-rename)) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A ~A" (imap.message self) (imap.mailbox self) (imap.new-mailbox self)))) ;; 6.3.6. SUBSCRIBE Command ;; Arguments: mailbox ;; Responses: no specific responses for this command ;; Result: OK - subscribe completed ;; NO - subscribe failure: can't subscribe to that name ;; BAD - command unknown or arguments invalid (defcommand imap-subscribe (imap-mailbox-command) () (:default-initargs :message "SUBSCRIBE")) ;; 6.3.7. UNSUBSCRIBE Command ;; Arguments: mailbox name ;; Responses: no specific responses for this command ;; Result: OK - unsubscribe completed ;; NO - unsubscribe failure: can't unsubscribe that name ;; BAD - command unknown or arguments invalid (defcommand imap-unsubscribe (imap-mailbox-command) () (:default-initargs :message "UNSUBSCRIBE")) ;; 6.3.8. LIST Command ;; Arguments: reference name ;; mailbox name with possible wildcards ;; Responses: untagged responses: LIST ;; Result: OK - list completed ;; NO - list failure: can't list that reference or name ;; BAD - command unknown or arguments invalid (defparser imap-list? (cont status flags c reference mailbox result) (:zom #\* (:lwsp?) (:or (:seq "LSUB") (:seq "LIST")) (:lwsp?) (:imap-flags? flags) (:lwsp?) (:or (:quoted? reference) (:and (:do (setf reference (make-accumulator))) (:zom (:type visible-char? c) (:collect c reference)))) (:or (:quoted? mailbox) (:and (:do (setf mailbox (make-accumulator))) (:zom (:type visible-char? c) (:collect c mailbox)))) (:do (push (list (if (eq 'non-existent-imap-flag flags) nil flags) reference mailbox) result))) (:lwsp?) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse result))))) (defcommand imap-list (imap-mailbox-command) ((reference :accessor imap.reference :initarg :reference :initform "" :host local)) (:default-initargs :mailbox "" :message "LIST" :parser #'imap-list?)) (defrender imap-list! (cont message reference mailbox) (:string! cont) (:char! #\Space) (:string! message) (:char! #\Space) (:quoted! reference) (:char! #\Space) (:quoted! mailbox) (:char! #\Newline)) (defmethod render ((self imap-list)) (imap-list! (imap.stream self) (imap.continuation self) (imap.message self) (imap.reference self) (imap.mailbox self))) ;; 6.3.9. LSUB Command ;; Arguments: reference name ;; mailbox name with possible wildcards ;; Responses: untagged responses: LSUB ;; Result: OK - lsub completed ;; NO - lsub failure: can't list that reference or name ;; BAD - command unknown or arguments invalid (defcommand imap-lsub (imap-list) () (:default-initargs :message "LSUB")) ;; 6.3.10. STATUS Command ;; Arguments: mailbox name ;; status data item names ;; Responses: untagged responses: STATUS ;; Result: OK - status completed ;; NO - status failure: no status for that name ;; BAD - command unknown or arguments invalid (defparser imap-status? (c mbox messages uidnext recent uidvalidity unseen cont status) #\* (:lwsp?) (:seq "STATUS") (:lwsp?) (:or (:quoted? mbox) (:and (:do (setf mbox (make-accumulator))) (:zom (:type visible-char? c) (:collect c mbox)))) (:lwsp?) #\( (:zom (:or (:and (:seq "MESSAGES") (:lwsp?) (:fixnum? messages)) (:and (:seq "UIDNEXT") (:lwsp?) (:fixnum? uidnext)) (:and (:seq "RECENT") (:lwsp?) (:fixnum? recent)) (:and (:seq "UIDVALIDITY") (:lwsp?) (:fixnum? uidvalidity)) (:and (:seq "UNSEEN") (:lwsp?) (:fixnum? unseen))) (:lwsp?)) #\) (:lwsp?) (:imap-status-line? cont status) (:return (cons cont (cons status (list (cons 'messages messages) (cons 'uidnext uidnext) (cons 'recent recent) (cons 'uidvalidity uidvalidity) (cons 'unseen unseen)))))) (defcommand imap-status (imap-mailbox-command) ((messages :initform t :initarg :messages :host local :accessor imap.messages) (recent :initform t :initarg :recent :host local :accessor imap.recent) (uidnext :initform t :initarg :uidnext :host local :accessor imap.uidnext) (uidvalidity :initform t :initarg :uidvalidity :host local :accessor imap.uidvalidity) (unseen :initform t :initarg :unseen :host local :accessor imap.unseen)) (:default-initargs :message "STATUS" :parser #'imap-status?)) (defmethod render ((self imap-status)) (let ((data (reduce (lambda (acc atom) (if (slot-value self atom) (cons atom acc) acc)) '(messages recent uidnext uidvalidity unseen) :initial-value nil))) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A ~(~A~)" (imap.message self) (imap.mailbox self) data)))) ;; 6.3.11. APPEND Command ;; Arguments: mailbox name ;; OPTIONAL flag parenthesized list ;; OPTIONAL date/time string ;; message literal ;; Responses: no specific responses for this command ;; Result: OK - append completed ;; NO - append error: can't append to that mailbox, error ;; in flags or date/time or message text ;; BAD - command unknown or arguments invalid (defcommand imap-append (imap-mailbox-command) ((flags :host local :accessor imap.flags :initarg :flags :initform nil) (timestamp :host local :accessor imap.timestamp :initarg :timestamp :initform nil) (envelope :host local :accessor imap.envelope :initarg :envelope :initform (error "Please specify :envelope"))) (:default-initargs :message "APPEND")) (defrender imap-append! (cont message mailbox flags length) (:string! cont) #\Space (:string! message) #\Space (:string! mailbox) #\Space (:imap-flags! flags) #\Space #\{ (:fixnum! length) #\} #\Newline) (defparser imap-append-ready? () (:seq "+ ") (:zom (:not #\Newline) (:type (or space? visible-char?))) (:return t)) (defrender imap-append-envelope! (envelope) (:string! envelope)) (defmethod run ((self imap-append)) (with-core-stream (s "") (envelope! s (imap.envelope s)) (imap-append! (imap.stream self) (imap.continuation self) (imap.message self) (imap.mailbox self) (filter-imap-flags (ensure-list (imap.flags self))) (length (return-stream s))) (imap-append-ready? (imap.stream self)) (imap-append-envelope! (imap.stream self) (return-stream s)) (imap? (imap.stream self)))) ;; 6.4. Client Commands - Selected State ;; 6.4.1. CHECK Command ;; Arguments: none ;; Responses: no specific responses for this command ;; Result: OK - check completed ;; BAD - command unknown or arguments invalid (defcommand imap-check (imap) () (:default-initargs :message "CHECK")) ;; 6.4.2. CLOSE Command ;; Arguments: none ;; Responses: no specific responses for this command ;; Result: OK - close completed, now in authenticated state ;; BAD - command unknown or arguments invalid (defcommand imap-close (imap) () (:default-initargs :message "CLOSE")) ;; 6.4.3. EXPUNGE Command ;; Arguments: none ;; Responses: untagged responses: EXPUNGE ;; Result: OK - expunge completed ;; NO - expunge failure: can't expunge (e.g., permission ;; denied) ;; BAD - command unknown or arguments invalid (defparser imap-expunge? (cont status id messages) (:zom #\* (:lwsp?) (:fixnum? id) (:do (push id messages)) (:seq "EXPUNGE") (:lwsp?)) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse messages))))) (defcommand imap-expunge (imap) () (:default-initargs :message "EXPUNGE" :parser #'imap-expunge?)) ;; 6.4.4. SEARCH Command ;; Arguments: OPTIONAL [CHARSET] specification ;; searching criteria (one or more) ;; Responses: REQUIRED untagged response: SEARCH ;; Result: OK - search completed ;; NO - search error: can't search that [CHARSET] or ;; criteria ;; BAD - command unknown or arguments invalid (defparser imap-search? (num result cont status) #\* (:lwsp?) (:seq "SEARCH") (:lwsp?) (:zom (:fixnum? num) (:do (push num result)) (:type space?)) (:lwsp?) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse result))))) (defcommand imap-search (imap) ((charset :accessor imap.charset :initarg :charset :host local :initform nil) (query :accessor imap.query :initarg :query :host local :initform (error "Please specify query"))) (:default-initargs :message "SEARCH" :parser #'imap-search?)) (defmethod render ((self imap-search)) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A" (imap.message self) (if (imap.charset self) (format nil "~A ~A" (imap.charset self) (imap.query self)) (imap.query self))))) ;; 6.4.5. FETCH Command ;; Arguments: sequence set ;; message data item names or macro ;; Responses: untagged responses: FETCH ;; Result: OK - fetch completed ;; NO - fetch error: can't fetch that data ;; BAD - command unknown or arguments invalid ;; TODO: Handle BODY replies, parse result ;; "(FLAGS (\\Seen) INTERNALDATE \"20-Jun-2008 14:06:51 +0300\" RFC822.SIZE 7143 ENVELOPE (\"Fri, 20 Jun 2008 13:47:02 +0300\" \"=?windows-1254?Q?ileri_Excel_ve_=DDnternet_Pazarlama?=\" ((\"Bilisim Seminer\" NIL \"news\" \"zeru-news.com\")) ((\"Bilisim Seminer\" NIL \"news\" \"zeru-news.com\")) ((NIL NIL \"news\" \"zerumail.com\")) ((NIL NIL \"evrim\" \"core.gen.tr\")) NIL NIL NIL \"<[email protected]>\"))" (defparser imap-fetch? (id result c (acc (make-accumulator)) cont status) (:zom #\* (:lwsp?) (:fixnum? id) (:lwsp?) (:seq "FETCH") (:lwsp?) (:zom (:type (or space? visible-char?) c) (:collect c acc)) (:do (push (cons id acc) result)) (:lwsp?)) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse result))))) (defcommand imap-fetch (imap) ((sequence :initarg :sequence :accessor imap.sequence :host local :initform (error "Please specify sequence")) (macro :initarg :macro :accessor imap.macro :host local :initform (error "Please specify data item names or macro"))) (:default-initargs :message "FETCH" :parser #'imap-fetch?)) (defmethod render ((self imap-fetch)) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A ~A" (imap.message self) (if (consp (imap.sequence self)) (format nil "~D:~D" (car (imap.sequence self)) (cdr (imap.sequence self))) (imap.sequence self)) (imap.macro self)))) ;; 6.4.6. STORE Command ;; Arguments: sequence set ;; message data item name ;; value for message data item ;; Responses: untagged responses: FETCH ;; Result: OK - store completed ;; NO - store error: can't store that data ;; BAD - command unknown or arguments invalid (defparameter +imap-store-commands+ '((set "FLAGS") (silent-set "FLAGS.SILENT") (append "+FLAGS") (silent-append "+FLAGS.SILENT") (remove "-FLAGS") (silent-remove "-FLAGS.SILENT"))) (defparser imap-store? (id flags result cont status) (:zom #\* (:lwsp?) (:fixnum? id) (:lwsp?) (:seq "FETCH") (:lwsp?) (:seq "(FLAGS ") (:imap-flags? flags) (:do (push (cons id flags) result)) #\) (:lwsp?)) (:imap-status-line? cont status) (:return (cons cont (cons status (nreverse result))))) (defcommand imap-store (imap) ((sequence :host local :initform (error "Please specify :sequence") :accessor imap.sequence :initarg :sequence) (command :host local :initform (error "Please specify :comand") :accessor imap.command :initarg :command) (flags :host local :initform (error "Please specify :flags") :accessor imap.flags :initarg :flags)) (:default-initargs :message "STORE" :parser #'imap-store?)) (defrender imap-store! (cont message sequence command flags) (:string! cont) (:char! #\Space) (:string! message) (:char! #\Space) (:string! sequence) (:char! #\Space) (:string! command) (:char! #\Space) (:char! #\() (:sep " " flags) (:char! #\)) (:char! #\Newline)) (defmethod render ((self imap-store)) (assert (member (imap.command self) +imap-store-commands+ :key #'car)) (imap-store! (imap.stream self) (imap.continuation self) (imap.message self) (if (consp (imap.sequence self)) (format nil "~D:~D" (car (imap.sequence self)) (cdr (imap.sequence self))) (format nil "~D" (imap.sequence self))) (cadr (assoc (imap.command self) +imap-store-commands+)) (filter-imap-flags (ensure-list (imap.flags self))))) ;; 6.4.7. COPY Command ;; Arguments: sequence set ;; mailbox name ;; Responses: no specific responses for this command ;; Result: OK - copy completed ;; NO - copy error: can't copy those messages or to that ;; name ;; BAD - command unknown or arguments invalid (defcommand imap-copy (imap) ((sequence :accessor imap.sequence :host local :initarg :sequence :initform (error "Please specify :sequence")) (mailbox :accessor imap.mailbox :host local :initarg :mailbox :initform (error "Please specify :mailbox"))) (:default-initargs :message "COPY")) (defmethod render ((self imap-copy)) (imap! (imap.stream self) (imap.continuation self) (format nil "~A ~A ~A" (imap.message self) (if (consp (imap.sequence self)) (format nil "~D:~D" (car (imap.sequence self)) (cdr (imap.sequence self))) (imap.sequence self)) (imap.mailbox self)))) ;; 6.4.8. UID Command ;; Arguments: command name ;; command arguments ;; Responses: untagged responses: FETCH, SEARCH ;; Result: OK - UID command completed ;; NO - UID command error ;; BAD - command unknown or arguments invalid ;; TODO: Implement UID (defcommand imap-uid (imap) ()) ;; (defun test-imap () ;; (let ((s (make-core-stream ;; (cl+ssl::make-ssl-client-stream ;; (slot-value (connect "imap.core.gen.tr" 993) '%stream))))) ;; (list (imap-greeting? s) ;; (imap-capability :stream s) ;; (imap-noop :stream s) ;; ;; (imap-starttls :stream s) ;; (imap-login :stream s :username "evrim.ulu" :password "d0m1n0z") ;; (imap-select :stream s :mailbox "INBOX") ;; (imap-examine :stream s :mailbox "INBOX") ;; (let ((folder (random-string 5)) ;; (folder2 (random-string 5))) ;; (imap-create :stream s :mailbox folder) ;; (imap-rename :stream s :mailbox folder :new-mailbox folder2) ;; (imap-select :stream s :mailbox folder2) ;; (imap-delete :stream s :mailbox folder2)) ;; (imap-select :stream s :mailbox "INBOX") ;; (imap-status :stream s :mailbox "INBOX") ;; (imap-list :stream s) ;; (imap-lsub :stream s) ;; (imap-check :stream s) ;; (imap-search :stream s :query "FROM \"evrim\"") ;; (imap-fetch :stream s :sequence 2457 :macro "ALL") ;; (imap-store :stream s :sequence 2457 :command 'set :flags '(seen)) ;; (imap-copy :stream s :sequence 2457 :mailbox "Sent") ;; (imap-expunge :stream s) ;; (imap-logout :stream s)))) ;; openssl s_client -host mail.core.gen.tr -port 993
27,851
Common Lisp
.lisp
683
37.689605
439
0.638658
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e65ecbacad91d50cfaabbdfc84e62a1d20d9ce0bfd68ca3c3972420b2f6ba901
8,317
[ -1 ]
8,318
2388.lisp
evrim_core-server/src/rfc/2388.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;;----------------------------------------------------------------------------- ;;; RFC 2388 - Returning Values from Forms: multipart/form-data ;;; http://www.ietf.org/rfc/rfc2388.txt ;;;----------------------------------------------------------------------------- ;; 3. Definition of multipart/form-data ;; content-disposition: form-data; name=\"field1\" ;; Content-Disposition: form-data; name=\"abuzer2\"; filename=\"a.html\" (defatom rfc2388-parameter-value? () (and (not (eq #.(char-code #\;) c)) (or (visible-char? c) (space? c)))) (defrule rfc2388-content-disposition? ((parameters '()) (type (make-accumulator)) c (key (make-accumulator)) value) (:lwsp?) (:type http-header-name? c) (:collect c type) (:zom (:not #\;) (:type (or visible-char? space?) c) (:collect c type)) (:lwsp?) (:zom (:type http-header-name? c) (:collect c key) (:zom (:not #\=) (:type http-header-name? c) (:collect c key)) (:or (:and (:quoted? value)) (:and (:do (setq value (make-accumulator :byte))) (:type http-header-value? c) (:collect c value) (:zom (:type rfc2388-parameter-value? c) (:collect c value)))) (:do (push (cons key value) parameters) (setq key (make-accumulator))) #\; (:lwsp?)) (:return (list type (nreverse parameters)))) (defun rfc2388-mimes? (stream &optional (boundary nil)) (let ((mimes (mimes? stream boundary))) (when mimes (mapc #'(lambda (mime) (mime-search mime #'(lambda (mime) (setf (mime.header mime 'disposition) (rfc2388-content-disposition? (make-core-stream (mime.header mime 'disposition)))) nil))) mimes) mimes))) (deftrace rfc2388 '(rfc2388-mimes? rfc2388-content-disposition?))
2,505
Common Lisp
.lisp
55
42.127273
83
0.637444
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f3ac8100c8d0d7913b5854e47bc065f0b24fea84d766557b7ebd9619623d6186
8,318
[ -1 ]
8,319
2045.lisp
evrim_core-server/src/rfc/2045.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;;-------------------------------------------------------------------------- ;;; RFC 2045 - Multipurpose Internet Mail Extensions (MIME) ;;; Part One: Format of Internet Message Bodies ;;;-------------------------------------------------------------------------- ;;;-------------------------------------------------------------------------- ;;; 6.7. Quoted-Printable Content-Transfer-Encoding ;;;-------------------------------------------------------------------------- ;; transport-padding := *LWSP-char ;; Composers MUST NOT generate non-zero length transport padding, but ;; receivers MUST be able to handle padding added by message ;; transports. (defatom lwsp-char? () (or (space? c) (tab? c) (carriage-return? c) (linefeed? c))) (defrule transport-padding? () (:zom (:type lwsp-char?)) (:return t)) ;; hex-octet := "=" 2(DIGIT / "A" / "B" / "C" / "D" / "E" / "F") ;; Octet must be used for characters > 127, =, SPACEs or TABs at the ;; ends of lines, and is recommended for any character not listed in ;; RFC 2049 as "mail-safe". (defrule hex-octet? (hex) (:and #\= (:hex-value? hex) (:return hex))) ;; safe-char := <any octet with decimal value of 33 through ;; 60 inclusive, and 62 through 126> ;; Characters not listed as "mail-safe" in RFC 2049 are also not recommended. (defatom safe-char? () (or (and (> c 32) (< c 61)) (and (> c 61) (< c 127)))) ;; ptext := hex-octet / safe-char (defrule ptext? (c) (:or (:and (:type safe-char? c) (:return c)) (:and (:hex-octet? c) (:return c)))) ;; qp-section := [*(ptext / SPACE / TAB) ptext] (defrule qp-section? (c (acc (make-accumulator :byte))) (:zom (:or (:ptext? c) (:type (or space? tab?) c)) (:collect c acc) (:or (:ptext? c) (:type (or space? tab?) c)) (:collect c acc) (:zom (:type (or space? tab?)))) (:return acc)) ;; qp-segment := qp-section *(SPACE / TAB) "=" ;; Maximum length of 76 characters (defrule qp-segment? (qp) (:qp-section? qp) (:zom (:type (or space? tab?))) #\= (:return qp)) ;; qp-part := qp-section ; Maximum length of 76 characters (defrule qp-part? (qp) (:qp-section? qp) (:return qp)) ;; qp-line := *(qp-segment transport-padding CRLF) ;; qp-part transport-padding (defrule qp-line? (segments qs) (:zom (:qp-segment? qs) (:do (push qs segments)) (:crlf?)) (:and (:qp-part? qs) (:do (push qs segments))) (:transport-padding?) (:return (apply #'concatenate '(vector (unsigned-byte 8)) (nreverse segments)))) ;; quoted-printable := qp-line *(CRLF qp-line) (defrule quoted-printable? (lines line) (:qp-line? line) (:do (push line lines)) (:zom (:crlf?) (:qp-line? line) (:do (push line lines))) (:return (apply #'concatenate '(vector (unsigned-byte 8)) (nreverse lines)))) (defun hex-octet! (stream atom) (char! stream #\=) (hex-value! stream atom)) ;; This is depreciated. Use make-quoted-printable-stream ;; instead. -evrim. (defun quoted-printable! (stream array &aux (line-length 0)) (etypecase array (string (setq array (string-to-octets array :utf-8))) (array t)) (flet ((do-crlf () (byte! stream #.(char-code #\=)) ;; (byte! stream 13) (byte! stream 10) (setq line-length 0))) (reduce #'(lambda (acc atom) (declare (ignore acc)) (cond ((safe-char? atom) (if (> line-length 74) (do-crlf) (incf line-length)) (byte! stream atom)) (t (if (> line-length 72) (do-crlf) (incf line-length 3)) (hex-octet! stream atom))) nil) array :initial-value nil)) array) ;; #| ;; (defparameter *qptext-1* "abc def ghi=0A= ;; abc def ghi=0A= ;; ghi") ;; (defparameter *qptext* "abc def ghi ;; abc def ghi ;; ghi") ;; (equal (octets-to-string (quoted-printable? (make-core-stream *qptext-1*)) :utf-8) ;; *qptext*) ;; => t ;; SERVER> (let ((stream (make-core-stream ""))) ;; (quoted-printable! stream "AAAAAAAAAAAAAAAAAAAAAAA ;; A AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB") ;; (stream-data stream)) ;; "AAAAAAAAAAAAAAAAAAAAAAA=0A=20A=20AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= ;; AAAAAAAAAAB" ;; SERVER> (length "AAAAAAAAAAAAAAAAAAAAAAA=0A=20A=20AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") ;; 76 ;; SERVER> (let ((stream (make-core-stream ""))) ;; (quoted-printable! stream "AAAAAAAAAAAAAAAAAAAAAAA ;; A AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB") ;; (stream-data stream)) ;; "AAAAAAAAAAAAAAAAAAAAAAA=0A=20A=20AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= ;; AAAAAAAAAAB" ;; SERVER> (quoted-printable? (make-core-stream *)) ;; "AAAAAAAAAAAAAAAAAAAAAAA ;; A AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB" ;; |# ;;;----------------------------------------------------------------------------- ;;; 6.8. Base64 Content-Transfer-Encoding ;;;----------------------------------------------------------------------------- ;;; Got binary aritmetic functions from mr. Sven Van Caekenberghe ;;; http://cl-debian.alioth.debian.org/repository/pvaneynd/s-base64-upstream/src/base64.lisp ;;; Those have licenses at: http://opensource.franz.com/preamble.html ;; Table 1: The Base64 Alphabet ;; ;; Value Encoding Value Encoding Value Encoding Value Encoding ;; 0 A 17 R 34 i 51 z ;; 1 B 18 S 35 j 52 0 ;; 2 C 19 T 36 k 53 1 ;; 3 D 20 U 37 l 54 2 ;; 4 E 21 V 38 m 55 3 ;; 5 F 22 W 39 n 56 4 ;; 6 G 23 X 40 o 57 5 ;; 7 H 24 Y 41 p 58 6 ;; 8 I 25 Z 42 q 59 7 ;; 9 J 26 a 43 r 60 8 ;; 10 K 27 b 44 s 61 9 ;; 11 L 28 c 45 t 62 + ;; 12 M 29 d 46 u 63 / ;; 13 N 30 e 47 v ;; 14 O 31 f 48 w (pad) = ;; 15 P 32 g 49 x ;; 16 Q 33 h 50 y (defparameter +base64-alphabet+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") (defparameter +inverse-base64-alphabet+ (let ((inverse-base64-alphabet (make-array 127))) (dotimes (i 127 inverse-base64-alphabet) (setf (aref inverse-base64-alphabet i) (position (code-char i) +base64-alphabet+))))) (defun base64-decode (byte1 byte2 byte3 byte4) (flet ((inverse (byte) (if byte (aref +inverse-base64-alphabet+ byte) 0))) (let ((v1 (inverse byte1)) (v2 (inverse byte2)) (v3 (inverse byte3)) (v4 (inverse byte4))) (values (logior (ash v1 2) (ash v2 -4)) (if byte3 (logior (ash (logand v2 #B1111) 4) (ash v3 -2))) (if (and byte3 byte4) (logior (ash (logand v3 #B11) 6) v4)))))) (defatom base64-char? () (or (alphanum? c) (eq c #.(char-code #\+)) (eq c #.(char-code #\/)))) (defrule base64-block? (c1 c2 c3 c4) (:type base64-char? c1) (:type base64-char? c2) (:or #\= (:type base64-char? c3)) (:or #\= (:type base64-char? c4)) (:return (base64-decode c1 c2 c3 c4))) (defrule base64? (v1 v2 v3 (acc (make-accumulator :byte))) (:oom (:base64-block? v1 v2 v3) (:if v1 (:collect v1 acc)) (:if v2 (:collect v2 acc)) (:if v3 (:and (:collect v3 acc) (:lwsp?)) (:return acc))) (:return acc)) (defun base64-encode (byte1 byte2 byte3) (values (char +base64-alphabet+ (ash byte1 -2)) (char +base64-alphabet+ (logior (ash (logand byte1 #B11) 4) (ash (logand (or byte2 0) #B11110000) -4))) (if byte2 (char +base64-alphabet+ (logior (ash (logand byte2 #B00001111) 2) (ash (logand (or byte3 0) #B11000000) -6))) #\=) (if byte3 (char +base64-alphabet+ (logand byte3 #B111111)) #\=))) (defun base64! (stream array) (etypecase array (string (setq array (string-to-octets array :utf-8))) (array t)) (let ((i 0) leak) (labels ((out (char) (when (= (the fixnum i) 76) (char! stream #\Newline) (setq i 0)) (char! stream char) (incf i)) (write-blocks () (reduce (lambda (acc atom) (cond ((= (length acc) 2) (push-atom atom acc) (multiple-value-bind (out1 out2 out3 out4) (base64-encode (aref acc 0) (aref acc 1) (aref acc 2)) (out out1) (out out2) (out out3) (out out4)) (make-accumulator :byte)) (t (push-atom atom acc) acc))) array :initial-value (make-accumulator :byte)))) (setq leak (write-blocks)) (let ((len (length leak))) (if (> len 0) (multiple-value-bind (out1 out2 out3 out4) (base64-encode (aref leak 0) (if (>= len 2) (aref leak 1)) (if (>= len 3) (aref leak 2))) (out out1) (out out2) (out out3) (out out4)))))) t) ;; #| ;; (defparameter +base64-encoded+ "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz ;; IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg ;; dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu ;; dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo ;; ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=sometrash") ;; (defparameter +base64-string+ "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.") ;; (equal (octets-to-string (base64? (make-core-stream +base64-encoded+)) ;; :utf-8) +base64-string+) ;; (equal (let ((stream (make-core-stream ""))) ;; (base64! stream +base64-string+) ;; (return-strteam stream)) ;; +base64-encoded+) ;; |# ;;;----------------------------------------------------------------------------- ;;; 4. MIME-Version Header Field ;;;----------------------------------------------------------------------------- ;; version := "MIME-Version" ":" 1*DIGIT "." 1*DIGIT (defrule mime-version? (v) (:sci "mime-version:") (:lwsp?) (:version? v) (:return v)) ;;;----------------------------------------------------------------------------- ;;; 5. Content-Type Header Field ;;;----------------------------------------------------------------------------- (defrule rfc2045-content-type? (content-type) (:sci "content-type:") (:lwsp?) (:http-content-type? content-type) (:return content-type)) ;;;----------------------------------------------------------------------------- ;;; 6. Content-Transfer-Encoding Header Field ;;;----------------------------------------------------------------------------- ;; encoding := "Content-Transfer-Encoding" ":" mechanism ;; mechanism := "7bit" / "8bit" / "binary" / "quoted-printable" / "base64" / ;; ietf-token / x-token (defrule rfc2045-content-transfer-encoding? () (:sci "content-transfer-encoding:") (:lwsp?) (:or (:and (:sci "7bit") (:return '7bit)) (:and (:sci "8bit") (:return '8bit)) (:and (:sci "binary") (:return 'binary)) (:and (:sci "quoted-printable") (:return 'quoted-printable)) (:and (:sci "base64") (:return 'base64)))) ;;;----------------------------------------------------------------------------- ;;; 7. Content-ID Header Field ;;;----------------------------------------------------------------------------- ;; id := "Content-ID" ":" msg-id ;; fixme: implement msg-id (defrule rfc2045-content-id? (c (acc (make-accumulator :byte))) (:sci "content-id:") (:lwsp?) (:type http-header-value? c) (:collect c acc) (:zom (:type http-header-value? c) (:collect c acc)) (:return acc)) ;;;----------------------------------------------------------------------------- ;;; 8. Content-Description Header Field ;;;----------------------------------------------------------------------------- ;;; description := "Content-Description" ":" *text (defrule rfc2045-content-description? (c (acc (make-accumulator :byte))) (:sci "content-description:") (:lwsp?) (:type http-header-value? c) (:collect c acc) (:zom (:type http-header-value? c) (:collect c acc)) (:return acc)) ;;;----------------------------------------------------------------------------- ;;; 9. Additional Header Fields ;;;----------------------------------------------------------------------------- ;; MIME-extension-field := <Any RFC 822 header field which begins ;; with the string "Content-"> ;; fixme: implement extenstion fields.
13,569
Common Lisp
.lisp
312
40.413462
305
0.552233
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
045ffc7c2da171be47c32c64eb58976350b0bf3a580e6f7ec7819013f0083aa8
8,319
[ -1 ]
8,320
2046.lisp
evrim_core-server/src/rfc/2046.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;;-------------------------------------------------------------------------- ;;; RFC 2046 - Multipurpose Internet Mail Extensions (MIME) ;;; Part Two: Media Types ;;;-------------------------------------------------------------------------- (defclass mime () ((headers :accessor mime.headers :initarg :headers :initform nil))) (defmethod mime.header ((mime mime) name-or-symbol) (cdr (assoc (if (stringp name-or-symbol) (intern (string-upcase name-or-symbol)) name-or-symbol) (mime.headers mime) :test #'string= :key #'(lambda (k) (if (symbolp k) k (string-upcase k)))))) (defmethod (setf mime.header) (value (mime mime) name-or-symbol) (if (mime.header mime name-or-symbol) (setf (cdr (assoc (if (stringp name-or-symbol) (intern (string-upcase name-or-symbol)) name-or-symbol) (mime.headers mime) :test #'string= :key #'(lambda (k) (if (symbolp k) k (string-upcase k))))) value) (setf (mime.headers mime) (cons (cons name-or-symbol value) (mime.headers mime)))) value) (defmethod mime.filename ((mime mime)) (cdr (assoc 'filename (car (reverse (assoc 'disposition (mime.headers mime) :test #'string-equal))) :test #'string-equal))) (defmethod mime.name ((mime mime)) (cdr (assoc 'name (car (reverse (assoc 'disposition (mime.headers mime) :test #'string-equal))) :test #'string-equal))) (defmethod mime.content-type ((mime mime)) (mime.header mime 'content-type)) (defmethod mime.serialize ((mime mime) path) (let ((stream (make-core-file-output-stream path))) (write-stream stream (mime.data mime)) (close-stream stream) path)) (defclass top-level-media (mime) ((data :accessor mime.data :initarg :data :initform nil))) (defmethod mime.children ((mime top-level-media)) nil) (defun make-top-level-media (headers data) (make-instance 'top-level-media :headers headers :data data)) (defclass composite-level-media (mime) ((children :accessor mime.children :initarg :children :initform nil))) (defun make-composite-level-media (headers children) (make-instance 'composite-level-media :headers headers :children children)) (defun mime-search (root-mime-or-mimes goal-p &key (succ #'mime.children)) (core-search (if (listp root-mime-or-mimes) root-mime-or-mimes (list root-mime-or-mimes)) goal-p succ #'(lambda (x y) (append y x)))) (defatom mime-boundary-char? () (and (or (visible-char? c) (space? c)) (not (eq c #.(char-code #\-))))) (defvar +mime-boundary+ nil) (defrule mime-boundary? (c (boundary (make-accumulator)) last) (:zom (:or (:checkpoint #\- #\- (:if +mime-boundary+ (:and (:seq +mime-boundary+) (:do (setq boundary +mime-boundary+))) (:and (:zom #\- (:collect #\- boundary)) (:type mime-boundary-char? c) (:collect c boundary) (:zom (:type mime-boundary-char? c) (:collect c boundary)))) (:zom #\- (:do (setq last t))) (:if (> (length boundary) 0) (:return (values boundary last)) (:commit))) (:and (:type octet?))))) (defrule mime-headers? ((headers '()) stub c (key (make-accumulator)) (value (make-accumulator))) (:zom (:or (:and (:rfc2045-content-type? stub) (:do (push (cons 'content-type stub) headers))) (:and (:rfc2045-content-transfer-encoding? stub) (:do (push (cons 'transfer-encoding stub) headers))) (:and (:rfc2045-content-id? stub) (:do (push (cons 'id stub) headers))) (:and (:rfc2045-content-description? stub) (:do (push (cons 'description stub) headers))) (:checkpoint (:sci "content-") (:zom (:not #\:) (:type visible-char? c) (:collect c key)) (:lwsp?) (:zom (:type (or visible-char? space?) c) (:collect c value)) (:do (push (cons (string-downcase key) value) headers) (setq key (make-accumulator) value (make-accumulator))) (:commit))) (:crlf?)) (:crlf?) (:return headers)) (defrule mime-binary-data? (c (acc (make-accumulator :byte))) (:if (null +mime-boundary+) (:return nil)) ;; must have some binary to match to end (:zom (:or (:checkpoint (:crlf?) #\- #\- (:seq +mime-boundary+) (:rewind-return acc)) (:and (:type octet? c) (:collect c acc))))) (defun mime? (stream &aux data headers) (checkpoint-stream stream) (setq headers (mime-headers? stream)) (cond ((and (string= "multipart" (cadr (assoc 'content-type headers))) (or (string= "mixed" (caddr (assoc 'content-type headers))) (string= "alternative" (caddr (assoc 'content-type headers))))) (make-composite-level-media headers (mimes? stream (cdr (assoc "boundary" (cadddr (assoc 'content-type headers :test #'string=)) :test #'string=))))) (t (case (cdr (assoc 'transfer-encoding headers)) (quoted-printable (setq data (quoted-printable? stream))) (base64 (setq data (base64? stream))) (t (setq data (mime-binary-data? stream)))) (if (and (null headers) (null data)) (progn (rewind-stream stream) nil) (prog1 (make-top-level-media headers data) (commit-stream stream)))))) (defun mimes? (stream &optional (boundary nil) &aux last mimes) (flet ((rew-ret (var) (when (not var) (rewind-stream stream) (return-from mimes? nil)))) (checkpoint-stream stream) (let ((+mime-boundary+ boundary)) (multiple-value-setq (boundary last) (mime-boundary? stream)) (rew-ret boundary) (rew-ret (not last)) (crlf? stream) (let ((+mime-boundary+ boundary) (last nil)) (do ((mime (mime? stream) (mime? stream))) (nil nil) (when (null mime) (rew-ret mimes) (commit-stream stream) (return-from mimes? (nreverse mimes))) (push mime mimes) (lwsp? stream) (multiple-value-setq (boundary last) (mime-boundary? stream)) (rew-ret boundary) (when last (commit-stream stream) (return-from mimes? (nreverse mimes))) (crlf? stream))) (rewind-stream stream) nil))) ;; tests are in rfc 2388. (deftrace mime-parsers '(mimes? mime? mime-binary-data? mime-headers? mime-boundary? mime-search))
6,961
Common Lisp
.lisp
167
36.868263
84
0.63909
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
071268295232852a5bfebfad120d33ac84f5f4c14c815715b89755f06ef2248b
8,320
[ -1 ]
8,321
2821.lisp
evrim_core-server/src/rfc/2821.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| RFC 2821 SMTP Protocol ;;+---------------------------------------------------------------------------- ;; ;; This file implements client side operations ;; ;; 4.1 SMTP Commands (defcommand smtp () ((code :host remote :accessor smtp.code :initarg :code :initform nil) (message :host local :accessor smtp.message :initarg :message :initform nil) (stream :host local :accessor smtp.stream :initarg :stream :initform nil))) ;; EHLO localhost ;; 250-node2.core.gen.tr ;; 250-PIPELINING ;; 250-SIZE 100000000 ;; 250-ETRN ;; 250-STARTTLS ;; 250-ENHANCEDSTATUSCODES ;; 250-8BIT ;; 250 DSN (defparser smtp-ehlo? (c (acc (make-accumulator)) params) (:lwsp?) (:zom (:seq "250-") (:lwsp?) (:zom (:not #\Newline) (:not #\Return) (:type octet? c) (:collect c acc)) (:lwsp?) (:do (push acc params) (setf acc (make-accumulator)))) (:seq "250 ") (:zom (:not #\Newline) (:not #\Return) (:type octet? c) (:collect c acc)) (:return (values 250 acc (nreverse params)))) (defrule smtp? (c temp (acc (make-accumulator))) (:lwsp?) (:fixnum? c) (:lwsp?) (:zom (:not #\Newline) (:not #\Return) (:type octet? temp) (:collect temp acc)) (:return (values c acc))) (defrender smtp! (message) (:string! message) (:char! #\Newline)) (defmethod run ((self smtp)) (if (smtp.message self) (smtp! (smtp.stream self) (smtp.message self))) (or (smtp-ehlo? (smtp.stream self)) (smtp? (smtp.stream self)))) ;; 4.1.1.1 Extended HELLO (EHLO) or HELLO (HELO) (defcommand smtp-ehlo (smtp) () (:default-initargs :message "EHLO localhost")) (defcommand smtp-quit (smtp) () (:default-initargs :message "QUIT")) (defcommand smtp-auth-plain (smtp) ((username :host local :initarg :username :initform nil) (password :host local :initarg :password :initform nil))) (defmethod run ((self smtp-auth-plain)) (when (and (s-v 'username) (s-v 'password)) (smtp! (s-v 'stream) (with-core-stream (s "") (string! s "AUTH PLAIN ") (base64! s (with-core-stream (s "") (write-stream s 0) (string! s (s-v 'username)) (write-stream s 0) (string! s (s-v 'password)) (return-stream s))) (return-stream s))) (smtp? (s-v 'stream)))) (defcommand smtp-auth-login (smtp-auth-plain) ()) (defmethod run ((self smtp-auth-login)) (when (and (s-v 'username) (s-v 'password)) (smtp! (s-v 'stream) "AUTH LOGIN") (let ((code (smtp? (s-v 'stream)))) (if (> code 400) (error "Remote mail server raises condition: ~D" code)) (smtp! (s-v 'stream) (with-core-stream (s "") (base64! s (with-core-stream (s "") (write-stream s 0) (string! s (s-v 'username)) (write-stream s 0) (string! s (s-v 'password)) (return-stream s))) (return-stream s))) (smtp? (s-v 'stream))))) (defcommand smtp-mail-from (smtp) ((email :host local :initarg :email)) (:default-initargs :message "MAIL FROM:")) (defmethod run ((self smtp-mail-from)) (when (s-v 'email) (smtp! (s-v 'stream) (format nil "~A<~A>" (smtp.message self) (s-v 'email))) (smtp? (s-v 'stream)))) (defcommand smtp-rcpt-to (smtp) ((email :host local :initarg :email)) (:default-initargs :message "RCPT TO:")) (defmethod run ((self smtp-rcpt-to)) (when (s-v 'email) (smtp! (s-v 'stream) (format nil "~A<~A>" (smtp.message self) (s-v 'email))) (smtp? (s-v 'stream)))) ;; This is the mail adt. (defclass envelope () ((from :accessor envelope.from :initarg :from :initform (error "from field required for envelope") :documentation "envelope from field") (display-name :accessor envelope.display-name :initarg :display-name :initform nil :documentation "Display name of the sender. Ex: john doe") (to :accessor envelope.to :initarg :to :initform (error "to field required for envelope") :documentation "Recipient of the mail") (cc :accessor envelope.cc :initarg :cc :initform nil :documentation "carbon copy goes to") (relpy-to :accessor envelope.reply-to :initarg :reply-to :initform nil :documentation "reply to address") (subject :accessor envelope.subject :initarg :subject :initform (error "subject field required for envelope") :documentation "mail subject") (text :accessor envelope.text :initarg :text :initform "" :documentation "mail body which is a string") (date :accessor envelope.date :initarg :date :initform (get-universal-time) :documentation "creation date of envelope") (message-id :accessor envelope.message-id :initarg :message-id :initform (random-string 32) :documentation "message-id") (extra-headers :accessor envelope.extra-headers :initarg :extra-headers :initform nil :documentation "extra headers for this envelope. List of string tuples."))) (defprint-object (self envelope :identity t :type t) (format t "~A->~A:~A" (slot-value self 'from) (slot-value self 'to) (slot-value self 'subject))) (defparser email? (c (username (make-accumulator)) (domain (make-accumulator))) (:oom (:type unreserved? c) (:collect c username)) #\@ (:oom (:type unreserved? c) (:collect c domain)) (:return (cons username domain))) (defmethod envelope! ((s core-stream) (e envelope)) (flet ((write-address (name address) (cond (name (let ((s (make-quoted-printable-stream s))) (string! s name) (close-stream s)) (string! s " <") (string! s address) (char! s #\>)) (t (string! s (envelope.from e)))))) (prog1 s (checkpoint-stream s) (when (envelope.date e) (string! s "Date: ") (http-date! s (envelope.date e)) (char! s #\Newline)) (string! s "From:") (write-address (envelope.display-name e) (envelope.from e)) (char! s #\Newline) (string! s "To:") (string! s (format nil "~{ ~a~^,~}" (ensure-list (envelope.to e)))) (char! s #\Newline) (when (envelope.cc e) (string! s "Cc:") (string! s (format nil "~{ ~a~^,~}" (ensure-list (envelope.cc e)))) (char! s #\Newline)) (when (envelope.reply-to e) (string! s "Reply-To: ") (string! s (envelope.reply-to e)) (char! s #\Newline)) (string! s "Subject:") (let ((s (make-quoted-printable-stream s))) (string! s (envelope.subject e)) (close-stream s)) (char! s #\Newline) (string! s "Message-Id: <") (string! s (envelope.message-id e)) (char! s #\@) (string! s (cdr (email? (make-core-stream (envelope.from e))))) (char! s #\>) (char! s #\Newline) (smtp! s (format nil "X-Mailer: ~A" +x-mailer+)) (let ((hdrs (envelope.extra-headers e))) (when (and hdrs (listp hdrs)) (dolist (h hdrs) (smtp! s (format nil "~A: ~A" (car h) (cdr h)))))) (smtp! s "MIME-Version: 1.0") (smtp! s "Content-Type: text/html; charset=UTF-8; format=flowed") (smtp! s "Content-Transfer-Encoding: 8bit") (char! s #\Newline) (cond ((typep (envelope.text e) 'xml) (write-stream (make-xml-stream s "html") (envelope.text e))) (t (string! s (envelope.text e)))) (char! s #\Newline) (commit-stream s)))) ;; SERVER> (let ((s (make-core-file-output-stream #P"/tmp/foo")) ;; (e (make-instance 'core-server::envelope ;; :to (list "[email protected]" ;; "[email protected]") ;; :from "[email protected]" ;; :subject "[Coretal.net] ĞÜLŞÖÇİIÜĞŞİÇÇ:ÖÖMÖIOIOIğülşölöşğü" ;; :text (<:div "text123") ;; :display-name "ĞÜŞİÇÖI"))) ;; (core-server::envelope! s e) ;; (close-stream s) ;; (read-string-from-file #P"/tmp/foo" :external-format :utf-8)) ;; "Date: Fri, 22 Aug 2011 22:14:23 GMT ;; From: =?UTF-8?Q?=C4=9E=C3=9C=C5=9E=C4=B0=C3=87=C3=96I?= <[email protected]> ;; To: [email protected], [email protected] ;; Subject: =?UTF-8?Q?[Coretal.net]=20=C4=9E=C3=9CL=C5=9E=C3=96=C3=87=C4=B0I=C3=9C=C4=9E?= ;; =?UTF-8?Q?=C5=9E=C4=B0=C3=87=C3=87:=C3=96=C3=96M=C3=96IOIOI=C4=9F=C3=BCl=C5?= ;; =?UTF-8?Q?=9F=C3=B6l=C3=B6=C5=9F=C4=9F=C3=BC?= ;; X-Mailer: [Core-serveR] (http://labs.core.gen.tr) ;; MIME-Version: 1.0 ;; Content-Type: text/html; charset=UTF-8; format=flowed ;; Content-Transfer-Encoding: 8bit ;; <div>text123</div> ;; " (defcommand smtp-send (smtp) ((envelope :host local :initarg :envelope)) (:default-initargs :message "DATA")) (defmethod run ((self smtp-send)) (with-accessors ((from envelope.from) (to envelope.to)) (s-v 'envelope) (smtp-mail-from :email from :stream (s-v 'stream)) (mapcar (lambda (rcpt) (smtp-rcpt-to :email rcpt :stream (s-v 'stream))) (ensure-list to)) (smtp! (s-v 'stream) "DATA") (envelope! (s-v 'stream) (s-v 'envelope)) (smtp! (s-v 'stream) ".") (smtp? (s-v 'stream)))) (deftrace smtp '(smtp! smtp? smtp-ehlo? smtp smtp-auth-plain smtp-auth-login smtp-rcpt-to smtp-mail-from smtp-send)) ;; 4.2.2 Reply Codes by Function Groups ;; 500 Syntax error, command unrecognized ;; (This may include errors such as command line too long) ;; 501 Syntax error in parameters or arguments ;; 502 Command not implemented (see section 4.2.4) ;; 503 Bad sequence of commands ;; 504 Command parameter not implemented ;; 211 System status, or system help reply ;; 214 Help message ;; (Information on how to use the receiver or the meaning of a ;; particular non-standard command; this reply is useful only ;; to the human user) ;; 220 <domain> Service ready ;; 221 <domain> Service closing transmission channel ;; 421 <domain> Service not available, closing transmission channel ;; (This may be a reply to any command if the service knows it ;; must shut down) ;; 250 Requested mail action okay, completed ;; 251 User not local; will forward to <forward-path> ;; (See section 3.4) ;; 252 Cannot VRFY user, but will accept message and attempt ;; delivery ;; (See section 3.5.3) ;; 450 Requested mail action not taken: mailbox unavailable ;; (e.g., mailbox busy) ;; 550 Requested action not taken: mailbox unavailable ;; (e.g., mailbox not found, no access, or command rejected ;; for policy reasons) ;; 451 Requested action aborted: error in processing ;; 551 User not local; please try <forward-path> ;; (See section 3.4) ;; 452 Requested action not taken: insufficient system storage ;; 552 Requested mail action aborted: exceeded storage allocation ;; 553 Requested action not taken: mailbox name not allowed ;; (e.g., mailbox syntax incorrect) ;; 354 Start mail input; end with <CRLF>.<CRLF> ;; 554 Transaction failed (Or, in the case of a connection-opening ;; response, "No SP service here") (defun test-smtp () (let ((s (connect "localhost" 25)) (en (make-instance 'envelope :from "[email protected]" :to "[email protected]" :display-name "zebedisplayname" :text "zoooo" :subject "keh keh al sana subject"))) (list (smtp? s) (smtp-ehlo :stream s) (smtp-send :envelope en :stream s) (smtp-quit :stream s))))
11,922
Common Lisp
.lisp
300
35.906667
90
0.64499
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8eca3347d6ecb28aa3f66930e7107ef89bf94289855812e00ed97c88c8d71841
8,321
[ -1 ]
8,322
prevalence.lisp
evrim_core-server/src/compat/prevalence.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :cl-prevalence) ;;+---------------------------------------------------------------------------- ;;| Cl-Prevalence Compat Functions ;;+---------------------------------------------------------------------------- ;; ;; This file overrides some properties of cl-prevalence database. (defun cl-prevalence::get-objects-slot-index-name (class &optional (slot 'id)) (core-server::any (lambda (class) (if (member slot (mapcar #'core-server::slot-definition-name (mopp::class-direct-slots class))) (intern (concatenate 'string (symbol-name (class-name class)) "-" (symbol-name slot) "-INDEX") :keyword))) (core-server::class-superclasses class))) (defun cl-prevalence::class-compile-timestamp (system class) (or (get-root-object system (intern (symbol-name (core-server::class+.name (core-server::find-class+ class))) :keyword)) 0)) (defsetf cl-prevalence::class-compile-timestamp (system class) (value) `(setf (get-root-object ,system (intern (symbol-name (core-server::class+.name (core-server::find-class+ ,class))) :keyword)) ,value)) (defun cl-prevalence::class-expired (system class) (let ((class+ (core-server::find-class+ class))) (when class+ (if (> (slot-value class+ 'core-server::%timestamp) (cl-prevalence::class-compile-timestamp system (core-server::class+.name class))) t)))) (defun cl-prevalence::create-object-slot-indexes (system class) (let ((class+ (core-server::find-class+ class))) (when (and class+ (cl-prevalence::class-expired system class+)) (mapcar (lambda (slot) (cl-prevalence::tx-create-objects-slot-index system class slot #'equalp)) (mapcar #'core-server::slot-definition-name (core-server::class+.indexes class+)))) (setf (cl-prevalence::class-compile-timestamp system class) (slot-value class+ 'core-server::%timestamp)))) (defun cl-prevalence::tx-create-object (system class &optional slots-and-values) "Create a new object of class in system, assigning it a unique id, optionally setting some slots and values" (cl-prevalence::create-object-slot-indexes system class) (let* ((id (next-id system)) (object (let ((object (allocate-instance (find-class class)))) (setf (slot-value object 'id) id) object)) (index-name (cl-prevalence::get-objects-slot-index-name class 'id)) (index (or (get-root-object system index-name) (setf (get-root-object system index-name) (make-hash-table))))) (push object (get-root-object system (cl-prevalence::get-objects-root-name class))) (setf (gethash id index) object) (tx-change-object-slots system class id slots-and-values) (initialize-instance object) object)) (defun cl-prevalence::tx-delete-object (system class id) "Delete the object of class with id from the system" (let ((object (find-object-with-id system class id))) (if object (let ((root-name (get-objects-root-name class)) (index-name (get-objects-slot-index-name class 'id))) (setf (get-root-object system root-name) (delete object (get-root-object system root-name))) (remhash id (get-root-object system index-name)) (mapcar (lambda (slot) (remhash (slot-value object slot) (get-root-object system (get-objects-slot-index-name class slot)))) (mapcar #'core-server::slot-definition-name (core-server::class+.indexes (core-server::find-class+ class))))) (error "no object of class ~a with id ~d found in ~s" class id system))))
4,273
Common Lisp
.lisp
84
46.619048
110
0.680948
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
0d799ea8266a928da2dbbf42183c004cb772c335940c7ec9607a32d28f2a526a
8,322
[ -1 ]
8,323
sockets.lisp
evrim_core-server/src/compat/sockets.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| BSD Sockets Compatibilty Functions ;;+---------------------------------------------------------------------------- ;; ;; This file contains compat layer for BSD Sockets (defun resolve-hostname (name) "Resolves the host 'name' by using gethostbyname(3)" (cond ((typep name '(vector * 4)) name) (t (car (host-ent-addresses (get-host-by-name name)))))) (defun make-server (&key (host (vector 0 0 0 0)) (port 0) (reuse-address t) (backlog 1) (protocol :tcp)) "Returns a SERVER object and the port that was bound, as multiple values" (let ((socket (make-instance 'inet-socket :type :stream :protocol protocol))) (when reuse-address (setf (sockopt-reuse-address socket) t)) (socket-bind socket (resolve-hostname host) port) (socket-listen socket backlog) (apply #'values socket (multiple-value-list (socket-name socket))))) (defun close-server (server) "Closes a server socket created by make-server" (socket-close server)) (defun accept (socket &key (element-type '(unsigned-byte 8))) "Returns a new client core-stream that is just connected to 'socket'" (multiple-value-bind (s peer) (socket-accept socket) (values (make-instance 'core-fd-io-stream :stream (socket-make-stream s :input t :output t ;; :element-type ;; element-type ;; 'character :element-type element-type :buffering :full)) peer))) (defun connect (server-host server-port &key (element-type '(unsigned-byte 8)) (protocol :tcp) (external-format :utf-8)) "Connects to the specified 'server-host' 'server-port' and returns a new core-stream" (let ((socket (make-instance 'inet-socket :type :stream :protocol protocol))) (socket-connect socket (resolve-hostname server-host) server-port) (make-core-stream (socket-make-stream socket :input t :output t :element-type element-type :buffering :full :external-format :utf-8)))) (defun nio-make-server (&key (host "0.0.0.0") (port 0) (reuse-address t) (backlog 10) (protocol :tcp)) (core-ffi::bind host port protocol backlog reuse-address)) (defun nio-close-server (server) (core-ffi::%close server)) (defun nio-accept (socket &key (element-type '(unsigned-byte 8))) (core-ffi::accept socket))
3,151
Common Lisp
.lisp
65
44.415385
79
0.671875
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
765bda796dfbc047b602aaf95c0d744098b3ed79ce260db211cc2ef9aee1f301
8,323
[ -1 ]
8,324
threads.lisp
evrim_core-server/src/compat/threads.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;;+---------------------------------------------------------------------------- ;;| POSIX Threads Compatiblity Functions ;;+---------------------------------------------------------------------------- ;; ;; This file contains compat layer for POSIX Threads (declaim (type hash-table *thread-mailboxes*)) (defvar *thread-mailbox-lock* (make-lock "Thread Mailbox Lock") "Lock for manipulating *thread-mailboxes*") (defvar *thread-mailboxes* (make-hash-table :test #'eq :weakness :value) "A global place to store thread mailboxes") (defstruct (thread-mailbox (:conc-name mailbox.)) thread (lock (make-lock "A Thread Mailbox Lock")) (waitqueue (make-condition-variable)) (queue '() :type list)) ;; TODO: not portable (defun thread-alive-p (thread) "Return t if 'thread' is alive and running" (sb-thread:thread-alive-p thread)) ;; TODO: not portable (defun find-thread-mailbox (thread) "Return the mailbox for the 'thread'" (gethash (sb-thread::thread-os-thread thread) *thread-mailboxes*)) ;; TODO: not portable (defun thread-mailbox (thread) "Return thread's mailbox, creates if none exists" (with-lock-held (*thread-mailbox-lock*) (or (find-thread-mailbox thread) (setf (gethash (sb-thread::thread-os-thread thread) *thread-mailboxes*) (make-thread-mailbox :thread thread))))) (defun thread-send (thread message) "Send message to a 'thread'" (let* ((mbox (thread-mailbox thread)) (lock (mailbox.lock mbox))) (with-lock-held (lock) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (condition-notify (mailbox.waitqueue mbox))))) (defun thread-receive (&optional (thread (current-thread)) (non-block nil)) "Waits until a message pops from the thread queue" (let* ((mbox (thread-mailbox thread)) (lock (mailbox.lock mbox))) (with-lock-held (lock) (loop (let ((q (mailbox.queue mbox))) (cond (q (return (pop (mailbox.queue mbox)))) (non-block (return nil)) (t (condition-wait (mailbox.waitqueue mbox) lock)))))))) ;; TODO: not portable (defun cleanup-mailbox (&optional (thread (current-thread))) "Cleanup a threads mailbox. By default it cleans up current-thread's mailbox" (with-lock-held (*thread-mailbox-lock*) (remhash (sb-thread::thread-os-thread thread) *thread-mailboxes*))) (defun thread-spawn (fn &key name) "Make a new thread with the given function and name. Returns a thread." (make-thread #'(lambda () (unwind-protect (funcall (the function fn)) (cleanup-mailbox))) :name name)) (defun thread-kill (thread) "Destroy thread and cleanup it's mailbox" (destroy-thread thread) (cleanup-mailbox thread)) ;; TODO: What to do with below? -evrim ;; (defmethod make-condition-variable () ;; (sb-thread:make-waitqueue)) ;; (defmethod condition-wait ((condition-variable sb-thread:waitqueue) ;; (lock sb-thread:mutex)) ;; (sb-thread:condition-wait condition-variable lock)) ;; (defmethod condition-notify ((condition-variable sb-thread:waitqueue)) ;; (sb-thread:condition-notify condition-variable)) ;; (defmethod thread-yield () ;; (sb-thread:release-foreground)) ;; TODO: not portable ;; (defmethod threadp ((thread t)) ;; nil) ;; (defmethod threadp ((object sb-thread:thread)) ;; t) ;; (defun current-thread () ;; (swank::current-thread)) ;; (defmethod make-thread (function &key name) ;; (swank::spawn function :name name)) ;; (defmethod destroy-thread ((thread sb-thread:thread)) ;; (sb-thread:terminate-thread thread)) ;; (defmacro with-lock-held ((lock) &body body) ;; `(swank::call-with-lock-held ,lock ;; (lambda () ;; ,@body)))
4,432
Common Lisp
.lisp
103
40.436893
79
0.689463
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
b54b743e534404688d41710dd16ba627fe0d9e36441b319e796a99bf7fa6f101
8,324
[ -1 ]
8,325
hxpath.lisp
evrim_core-server/src/commands/hxpath.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) (defparameter +hxpath+ (merge-pathnames #P"bin/HXPath" (bootstrap:home))) (defrule hxpath? (expr c (acc (core-server::make-accumulator))) (:checkpoint (:seq "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") (:commit)) (:lwsp?) (:seq "<xpath-result") (:lwsp?) (:zom (:not #\>) (:or (:and (:seq "/>") (:return nil)) (:and (:seq "expr=") (:quoted? expr) (:lwsp?)) (:and (:seq "source=") (:quoted? expr) (:lwsp?)))) (:lwsp?) (:zom (:or (:and (:seq "</xpath-result>") (:return acc)) (:and (:type octet? c) (:collect c acc)))) (:return nil)) ;; core@node5 ~/core-server/bin $ ./HXPath --help ;; HXPath - XPath Evaluator of the Haskell XML Toolbox (Arrow Version) ;; Usage: HXPath [OPTION...] <XPath expr> <URL or FILE> ;; -v --verbose verbose output ;; -h, -? --help this message ;; -t[LEVEL] --trace[=LEVEL] trace level (0-4), default 1 ;; -p PROXY --proxy=PROXY proxy for http access (e.g. "www-cache:3128") ;; --use-curl HTTP access via external program "curl", more functionality, supports HTTP/1.0, less efficient ;; --do-not-use-curl HTTP access via built in HTTP/1.1 module (default) ;; --options-curl=STR additional curl options, e.g. for timeout, ... ;; --default-base-URI=URI default base URI, default: "file:///<cwd>/" ;; -e CHARSET --encoding=CHARSET default document encoding (UTF-8, ISO-8859-1, US-ASCII, ...) ;; --issue-errors issue all errorr messages on stderr (default) ;; --do-not-issue-errors ignore all error messages ;; -H --parse-html parse input as HTML, try to interprete everything as HTML, no validation ;; --issue-warnings issue warnings, when parsing HTML (default) ;; -Q --do-not-issue-warnings ignore warnings, when parsing HTML ;; --parse-xml parse input as XML (default) ;; --validate document validation when parsing XML (default) ;; -w --do-not-validate only wellformed check, no validation ;; --canonicalize canonicalize document, remove DTD, comment, transform CDATA, CharRef's, ... (default) ;; -c --do-not-canonicalize do not canonicalize document, don't remove DTD, comment, don't transform CDATA, CharRef's, ... ;; -C --preserve-comment don't remove comments during canonicalisation ;; --do-not-preserve-comment remove comments during canonicalisation (default) ;; -n --check-namespaces tag tree with namespace information and check namespaces ;; --do-not-check-namespaces ignore namespaces (default) ;; -r --remove-whitespace remove redundant whitespace, simplifies tree and processing ;; --do-not-remove-whitespace don't remove redundant whitespace (default) ;; -i --indent indent XML output for readability ;; -o CHARSET --output-encoding=CHARSET encoding of output (UTF-8, ISO-8859-1, US-ASCII) ;; -f FILE --output-file=FILE output file for resulting document (default: stdout) ;; --output-html output of none ASCII chars as HTMl entity references ;; --no-xml-pi output without <?xml ...?> processing instruction, useful in combination with --"output-html" ;; ;; EXAMPLE: ./HXPath -Hw "//div[@id='content']/" /tmp/zeben.html ;; (defcommand hxpath (shell) ((xquery :host local :initform (error "Specify query") ) (uri :host local :initform (error "specify uri"))) (:default-initargs :cmd +hxpath+ :args '( "--use-curl" "--output-html" "--no-xml-pi" "-Hw" "--indent") :verbose nil)) (defmethod render-arguments ((self hxpath)) (append (args self) (list (s-v 'xquery) (s-v 'uri)))) (defmethod run ((self hxpath)) (handler-bind ((error #'(lambda (condition) (declare (ignore condition)) (return-from run nil)))) (call-next-method)) (hxpath? (make-core-stream (command.output-stream self)))) (defparameter +xmltr+ (merge-pathnames #P"bin/xmltr" (pathname (sb-posix:getenv "CORESERVER_HOME")))) ;; core@node5 ~/core-server/bin $ echo "hobaaa" |./xmltr content /tmp/ge.html /tmp/zeben.html (defcommand xmltr (shell) ((id :host local) (in :host local) (out :host local) (text :host local)) (:default-initargs :cmd +xmltr+ :verbose nil :wait nil)) (defmethod render-arguments ((self xmltr)) (append (args self) (list (s-v 'id) (s-v 'in) (s-v 'out)))) (defmethod run ((self xmltr)) (call-next-method) (format (command.input-stream self) "~A" (s-v 'text)) (close (command.input-stream self)) ;; (let ((cs (core-server::make-core-stream (command.input-stream self)))) ;; (core-server::string! cs (text self)) ;; (core-server::close-stream cs)) (wait-process self))
5,882
Common Lisp
.lisp
104
54.019231
139
0.616079
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
7356af4b305c776cd5fae31dac02a62514f961d6e7c175882228ac8cf9dcf768
8,325
[ -1 ]
8,326
image.lisp
evrim_core-server/src/commands/image.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) (defcommand thumbnail (shell) ((option :initform "-thumbnail" :host local) (width :initform "150" :host local) (height :initform "150" :host local) (source :initform (error "Please supply source pathname") :host local) (target :initform (error "Please supply target pathname") :host local)) (:default-initargs :cmd (whereis "convert"))) (defmethod run ((self thumbnail)) (setf (args self) (list (thumbnail.option self) (format nil "~Dx~D>" (thumbnail.width self) (thumbnail.height self)) (thumbnail.source self) (thumbnail.target self))) (call-next-method))
1,369
Common Lisp
.lisp
27
47.925926
75
0.737275
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8988a424a17d40b9a65904e4602cf0360c12016c995ae35f51eeae46a67f69c0
8,326
[ -1 ]
8,327
scm.lisp
evrim_core-server/src/commands/scm.lisp
(in-package :core-server) ;; +---------------------------------------------------------------------------- ;; | SCM Commands ;; +---------------------------------------------------------------------------- ;; ---------------------------------------------------------------------------- ;; CVS ;; ---------------------------------------------------------------------------- (defcommand cvs (shell) ((op :host local :initform "co") (repo-type :host local :initform "pserver") (username :host local :initform "anonymous") (password :host local :initform "anonymous") (repo :host local :initform (error "repo can't be nil")) (module :host local) (target :host local :initform (error "target can't be nil"))) (:default-initargs :cmd (whereis "cvs"))) (defmethod render-arguments ((self cvs)) (list (format nil "-d:~A:~A:~A@~A" (cvs.repo-type self) (cvs.username self) (cvs.password self) (cvs.repo self)) (cvs.op self) "-d" (cvs.target self) (cvs.module self))) ;; ---------------------------------------------------------------------------- ;; Darcs ;; ---------------------------------------------------------------------------- (defcommand darcs (shell) ((op :host local :initform "get") (repo :host local :initform nil) (target :host local :initform nil) (lazy :host local :initform t)) (:default-initargs :cmd (whereis "darcs"))) (defmethod render-arguments ((self darcs)) (cons (darcs.op self) (cond ((equal (darcs.op self) "get") (if (or (null (darcs.repo self)) (null (darcs.target self))) (error "Please specify repo/target.")) (if (s-v 'lazy) (list "--lazy" (darcs.repo self) (darcs.target self)) (list (darcs.repo self) (darcs.target self)))) ((equal (darcs.op self) "unpull") nil)))) ;; ---------------------------------------------------------------------------- ;; Git ;; ---------------------------------------------------------------------------- (defcommand git (shell) ((op :host local :initform "clone") (repo :host local :initform nil) (target :host local :initform nil)) (:default-initargs :cmd (whereis "git"))) (defmethod render-arguments ((self git)) (cons (git.op self) (cond ((equal (git.op self) "clone") (if (or (null (git.repo self)) (null (git.target self))) (error "Please specify repo/target.")) (list (git.repo self) (git.target self))) (t (error "Not implemented."))))) ;; ---------------------------------------------------------------------------- ;; SVN ;; ---------------------------------------------------------------------------- (defcommand svn (shell) ((op :host local :initform "co") (repo :host local :initform (error "repo can't be nil")) (target :host local :initform (error "target can't be nil"))) (:default-initargs :cmd (whereis "svn"))) (defmethod render-arguments ((self svn)) (list (svn.op self) (svn.repo self) (svn.target self))) ;; ---------------------------------------------------------------------------- ;; Tarball ;; ---------------------------------------------------------------------------- (defcommand tarball (shell) ((repo :host local :initform (error "repo can't be nil")) (temp-fname :host none :initform (make-pathname :name (tmpnam nil))) (target :host local :initform (error "target can't be nil")) (sandbox :host none :initform nil)) (:default-initargs :cmd (whereis "tar") :wait t)) (defmethod render-arguments ((self tarball)) (cond ((search ".gz" (s-v 'repo)) (list "zxvf" (s-v 'temp-fname))) ((search ".bz2" (s-v 'repo)) (list "jxvf" (s-v 'temp-fname))))) (defmethod run ((self tarball)) (wget :source (s-v 'repo) :target (s-v 'temp-fname)) (let ((sandbox-path (make-pathname :directory (tmpnam nil)))) (ensure-directories-exist sandbox-path) (setf (tarball.sandbox self) sandbox-path) (with-current-directory sandbox-path (call-next-method)))) (defmethod run :after ((self tarball)) (let ((package-directory (car (directory (make-pathname :name :wild :type :wild :defaults (s-v 'sandbox)))))) (if package-directory ;; STUPID Debian and gnuutils this one should be simply: ;; (shell :cmd +mv+ :args (list package-directory (target self))) (shell :cmd +mv+ :args (list package-directory (subseq (format nil "~A" (tarball.target self)) 0 (1- (length (namestring (tarball.target self))))))) (error "package tarball is bogus.")) (when (tarball.temp-fname self) (delete-file (namestring (tarball.temp-fname self))))))
4,547
Common Lisp
.lisp
101
41.445545
80
0.516013
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
40743c5cf6d40da3659f4d10cc89ce74cce95b74e6bde6ddd6b0a29405450ad7
8,327
[ -1 ]
8,328
admin.lisp
evrim_core-server/src/commands/admin.lisp
(in-package :core-server) ;; ---------------------------------------------------------------------------- ;; User Add ;; ---------------------------------------------------------------------------- (defcommand useradd (shell) ((username :host local :initform (error "Username must be provided.")) (group :host local :initform nil) (extra-groups :host local :initform '()) (home-directory :host local :initform nil) (user-group :host local :initform nil) (create-home :host local :initform nil) (comment :host local :initform nil)) (:default-initargs :cmd #P"/usr/sbin/useradd")) (defmethod render-arguments ((self useradd)) (cons (s-v 'username) (reduce #'(lambda (acc item) (if (s-v (car item)) (cons (cadr item) acc) acc)) '((user-group "-n") (create-home "-m")) :initial-value (reduce #'(lambda (acc item) (if (s-v (car item)) (cons (cadr item) (if (listp (s-v (car item))) (cons (reduce #'(lambda (acc i) (format nil "~A,~A" acc i)) (s-v (car item))) acc) (cons (s-v (car item)) acc))) acc)) '((group "-g") (extra-groups "-G") (home-directory "-d") (comment "-c")) :initial-value nil)))) ;; ---------------------------------------------------------------------------- ;; Group Add ;; ---------------------------------------------------------------------------- (defcommand groupadd (shell) ((groupname :host local :initform (error "Group name must be provided."))) (:default-initargs :cmd #P"/usr/bin/groupadd" :errorp nil)) (defmethod render-arguments ((self groupadd)) (list (s-v 'groupname)))
1,643
Common Lisp
.lisp
42
34.714286
79
0.49593
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e0f205e379cb1715a6f0f08faab60dc4a98c9f1f54b87b817886b0e0120fafaf
8,328
[ -1 ]
8,329
persistent.lisp
evrim_core-server/src/applications/persistent.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Persistent Application ;; ------------------------------------------------------------------------- (defclass+ persistent-application (application) ((start-stop-state :host local :export nil))) (defmethod start ((self persistent-application)) (setf (slot-value self 'start-stop-state) t)) (defmethod stop ((self persistent-application)) (setf (slot-value self 'start-stop-state) nil))
500
Common Lisp
.lisp
10
48.1
76
0.523614
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
137446d2a382f9913a6036b46558d1b370bf31400e9ce1820445ae1c6abb35e3
8,329
[ -1 ]
8,330
http.lisp
evrim_core-server/src/applications/http.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;; +------------------------------------------------------------------------- ;; | Http Application ;; +------------------------------------------------------------------------- ;; -------------------------------------------------------------------------- ;; HTTP Constants ;; -------------------------------------------------------------------------- (defvar +continuation-query-name+ "k" "Query key for continuations") (defvar +session-query-name+ "s" "Query key for sessions") (defvar +session-timeout+ (* 12 3600) "Session timeout in milisecons, half day") (defvar +invalid-session+ "invalid-session-id") (defvar +invalid-continuation-id "invalid-continuation-id") ;; -------------------------------------------------------------------------- ;; HTTP Special Variables ;; -------------------------------------------------------------------------- (defvar +context+ nil "A special variable that holds HTTP context") (defvar +k+ nil "A special variable that holds current continuation") ;; -------------------------------------------------------------------------- ;; HTTP Session ;; -------------------------------------------------------------------------- (defclass http-session () ((id :reader session.id :initarg :id :initform (random-string 8)) (application :reader session.application :initarg :application :initform (error "Please specify :application")) (continuations :reader session.continuations :initform (make-hash-table :test #'equal :synchronized t)) (timestamp :accessor session.timestamp :initform (get-universal-time)) (data :accessor session.data :initform (make-hash-table :test #'equal :synchronized t)))) (defprint-object (self http-session :identity t :type t) (format t "~A" (session.id self))) (defun make-new-session (application &optional (id (random-string 8))) "HTTP Session Constructor" (make-instance 'http-session :id id :application application)) (defmethod find-session-id ((request http-request)) "Returns session id string provided in request query or by cookie that has set before" (or (uri.query (http-request.uri request) +session-query-name+) (aif (http-request.cookie request +session-query-name+) (cookie.value it)))) (defmethod find-continuation ((session http-session) id) "Returns the continuation associated with 'id'" (aif (gethash id (session.continuations session)) (return-from find-continuation (values it session)))) (defmacro update-session (key val &optional (session `(context.session +context+))) "Update a session variable." `(setf (gethash ,key (session.data ,session)) ,val)) (defmacro query-session (key &optional (session `(context.session +context+))) "Query a session variable." `(gethash ,key (session.data ,session))) ;; -------------------------------------------------------------------------- ;; HTTP Context ;; -------------------------------------------------------------------------- (defclass http-context ();; (core-cps-stream) ((request :accessor context.request :initarg :request :initform nil) (response :accessor context.response :initarg :response :initform nil) (session :accessor context.session :initarg :session :initform nil) (application :accessor context.application :initarg :application :initform nil) (continuation :accessor context.continuation :initform nil :initarg :continuation) (returns :accessor context.returns :initform nil :initarg :returns))) (defun make-new-context (application request response session &optional continuation returns) "Returns a new HTTP context having parameters provided" (make-instance 'http-context :application application :request request :response response :session session ;; :input (http-request.stream request) ;; :output (http-response.stream response) :continuation continuation :returns returns)) (defmethod copy-context ((self http-context)) "Returns a copy of the HTTP context 'self'" (with-slots (application session continuation returns) self (make-new-context application nil nil session continuation returns))) (defmethod context.session ((self http-context)) "Returns the session of the HTTP context 'self', creates if none exists" (aif (slot-value self 'session) ;; Session exists, update access timestamp (prog1 it (setf (session.timestamp it) (get-universal-time))) ;; Insert this session to applications session table. (let ((new-session (make-new-session (context.application self))) (application (context.application self))) (setf (gethash (session.id new-session) (http-application.sessions application)) new-session (context.session self) new-session) new-session))) ;; FIXME: r these necessary? (defmethod context.remove-action ((self http-context) &optional k-url) (let ((k-url (or k-url (http-request.query (context.request self) +continuation-query-name+)))) (remhash k-url (session.continuations (context.session self))))) ;; -------------------------------------------------------------------------- ;; Method that deletes "Session ID" Cookie ;; -------------------------------------------------------------------------- (defmethod (setf context.session) :after ((session t) (self http-context)) (prog1 session (let* ((request (context.request self)) (cookie (if (http-request.relative-p request) (make-cookie +session-query-name+ "" :comment "Core Server Session Cookie" :path (concat "/" (web-application.fqdn (context.application self)) "/")) (make-cookie +session-query-name+ (session.id session) :comment "Core Server Session Cookie")))) (http-response.add-cookie (context.response self) cookie)))) ;; -------------------------------------------------------------------------- ;; Methods that add "Session" Cookie to Response ;; -------------------------------------------------------------------------- (defmethod (setf context.session) :after ((session http-session) (self http-context)) (prog1 session (let* ((request (context.request self)) (cookie (if (http-request.relative-p request) (make-cookie +session-query-name+ (session.id session) :comment "Core Server Session Cookie" :path (concat "/" (web-application.fqdn (context.application self)) "/")) (make-cookie +session-query-name+ (session.id session) :comment "Core Server Session Cookie")))) (http-response.add-cookie (context.response self) cookie)))) ;;+-------------------------------------------------------------------------- ;;| HTTP Application Metaclass ;;+-------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defclass http-application+ (class+) ((handlers :initarg :handlers :accessor http-application+.handlers :initform nil :documentation "A list that contains URLs that this application handles") (security-handlers :initarg :security-handlers :accessor http-application+.security-handlers :initform nil :documentation "A list of URLs that need to be authenticated.")) (:documentation "HTTP Application Metaclass")) (defmethod validate-superclass ((class http-application+) (super standard-class)) t) (defmethod validate-superclass ((class standard-class) (super http-application+)) nil) (defmethod http-application+.handlers ((self http-application+)) (uniq (copy-list (reduce #'append (mapcar (rcurry #'slot-value 'handlers) (filter (lambda (a) (if (typep a 'http-application+) a)) (class-superclasses self))))) :key #'car)) (defmethod find-handler ((self http-application+) method-name) (find method-name (http-application+.handlers self) :key #'car)) (defmethod add-handler ((application+ http-application+) method-name url) (setf (slot-value application+ 'handlers) (cons (list method-name url (cl-ppcre:create-scanner url)) (remove-handler application+ method-name)))) (defmethod remove-handler ((application+ http-application+) method-name) (setf (slot-value application+ 'handlers) (remove method-name (slot-value application+ 'handlers) :key #'car))) (defmethod http-application+.security-handlers ((self http-application+)) (uniq (nreverse (copy-list (reduce #'append (mapcar (rcurry #'slot-value 'security-handlers) (filter (lambda (a) (if (typep a 'http-application+) a)) (class-superclasses self)))))) :key #'car)) (defmethod find-security-handler ((self http-application+) method-name) (find method-name (http-application+.security-handlers self) :key #'car)) (defmethod add-security-handler ((application+ http-application+) (method-name symbol) (url string) (type symbol)) (assert (member type '(basic digest)) nil "Authentication type can be: basic or digest, not ~A" type) (setf (slot-value application+ 'security-handlers) (cons (list method-name url (cl-ppcre:create-scanner url) type) (remove-security-handler application+ method-name)))) (defmethod remove-security-handler ((application+ http-application+) method-name) (setf (slot-value application+ 'security-handlers) (remove method-name (slot-value application+ 'security-handlers) :key #'car))) (defmethod class+.ctor ((application+ http-application+)) nil)) ;;+-------------------------------------------------------------------------- ;;| HTTP Application ;;+-------------------------------------------------------------------------- (eval-when (:load-toplevel :compile-toplevel :execute) (defclass http-application (web-application) ((sessions :accessor http-application.sessions :initform (make-hash-table :test #'equal :synchronized t) :documentation "A hash-table that holds sessions") (default-handler :accessor http-application.default-handler :initform nil :initarg :default-handler :documentation "Symbol of the default handler.")) (:documentation "HTTP Application Class") (:metaclass http-application+))) (defmethod start ((self http-application)) (clrhash (slot-value self 'sessions))) (defmethod snapshot ((self http-application)) (clrhash (slot-value self 'sessions)) (call-next-method self)) (defmethod reset-sessions ((self http-application)) (clrhash (slot-value self 'sessions))) ;; -------------------------------------------------------------------------- ;; defapplication Macro: Adds http-application+ metaclass ;; -------------------------------------------------------------------------- (defmacro defapplication (name supers slots &rest rest) `(defclass+ ,name ,supers ,slots ,@rest (:metaclass http-application+))) ;; +------------------------------------------------------------------------- ;; | HTTP Application Interface ;; +------------------------------------------------------------------------- (defmethod find-session ((application http-application) id) "Returns the session associated with 'id'" (aif (gethash id (http-application.sessions application)) (values it application))) (defmethod map-session (lambda (application http-application)) (mapcar (lambda (k v) (funcall lambda k v)) (hash-table-keys (slot-value application 'sessions)) (hash-table-values (slot-value application 'sessions)))) (defmethod find-file-to-serve ((application http-application) (request http-request)) (let ((htdocs-path (web-application.htdocs-pathname application)) (paths (let ((tmp (or (uri.paths (http-request.uri request)) '((""))))) (if (equal (caar tmp) "") '(("index.html")) tmp)))) ;; HTDOCS Not found (if (or (null htdocs-path) (not (probe-file htdocs-path))) (return-from find-file-to-serve nil)) (let* ((file-and-ext (pathname (caar (last paths)))) (path (append '(:relative) (mapcar #'car (butlast paths)))) (abs-path (merge-pathnames (merge-pathnames (make-pathname :directory path) file-and-ext) htdocs-path))) ;; File Not Found or Directory Request, we do not serve it, yet. (if (or (not (probe-file abs-path)) (cl-fad:directory-exists-p abs-path)) nil abs-path)))) (defmethod gc ((self http-application)) "Garbage collector for HTTP application, removes expired sessions/continuations" (let* ((sessions (http-application.sessions self))) (mapc (rcurry #'remhash sessions) (let (expired) (maphash #'(lambda (k v) (when (> (- (get-universal-time) (session.timestamp v)) +session-timeout+) (push k expired))) sessions) expired)))) (defmacro defauth (url application-class &optional (method 'digest)) (let ((handler (intern (string-upcase url)))) `(eval-when (:compile-toplevel :load-toplevel :execute) (add-security-handler (find-class ',application-class) ',handler ,url ',method)))) ;; ------------------------------------------------------------------------- ;; Basic Authentication ;; ------------------------------------------------------------------------- (defmethod http-application.authorize ((application http-application) (request http-request) (method (eql 'basic)) (kontinue function)) (flet ((do-kontinue (username) (setf (http-request.authenticated-p request) t (http-request.authenticated-user request) username) (funcall kontinue application request)) (make-response () (let ((response (make-401-response))) (http-response.add-response-header response 'www-authenticate `(basic (("realm" . ,(web-application.realm application))))) response))) (let ((header (http-request.header request 'authorization))) (if (and header (eq (car header) 'basic)) (destructuring-bind (username password) (cdr header) (if (and username password (equal (web-application.password-of application username) password)) (do-kontinue username) (make-403-response))) (make-response))))) (defvar +nonce-key+ (random-string)) (defmethod http-application.authorize ((application http-application) (request http-request) (method (eql 'digest)) (kontinue function)) (let ((realm (web-application.realm application))) (labels ((get-nonce () (md5 (concat +nonce-key+ (princ-to-string (truncate (get-universal-time) 1000)) "000"))) (make-response (&optional (stale nil)) (let* ((response (make-401-response)) (opaque (random-string)) (nonce (get-nonce)) (attrs (list (cons "realm" realm) (cons "qop" "auth") (cons "nonce" nonce) (cons "opaque" opaque) (cons "stale" (if stale "true" "false"))))) (http-response.add-response-header response 'www-authenticate (cons 'digest attrs)) response)) (calc-auth-response (username uri nonce nc qop cnonce) (let ((password (web-application.password-of application username)) (method (symbol-name (http-request.method request)))) (let ((ha1 (md5 (concat username ":" realm ":" password))) (ha2 (md5 (concat method ":" uri)))) (md5 (concat ha1 ":" nonce ":" nc ":" cnonce ":" qop ":" ha2))))) (calc-response (username uri nonce) (let ((password (web-application.password-of application username)) (method (symbol-name (http-request.method request)))) (let ((ha1 (md5 (concat username ":" realm ":" password))) (ha2 (md5 (concat method ":" uri)))) (md5 (concat ha1 ":" nonce ":" ha2))))) (do-kontinue (username) (setf (http-request.authenticated-p request) t (http-request.authenticated-user request) username) (funcall kontinue application request))) (let ((header (http-request.header request 'authorization))) (if (and header (eq (car header) 'digest)) (let ((parameters (cdr header))) (flet ((get-param (name) (cdr (assoc name parameters :test #'equal)))) (let ((username (get-param "username")) (qop (get-param "qop")) (response (get-param "response")) (uri (get-param "uri")) (nonce (get-param "nonce")) (nc (get-param "nc")) (cnonce (get-param "cnonce"))) (cond ((not (equal nonce (get-nonce))) (make-response t)) ((equal qop "auth") (if (equal response (calc-auth-response username uri nonce nc qop cnonce)) (do-kontinue username) (make-403-response))) ;; Not supported. ((equal qop "auth-int") (make-403-response)) (t (if (equal response (calc-response username uri nonce)) (do-kontinue username) (make-403-response))))))) (make-response)))))) (defmethod dispatch :around ((application http-application) (request http-request)) (when (> (random 100) 40) (gc application)) (let ((handlers (http-application+.security-handlers (class-of application)))) (aif (any #'(lambda (handler) (destructuring-bind (method url scanner type) handler (declare (ignore url method)) (let ((uri (uri->string (make-uri :paths (uri.paths (http-request.uri request)))))) (if (cl-ppcre:scan-to-strings scanner uri) type)))) handlers) (http-application.authorize application request it #'call-next-method) (call-next-method application request)))) (defmethod dispatch ((self http-application) (request http-request)) "Dispatch 'request' to 'self' application with empty 'response'" (let ((session (gethash (find-session-id request) (http-application.sessions self))) (k-arg (uri.query (http-request.uri request) +continuation-query-name+))) (acond ((and session (gethash k-arg (session.continuations session))) (log-me (application.server self) 'http-application (format nil "fqdn: ~A, k-url: ~A" (web-application.fqdn self) (uri.query (http-request.uri request) +continuation-query-name+))) (let ((response (make-response))) (funcall it request response) response)) ((and session k-arg) (log-me (application.server self) 'http-application (format nil "fqdn: ~A, invalid k-url: ~A" (web-application.fqdn self) (http-request.uri request))) (make-404-response)) ((any #'(lambda (handler) (destructuring-bind (method url scanner) handler (declare (ignore url)) (aif (caar (uri.paths (http-request.uri request))) (let ((uri (uri->string (make-uri :paths (uri.paths (http-request.uri request)))))) (and (cl-ppcre:scan-to-strings scanner uri) method))))) (reverse (http-application+.handlers (class-of self)))) (log-me (application.server self) 'http-application (format nil "fqdn: ~A, static-handler:: ~A" (web-application.fqdn self) (http-request.uri request))) (let ((response (make-response))) (funcall it self (make-new-context self request response session)) response)) ((and (or (null (uri.paths (http-request.uri request))) (equal "" (caar (uri.paths (http-request.uri request))))) (http-application.default-handler self)) (let ((response (make-response))) (funcall it self (make-new-context self request response session)) response)) ((find-file-to-serve self request) (log-me (application.server self) 'http-application (format nil "fqdn: ~A, static-url: ~A, serving file:~A" (web-application.fqdn self) (http-request.uri request) it)) (let ((response (make-response))) (http-response.add-entity response it) response)) (t (make-404-response))))) ;; +------------------------------------------------------------------------- ;; | HTTP Macros ;; +------------------------------------------------------------------------- (defmacro with-query (queries request &body body) "Executes 'body' while binding 'queries' from 'request'" `(let ,(mapcar #'(lambda (p) `(,(car p) (or (uri.query (http-request.uri ,request) ,(cadr p)) ,(caddr p)))) queries) ,@body)) (defmacro with-context (context &body body) "Executes 'body' with HTTP context bind to 'context'" `(with-call/cc (let ((+context+ ,context)) (declare (special +context+)) ,@body))) (defmethod %scan-uri ((application http-application) (handler-name symbol) (context http-context)) (let* ((handler (find-handler (class-of application) handler-name)) (scanner (if handler (caddr handler))) (request (context.request context)) (uri (uri->string (make-uri :paths (uri.paths (http-request.uri request)))))) (if scanner (multiple-value-bind (ignore1 result) (scan-to-strings scanner uri) (declare (ignore ignore1)) (if result (ensure-list (reduce #'cons result))))))) ;; -------------------------------------------------------------------------- ;; defhandler Macro: Defines a static url handler ;; -------------------------------------------------------------------------- (defmacro defhandler (url ((application application-class) &rest queries) &body body) "Defines an entry point/url handler to the application-class" (let* ((url-arguments (if (listp url) (cdr url))) (url (if (listp url) (car url) url)) (handler-symbol (intern (string-upcase url)))) (assert (stringp url)) (with-unique-names (context) (setf context (intern (symbol-name context))) `(progn (eval-when (:load-toplevel :compile-toplevel :execute) (add-handler (find-class ',application-class) ',handler-symbol ,url)) (defmethod ,handler-symbol ((,application ,application-class) (,context http-context)) (with-context ,context (with-html-output (http-response.stream (context.response +context+)) (with-query ,queries (context.request +context+) ,(if url-arguments (with-unique-names (result) `(let ((,result (%scan-uri ,application ',handler-symbol +context+))) (destructuring-bind ,url-arguments ,result ,@body))) `(progn ,@body)))))))))) (defmacro defhandler/js (url ((application application-class) &rest queries) &body body) `(defhandler ,url ((,application ,application-class) ,@queries) (javascript/suspend (lambda (stream) (let ,(mapcar (lambda (a) `(,a (json-deserialize ,a))) (mapcar #'car queries)) (with-js ,(mapcar #'car queries) stream ,@body) nil))))) (defmacro defurl (application regexp-url queries &body body) "Backward compat macro" (let ((class-name (class-name (class-of (symbol-value application))))) `(defhandler ,regexp-url ((application ,class-name) (context http-context) ,@queries) ,@body))) ;; +------------------------------------------------------------------------- ;; | CPS Style Web Framework ;; +------------------------------------------------------------------------- (defun escape (&rest values) (funcall (apply (arnesi::toplevel-k) values)) (break "You should not see this, call/cc must be escaped already.")) (defmacro send/suspend (&body body) "Saves current continuation, executes 'body', terminates." (with-unique-names (result) `(let ((,result (multiple-value-list (let/cc k (setf (context.continuation +context+) k) (with-html-output (http-response.stream (context.response +context+)) ,@body) (setf (context.response +context+) nil (context.request +context+) nil) (escape (reverse (context.returns +context+))) (break "send/suspend failed."))))) (setf (context.request +context+) (context.request (car ,result)) (context.response +context+) (context.response (car ,result))) (apply #'values (cdr ,result))))) (defmacro send/forward (&body body) (with-unique-names (result) `(progn (clrhash (session.continuations (context.session +context+))) (let ((,result (multiple-value-list (send/suspend ,@body)))) (send/suspend (setf (http-response.status-code (context.response +context+)) '(301 . "Moved Permanently")) (http-response.add-response-header (context.response +context+) 'location (action/url () (answer (apply #'values ,result))))))))) (defun/cc send/redirect (url) (let ((response (context.response +context+))) (setf (http-response.status-code response) '(302 . "Found")) (http-response.add-response-header response 'location url) nil)) (defmacro send/finish (&body body) `(with-html-output (http-response.stream (context.response +context+)) (clrhash (session.continuations (context.session +context+))) ,@body)) (defvar +action-hash-override+ nil) (defmacro action/hash (parameters &body body) "Registers a continuation at run time and binds 'parameters' while executing 'body'" (with-unique-names (name context) `(if +context+ (let* ((,name (or +action-hash-override+ (format nil "act-~A" (make-unique-random-string 8)))) (,context (copy-context +context+)) (kont (lambda (req rep &optional ,@(mapcar #'car parameters)) (assert (and (not (null req)) (not (null rep)))) (let ((+context+ ,context)) (setf (context.request +context+) req (context.response +context+) rep) (with-query ,(mapcar (lambda (param) (reverse (cons (car param) (reverse param)))) parameters) (context.request +context+) (with-html-output (http-response.stream (context.response +context+)) ,@body)))))) (prog1 ,name (setf (gethash ,name (session.continuations (context.session +context+))) kont) (setf (context.returns +context+) (cons (cons ,name (lambda ,(mapcar #'car parameters) (funcall kont (make-instance 'http-request :uri (make-instance 'uri)) (make-response *core-output*) ,@(mapcar #'car parameters)))) (remove-if #'(lambda (x) (equal x ,name)) (context.returns ,context) :key #'car))))) "invalid-function-hash"))) (defmacro function/hash (parameters &body body) "Registers a continuation at macro-expansion time and binds 'parameters' while executing 'body'" (with-unique-names (context) (let ((name (format nil "fun-~A" (make-unique-random-string 3)))) `(if +context+ (let* ((,context (copy-context +context+)) (kont (let ((+context+ ,context)) (lambda (req rep &optional ,@(mapcar #'car parameters)) (setf (context.request +context+) req (context.response +context+) rep) (with-query ,(mapcar (lambda (param) (reverse (cons (car param) (reverse param)))) parameters) (context.request +context+) (with-html-output (http-response.stream (context.response +context+)) ,@body)))))) (prog1 ,name (setf (gethash ,name (session.continuations (context.session ,context))) kont) (setf (context.returns ,context) (cons (cons ,name (lambda ,(mapcar #'car parameters) (funcall kont (make-instance 'http-request :uri (make-instance 'uri)) (make-response *core-output*) ,@(mapcar #'car parameters)))) (remove-if #'(lambda (x) (equal x ,name)) (context.returns ,context) :key #'car))))) "invalid-action-hash")))) (defmacro function/url (parameters &body body) "Returns URI representation of function/hash" `(format nil "?~A:~A$~A:~A" +session-query-name+ (if +context+ (session.id (context.session +context+)) +invalid-session+) +continuation-query-name+ (function/hash ,parameters ,@body))) (defmacro action/url (parameters &body body) "Returns URI representation of action/hash" `(format nil "?~A:~A$~A:~A" +session-query-name+ (if +context+ (session.id (context.session +context+)) +invalid-session+) +continuation-query-name+ (action/hash ,parameters ,@body))) (defmacro answer (&rest values) "Continues from the continuation saved by action/hash or function/hash" `(if (null (context.continuation +context+)) (error "Surrounding send/suspend not found, can't answer") (kall (context.continuation +context+) +context+ ,@values))) (defmacro answer/dispatch (to &rest arguments) `(answer (list ,to ,@arguments))) (defmacro answer/url (parameters) `(action/url ,parameters (answer (list ,@(mapcar #'car parameters))))) (defun/cc javascript/suspend (lambda) "Javascript version of send/suspend, sets content-type to application/javascript" (http-response.set-content-type (context.response +context+) '("application" "javascript" ("charset" "UTF-8"))) (send/suspend (prog1 nil (funcall lambda (http-response.stream (context.response +context+)))))) (defmacro json/suspend (&body body) "Json version of send/suspend, sets content-type to text/json" `(progn (http-response.set-content-type (context.response +context+) '("text" "json" ("charset" "UTF-8"))) (send/suspend ,@body))) (defmacro xml/suspend (&body body) "Xml version of send/suspend, sets content-type to text/xml" `(progn (http-response.set-content-type (context.response +context+) '("text" "xml" ("charset" "UTF-8"))) (send/suspend ,@body))) (defmacro css/suspend (&body body) "Css version of send/suspend, sets content-type to text/css" `(progn (http-response.set-content-type (context.response +context+) '("text" "css" ("charset" "UTF-8"))) (send/suspend ,@body))) ;; +------------------------------------------------------------------------- ;; | HTTP Application Testing Utilities ;; +------------------------------------------------------------------------- (defmacro with-test-context ((context-var uri application) &body body) "Executes 'body' with context bound to 'context-var'" `(let ((,context-var (make-new-context ,application (make-instance 'http-request :uri ,uri) (make-response (make-indented-stream *core-output*)) nil))) ,@body)) (defun kontinue (number result &rest parameters) "Continues a contination saved by function/hash or action/hash" (let ((fun (cdr (nth number result)))) (if (null fun) (error "Continuation not found, please correct name.") (apply fun parameters)))) (defun test-url (url application) "Conventional macro to test urls wihout using a browser. One may provide query parameters inside URL as key=value" (assert (stringp url)) (let ((uri (uri? (make-core-stream url)))) (dispatch application (make-instance 'http-request :uri uri :stream *core-output*) (make-response *core-output*)))) (defparameter +etag-key+ (string-to-octets "gLZntebnfM" :utf-8)) (defmacro with-cache (etag-key &body body) `(let ((response (context.response +context+)) (timestamp ,etag-key) (request (context.request +context+))) (labels ((calculate-etag () (hmac +etag-key+ (format nil "~A" timestamp) :sha1)) (add-cache-headers () ;; Date:Sat, 05 Nov 2011 22:05:05 GMT ;; ETag: "8eb52-e2b-4b0dbed652d80" (http-response.remove-header response 'pragma) (http-response.remove-header response 'cache-control) (http-response.remove-header response 'expires) (http-response.add-general-header response 'date (get-universal-time)) (http-response.add-response-header response 'etag (cons (calculate-etag) nil)) (http-response.add-entity-header response 'expires (+ (get-universal-time) 50000)) (http-response.add-entity-header response 'last-modified timestamp) (http-response.add-general-header response 'cache-control (list 'public ;; 'must-revalidate ;; 'no-transform (cons 'max-age 50000)))) (render-response () (add-cache-headers) ,@body)) ;; If-Modified-Since:Thu, 03 Nov 2011 22:15:34 GMT ;; If-None-Match: "8eb50-b16-4b0dbed652d80" (let* ((date (http-request.header request 'if-modified-since)) (etag (http-request.header request 'if-none-match))) (cond ((application.debug (context.application +context+)) ,@body) ((and timestamp (> timestamp 0) etag (equal (calculate-etag) (caar etag))) (prog1 nil (add-cache-headers) (setf (http-response.status-code response) (core-server::make-status-code 304)))) (t (render-response))))))) ;; ------------------------------------------------------------------------- ;; Library.core - Javascript Library ;; ------------------------------------------------------------------------- (defparameter +library.core-timestamp+ (get-universal-time)) (defhandler "library.core" ((self http-application)) (javascript/suspend (lambda (s) (flet ((foo () +library.core-timestamp+)) (with-cache (foo) (core-server::core-library! s)))))) (defhandler "multipart.core" ((self http-application) (action "action") (hash "__hash")) (let* ((uri (uri? (make-core-stream (json-deserialize action)))) (action-s (uri.query uri +session-query-name+)) (action-k (uri.query uri +continuation-query-name+)) (paths (uri.paths uri)) (stream (make-core-stream ""))) (write-stream stream (json-deserialize action)) (labels ((commit (hash context) (let* ((uri-full (uri? (make-core-stream (return-stream stream)))) (req (context.request context)) (rep (context.response context)) (current-uri (http-request.uri req))) (setf (uri.paths current-uri) (if (equal (web-application.fqdn self) (car (uri.paths uri))) (cdr (uri.paths uri)) (uri.paths uri))) (setf (uri.queries current-uri) (cons (cons "__hash" hash) (uri.queries uri-full))) (escape (dispatch self req rep)))) (multipart-action (hash) (javascript/suspend (lambda (s) (let ((k-url (action/url ((data "data") (commit "commit") (hash "__hash")) (context.remove-current-action +context+) (cond (commit (commit hash +context+)) (t (write-stream stream (subseq data 1 (- (length data) 1))) (multipart-action (json-deserialize hash))))))) (with-js (k-url hash) s (apply (slot-value window hash) this (list k-url)))))))) (multipart-action (json-deserialize hash))))) (defmacro defhandler/static (pathname url &optional application-class) (let ((xml (read-stream (make-html-stream (make-core-stream pathname))))) `(defhandler ,url ((self ,(or application-class 'http-application))) ,(dom->lisp xml)))) ;; (defhandler/static #P"~/core-server/src/manager/wwwroot/index.html" ;; "myproject.core") ;; (defapplication test1 (http-application) ;; () ;; (:default-initargs :fqdn "en.core.gen.tr" :admin-email "zoo")) ;; (defhandler "index.core" ((app test1) (context http-context) (abc "abc") (def "def")) ;; (<:div abc def)) ;; (defvar *e (make-instance 'test1)) ;; (register *server* *e) ;; TODO: what if /../../../etc/passwd ? filter those. ;; (defun directory-handler (context) ;; "Default directory handler which serves static files" ;; (let ((htdocs-path (web-application.htdocs-pathname (context.application context))) ;; (paths (let ((tmp (or (uri.paths (http-request.uri (context.request context))) '((""))))) ;; (if (equal (caar tmp) "") ;; '(("index.html")) ;; tmp)))) ;; ;; 404 when htdocs not found ;; (if (or (null htdocs-path) (not (cl-fad:file-exists-p htdocs-path))) ;; (render-404 (context.application context) (context.request context) (context.response context)) ;; (let* ((file-and-ext (pathname (caar (last paths)))) ;; (path (append '(:relative) (mapcar #'car (butlast paths)))) ;; (output (http-response.stream (context.response context))) ;; (abs-path (merge-pathnames ;; (merge-pathnames (make-pathname :directory path) file-and-ext) ;; htdocs-path)) ;; (mime-type (mime-type abs-path))) ;; (if (and (cl-fad:file-exists-p abs-path) ;; (not (cl-fad:directory-exists-p abs-path))) ;; (progn ;; (setf (cdr (assoc 'content-type (http-response.entity-headers (context.response context)))) ;; (split "/" mime-type)) ;; (with-open-file (input abs-path :element-type '(unsigned-byte 8) :direction :input) ;; (let ((seq (make-array (file-length input) :element-type 'unsigned-byte))) ;; (read-sequence seq input) ;; (write-stream output seq)))) ;; (render-404 (context.application context) (context.request context) (context.response context))))))) ;; (defmacro defhandler (name queries &body body) ;; (with-unique-names (context) ;; `(defun ,name (,context) ;; (with-context ,context ;; (with-html-output (http-response.stream (context.response ,context)) ;; (with-query ,queries (context.request ,context) ;; ,@body)) ;; (setf (context.request ,context) nil ;; (context.response ,context) nil)) ;; t))) ;; (defmacro defurl (application regexp-url queries &body body) ;; "Defines a new entry point to 'application' having url ;; 'regexp-url'. 'queries' are bounded while executing 'body'" ;; `(register-url ,application ,regexp-url ;; (lambda (context) ;; (with-context context ;; (with-html-output (http-response.stream (context.response +context+)) ;; (with-query ,queries (context.request +context+) ;; ,@body)) ;; (setf (context.request +context+) nil ;; (context.response +context+) nil) ;; t)))) ;; (defmethod register-handler ((application http-application) regexp-url lambda) ;; "Registers a new 'regexp-url' to application to execute 'lambda' ;; when requested" ;; (setf (application.handlers application) ;; (cons (list regexp-url (cl-ppcre:create-scanner regexp-url) lambda) ;; (unregister-url application regexp-url)))) ;; (defmethod unregister-handler ((self http-application) regexp-url) ;; "Removes 'regexp-url' from applications handlers" ;; (setf (application.handlers self) ;; (remove regexp-url (application.handlers self) :test #'equal :key #'car))) ;; (defmethod dispatch ((self http-application) (request http-request) (response http-response)) ;; "Dispatch 'request' to 'self' application with empty 'response'" ;; (when (> (random 100) 40) ;; (gc self)) ;; (let ((session (gethash (find-session-id request) (application.sessions self)))) ;; (acond ;; ((and session (gethash (uri.query (http-request.uri request) +continuation-query-name+) ;; (session.continuations session))) ;; (log-me (application.server self) 'http-application ;; (format nil "fqdn: ~A, k-url: ~A" ;; (web-application.fqdn self) ;; (uri.query (http-request.uri request) +continuation-query-name+))) ;; (funcall it request response)) ;; ;; ((any #'(lambda (url) ;; ;; (aif (caar (uri.paths (http-request.uri request))) ;; ;; (and (cl-ppcre:scan-to-strings (cadr url) it :sharedp t) url))) ;; ;; (application.urls self)) ;; ;; (log-me (application.server self) 'http-application ;; ;; (format nil "fqdn: ~A, dyn-url: ~A" (web-application.fqdn self) ;; ;; (http-request.uri request))) ;; ;; (funcall (caddr it) (make-new-context self request response session))) ;; ((any #'(lambda (handler) ;; (aif (caar (uri.paths (http-request.uri request))) ;; (and (cl-ppcre:scan-to-strings (cdr handler) it :sharedp t) ;; (car handler)))) ;; (application+.handlers (class-of self))) ;; (log-me (application.server self) 'http-application ;; (format nil "fqdn: ~A, static-handler:: ~A" (web-application.fqdn self) ;; (http-request.uri request))) ;; (funcall it self (make-new-context self request response session))) ;; ((directory-handler (make-new-context self request response session)) ;; (log-me (application.server self) 'http-application ;; (format nil "fqdn: ~A, static-url: ~A" (web-application.fqdn self) ;; (http-request.uri request))) ;; t) ;; (t ;; (render-404 self request response))))) ;; (defun make-dispatcher (regexp-string handler) ;; "Returns a new dispatcher list having url 'regexp-string' and lambda ;; 'handler'" ;; (list regexp-string (cl-ppcre:create-scanner regexp-string) handler)) ;; #:http-application ;; #:find-session ;; #:query-session ;; #:update-session ;; #:find-continuation ;; #:with-context ;; helper for defurl ;; #:with-query ;; helper macro ;; #:defurl ;; #:defhandler ;; #:register-url ;; #:unregister-url ;; #:make-dispatcher ;; #:find-url ;; #:http-session ;; #:session ;; #:session.id ;; #:session.timestamp ;; #:session.continuations ;; #:session.data ;; #:make-new-session ;; #:http-context ;; #:context.request ;; #:context.response ;; #:context.session ;; #:context.session-boundp ;; #:context.application ;; #:context.continuation ;; #:context.returns ;; #:+context+ ;; #:+html-output+ ;; #:make-new-context ;; #:copy-context ;; #:request ;; #:response ;; #:send/suspend ;; #:send/forward ;; #:send/finish ;; #:javascript/suspend ;; #:json/suspend ;; #:xml/suspend ;; #:css/suspend ;; #:function/hash ;; #:action/hash ;; #:function/url ;; #:action/url ;; #:answer ;; #:answer/dispatch ;; #:dispatch ;; #:kontinue ;; #:test-url ;; (defmethod render-file ((application http-application) ;; (request http-request) (response http-response)) ;; "Default directory handler which serves static files" ;; (let ((htdocs-path (web-application.htdocs-pathname application)) ;; (paths (let ((tmp (or (uri.paths (http-request.uri request)) ;; '((""))))) ;; (if (equal (caar tmp) "") ;; '(("index.html")) ;; tmp)))) ;; ;; HTDOCS Not found ;; (if (or (null htdocs-path) (not (probe-file htdocs-path))) ;; (return-from render-file nil)) ;; (let* ((file-and-ext (pathname (caar (last paths)))) ;; (path (append '(:relative) (mapcar #'car (butlast paths)))) ;; (output (http-response.stream response)) ;; (abs-path (merge-pathnames ;; (merge-pathnames (make-pathname :directory path) ;; file-and-ext) ;; htdocs-path)) ;; (mime-type (mime-type abs-path))) ;; ;; File Not Found ;; (if (not (probe-file abs-path)) ;; (return-from render-file nil)) ;; ;; Directory Request, we do not serve it, yet. ;; (if (cl-fad:directory-exists-p abs-path) ;; (return-from render-file nil)) ;; (http-response.set-content-type response (split "/" mime-type)) ;; (with-open-file (input abs-path :element-type '(unsigned-byte 8) ;; :direction :input) ;; (let ((seq (make-array (file-length input) ;; :element-type 'unsigned-byte))) ;; (read-sequence seq input) ;; (write-stream output seq))) ;; t)))
44,011
Common Lisp
.lisp
989
39.897877
110
0.622284
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e7098322bd028535469305cc167c9d5cbeb393add3ea93fc1dd5554eda52b3df
8,330
[ -1 ]
8,331
serializable-application.lisp
evrim_core-server/src/applications/serializable-application.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| Serializable Application ;;+---------------------------------------------------------------------------- ;; ;; This file contains base implementation of serializable application. The main ;; aim is to create a stub object that holds some important properties of our ;; application. This object is created by executing function: ;; ;; (make-serializable-application (fqdn project-name admin-email project-pathname ;; &optional htdocs-pathname use depends-on)) ;; ;; Above method creates a stub application object so that we serialize it to disk: ;; ;; (serialize *stub*) ;; ;; See http://labs.core.gen.tr/#firstapp for a detailed tutorial. ;; ;; Currently, there are three types of serializable application: ;; ;; SCM Class ;; ------------------------------------ ;; 1) - serializable-application ;; 2) Darcs darcs-application ;; 3) Git git-application ;; (defclass+ serializable-web-application (web-application) ((sources :accessor serializable-web-application.sources :initarg :sources :initform '(src/packages src/model src/tx src/interfaces src/application src/security src/ui/main)) (directories :accessor serializable-web-application.directories :initarg :directories :initform (list (make-pathname :directory '(:relative "src")) (make-pathname :directory '(:relative "src" "ui")) (make-pathname :directory '(:relative "t")) (make-pathname :directory '(:relative "doc")) (make-pathname :directory '(:relative "wwwroot")) (make-pathname :directory '(:relative "wwwroot" "style")) (make-pathname :directory '(:relative "wwwroot" "images")) (make-pathname :directory '(:relative "templates")) (make-pathname :directory '(:relative "db")))) (use :accessor serializable-web-application.use :initarg :use :initform (list :common-lisp :core-server :arnesi)) (depends-on :accessor serializable-web-application.depends-on :initarg :depends-on :initform (list :arnesi+ :core-server))) (:documentation "Base class for template application - This class is used to create a new application. See src/applications/serializable-application.lisp for implementation")) (defmethod package-keyword ((self serializable-web-application) &optional long) (or (and long (make-keyword (strcat "tr.gen.core." (web-application.project-name self)))) (make-keyword (web-application.project-name self)))) (defmethod package-test-keyword ((self serializable-web-application)) (make-keyword (format nil "~A.test" (package-keyword self)))) (defmethod model-class ((self serializable-web-application)) (intern (format nil "~A" (string-upcase (strcat (web-application.project-name self) "-model"))))) (defmethod application-class ((self serializable-web-application)) (intern (format nil "~A" (string-upcase (strcat (web-application.project-name self) "-application"))))) (defmethod serialize-source ((self serializable-web-application) symbol) (with-package :core-server (with-open-file (out (source-to-pathname self symbol) :direction :output :if-does-not-exist :create :if-exists :supersede) (let ((*print-escape* nil) (*print-pretty* t)) (mapcar #'(lambda (line) (format out "~A" (string-downcase (format nil "~S~%~%" line)))) (cdr (apply symbol (list self)))))))) (defmethod serialize-asd ((self serializable-web-application)) (with-open-file (out (merge-pathnames (make-pathname :name (web-application.project-name self) :type "asd") (web-application.project-pathname self)) :direction :output :if-does-not-exist :create :if-exists :supersede) (mapcar #'(lambda (line) (format out "~A" (string-downcase (format nil "~S~%~%" line)))) (cdr (apply 'asd (list self)))))) (defmethod source-to-pathname ((self serializable-web-application) symbol) (let* ((result (cl-ppcre:split "(/)" (string-downcase (string symbol)))) (directories (butlast result)) (file (last1 result))) (merge-pathnames (make-pathname :directory (cons :relative directories) :name file :type "lisp") (web-application.project-pathname self)))) (defmethod serialize ((self serializable-web-application)) ;; Create template folders (mapcar #'(lambda (dir) (ensure-directories-exist (merge-pathnames dir (web-application.project-pathname self)))) (serializable-web-application.directories self)) (serialize-asd self) (mapcar (curry #'serialize-source self) (serializable-web-application.sources self))) (defmethod evaluate ((self serializable-web-application)) (pushnew (web-application.project-pathname self) asdf:*central-registry*) (asdf:oos 'asdf:load-op (package-keyword self))) (defmethod asd ((self serializable-web-application)) `(progn (in-package :asdf) (asdf::defsystem ,(package-keyword self) :description "Core Template Application" :version ".1" :author ,(web-application.admin-email self) :maintainer ,(web-application.admin-email self) :licence "LGPL v2" :components ((:static-file ,(strcat (web-application.project-name self) ".asd")) (:module :src :serial t :components ((:file "packages") (:file "model" :depends-on ("packages")) (:file "tx" :depends-on ("model")) (:file "application" :depends-on ("packages" "model" "tx")) (:file "interfaces" :depends-on ("application")) (:module :ui :serial t :components ((:file "main")))))) :depends-on ,(serializable-web-application.depends-on self) :serial t) (asdf::defsystem ,(package-test-keyword self) :components ((:module :t :components ((:file "packages")))) :depends-on (,(package-keyword self) :core-server :rt)) (defmethod perform ((op asdf:test-op) (system (eql (asdf::find-system ,(package-keyword self))))) (asdf:oos 'asdf:load-op ,(package-test-keyword self))))) (defmethod src/packages ((self serializable-web-application)) `(progn (in-package :cl-user) (defpackage ,(package-keyword self t) (:nicknames ,(package-keyword self)) (:use ,@(serializable-web-application.use self)) (:shadowing-import-from #:arnesi #:new)))) (defmethod src/model ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)) (defclass ,(model-class self) () ()) (defmethod print-object ((self ,(model-class self)) stream) (print-unreadable-object (self stream :type t :identity t))))) (defmethod src/tx ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)))) (defmethod src/interfaces ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)))) (defmethod src/application ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)) (defvar *wwwroot* (make-project-path ,(symbol-name (package-keyword self)) "wwwroot")) (defvar *db-location* (merge-pathnames (make-pathname :directory '(:relative "var" ,(web-application.fqdn self) "db")) (bootstrap:home))) (defapplication ,(application-class self) (http-application apache-web-application database-server logger-server serializable-web-application) () (:default-initargs :database-directory *db-location* :db-auto-start t :fqdn ,(web-application.fqdn self) :admin-email ,(web-application.admin-email self) :project-name ,(web-application.project-name self) :project-pathname ,(web-application.project-pathname self) :htdocs-pathname ,(or (web-application.htdocs-pathname self) `*wwwroot*) :sources ',(serializable-web-application.sources self) :directories ',(serializable-web-application.directories self) :use ',(serializable-web-application.use self) :depends-on ',(serializable-web-application.depends-on self))) (defvar *app* (make-instance ',(application-class self))) (defun register-me (&optional (server *server*)) (core-server::register server *app*)) (defun unregister-me (&optional (server *server*)) (core-server::unregister server *app*)))) (defmethod src/security ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)))) (defmethod src/ui/main ((self serializable-web-application)) `(progn (in-package ,(package-keyword self)) ;; (defun header () ;; (<:h1 "Header")) ;; (defun footer () ;; (<:h1 "Footer")) ;; (defcomponent main-window (ajax-window) ;; ()) ;; (defmethod render ((self main-window)) ;; (<:div :id "header" (header)) ;; (<:div :id "body" (<:h1 "Hi, i'm a template *core* application.")) ;; (<:div :id "footer" (footer))) )) (defun make-serializable-application (fqdn project-name admin-email project-pathname &optional htdocs-pathname use depends-on) "Returns a new serializable application object having provided parameters" (let ((params (list :fqdn fqdn :project-name project-name :admin-email admin-email :project-pathname project-pathname))) (and htdocs-pathname (nconc params (list :htdocs-pathname htdocs-pathname))) (and use (nconc params (list :use use))) (and depends-on (nconc params (list :depends-on depends-on))) (apply #'make-instance 'serializable-web-application params)))
10,288
Common Lisp
.lisp
212
44.018868
109
0.682117
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
146024b894b539488a25d8015239a89a3325506bafd0e4838957ba4ed4d6b9af
8,331
[ -1 ]
8,332
git.lisp
evrim_core-server/src/applications/git.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| Git Application ;;+---------------------------------------------------------------------------- ;; ;; This application is the extension of serializable-application to be used ;; along with SCM Git (http://git.or.cz) ;; (defclass+ git-application (serializable-web-application) () (:documentation "Git Application Class - A serializable-application that uses GIT (http://git.or.cz) as SCM") (:ctor %make-git-application)) (defun make-git-application (fqdn project-name admin-email project-pathname &optional use depends-on) "Returns a new git-application having parameters provided" (let ((params (list :fqdn fqdn :project-name project-name :admin-email admin-email :project-pathname project-pathname))) (and use (nconc params (list :use use))) (and depends-on (nconc params (list :depends-on depends-on))) (apply #'make-instance 'git-application params))) (defun git (&rest args) (unwind-protect (sb-ext::process-exit-code (sb-ext:run-program +git+ args :output *standard-output*)))) (defmethod git-directory ((self git-application)) (merge-pathnames (make-pathname :directory '(:relative ".git")) (web-application.project-name self))) (defmethod serialize ((self git-application)) ;;error if already exists (when (probe-file (git-directory self)) (error "Project already has .git folder.")) (call-next-method)) (defmethod init ((self git-application)) (unless (zerop (with-current-directory (web-application.project-pathname self) (git "init") (git "add" "."))) (error "git init failed."))) (defmethod share ((self git-application)) (init self))
2,513
Common Lisp
.lisp
56
41.75
80
0.681521
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8157ae334f51adc672998d9f97b8084f4852bd714b426d958f34966d5ed8e8d8
8,332
[ -1 ]
8,333
darcs.lisp
evrim_core-server/src/applications/darcs.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;+---------------------------------------------------------------------------- ;;| Darcs Application ;;+---------------------------------------------------------------------------- ;; ;; This application is the extension of serializable-application to be used ;; along with SCM Darcs (http://darcs.net) ;; (defclass+ darcs-application (serializable-web-application) () (:documentation "Darcs Application Class - A serializable-application that uses Darcs (http://darcs.net) as SCM") (:ctor %make-darcs-application)) (defun make-darcs-application (fqdn project-name admin-email project-pathname &optional use depends-on) "Returns a new darcs-aplication having parameters provided" (let ((params (list :fqdn fqdn :project-name project-name :admin-email admin-email :project-pathname project-pathname))) (and use (nconc params (list :use use))) (and depends-on (nconc params (list :depends-on depends-on))) (apply #'make-instance 'darcs-application params))) (defun darcs (&rest args) (unwind-protect (sb-ext::process-exit-code (sb-ext:run-program +darcs+ args :output *standard-output*)))) (defmethod darcs-directory ((self darcs-application)) (merge-pathnames (make-pathname :directory '(:relative "_darcs")) (web-application.project-pathname self))) (defmethod darcs-author-file ((self darcs-application)) (merge-pathnames (make-pathname :directory '(:relative "prefs") :name "author") (darcs-directory self))) (defmethod serialize ((self darcs-application)) ;; Error if exists (when (probe-file (darcs-directory self)) (error "Project already has _darcs folder.")) (call-next-method)) (defmethod share ((self darcs-application)) (init self) (record self) (put self)) ;; ------------------------------------------------------------------------- ;; fix this init method is already used in components/overrides this ;; ------------------------------------------------------------------------- (defmethod init ((self darcs-application)) (if (zerop (with-current-directory (web-application.project-pathname self) (darcs "init"))) (progn (with-open-file (out (darcs-author-file self) :direction :output :if-does-not-exist :create) (format out " <~A>" "[email protected]"))) (error "darcs init failed."))) (defmethod record ((self darcs-application) &optional patch-name) (with-current-directory (web-application.project-pathname self) (darcs "record" "-m" (or patch-name "core-server checkpoint") "--all" "--author" "[email protected]" "--skip-long-comment" "--look-for-adds"))) (defmethod put ((self darcs-application) &optional (remote-repo (format nil "~A@node2:/home/projects/~A" +remote-user+ (web-application.project-name self)))) (with-current-directory (web-application.project-pathname self) (darcs "put" remote-repo))) (defmethod push-all ((self darcs-application)) (with-current-directory (web-application.project-pathname self) (darcs "push" "--all")))
3,816
Common Lisp
.lisp
78
45.461538
93
0.664964
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
179650b31f0a4094c6db47b5c07c6904838a96ba05cbd369c03ffa271f4b6a39
8,333
[ -1 ]
8,334
dns.lisp
evrim_core-server/src/applications/dns.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :core-server) ;;----------------------------------------------------------------------------- ;; DNS Application ;;----------------------------------------------------------------------------- (defclass+ abstract-dns-application () ((ns :accessor dns-application.ns :initform (list +ns1+ +ns2+) :initarg :ns :documentation "List of nameserver IP addresses") (mx :accessor dns-application.mx :initform (list +mx+) :initarg :mx :documentation "List of mail exchanger IP addresses") (alias :accessor dns-application.alias :initform nil :initarg :alias :documentation "List of aliases that this application has"))) (defmethod deploy-ns ((self abstract-dns-application)) "Add nameserver records for 'application' to nameserver configuration" (mapcar (lambda (ns) (when (null (find-ns (application.server self) (web-application.fqdn self))) (add-ns (application.server self) (web-application.fqdn self) ns))) (ensure-list (dns-application.ns self)))) (defmethod deploy-mx ((self abstract-dns-application)) "Add mail exchanger records for 'application' to nameserver configuration" (mapcar (lambda (mx) (when (null (find-mx (application.server self) (web-application.fqdn self))) (add-mx (application.server self) (web-application.fqdn self) mx))) (ensure-list (dns-application.mx self)))) (defmethod deploy-alias ((self abstract-dns-application)) "Add aliases record for 'application' to nameserver configuration" (mapcar (lambda (alias) (when (null (find-alias (application.server self) (web-application.fqdn self))) (add-alias (application.server self) (car alias) (cdr alias)))) (ensure-list (dns-application.alias self)))) (defclass+ dns-application (abstract-dns-application) ()) (defmethod start ((self dns-application)) "Add related records to nameserver configuration like nameserver, mail exchanger, aliases" (deploy-ns self) (deploy-mx self) (deploy-alias self)) (defmethod stop ((self dns-application)) )
2,785
Common Lisp
.lisp
51
51.137255
91
0.696291
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ff4abed2b7a954297b661f7cd284ac9caa1d97a995c7e5e647af6d38fbbf6ed3
8,334
[ -1 ]
8,335
postfix.lisp
evrim_core-server/src/applications/postfix.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;; +------------------------------------------------------------------------- ;; | Mail Application ;; +------------------------------------------------------------------------- (defclass+ postfix-application (mail-application) ())
1,011
Common Lisp
.lisp
18
54.666667
77
0.647059
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
ffe1b81d71d234a38f7501cfcc2000b2c71327f150a2a17ee95674cc2ebcf613
8,335
[ -1 ]
8,336
web.lisp
evrim_core-server/src/applications/web.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;; +------------------------------------------------------------------------- ;; | Web Application ;; +------------------------------------------------------------------------- (defclass+ web-application (application) ((fqdn :reader web-application.fqdn :initarg :fqdn :host local :print t :initform (error "Fqdn must be supplied.") :documentation "Fully qualified domain name of this application") (admin-email :accessor web-application.admin-email :initarg :admin-email :host local :initform (error "Admin email must be supplied.") :documentation "Administrators' email address") (project-name :accessor web-application.project-name :host local :initarg :project-name :initform nil :documentation "Name/Symbol of the project") (project-pathname :accessor web-application.project-pathname :initarg :project-pathname :initform nil :host local :documentation "Pathname of the project") (htdocs-pathname :accessor web-application.htdocs-pathname :initarg :htdocs-pathname :initform nil :host local :documentation "Htdocs pathname of the project, used for serving static files")) (:documentation "Base Web Application Class")) (defmethod print-object ((self web-application) stream) (print-unreadable-object (self stream :type t :identity t) (if (typep self 'server) (format stream "FQDN:\"~A\" is ~A running" (web-application.fqdn self) (if (status self) "" "*not*")) (format stream "FQDN:\"~A\"" (web-application.fqdn self))))) (defmethod web-application.base-url ((self web-application)) (format nil "/~A" (web-application.fqdn self))) (defmethod web-application.serve-url ((self web-application) (req t)) (format nil "/~A/TESTREQUEST" (web-application.fqdn self))) (defmethod web-application.serve-url ((self web-application) (req http-request)) (format nil "~A~A" (web-application.base-url self) (with-core-stream (s "") (mapc #'(lambda (path) (char! s core-server::+uri-path-seperator+) (string! s (car path)) (mapc #'(lambda (path) (core-server::char! s core-server::+uri-segment-seperator+) (core-server::string! s path)) (cdr path))) (core-server::uri.paths (http-request.uri req))) (return-stream s)))) ;; ------------------------------------------------------------------------- ;; Web Application Security Protocol (required for HTTP Authentication) ;; ------------------------------------------------------------------------- (defmethod web-application.realm ((application web-application)) (concat (web-application.fqdn application) " Security Zone")) (defmethod web-application.password-of ((application web-application) (username string)) (error "Implement (web-application.password-of ~A username)" (class-name (class-of application)))) (defmethod web-application.find-user ((application web-application) (username string)) (error "Implement (web-application.find-user ~A username)" (class-name (class-of application)))) ;; -------------------------------------------------------------------------- ;; Overriden get-directory method: This allows us to use default ;; database directory for database driven http applications. ;; -------------------------------------------------------------------------- (defmethod database.directory ((application web-application)) (ensure-directories-exist (merge-pathnames (make-pathname :directory (list :relative "var" (web-application.fqdn application) "db")) (bootstrap::home)))) ;; +------------------------------------------------------------------------- ;; | Root Http Application (App to serve at /) ;; +------------------------------------------------------------------------- (defclass+ root-web-application-mixin () ()) ;; (defmethod web-application.base-url ((self root-web-application-mixin)) ;; (call-next-method self) ;; ;; (let ((server (application.server self))) ;; ;; (format nil "http://~A:~A/" (web-application.fqdn self) ;; ;; (socket-server.port server))) ;; ) ;; (defmethod web-application.serve-url ((self root-web-application-mixin) (req t)) ;; (format nil "~A/TESTREQUEST" (web-application.base-url self))) ;; (defmethod web-application.serve-url ((self root-web-application-mixin) (req http-request)) ;; ;; (format nil "~A~A" (web-application.base-url self) ;; ;; (with-core-stream (s "") ;; ;; (flet ((one (path) ;; ;; (string! s (car path)) ;; ;; (mapc #'(lambda (path) ;; ;; (core-server::char! ;; ;; s core-server::+uri-segment-seperator+) ;; ;; (core-server::string! s path)) ;; ;; (cdr path)))) ;; ;; (mapc #'(lambda (path) ;; ;; (one path) ;; ;; (char! s core-server::+uri-path-seperator+)) ;; ;; (core-server::uri.paths (http-request.uri req)))) ;; ;; (return-stream s))) ;; (call-next-method self req) ;; )
5,709
Common Lisp
.lisp
111
48.468468
94
0.617136
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
842256470934dbf643df8e9501af367fede4d42580e77c674bdd34b3e0b68ea9
8,336
[ -1 ]
8,337
apache.lisp
evrim_core-server/src/applications/apache.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;; +------------------------------------------------------------------------- ;; | Apache Web Application ;; +------------------------------------------------------------------------- (defclass+ apache-web-application (web-application) ((vhost-template-pathname :accessor apache-web-application.vhost-template-pathname :initarg :vhost-template-pathname :initform (merge-pathnames (make-pathname :directory '(:relative "etc") :name "vhost" :type "conf") (asdf:component-pathname (asdf:find-system :core-server))) :documentation "Apache Virtual Host Template Configuration Pathname - see etc/vhost.conf") (default-entry-point :accessor apache-web-application.default-entry-point :initarg :default-entry-point :initform nil ;; "index.core" :documentation "Default Entry Point for redirector creation, setq nil not to.") (skel-pathname :accessor apache-web-application.skel-pathname :initarg :skel-pathname :initform (merge-pathnames (make-pathname :directory '(:relative "etc" "skel")) (asdf:component-pathname (asdf:find-system :core-server))) :documentation "Skeleton Pathname which is copied to htdoc directory. setq nil no to.")) (:documentation "Apache Web Application Class - This class is used this to manage vhost configuration for this application. It generates a new vhost configuration from 'vhost-template-pathname' and wkrites it to apache vhost configuration directory. See src/servers/apache.lisp for implementation.")) ;; FIXmE: move two accessor to apache web application file. (defmethod apache-web-application.config-pathname ((self apache-web-application)) "Returns confiugration pathname of the application 'self'" (merge-pathnames (make-pathname :name (web-application.fqdn self) :type *apache-default-config-extenstion*) (apache-server.vhosts.d-pathname (application.server self)))) (defmethod apache-web-application.docroot-pathname ((self apache-web-application)) (merge-pathnames (make-pathname :directory (list :relative (web-application.fqdn self))) (apache-server.htdocs-pathname (application.server self)))) (defmethod web-application.serve-url ((self apache-web-application) (req http-request)) (format nil "http://~A~A" (web-application.fqdn self) (with-core-stream (s "") (mapc #'(lambda (path) (core-server::char! s core-server::+uri-path-seperator+) (core-server::string! s (car path)) (mapc #'(lambda (path) (core-server::char! s core-server::+uri-segment-seperator+) (core-server::string! s path)) (cdr path))) (core-server::uri.paths (http-request.uri req))) (return-stream s))))
3,501
Common Lisp
.lisp
69
46.623188
87
0.701724
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
97c84025f9ba161504c570a9952ca9e2766698a98539c5c42bfd49587292237a
8,337
[ -1 ]
8,338
mail.lisp
evrim_core-server/src/applications/mail.lisp
;; Core Server: Web Application Server ;; Copyright (C) 2006-2008 Metin Evrim Ulu, Aycan iRiCAN ;; 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/>. (in-package :tr.gen.core.server) ;; +------------------------------------------------------------------------- ;; | Mail Application ;; +------------------------------------------------------------------------- (defclass+ mail-application (application) ((domain :accessor mail-application.domain :initarg :domain :initform (error "Please specify mail :domain"))))
1,118
Common Lisp
.lisp
20
54.05
77
0.655362
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
8cdfc6664a5666acfb4d5302093cc60e5a39ca9bda4fe4599dee5aa544905712
8,338
[ -1 ]
8,339
rest.lisp
evrim_core-server/src/web/rest.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Rest API ;; ------------------------------------------------------------------------- ;; ------------------------------------------------------------------------- ;; Rest+ Meta Class ;; ------------------------------------------------------------------------- (defclass+ rest+ (component+) ((url :initarg :url) (authenticate :initarg :authenticate :initform nil) (data-class :initarg :data-class :initform nil) (rest-class :initarg :rest-class :initform nil) (prefix :initarg :prefix :initform nil))) (defmethod validate-superclass ((class rest+) (super component+)) t) (defmethod validate-superclass ((class component+) (super rest+)) t) (defmethod rest+.rest-class ((self rest+)) (or (slot-value self 'rest-class) (class-name self))) (defmethod rest+.data+ ((self rest+)) (class+.find (slot-value self 'data-class))) (defmethod rest+.index ((self rest+)) (with-slots (data-class) self (let* ((data+ (class+.find data-class)) (index (car (class+.indexes data+))) (index-definition (slot-definition-to-plist index)) (index-name (getf index-definition :name)) (index-type (getf index-definition :type)) (index-initarg (getf index-definition :initarg))) (list index-name index-type index-initarg)))) (defmethod component+.local-morphism ((class rest+) name self args body) (let ((class-name (class-name class))) `(progn (class+.add-method (find-class+ ',class-name) ',name 'local '((,self ,class-name) ,@args)) (defmethod ,name ((,self ,class-name) ,@args) (let ((application (secure.application ,self))) ,@body))))) (defmethod rest+.list ((self rest+)) (let* ((data+ (rest+.data+ self)) (name (class+.list-function self (rest+.prefix self)))) `(defmethod/local ,name ((self ,(class-name self))) (,(class+.list-function data+) application)))) (defmethod rest+.find ((self rest+)) (let* ((data+ (rest+.data+ self)) (name (class+.find-function self (rest+.prefix self)))) (destructuring-bind (index-name index-type index-initarg) (rest+.index self) (declare (ignore index-name)) `(defmethod/local ,name ((self ,(class-name self)) (key ,index-type)) (,(class+.find-function data+) application ,index-initarg key))))) (defmethod rest+.add ((self rest+)) (let* ((data+ (rest+.data+ self)) (name (class+.add-function self (rest+.prefix self))) (slots (mapcar #'slot-definition-name (filter (lambda (slot) (slot-definition-export slot)) (class+.local-slots data+)))) (ctor-lambda-list (class+.ctor-lambda-list data+ t)) (lambda-list (filter (lambda (a) (member (car a) slots)) ctor-lambda-list)) (arguments (class+.ctor-keyword-arguments data+ lambda-list))) (destructuring-bind (index-name index-type index-initarg) (rest+.index self) (declare (ignore index-type)) `(defmethod/local ,name ((self ,(class-name self)) &key ,@lambda-list) (if (,(class+.find-function data+) application ,index-initarg ,index-name) (jobject :error "zaten var haci") (apply ',(class+.add-function data+) application (append (list :owner (secure.owner self) :group (user.group (secure.owner self))) ,arguments))))))) (defmethod rest+.update ((self rest+)) (let* ((data+ (rest+.data+ self)) (name (class+.update-function self (rest+.prefix self))) (slots (mapcar #'slot-definition-name (filter (lambda (slot) (slot-definition-export slot)) (class+.local-slots data+)))) (ctor-lambda-list (class+.ctor-lambda-list data+ t)) (lambda-list (filter (lambda (a) (member (car a) slots)) ctor-lambda-list)) (arguments (class+.ctor-keyword-arguments data+ lambda-list))) (destructuring-bind (index-name index-type index-initarg) (rest+.index self) (declare (ignore index-name)) `(defmethod/local ,name ((self ,(class-name self)) (key ,index-type) &key ,@lambda-list) (aif (,(class+.find-function data+) application ,index-initarg key) (apply ',(class+.update-function data+) application (cons it ,arguments)) (jobject :error "not found haci")))))) (defmethod rest+.delete ((self rest+)) (let* ((data+ (rest+.data+ self)) (name (class+.delete-function self (rest+.prefix self)))) (destructuring-bind (index-name index-type index-initarg) (rest+.index self) (declare (ignore index-name)) `(defmethod/local ,name ((self ,(class-name self)) (key ,index-type)) (aif (,(class+.find-function data+) application ,index-initarg key) (,(class+.delete-function data+) application it) (jobject :error "not found haci")))))) ;; ------------------------------------------------------------------------- ;; defrest-crud: Macro that defines crud interface ;; ------------------------------------------------------------------------- (defmacro defrest-crud (rest-class) (let ((rest+ (class+.find rest-class))) `(progn ,(rest+.list rest+) ,(rest+.find rest+) ,(rest+.add rest+) ,(rest+.update rest+) ,(rest+.delete rest+)))) ;; ------------------------------------------------------------------------- ;; Abstract Rest ;; ------------------------------------------------------------------------- (defclass+ abstract-rest (secure-object) ((offset :initform 0 :accessor rest.offset :host local) (size :initform 100 :accessor rest.size :host local)) (:metaclass rest+) (:default-intiargs :levels '(abstract-rest/anonymous abstract-rest/user) :permissions ((other . 1) (anonymous . 0)))) (defmethod rest.serialize ((self abstract-rest) (object t)) object) (defmethod rest.deserialize ((self abstract-rest) (object t)) object) (defmethod rest.get-method ((self abstract-rest) http-method key) (error "Implement (REST.GET-METHOD ~A)" (class-name (class-of self)))) (defmethod rest.method-call ((self abstract-rest) method-name args) (let ((method (class+.find-local-method (class-of self) method-name))) (when (null method) (warn "Method (~A ~A) not found." method-name (class-name (class-of self))) (return-from rest.method-call nil)) (flet ((find-argument (name) (aif (find (symbol-to-js name) args :key #'car :test #'string=) (rest.deserialize self (json-deserialize (cdr it)))))) (let* ((arguments (walk-lambda-list (cdddr method) nil nil :allow-specializers t)) (arguments (reduce (lambda (acc arg) (with-slots (name) arg (typecase arg (keyword-function-argument-form (cons (make-keyword name) (cons (find-argument name) acc))) (specialized-function-argument-form (cons (find-argument name) acc)) (rest-function-argument-form (append (find-argument name) acc))))) (nreverse arguments) :initial-value nil))) (with-call/cc (apply (car method) self arguments)))))) (defmethod rest.handle ((self abstract-rest) http-method key args) (let ((method (rest.get-method self http-method key))) ;; (authorize (rest.application self) ;; (secure.owner self) ;; (rest.serialize self (rest.method-call self method args))) (rest.serialize self (rest.method-call self method (cons (cons "key" key) args))))) ;; ------------------------------------------------------------------------- ;; Anonymous Abstract Rest ;; ------------------------------------------------------------------------- (defclass+ abstract-rest/anonymous (abstract-rest) ()) (defmethod rest.get-method ((self abstract-rest/anonymous) http-method key) (destructuring-bind (rest-list rest-find ig1 ig2 ig3 ig4) (class+.crud-functions (find-class (rest+.rest-class (class-of self)))) (declare (ignore ig1 ig2 ig3 ig4)) (cond ((eq http-method 'get) (if (or (null key) (equal "" key)) rest-list rest-find)) (t (error "Method ~A is unknown." http-method))))) ;; ------------------------------------------------------------------------- ;; Admin Abstract Rest ;; ------------------------------------------------------------------------- (defclass+ abstract-rest/user (abstract-rest) ()) (defmethod rest.get-method ((self abstract-rest/user) http-method key) (destructuring-bind (rest-list rest-find ignr rest-add rest-update rest-delete) (class+.crud-functions (find-class (rest+.rest-class (class-of self)))) (declare (ignore ignr)) (cond ((eq http-method 'get) (if (or (null key) (equal "" key)) rest-list rest-find)) ((eq http-method 'post) rest-add) ((eq http-method 'put) rest-update) ((eq http-method 'delete) rest-delete) (t (error "Method ~A is unknown." http-method))))) ;; ------------------------------------------------------------------------- ;; make-rest: Rest Constructor ;; ------------------------------------------------------------------------- (defun make-rest (class args &rest extra) (let* ((class+ (class+.find class)) (local-slots (class+.local-slots class+))) (apply #'make-instance class (reduce (lambda (acc slot) (with-slotdef (name initarg) slot (aif (assoc (symbol-to-js name) args :test #'equal) (cons initarg (cons (json-deserialize (cdr it)) acc)) acc))) local-slots :initial-value extra)))) (defmacro defrest-handler (name url authenticate-p) (let ((url (concat (or url (symbol-to-js name)) "\\/?(.*)"))) `(progn ,(if authenticate-p `(defauth ,url http-application)) (defhandler (,url key) ((self http-application)) (let* ((request (context.request +context+)) (username (if (http-request.authenticated-p request) (http-request.authenticated-user request))) (user (if username (http-application.find-user self username) (make-anonymous-user))) (args (uri.queries (http-request.uri request))) (instance (authorize self user (make-rest ',name args :owner user :group (user.group user) :application self))) (result (rest.handle instance (http-request.method request) key args))) (component/suspend result)))))) ;; ------------------------------------------------------------------------- ;; defrest: Rest Macro ;; ------------------------------------------------------------------------- (defmacro defrest (name supers slots &rest rest) (flet ((get-param (name) (cadr (assoc name rest))) (make-method (key) (intern (format nil "~A.~A" name key)))) (let* ((data-class (or (get-param :class) (error "Provide :class"))) (auth (or (get-param :authenticate) nil)) (metaclass (or (get-param :metaclass) 'rest+)) (url (or (get-param :url) (symbol-to-js name))) (rest (remove-if-member '(:metaclass :class :authenticate :url) rest :key #'car)) (anonymous-class (intern (format nil "~A/ANONYMOUS" name) (symbol-package name))) (user-class (intern (format nil "~A/USER" name) (symbol-package name)))) `(progn (defclass+ ,name (,@supers abstract-rest) ,slots (:data-class . ,data-class) (:authenticate . ,auth) (:metaclass ,metaclass) (:url . ,url) (:prefix . ,name) (:rest-class . ,name) (:default-initargs :levels '(,anonymous-class ,user-class)) ,@rest) (defclass+ ,anonymous-class (,@supers secure-object/authorized abstract-rest/anonymous) ((secure-object :host lift :type ,name)) (:metaclass rest+) (:prefix . ,name) (:rest-class . ,name) (:data-class . ,data-class)) (defclass+ ,user-class (,@supers secure-object/authorized abstract-rest/user) ((secure-object :host lift :type ,name)) (:prefix . ,name) (:metaclass rest+) (:rest-class . ,name) (:data-class . ,data-class)) (defrest-handler ,name ,url ,auth) (defrest-crud ,anonymous-class) (defrest-crud ,user-class) ;; (defrest-crud/lift ,anonymous-class ,name) ;; (defrest-crud/lift ,user-class ,name) (find-class ',name))))) (deftrace rest+ '(rest+.list rest+.add rest+.find rest+.delete rest+.update)) ;; ------------------------------------------------------------------------- ;; <rest namespace: A Rest Client ;; ------------------------------------------------------------------------- (defcommand <rest:list (http) ()) (defcommand <rest:add (http) ((args :host local :initform nil :accessor rest.args)) (:default-initargs :method 'post)) (defmethod run ((self <rest:add)) (mapcar (lambda (arg) (destructuring-bind (a b) arg (http.add-post self a b))) (rest.args self)) (call-next-method self)) (defclass+ rest-key-mixin () ((key :host local :initform (error "Provide :key") :accessor rest.key))) (defmethod http.setup-uri ((self rest-key-mixin)) (let ((uri (call-next-method self))) (prog1 uri (with-slots (paths) uri (setf paths (if (equal (caar paths) "") (list (list (rest.key self))) (append paths (list (list (rest.key self)))))))))) (defcommand <rest:find (rest-key-mixin http) ()) (defcommand <rest:update (rest-key-mixin http) ((args :host local :initform nil :accessor rest.args)) (:default-initargs :method 'put)) (defmethod run ((self <rest:update)) (mapcar (lambda (arg) (destructuring-bind (a b) arg (http.add-post self a b))) (rest.args self)) (call-next-method self)) (defcommand <rest:delete (rest-key-mixin http) () (:default-initargs :method 'delete)) (defmacro defrest-client (url data-class namespace) (let* ((namespace (find-package namespace)) (class (find-class data-class)) (local-slots (reduce0 (lambda (acc slot) (if (slot-definition-export slot) (cons (slot-definition-name slot) acc) acc)) (class+.local-slots class)))) (destructuring-bind (list find query add update delete) (class+.crud-functions class) (declare (ignore query)) (let* ((list-symbol (intern (symbol-name list) namespace)) (add-symbol (intern (symbol-name add) namespace)) (find-symbol (intern (symbol-name find) namespace)) (update-symbol (intern (symbol-name update) namespace)) (delete-symbol (intern (symbol-name delete) namespace)) (index (car (class+.indexes class))) (index-initarg (car (slot-definition-initargs index))) (index-slot `(key :host local :initform (error ,(format nil "Provide :~A" index-initarg)) :accessor rest.key :initarg ,index-initarg))) `(progn (defcommand ,list-symbol (<rest:list) () (:default-initargs :url ,url)) (defcommand ,add-symbol (<rest:add) (,@(mapcar (lambda (slot) `(,slot :host local)) local-slots)) (:default-initargs :url ,url)) (defmethod rest.args ((self ,add-symbol)) (reduce0 (lambda (acc slot) (let ((value (slot-value self slot))) (if value (cons (list (string-downcase (symbol-name slot)) value) acc) acc))) ',local-slots)) (defcommand ,find-symbol (<rest:find) (,index-slot) (:default-initargs :url ,url)) (defcommand ,update-symbol (<rest:update) (,index-slot ,@(mapcar (lambda (slot) `(,slot :host local)) (remove (slot-definition-name index) local-slots))) (:default-initargs :url ,url)) (defmethod rest.args ((self ,update-symbol)) (reduce0 (lambda (acc slot) (let ((value (slot-value self slot))) (if value (cons (list (string-downcase (symbol-name slot)) value) acc) acc))) ',local-slots)) (defcommand ,delete-symbol (<rest:delete) (,index-slot) (:default-initargs :url ,url))))))) ;; Core Server: Web Application Server ;; Copyright (C) 2006-2012 Metin Evrim Ulu ;; 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/>. ;; Garbage below ;; (defmethod/cc rest.handle ((self abstract-rest) ()) ;; (flet ((get-local-method (http-method key) ;; )) ;; (let* ((request (context.request +context+)) ;; (method (or method (http-request.method request))) ;; (object (authorize self (query-session :user) ;; (make-instance ,'name))) ;; (args (cons (cons "key" key) ;; (uri.queries (http-request.uri request)))) ;; (result (component.serialize object ;; (component.method-call object local-method args)))) ;; (component/suspend result)))) ;; (defmacro defrest-crud (rest-class data-class authenticate) ;; (let* ((class+ (class+.find rest-class)) ;; (data+ (class+.find data-class)) ;; (index (car (class+.indexes data+))) ;; (index-definition (slot-definition-to-plist index)) ;; (index-name (getf index-definition :name)) ;; (index-type (getf index-definition :type)) ;; (index-initarg (getf index-definition :initarg)) ;; (slots (mapcar #'slot-definition-name ;; (filter (lambda (slot) (slot-definition-export slot)) ;; (class+.local-slots data+)))) ;; (ctor-lambda-list (class+.ctor-lambda-list data+ t)) ;; (lambda-list (filter (lambda (a) (member (car a) slots)) ;; ctor-lambda-list)) ;; (arguments (class+.ctor-keyword-arguments class+ lambda-list))) ;; (destructuring-bind (list find query add update delete) ;; (class+.crud-functions class+) ;; (declare (ignore query)) ;; (destructuring-bind (crud-list crud-find crud-query crud-add ;; crud-update crud-delete) ;; (class+.crud-functions data+) ;; (declare (ignore crud-query)) ;; `(progn ;; (defmethod/local ,list ((self ,rest-class)) ;; (,crud-list application)) ;; (defmethod/local ,find ((self ,rest-class) (key ,index-type)) ;; (,crud-find application ,index-initarg key)) ;; (defmethod/local ,add ((self ,rest-class) &key ,@lambda-list) ;; (if (,crud-find application ,index-initarg ,index-name) ;; (jobject :error "zaten var haci") ;; (apply ',crud-add application ;; ,(if authenticate ;; `(append ,arguments ;; ,(if authenticate ;; `(list :owner (secure.owner self) ;; :group (user.group ;; (secure.owner self))))) ;; arguments)))) ;; (defmethod/local ,update ((self ,rest-class) (key ,index-type) ;; &key ,@lambda-list) ;; (aif (,crud-find application ,index-initarg key) ;; (apply ',crud-update application (cons it ,arguments)) ;; (jobject :error "not found haci"))) ;; (defmethod/local ,delete ((self ,rest-class) (key ,index-type)) ;; (aif (,crud-find application ,index-initarg key) ;; (,crud-delete application it) ;; (jobject :error "not found haci")))))))) ;; (defmacro defrest-handler (name url auth) ;; (let ((url (concat (or url (symbol-to-js name)) "\\/?(.*)"))) ;; `(progn ;; ,(if auth `(defauth ,url http-application)) ;; (defhandler (,url key) ((self http-application)) ;; (flet ((%make-component (args) ;; ,(if auth ;; `(let* ((request (context.request +context+)) ;; (username (http-request.authenticated-user request)) ;; (user (http-application.find-user self username)) ;; (component (make-component-from-args ;; ',name args ;; :owner user ;; :group (user.group user)))) ;; ;; (authorize self user component) ;; component) ;; `(make-component-from-args ',name args)))) ;; (let* ((request (context.request +context+)) ;; (args (if key ;; (cons (cons "key" key) ;; (uri.queries (http-request.uri request))) ;; (uri.queries (http-request.uri request)))) ;; (component (%make-component args)) ;; (method (rest.get-method component ;; (http-request.method request) ;; key))) ;; (let ((result (component.serialize component ;; (component.method-call component method args)))) ;; (component/suspend result)))))))) ;; (defmacro defrest-crud/lift (target-class source-class) ;; (let ((source (class+.find source-class)) ;; (target (class+.find target-class))) ;; (destructuring-bind (lst find query add update delete) (class+.crud-functions ;; source) ;; (declare (ignore query)) ;; `(progn ;; ,@(mapcar ;; (lambda (method) ;; (let ((method (class+.find-local-method source method))) ;; (when method ;; (destructuring-bind (name type &rest args) method ;; (declare (ignore type)) ;; `(defmethod/lift ,name ;; ((,(caar args) ,(class-name target)) ,@(cdr args))))))) ;; (list lst find add update delete))))))
21,022
Common Lisp
.lisp
467
41.017131
89
0.604675
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
f465e8dbd427ec9d03096faee65282030ed391dae4682f422bd95a50429f2522
8,339
[ -1 ]
8,340
menu.lisp
evrim_core-server/src/web/widgets/menu.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Simple Menu Widget ;; ------------------------------------------------------------------------- (defcomponent <widget:simple-menu (<:ul <widget:simple) ((items :host remote :initarg :children) (hilight-class :host remote :initform "hilight"))) (defmethod/remote on-page-load ((self <widget:simple-menu) name) (mapcar (lambda (a) (if (eq name (get-parameter "page" (slot-value a 'href))) (add-class a (hilight-class self)) (remove-class a (hilight-class self)))) (node-search (lambda (a) (eq (slot-value a 'tag-name) "A")) self))) (defmethod/remote init ((self <widget:simple-menu)) (mapcar-cc (lambda (a) (append self a)) (mapcar-cc (lambda (menu) (with-slots (name title) menu (<:li (<:a :href (+ "#page:" name) title)))) (items self))))
890
Common Lisp
.lisp
19
43.473684
76
0.543779
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
24e9e805f86fa4c5217e7c03621b55bc92c872be9f340c01c8be391e4477a6f0
8,340
[ -1 ]
8,341
tab.lisp
evrim_core-server/src/web/widgets/tab.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Tab Widget ;; ------------------------------------------------------------------------- (defcomponent <widget:tab (<core:tab <widget:simple) ())
254
Common Lisp
.lisp
6
40.833333
76
0.275304
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
c9d847a8b9d226abec079e004231ce80081cff80c45a4b5c787a712c3e71fade
8,341
[ -1 ]
8,342
content.lisp
evrim_core-server/src/web/widgets/content.lisp
(in-package :core-server) (defcomponent <widget:simple-content (<:div <widget:simple) ((content :host remote :initform nil :initarg :children))) (defmethod/remote init ((self <widget:simple-content)) (call-next-method self) (mapcar-cc (lambda (a) (if (typep a 'function) (append self (make-component a)) (append self a))) (content self)))
371
Common Lisp
.lisp
10
32.9
60
0.680556
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
fb3c02145631372291d5edda01cc8f13be240f9426827c9d9dff4cc4c4a9dfd0
8,342
[ -1 ]
8,343
sidebar.lisp
evrim_core-server/src/web/framework/sidebar.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Sidebar ;; ------------------------------------------------------------------------- (defcomponent <core:sidebar (<:div callable-component cached-component) ((sidebar-css :host remote :initform +sidebar.css+) (dirty-p :host remote :initform nil))) (defmethod/remote destroy ((self <core:sidebar)) (remove-class self "core") (remove-class self "core-sidebar") (call-next-method self)) (defmethod/remote do-close ((self <core:sidebar)) (if (dirty-p self) (if (confirm (_"Do you want to discard changes?")) (hide-component self)) (hide-component self))) (defmethod/remote init ((self <core:sidebar)) (add-class self "core-sidebar") (add-class self "core") (prepend self (<:div :class "right" (<:a :onclick (lifte (do-close self)) :class "sidebar-close-button" :title (_"close this sidebar") " "))) (call-next-method self)) (defmethod/remote show-component ((self <core:sidebar)) (load-css (sidebar-css self)) (append (slot-value document 'body) self)) (defmethod/remote hide-component ((self <core:sidebar)) (.remove-child (slot-value document 'body) self) (remove-css (sidebar-css self))) (defmethod/remote call-component ((self <core:sidebar)) (show-component self) (call-next-method self)) (defmethod/remote answer-component ((self <core:sidebar) arg) (hide-component self) (destroy self) (call-next-method self arg))
1,510
Common Lisp
.lisp
37
37.513514
76
0.628669
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
d6b4e98cca636706adee2967ecc6ef7aec67ced7185ea76f5f7f4e7e479886b6
8,343
[ -1 ]
8,344
page.lisp
evrim_core-server/src/web/framework/page.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Simple Page ;; ------------------------------------------------------------------------- (defcomponent <core:simple-page (secure-object <:div) ((name :host both :index t :print t :type string) (widgets :host remote :type abstract-widget-map* :initarg :children)) (:default-initargs :levels '(<core:simple-page/unauthorized <core:simple-page/anonymous <core:simple-page/registered) :permissions '((owner . 2) (group . 2) (other . 2) (anonymous . 1) (unauthorized . 0)) :owner (make-simple-user :name "admin") :group (make-simple-group :name "admin"))) ;; ------------------------------------------------------------------------- ;; Unauthorized Controller ;; ------------------------------------------------------------------------- (defcomponent <core:simple-page/unauthorized (<core:simple-page secure-object/unauthorized) ()) (defmethod/remote init ((self <core:simple-page/unauthorized)) (alert "Sorry, you are unauthorized to view this page.")) ;; ------------------------------------------------------------------------- ;; Simple Page / Anonymous ;; ------------------------------------------------------------------------- (defcomponent <core:simple-page/anonymous (<core:simple-page secure-object/authorized) ((secure-object :host lift :type <core:simple-page) (widgets :host remote :lift t :authorize t) (name :host remote :lift t) (controller :host remote))) (defmethod/remote destroy ((self <core:simple-page/anonymous)) (mapcar-cc (lambda (a) (if a (destroy a))) (widgets self)) (delete-slots self 'widgets) (call-next-method self)) (defmethod/remote init ((self <core:simple-page/anonymous)) (setf (widgets self) (mapcar-cc (lambda (m) (make-component m :controller (controller self))) (widgets self)))) ;; ------------------------------------------------------------------------- ;; Simple Page / Registered ;; ------------------------------------------------------------------------- (defcomponent <core:simple-page/registered (<core:simple-page/anonymous) ())
2,174
Common Lisp
.lisp
44
46.318182
76
0.507772
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
1abe0a0b4f18c5f6a9a7397db555ac46fe0e897aafa2966a195a7d5931b1a964
8,344
[ -1 ]
8,345
map.lisp
evrim_core-server/src/web/framework/map.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Abstract Widget Map ;; ------------------------------------------------------------------------- (defcomponent abstract-widget-map (<:div) ((selector :host both :type string :print t) (widget :host both :type abstract-widget :print t) (enabled :host remote :initform nil)) (:ctor %make-abstract-widget-map)) ;; ------------------------------------------------------------------------- ;; Simple Widget Map ;; ------------------------------------------------------------------------- (defcomponent <core:simple-widget-map (secure-object abstract-widget-map) () (:default-initargs :levels '(<core:simple-widget-map/anonymous) :permissions '((owner . 0) (group . 0) (other . 0) (anonymous . 0) (unauthorized . 0)) :owner (make-simple-user :name "admin") :group (make-simple-group :name "admin"))) ;; ------------------------------------------------------------------------- ;; Simple Widget Map / Anonymous ;; ------------------------------------------------------------------------- (defcomponent <core:simple-widget-map/anonymous (<core:simple-widget-map secure-object/authorized) ((secure-object :host lift :type <core:simple-widget-map) (selector :host remote :lift t) (widget :host remote :lift t :authorize t) (enabled :host remote :lift t) (controller :host remote))) (defmethod/remote on-page-load ((self <core:simple-widget-map/anonymous) name) (if (and (enabled self) (typep (slot-value (widget self) 'on-page-load) 'function)) (on-page-load (widget self) name))) (defmethod/remote destroy ((self <core:simple-widget-map/anonymous)) (when (enabled self) (destroy (widget self)))) (defmethod/remote init ((self <core:simple-widget-map/anonymous)) (awhen (document.get-element-by-id (selector self)) (setf (enabled self) t (widget self) (call/cc (widget self) (extend (jobject :widget-map self) it)))))
2,003
Common Lisp
.lisp
42
44.571429
78
0.540665
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
e50aba5391fd17d3ca6465368a366a6b7041be5203bc435cb0808e6b09d5f017
8,345
[ -1 ]
8,346
widget.lisp
evrim_core-server/src/web/framework/widget.lisp
(in-package :core-server) ;; ------------------------------------------------------------------------- ;; Simple Widget ;; ------------------------------------------------------------------------- (defcomponent <widget:simple () ((widget-map :host both :type abstract-widget-map) (_child-nodes :host remote)) (:ctor make-simple-widget)) (defmethod/remote destroy ((self <widget:simple)) (mapcar (lambda (a) (.remove-child self a)) (reverse (slot-value self 'child-nodes))) (mapcar (lambda (a) (.append-child self a)) (_child-nodes self)) (call-next-method self)) (defmethod/remote init ((self <widget:simple)) (mapcar (lambda (a) (.remove-child self a)) (setf (_child-nodes self) (reverse (slot-value self 'child-nodes)))) (call-next-method self))
776
Common Lisp
.lisp
17
43
76
0.556878
evrim/core-server
16
3
1
GPL-3.0
9/19/2024, 11:26:41 AM (Europe/Amsterdam)
71ccb80d64d692d3c8c082a2092d35c19e371d8c086da69f74654666048f2706
8,346
[ -1 ]