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
42,570
binding.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/binding.lisp
(in-package :alexandria) (defmacro if-let (bindings &body (then-form &optional else-form)) "Creates new variable bindings, and conditionally executes either THEN-FORM or ELSE-FORM. ELSE-FORM defaults to NIL. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, the THEN-FORM is executed with the bindings in effect, otherwise the ELSE-FORM is executed with the bindings in effect." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (if (and ,@variables) ,then-form ,else-form)))) (defmacro when-let (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, then FORMS are executed as an implicit PROGN." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (when (and ,@variables) ,@forms)))) (defmacro when-let* (bindings &body body) "Creates new variable bindings, and conditionally executes BODY. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) Each INITIAL-FORM is executed in turn, and the variable bound to the corresponding value. INITIAL-FORM expressions can refer to variables previously bound by the WHEN-LET*. Execution of WHEN-LET* stops immediately if any INITIAL-FORM evaluates to NIL. If all INITIAL-FORMs evaluate to true, then BODY is executed as an implicit PROGN." (let ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings))) (labels ((bind (bindings body) (if bindings `(let (,(car bindings)) (when ,(caar bindings) ,(bind (cdr bindings) body))) `(progn ,@body)))) (bind binding-list body))))
2,959
Common Lisp
.lisp
69
35.985507
78
0.673405
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d4fa698ca790cc8116f9afeaf4774ffb6f96ba3463c48ad9d2e35a4ba6ad1f7a
42,570
[ 480698 ]
42,571
lists.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/lists.lisp
(in-package :alexandria) (declaim (inline safe-endp)) (defun safe-endp (x) (declare (optimize safety)) (endp x)) (defun alist-plist (alist) "Returns a property list containing the same keys and values as the association list ALIST in the same order." (let (plist) (dolist (pair alist) (push (car pair) plist) (push (cdr pair) plist)) (nreverse plist))) (defun plist-alist (plist) "Returns an association list containing the same keys and values as the property list PLIST in the same order." (let (alist) (do ((tail plist (cddr tail))) ((safe-endp tail) (nreverse alist)) (push (cons (car tail) (cadr tail)) alist)))) (declaim (inline racons)) (defun racons (key value ralist) (acons value key ralist)) (macrolet ((define-alist-get (name get-entry get-value-from-entry add doc) `(progn (declaim (inline ,name)) (defun ,name (alist key &key (test 'eql)) ,doc (let ((entry (,get-entry key alist :test test))) (values (,get-value-from-entry entry) entry))) (define-setf-expander ,name (place key &key (test ''eql) &environment env) (multiple-value-bind (temporary-variables initforms newvals setter getter) (get-setf-expansion place env) (when (cdr newvals) (error "~A cannot store multiple values in one place" ',name)) (with-unique-names (new-value key-val test-val alist entry) (values (append temporary-variables (list alist key-val test-val entry)) (append initforms (list getter key test `(,',get-entry ,key-val ,alist :test ,test-val))) `(,new-value) `(cond (,entry (setf (,',get-value-from-entry ,entry) ,new-value)) (t (let ,newvals (setf ,(first newvals) (,',add ,key ,new-value ,alist)) ,setter ,new-value))) `(,',get-value-from-entry ,entry)))))))) (define-alist-get assoc-value assoc cdr acons "ASSOC-VALUE is an alist accessor very much like ASSOC, but it can be used with SETF.") (define-alist-get rassoc-value rassoc car racons "RASSOC-VALUE is an alist accessor very much like RASSOC, but it can be used with SETF.")) (defun malformed-plist (plist) (error "Malformed plist: ~S" plist)) (defmacro doplist ((key val plist &optional values) &body body) "Iterates over elements of PLIST. BODY can be preceded by declarations, and is like a TAGBODY. RETURN may be used to terminate the iteration early. If RETURN is not used, returns VALUES." (multiple-value-bind (forms declarations) (parse-body body) (with-gensyms (tail loop results) `(block nil (flet ((,results () (let (,key ,val) (declare (ignorable ,key ,val)) (return ,values)))) (let* ((,tail ,plist) (,key (if ,tail (pop ,tail) (,results))) (,val (if ,tail (pop ,tail) (malformed-plist ',plist)))) (declare (ignorable ,key ,val)) ,@declarations (tagbody ,loop ,@forms (setf ,key (if ,tail (pop ,tail) (,results)) ,val (if ,tail (pop ,tail) (malformed-plist ',plist))) (go ,loop)))))))) (define-modify-macro appendf (&rest lists) append "Modify-macro for APPEND. Appends LISTS to the place designated by the first argument.") (define-modify-macro nconcf (&rest lists) nconc "Modify-macro for NCONC. Concatenates LISTS to place designated by the first argument.") (define-modify-macro unionf (list &rest args) union "Modify-macro for UNION. Saves the union of LIST and the contents of the place designated by the first argument to the designated place.") (define-modify-macro nunionf (list &rest args) nunion "Modify-macro for NUNION. Saves the union of LIST and the contents of the place designated by the first argument to the designated place. May modify either argument.") (define-modify-macro reversef () reverse "Modify-macro for REVERSE. Copies and reverses the list stored in the given place and saves back the result into the place.") (define-modify-macro nreversef () nreverse "Modify-macro for NREVERSE. Reverses the list stored in the given place by destructively modifying it and saves back the result into the place.") (defun circular-list (&rest elements) "Creates a circular list of ELEMENTS." (let ((cycle (copy-list elements))) (nconc cycle cycle))) (defun circular-list-p (object) "Returns true if OBJECT is a circular list, NIL otherwise." (and (listp object) (do ((fast object (cddr fast)) (slow (cons (car object) (cdr object)) (cdr slow))) (nil) (unless (and (consp fast) (listp (cdr fast))) (return nil)) (when (eq fast slow) (return t))))) (defun circular-tree-p (object) "Returns true if OBJECT is a circular tree, NIL otherwise." (labels ((circularp (object seen) (and (consp object) (do ((fast (cons (car object) (cdr object)) (cddr fast)) (slow object (cdr slow))) (nil) (when (or (eq fast slow) (member slow seen)) (return-from circular-tree-p t)) (when (or (not (consp fast)) (not (consp (cdr slow)))) (return (do ((tail object (cdr tail))) ((not (consp tail)) nil) (let ((elt (car tail))) (circularp elt (cons object seen)))))))))) (circularp object nil))) (defun proper-list-p (object) "Returns true if OBJECT is a proper list." (cond ((not object) t) ((consp object) (do ((fast object (cddr fast)) (slow (cons (car object) (cdr object)) (cdr slow))) (nil) (unless (and (listp fast) (consp (cdr fast))) (return (and (listp fast) (not (cdr fast))))) (when (eq fast slow) (return nil)))) (t nil))) (deftype proper-list () "Type designator for proper lists. Implemented as a SATISFIES type, hence not recommended for performance intensive use. Main usefullness as a type designator of the expected type in a TYPE-ERROR." `(and list (satisfies proper-list-p))) (defun circular-list-error (list) (error 'type-error :datum list :expected-type '(and list (not circular-list)))) (macrolet ((def (name lambda-list doc step declare ret1 ret2) (assert (member 'list lambda-list)) `(defun ,name ,lambda-list ,doc (unless (listp list) (error 'type-error :datum list :expected-type 'list)) (do ((last list fast) (fast list (cddr fast)) (slow (cons (car list) (cdr list)) (cdr slow)) ,@(when step (list step))) (nil) (declare (dynamic-extent slow) ,@(when declare (list declare)) (ignorable last)) (when (safe-endp fast) (return ,ret1)) (when (safe-endp (cdr fast)) (return ,ret2)) (when (eq fast slow) (circular-list-error list)))))) (def proper-list-length (list) "Returns length of LIST, signalling an error if it is not a proper list." (n 1 (+ n 2)) ;; KLUDGE: Most implementations don't actually support lists with bignum ;; elements -- and this is WAY faster on most implementations then declaring ;; N to be an UNSIGNED-BYTE. (fixnum n) (1- n) n) (def lastcar (list) "Returns the last element of LIST. Signals a type-error if LIST is not a proper list." nil nil (cadr last) (car fast)) (def (setf lastcar) (object list) "Sets the last element of LIST. Signals a type-error if LIST is not a proper list." nil nil (setf (cadr last) object) (setf (car fast) object))) (defun make-circular-list (length &key initial-element) "Creates a circular list of LENGTH with the given INITIAL-ELEMENT." (let ((cycle (make-list length :initial-element initial-element))) (nconc cycle cycle))) (deftype circular-list () "Type designator for circular lists. Implemented as a SATISFIES type, so not recommended for performance intensive use. Main usefullness as the expected-type designator of a TYPE-ERROR." `(satisfies circular-list-p)) (defun ensure-car (thing) "If THING is a CONS, its CAR is returned. Otherwise THING is returned." (if (consp thing) (car thing) thing)) (defun ensure-cons (cons) "If CONS is a cons, it is returned. Otherwise returns a fresh cons with CONS in the car, and NIL in the cdr." (if (consp cons) cons (cons cons nil))) (defun ensure-list (list) "If LIST is a list, it is returned. Otherwise returns the list designated by LIST." (if (listp list) list (list list))) (defun remove-from-plist (plist &rest keys) "Returns a property-list with same keys and values as PLIST, except that keys in the list designated by KEYS and values corresponding to them are removed. The returned property-list may share structure with the PLIST, but PLIST is not destructively modified. Keys are compared using EQ." (declare (optimize (speed 3))) ;; FIXME: possible optimization: (remove-from-plist '(:x 0 :a 1 :b 2) :a) ;; could return the tail without consing up a new list. (loop for (key . rest) on plist by #'cddr do (assert rest () "Expected a proper plist, got ~S" plist) unless (member key keys :test #'eq) collect key and collect (first rest))) (defun delete-from-plist (plist &rest keys) "Just like REMOVE-FROM-PLIST, but this version may destructively modify the provided PLIST." (declare (optimize speed)) (loop with head = plist with tail = nil ; a nil tail means an empty result so far for (key . rest) on plist by #'cddr do (assert rest () "Expected a proper plist, got ~S" plist) (if (member key keys :test #'eq) ;; skip over this pair (let ((next (cdr rest))) (if tail (setf (cdr tail) next) (setf head next))) ;; keep this pair (setf tail rest)) finally (return head))) (define-modify-macro remove-from-plistf (&rest keys) remove-from-plist "Modify macro for REMOVE-FROM-PLIST.") (define-modify-macro delete-from-plistf (&rest keys) delete-from-plist "Modify macro for DELETE-FROM-PLIST.") (declaim (inline sans)) (defun sans (plist &rest keys) "Alias of REMOVE-FROM-PLIST for backward compatibility." (apply #'remove-from-plist plist keys)) (defun mappend (function &rest lists) "Applies FUNCTION to respective element(s) of each LIST, appending all the all the result list to a single list. FUNCTION must return a list." (loop for results in (apply #'mapcar function lists) append results)) (defun setp (object &key (test #'eql) (key #'identity)) "Returns true if OBJECT is a list that denotes a set, NIL otherwise. A list denotes a set if each element of the list is unique under KEY and TEST." (and (listp object) (let (seen) (dolist (elt object t) (let ((key (funcall key elt))) (if (member key seen :test test) (return nil) (push key seen))))))) (defun set-equal (list1 list2 &key (test #'eql) (key nil keyp)) "Returns true if every element of LIST1 matches some element of LIST2 and every element of LIST2 matches some element of LIST1. Otherwise returns false." (let ((keylist1 (if keyp (mapcar key list1) list1)) (keylist2 (if keyp (mapcar key list2) list2))) (and (dolist (elt keylist1 t) (or (member elt keylist2 :test test) (return nil))) (dolist (elt keylist2 t) (or (member elt keylist1 :test test) (return nil)))))) (defun map-product (function list &rest more-lists) "Returns a list containing the results of calling FUNCTION with one argument from LIST, and one from each of MORE-LISTS for each combination of arguments. In other words, returns the product of LIST and MORE-LISTS using FUNCTION. Example: (map-product 'list '(1 2) '(3 4) '(5 6)) => ((1 3 5) (1 3 6) (1 4 5) (1 4 6) (2 3 5) (2 3 6) (2 4 5) (2 4 6)) " (labels ((%map-product (f lists) (let ((more (cdr lists)) (one (car lists))) (if (not more) (mapcar f one) (mappend (lambda (x) (%map-product (curry f x) more)) one))))) (%map-product (ensure-function function) (cons list more-lists)))) (defun flatten (tree) "Traverses the tree in order, collecting non-null leaves into a list." (let (list) (labels ((traverse (subtree) (when subtree (if (consp subtree) (progn (traverse (car subtree)) (traverse (cdr subtree))) (push subtree list))))) (traverse tree)) (nreverse list)))
14,161
Common Lisp
.lisp
331
32.725076
85
0.583527
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
b0917d5d7eb37eb856182d858f6c3770cf935efef4aef671e1447c2a1eaf8061
42,571
[ -1 ]
42,574
macros.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/macros.lisp
(in-package :alexandria) (defmacro with-gensyms (names &body forms) "Binds a set of variables to gensyms and evaluates the implicit progn FORMS. Each element within NAMES is either a symbol SYMBOL or a pair (SYMBOL STRING-DESIGNATOR). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL STRING-DESIGNATOR) specifies that the variable named by SYMBOL should be bound to a symbol constructed using GENSYM with the string designated by STRING-DESIGNATOR being its first argument." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Alias for WITH-GENSYMS." `(with-gensyms ,names ,@forms)) (defmacro once-only (specs &body forms) "Constructs code whose primary goal is to help automate the handling of multiple evaluation within macros. Multiple evaluation is handled by introducing intermediate variables, in order to reuse the result of an expression. The returned value is a list of the form (let ((<gensym-1> <expr-1>) ... (<gensym-n> <expr-n>)) <res>) where GENSYM-1, ..., GENSYM-N are the intermediate variables introduced in order to evaluate EXPR-1, ..., EXPR-N once, only. RES is code that is the result of evaluating the implicit progn FORMS within a special context determined by SPECS. RES should make use of (reference) the intermediate variables. Each element within SPECS is either a symbol SYMBOL or a pair (SYMBOL INITFORM). Bare symbols are equivalent to the pair (SYMBOL SYMBOL). Each pair (SYMBOL INITFORM) specifies a single intermediate variable: - INITFORM is an expression evaluated to produce EXPR-i - SYMBOL is the name of the variable that will be bound around FORMS to the corresponding gensym GENSYM-i, in order for FORMS to generate RES that references the intermediate variable The evaluation of INITFORMs and binding of SYMBOLs resembles LET. INITFORMs of all the pairs are evaluated before binding SYMBOLs and evaluating FORMS. Example: The following expression (let ((x '(incf y))) (once-only (x) `(cons ,x ,x))) ;;; => ;;; (let ((#1=#:X123 (incf y))) ;;; (cons #1# #1#)) could be used within a macro to avoid multiple evaluation like so (defmacro cons1 (x) (once-only (x) `(cons ,x ,x))) (let ((y 0)) (cons1 (incf y))) ;;; => (1 . 1) Example: The following expression demonstrates the usage of the INITFORM field (let ((expr '(incf y))) (once-only ((var `(1+ ,expr))) `(list ',expr ,var ,var))) ;;; => ;;; (let ((#1=#:VAR123 (1+ (incf y)))) ;;; (list '(incf y) #1# #1)) which could be used like so (defmacro print-succ-twice (expr) (once-only ((var `(1+ ,expr))) `(format t \"Expr: ~s, Once: ~s, Twice: ~s~%\" ',expr ,var ,var))) (let ((y 10)) (print-succ-twice (incf y))) ;;; >> ;;; Expr: (INCF Y), Once: 12, Twice: 12" (let ((gensyms (make-gensym-list (length specs) "ONCE-ONLY")) (names-and-forms (mapcar (lambda (spec) (etypecase spec (list (destructuring-bind (name form) spec (cons name form))) (symbol (cons spec spec)))) specs))) ;; bind in user-macro `(let ,(mapcar (lambda (g n) (list g `(gensym ,(string (car n))))) gensyms names-and-forms) ;; bind in final expansion `(let (,,@(mapcar (lambda (g n) ``(,,g ,,(cdr n))) gensyms names-and-forms)) ;; bind in user-macro ,(let ,(mapcar (lambda (n g) (list (car n) g)) names-and-forms gensyms) ,@forms))))) (defun parse-body (body &key documentation whole) "Parses BODY into (values remaining-forms declarations doc-string). Documentation strings are recognized only if DOCUMENTATION is true. Syntax errors in body are signalled and WHOLE is used in the signal arguments when given." (let ((doc nil) (decls nil) (current nil)) (tagbody :declarations (setf current (car body)) (when (and documentation (stringp current) (cdr body)) (if doc (error "Too many documentation strings in ~S." (or whole body)) (setf doc (pop body))) (go :declarations)) (when (and (listp current) (eql (first current) 'declare)) (push (pop body) decls) (go :declarations))) (values body (nreverse decls) doc))) (defun parse-ordinary-lambda-list (lambda-list &key (normalize t) allow-specializers (normalize-optional normalize) (normalize-keyword normalize) (normalize-auxilary normalize)) "Parses an ordinary lambda-list, returning as multiple values: 1. Required parameters. 2. Optional parameter specifications, normalized into form: (name init suppliedp) 3. Name of the rest parameter, or NIL. 4. Keyword parameter specifications, normalized into form: ((keyword-name name) init suppliedp) 5. Boolean indicating &ALLOW-OTHER-KEYS presence. 6. &AUX parameter specifications, normalized into form (name init). 7. Existence of &KEY in the lambda-list. Signals a PROGRAM-ERROR is the lambda-list is malformed." (let ((state :required) (allow-other-keys nil) (auxp nil) (required nil) (optional nil) (rest nil) (keys nil) (keyp nil) (aux nil)) (labels ((fail (elt) (simple-program-error "Misplaced ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (check-variable (elt what &optional (allow-specializers allow-specializers)) (unless (and (or (symbolp elt) (and allow-specializers (consp elt) (= 2 (length elt)) (symbolp (first elt)))) (not (constantp elt))) (simple-program-error "Invalid ~A ~S in ordinary lambda-list:~% ~S" what elt lambda-list))) (check-spec (spec what) (destructuring-bind (init suppliedp) spec (declare (ignore init)) (check-variable suppliedp what nil)))) (dolist (elt lambda-list) (case elt (&optional (if (eq state :required) (setf state elt) (fail elt))) (&rest (if (member state '(:required &optional)) (setf state elt) (fail elt))) (&key (if (member state '(:required &optional :after-rest)) (setf state elt) (fail elt)) (setf keyp t)) (&allow-other-keys (if (eq state '&key) (setf allow-other-keys t state elt) (fail elt))) (&aux (cond ((eq state '&rest) (fail elt)) (auxp (simple-program-error "Multiple ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (t (setf auxp t state elt)) )) (otherwise (when (member elt '#.(set-difference lambda-list-keywords '(&optional &rest &key &allow-other-keys &aux))) (simple-program-error "Bad lambda-list keyword ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (case state (:required (check-variable elt "required parameter") (push elt required)) (&optional (cond ((consp elt) (destructuring-bind (name &rest tail) elt (check-variable name "optional parameter") (cond ((cdr tail) (check-spec tail "optional-supplied-p parameter")) ((and normalize-optional tail) (setf elt (append elt '(nil)))) (normalize-optional (setf elt (append elt '(nil nil))))))) (t (check-variable elt "optional parameter") (when normalize-optional (setf elt (cons elt '(nil nil)))))) (push (ensure-list elt) optional)) (&rest (check-variable elt "rest parameter") (setf rest elt state :after-rest)) (&key (cond ((consp elt) (destructuring-bind (var-or-kv &rest tail) elt (cond ((consp var-or-kv) (destructuring-bind (keyword var) var-or-kv (unless (symbolp keyword) (simple-program-error "Invalid keyword name ~S in ordinary ~ lambda-list:~% ~S" keyword lambda-list)) (check-variable var "keyword parameter"))) (t (check-variable var-or-kv "keyword parameter") (when normalize-keyword (setf var-or-kv (list (make-keyword var-or-kv) var-or-kv))))) (cond ((cdr tail) (check-spec tail "keyword-supplied-p parameter")) ((and normalize-keyword tail) (setf tail (append tail '(nil)))) (normalize-keyword (setf tail '(nil nil)))) (setf elt (cons var-or-kv tail)))) (t (check-variable elt "keyword parameter") (setf elt (if normalize-keyword (list (list (make-keyword elt) elt) nil nil) elt)))) (push elt keys)) (&aux (if (consp elt) (destructuring-bind (var &optional init) elt (declare (ignore init)) (check-variable var "&aux parameter")) (progn (check-variable elt "&aux parameter") (setf elt (list* elt (when normalize-auxilary '(nil)))))) (push elt aux)) (t (simple-program-error "Invalid ordinary lambda-list:~% ~S" lambda-list))))))) (values (nreverse required) (nreverse optional) rest (nreverse keys) allow-other-keys (nreverse aux) keyp))) ;;;; DESTRUCTURING-*CASE (defun expand-destructuring-case (key clauses case) (once-only (key) `(if (typep ,key 'cons) (,case (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case ,key)))) (defmacro destructuring-case (keyform &body clauses) "DESTRUCTURING-CASE, -CCASE, and -ECASE are a combination of CASE and DESTRUCTURING-BIND. KEYFORM must evaluate to a CONS. Clauses are of the form: ((CASE-KEYS . DESTRUCTURING-LAMBDA-LIST) FORM*) The clause whose CASE-KEYS matches CAR of KEY, as if by CASE, CCASE, or ECASE, is selected, and FORMs are then executed with CDR of KEY is destructured and bound by the DESTRUCTURING-LAMBDA-LIST. Example: (defun dcase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)) ((t &rest rest) (format nil \"unknown: ~S\" rest)))) (dcase (list :foo 1 2)) ; => \"foo: 1, 2\" (dcase (list :bar :a 1 :b 2)) ; => \"bar: 1, 2\" (dcase (list :alt1 1)) ; => \"alt: 1\" (dcase (list :alt2 2)) ; => \"alt: 2\" (dcase (list :quux 1 2 3)) ; => \"unknown: 1, 2, 3\" (defun decase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar: ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)))) (decase (list :foo 1 2)) ; => \"foo: 1, 2\" (decase (list :bar :a 1 :b 2)) ; => \"bar: 1, 2\" (decase (list :alt1 1)) ; => \"alt: 1\" (decase (list :alt2 2)) ; => \"alt: 2\" (decase (list :quux 1 2 3)) ; =| error " (expand-destructuring-case keyform clauses 'case)) (defmacro destructuring-ccase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ccase)) (defmacro destructuring-ecase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ecase)) (dolist (name '(destructuring-ccase destructuring-ecase)) (setf (documentation name 'function) (documentation 'destructuring-case 'function)))
13,999
Common Lisp
.lisp
311
32.064309
96
0.529092
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a224d72a89d0fcdbd32d33a5b9a0a2ebcc4766313226a467d46e25200ae53ad3
42,574
[ 126417 ]
42,575
ci-test.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/scripts/ci-test.lisp
;; Install all the deps (ql:quickload "alexandria/tests") ;; Run the tests! (asdf:test-system "alexandria")
109
Common Lisp
.lisp
4
26
33
0.75
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
16fed17d90b9079944a6c18240faf31fe63e48309f2a6e46b804dbc604b967ac
42,575
[ -1 ]
42,576
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/package.lisp
(in-package :cl-user) (defpackage :alexandria-2 (:nicknames :alexandria.2) (:use :cl :alexandria.1.0.0) #+sb-package-locks (:lock t) (:export ;; arrays #:dim-in-bounds-p #:row-major-index #:rmajor-to-indices ;; lists #:delete-from-plist* ;; control-flow #:line-up-first #:line-up-last #:subseq* . #. (let (res) (do-external-symbols (sym :alexandria.1.0.0) (push sym res)) res) ))
427
Common Lisp
.lisp
19
19
85
0.625
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
6f966d7cff3360008d32af0aa3d1b49aa9ac7993b1690697f9c0bb97f070210c
42,576
[ -1 ]
42,577
sequences.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/sequences.lisp
(in-package :alexandria-2) (defun subseq* (sequence start &optional end) "Like SUBSEQ, but limits END to the length." (subseq sequence start (if end (min end (length sequence)))))
211
Common Lisp
.lisp
6
29
46
0.653465
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
2ea1038f64e06b03fda40adc8ae2e47428c14d690246bbfdcf268eb810a9bb86
42,577
[ -1 ]
42,578
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/tests.lisp
(in-package :cl-user) (defpackage :alexandria-2/tests (:use :cl :alexandria-2 #+sbcl :sb-rt #-sbcl :rtest) (:import-from #+sbcl :sb-rt #-sbcl :rtest #:*compile-tests* #:*expected-failures*)) (in-package :alexandria-2/tests) ;; Arrays Tests (deftest dim-in-bounds-p.0 (dim-in-bounds-p '(2 2) 0 1 1) nil) (deftest dim-in-bounds-p.1 (dim-in-bounds-p '(2 2) 0 1) t) (deftest dim-in-bounds-p.2 (dim-in-bounds-p '(2 2) 0 2) nil) (deftest row-major-index.0 (let* ((dims '(4 3 2 1)) (test-arr (make-array dims)) (idcs '(0 0 0 0))) (= 0 (apply #'row-major-index dims idcs) (apply #'array-row-major-index test-arr idcs))) t) (deftest row-major-index.1 (let* ((dims '(4 3 2 1)) (test-arr (make-array dims)) (idcs '(3 2 1 0))) (= 23 (apply #'row-major-index dims idcs) (apply #'array-row-major-index test-arr idcs))) t) (deftest row-major-index.2 (let* ((dims '(4 3 2 1)) (test-arr (make-array dims)) (idcs '(2 1 0 0))) (= 14 (apply #'row-major-index dims idcs) (apply #'array-row-major-index test-arr idcs))) t) (deftest row-major-index.3 (let* ((dims '(4 3 2 1)) (test-arr (make-array dims)) (idcs '(0 2 1 0))) (= 5 (apply #'row-major-index dims idcs) (apply #'array-row-major-index test-arr idcs))) t) (deftest rmajor-to-indices.0 (loop for dims in '((70 30 4 2) (50 200 5 7) (5 4 300 2) (5 2 30 19)) with index = 173 with indices = '(4 0 3 1) always (and (= index (apply #'row-major-index dims (rmajor-to-indices dims index))) (equalp indices (rmajor-to-indices dims (apply #'row-major-index dims indices))))) t) ;; List Tests (deftest delete-from-plist*.middle (let ((input (list 'a 1 'b 2 'c 3 'd 4 'd 5))) (multiple-value-list (delete-from-plist* input 'b 'c))) ((a 1 d 4 d 5) ((c . 3) (b . 2)))) (deftest delete-from-plist*.start (let ((input (list 'a 1 'b 2 'c 3 'd 4 'd 5))) (multiple-value-list (delete-from-plist* input 'a 'c))) ((b 2 d 4 d 5) ((c . 3) (a . 1)))) ;; Control Flow tests (deftest line-up-first.no-form (values (equal (macroexpand '(line-up-first 5)) 5) (equal (macroexpand '(line-up-first (+ 1 2))) '(+ 1 2))) t t) (deftest line-up-first.function-names-are-threaded (values (equal (macroexpand '(line-up-first 5 -)) '(- 5)) (equal (macroexpand '(line-up-first (+ 1 2) -)) '(- (+ 1 2)))) t t) (deftest line-up-first.list-promotion (macroexpand '(line-up-first 5 (+ 20) (/ 25) - (+ 40))) (+ (- (/ (+ 5 20) 25)) 40) t) (deftest line-up-first.multiple-args (macroexpand '(line-up-first "this-is-a-string" (subseq 0 4))) (subseq "this-is-a-string" 0 4) t) (deftest line-up-first.several-examples (values (equal (line-up-first (+ 40 2)) 42) (equal (line-up-first 5 (+ 20) (/ 25) - (+ 40)) 39) (equal (line-up-first "this-is-a-string" (subseq 4 5) (string-trim "--------good")) "good")) t t t) ;; Thread last tests (deftest line-up-last.no-forms (values (equal (macroexpand '(line-up-last 5)) 5) (equal (macroexpand '(line-up-last (+ 1 2))) '(+ 1 2))) t t) (deftest line-up-last.function-names-are-threaded (values (equal (macroexpand '(line-up-last 5 -)) '(- 5)) (equal (macroexpand '(line-up-last (+ 1 2) -)) '(- (+ 1 2)))) t t) (deftest line-up-last.lisp-promotion (macroexpand '(line-up-last 5 (+ 20) (/ 25) - (+ 40))) (+ 40 (- (/ 25 (+ 20 5)))) t) (deftest line-up-last.several-examples (values (equal (line-up-last (+ 40 2)) 42) (equal (line-up-last 5 (+ 20) (/ 25) - (+ 40)) 39) (equal (line-up-last (list 1 -2 3 -4 5) (mapcar #'abs) (reduce #'+) (format nil "abs sum is: ~D")) "abs sum is: 15")) t t t) (deftest subseq*.1 (values (subseq* "abcdef" 0 3) (subseq* "abcdef" 1 3) (subseq* "abcdef" 1) (subseq* "abcdef" 1 9)) "abc" "bc" "bcdef" "bcdef")
4,849
Common Lisp
.lisp
162
21.012346
99
0.478755
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
4716b8882876e4743dbd58104f12a56ef4da1ec092f707d40557cf5b50b534a0
42,578
[ -1 ]
42,579
control-flow.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/control-flow.lisp
(in-package :alexandria-2) (defun line-up-iter (thread-first-p acc forms) "Iterative implementation for `thread-iter'. The THREAD-FIRST-P decides where to thread the FORMS, accumulating in ACC." (if forms (line-up-iter thread-first-p (let ((form (car forms))) (if (listp form) (if thread-first-p (apply #'list (car form) acc (cdr form)) (append form (cons acc nil))) (list form acc))) (cdr forms)) acc)) (defmacro line-up-first (&rest forms) "Lines up FORMS elements as the first argument of their successor. Example: (line-up-first 5 (+ 20) / (+ 40)) is equivalent to: (+ (/ (+ 5 20)) 40) Note how the single '/ got converted into a list before threading." (line-up-iter t (car forms) (cdr forms))) (defmacro line-up-last (&rest forms) "Lines up FORMS elements as the last argument of their successor. Example: (line-up-last 5 (+ 20) / (+ 40)) is equivalent to: (+ 40 (/ (+ 20 5))) Note how the single '/ got converted into a list before threading." (line-up-iter nil (car forms) (cdr forms)))
1,229
Common Lisp
.lisp
40
23.875
75
0.588785
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
213c7b6d0e0acac76a12a40e420d4c1c3691ee361d430dc3e40fab270b06485f
42,579
[ -1 ]
42,580
lists.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/lists.lisp
(in-package :alexandria-2) (defun delete-from-plist* (plist &rest keys) "Just like REMOVE-FROM-PLIST, but this version may destructively modify the provided PLIST. The second return value is an alist of the removed items, in unspecified order." ;; TODO: a plist? (declare (optimize speed)) (loop with head = plist with tail = nil ; a nil tail means an empty result so far with kept = () for (key . rest) on plist by #'cddr do (assert rest () "Expected a proper plist, got ~S" plist) (if (member key keys :test #'eq) ;; skip over this pair (let ((next (cdr rest))) (push (cons key (car rest)) kept) (if tail (setf (cdr tail) next) (setf head next))) ;; keep this pair (setf tail rest)) finally (return (values head kept))))
944
Common Lisp
.lisp
23
30.521739
80
0.554348
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
1ab748a8b76bdc36cbe6f443383da670040b1c28ccab61df30e04ae280ec8e0d
42,580
[ -1 ]
42,581
arrays.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-2/arrays.lisp
(in-package :alexandria-2) (defun dim-in-bounds-p (dimensions &rest subscripts) "Mirrors cl:array-in-bounds-p, but takes dimensions (list of integers) as its first argument instead of an array. (array-in-bounds-p arr ...) == (dim-in-bounds-p (array-dimensions arr) ...)" (and (= (length dimensions) (length subscripts)) (every (lambda (i d) (and (integerp i) (< -1 i d))) subscripts dimensions))) (defun row-major-index (dimensions &rest subscripts) "Mirrors cl:array-row-major-index, but takes dimensions (list of integers) as its first argument instead of an array. Signals an error if lengths of dimensions and subscripts are not equal (array-row-major-index arr ...) == (row-major-index (array-dimensions arr) ...)" (unless (apply #'dim-in-bounds-p dimensions subscripts) (error (format nil "Indices ~a invalid for dimensions ~a" subscripts dimensions))) (loop with word-idx = 0 with dimprod = 1 for dim-size in (reverse dimensions) for dim-idx in (reverse subscripts) do (incf word-idx (* dim-idx dimprod)) (setf dimprod (* dimprod dim-size)) finally (return word-idx))) (defun rmajor-to-indices (dimensions index) "The inverse function to row-major-index. Given a set of dimensions and a row-major index, produce the list of indices <subscripts> such that (row-major-index dimensions sucscripts) = index" (when (null dimensions) (error "Dimensions must be non-null")) (let ((size (reduce #'* dimensions))) (unless (< -1 index size) (error (format nil "Row-major index ~a invalid for array of total size ~a" index size)))) (labels ((rec (dimensions index word-sizes acc) (if (null (cdr dimensions)) (reverse (cons index acc)) (multiple-value-bind (idx remainder) (floor index (car word-sizes)) (rec (cdr dimensions) remainder (cdr word-sizes) (cons idx acc)))))) (rec dimensions index (cdr (reduce (lambda (x y) (cons (* x (car y)) y)) dimensions :initial-value '(1) :from-end t)) nil)))
2,142
Common Lisp
.lisp
40
46.325
95
0.654121
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
f0c715a2921b168a33e331eabd399750cf696974f2278b4b42f37a6092f563f0
42,581
[ -1 ]
42,582
encode.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-base64-20201016-git/encode.lisp
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: encode.lisp ;;;; Purpose: cl-base64 encoding routines ;;;; Programmer: Kevin M. Rosenberg ;;;; Date Started: Dec 2002 ;;;; ;;;; $Id$ ;;;; ;;;; This file implements the Base64 transfer encoding algorithm as ;;;; defined in RFC 1521 by Borensten & Freed, September 1993. ;;;; See: http://www.ietf.org/rfc/rfc1521.txt ;;;; ;;;; Based on initial public domain code by Juri Pakaste <[email protected]> ;;;; ;;;; Copyright 2002-2003 Kevin M. Rosenberg ;;;; Permission to use with BSD-style license included in the COPYING file ;;;; ************************************************************************* ;;;; Extended by Kevin M. Rosenberg <[email protected]>: ;;;; - .asd file ;;;; - numerous speed optimizations ;;;; - conversion to and from integers ;;;; - Renamed functions now that supporting integer conversions ;;;; - URI-compatible encoding using :uri key ;;;; ;;;; $Id$ (in-package #:cl-base64) (defun round-next-multiple (x n) "Round x up to the next highest multiple of n." (declare (fixnum n) (optimize (speed 3) (safety 1) (space 0))) (let ((remainder (mod x n))) (declare (fixnum remainder)) (if (zerop remainder) x (the fixnum (+ x (the fixnum (- n remainder))))))) (defmacro def-*-to-base64-* (input-type output-type) `(defun ,(intern (concatenate 'string (symbol-name input-type) (symbol-name :-to-base64-) (symbol-name output-type))) (input ,@(when (eq output-type :stream) '(output)) &key (uri nil) (columns 0)) "Encode a string array to base64. If columns is > 0, designates maximum number of columns in a line and the string will be terminated with a #\Newline." (declare ,@(case input-type (:string '((string input))) (:usb8-array '((type (array (unsigned-byte 8) (*)) input)))) (fixnum columns) (optimize (speed 3) (safety 1) (space 0))) (let ((pad (if uri *uri-pad-char* *pad-char*)) (encode-table (if uri *uri-encode-table* *encode-table*))) (declare (simple-string encode-table) (character pad)) (let* ((string-length (length input)) (complete-group-count (truncate string-length 3)) (remainder (nth-value 1 (truncate string-length 3))) (padded-length (* 4 (truncate (+ string-length 2) 3))) ,@(when (eq output-type :string) '((num-lines (if (plusp columns) (truncate (+ padded-length (1- columns)) columns) 0)) (num-breaks (if (plusp num-lines) (1- num-lines) 0)) (strlen (+ padded-length num-breaks)) (result (make-string strlen)) (ioutput 0))) (col (if (plusp columns) 0 (the fixnum (1+ padded-length))))) (declare (fixnum string-length padded-length col ,@(when (eq output-type :string) '(ioutput))) ,@(when (eq output-type :string) '((simple-string result)))) (labels ((output-char (ch) (if (= col columns) (progn ,@(case output-type (:stream '((write-char #\Newline output))) (:string '((setf (schar result ioutput) #\Newline) (incf ioutput)))) (setq col 1)) (incf col)) ,@(case output-type (:stream '((write-char ch output))) (:string '((setf (schar result ioutput) ch) (incf ioutput))))) (output-group (svalue chars) (declare (fixnum svalue chars)) (output-char (schar encode-table (the fixnum (logand #x3f (the fixnum (ash svalue -18)))))) (output-char (schar encode-table (the fixnum (logand #x3f (the fixnum (ash svalue -12)))))) (if (> chars 2) (output-char (schar encode-table (the fixnum (logand #x3f (the fixnum (ash svalue -6)))))) (output-char pad)) (if (> chars 3) (output-char (schar encode-table (the fixnum (logand #x3f svalue)))) (output-char pad)))) (do ((igroup 0 (the fixnum (1+ igroup))) (isource 0 (the fixnum (+ isource 3)))) ((= igroup complete-group-count) (cond ((= remainder 2) (output-group (the fixnum (+ (the fixnum (ash ,(case input-type (:string '(char-code (the character (char input isource)))) (:usb8-array '(the fixnum (aref input isource)))) 16)) (the fixnum (ash ,(case input-type (:string '(char-code (the character (char input (the fixnum (1+ isource)))))) (:usb8-array '(the fixnum (aref input (the fixnum (1+ isource)))))) 8)))) 3)) ((= remainder 1) (output-group (the fixnum (ash ,(case input-type (:string '(char-code (the character (char input isource)))) (:usb8-array '(the fixnum (aref input isource)))) 16)) 2))) ,(case output-type (:string 'result) (:stream 'output))) (declare (fixnum igroup isource)) (output-group (the fixnum (+ (the fixnum (ash (the fixnum ,(case input-type (:string '(char-code (the character (char input isource)))) (:usb8-array '(aref input isource)))) 16)) (the fixnum (ash (the fixnum ,(case input-type (:string '(char-code (the character (char input (the fixnum (1+ isource)))))) (:usb8-array '(aref input (1+ isource))))) 8)) (the fixnum ,(case input-type (:string '(char-code (the character (char input (the fixnum (+ 2 isource)))))) (:usb8-array '(aref input (+ 2 isource)))) ))) 4))))))) (def-*-to-base64-* :string :string) (def-*-to-base64-* :string :stream) (def-*-to-base64-* :usb8-array :string) (def-*-to-base64-* :usb8-array :stream) (defun integer-to-base64-string (input &key (uri nil) (columns 0)) "Encode an integer to base64 format." (declare (integer input) (fixnum columns) (optimize (speed 3) (space 0) (safety 1))) (let ((pad (if uri *uri-pad-char* *pad-char*)) (encode-table (if uri *uri-encode-table* *encode-table*))) (declare (simple-string encode-table) (character pad)) (let* ((input-bits (integer-length input)) (byte-bits (round-next-multiple input-bits 8)) (padded-bits (round-next-multiple byte-bits 6)) (remainder-padding (mod padded-bits 24)) (padding-bits (if (zerop remainder-padding) 0 (- 24 remainder-padding))) (padding-chars (/ padding-bits 6)) (padded-length (/ (+ padded-bits padding-bits) 6)) (last-line-len (if (plusp columns) (- padded-length (* columns (truncate padded-length columns))) 0)) (num-lines (if (plusp columns) (truncate (+ padded-length (1- columns)) columns) 0)) (num-breaks (if (plusp num-lines) (1- num-lines) 0)) (strlen (+ padded-length num-breaks)) (last-char (1- strlen)) (str (make-string strlen)) (col (if (zerop last-line-len) columns last-line-len))) (declare (fixnum padded-length num-lines col last-char padding-chars last-line-len)) (unless (plusp columns) (setq col -1)) ;; set to flag to optimize in loop (dotimes (i padding-chars) (declare (fixnum i)) (setf (schar str (the fixnum (- last-char i))) pad)) (do* ((strpos (- last-char padding-chars) (1- strpos)) (int (ash input (/ padding-bits 3)))) ((minusp strpos) str) (declare (fixnum strpos) (integer int)) (cond ((zerop col) (setf (schar str strpos) #\Newline) (setq col columns)) (t (setf (schar str strpos) (schar encode-table (the fixnum (logand int #x3f)))) (setq int (ash int -6)) (decf col))))))) (defun integer-to-base64-stream (input stream &key (uri nil) (columns 0)) "Encode an integer to base64 format." (declare (integer input) (fixnum columns) (optimize (speed 3) (space 0) (safety 1))) (let ((pad (if uri *uri-pad-char* *pad-char*)) (encode-table (if uri *uri-encode-table* *encode-table*))) (declare (simple-string encode-table) (character pad)) (let* ((input-bits (integer-length input)) (byte-bits (round-next-multiple input-bits 8)) (padded-bits (round-next-multiple byte-bits 6)) (remainder-padding (mod padded-bits 24)) (padding-bits (if (zerop remainder-padding) 0 (- 24 remainder-padding))) (padding-chars (/ padding-bits 6)) (padded-length (/ (+ padded-bits padding-bits) 6)) (strlen padded-length) (nonpad-chars (- strlen padding-chars)) (last-nonpad-char (1- nonpad-chars)) (str (make-string strlen))) (declare (fixnum padded-length last-nonpad-char)) (do* ((strpos 0 (the fixnum (1+ strpos))) (int (ash input (/ padding-bits 3)) (ash int -6)) (6bit-value (the fixnum (logand int #x3f)) (the fixnum (logand int #x3f)))) ((= strpos nonpad-chars) (let ((col 0)) (declare (fixnum col)) (dotimes (i nonpad-chars) (declare (fixnum i)) (write-char (schar str i) stream) (when (plusp columns) (incf col) (when (= col columns) (write-char #\Newline stream) (setq col 0)))) (dotimes (ipad padding-chars) (declare (fixnum ipad)) (write-char pad stream) (when (plusp columns) (incf col) (when (= col columns) (write-char #\Newline stream) (setq col 0))))) stream) (declare (fixnum 6bit-value strpos) (integer int)) (setf (schar str (- last-nonpad-char strpos)) (schar encode-table 6bit-value)) ))))
13,400
Common Lisp
.lisp
311
25.842444
95
0.425906
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
ddcf9c0af0e1efeb4ad629f8336db131c17b1bc4efb4f2452315e1a8116aee14
42,582
[ -1 ]
42,583
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-base64-20201016-git/package.lisp
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: package.lisp ;;;; Purpose: Package definition for cl-base64 ;;;; Programmer: Kevin M. Rosenberg ;;;; Date Started: Dec 2002 ;;;; ;;;; $Id$ ;;;; ;;;; ************************************************************************* (defpackage #:cl-base64 (:nicknames #:base64) (:use #:cl) (:export #:base64-stream-to-integer #:base64-stream-to-string #:base64-stream-to-stream #:base64-stream-to-usb8-array #:base64-string-to-integer #:base64-string-to-string #:base64-string-to-stream #:base64-string-to-usb8-array #:string-to-base64-string #:string-to-base64-stream #:usb8-array-to-base64-string #:usb8-array-to-base64-stream #:stream-to-base64-string #:stream-to-base64-stream #:integer-to-base64-string #:integer-to-base64-stream ;; Conditions. #:base64-error #:bad-base64-character #:incomplete-base64-data ;; For creating custom encode/decode tables. #:make-decode-table #:+decode-table+ #:+uri-decode-table+ ;; What's the point of exporting these? #:*uri-encode-table* #:*uri-decode-table* )) (in-package #:cl-base64) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *encode-table* "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") (declaim (type simple-string *encode-table*)) (defvar *uri-encode-table* "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") (declaim (type simple-string *uri-encode-table*)) (defvar *pad-char* #\=) (defvar *uri-pad-char* #\.) (declaim (type character *pad-char* *uri-pad-char*)) (deftype decode-table () '(simple-array (signed-byte 8) (128))) (defun make-decode-table (encode-table pad-char &key (whitespace-chars '(#\Linefeed #\Return #\Space #\Tab))) (assert (< (length encode-table) 128) (encode-table) "Encode table too big: ~S" encode-table) (let ((dt (make-array 128 :element-type '(signed-byte 8) :initial-element -1))) (declare (type decode-table dt)) (loop for char across encode-table for index upfrom 0 do (setf (aref dt (char-code char)) index)) (setf (aref dt (char-code pad-char)) -2) (loop for char in whitespace-chars do (setf (aref dt (char-code char)) -3)) dt))) (defconstant +decode-table+ (if (boundp '+decode-table+) (symbol-value '+decode-table+) (make-decode-table *encode-table* *pad-char*))) (defvar *decode-table* +decode-table+ "Deprecated.") (declaim (type decode-table +decode-table+ *decode-table*)) (defconstant +uri-decode-table+ (if (boundp '+uri-decode-table+) (symbol-value '+uri-decode-table+) (make-decode-table *uri-encode-table* *uri-pad-char*))) (defvar *uri-decode-table* +uri-decode-table+ "Deprecated.") (declaim (type decode-table +uri-decode-table+ *uri-decode-table*))
3,332
Common Lisp
.lisp
83
32.650602
78
0.579191
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
dca3bbcffca967ce51178b39dd6ed36a5cb6c00845fcf97510032b9c0d515d1c
42,583
[ 458187 ]
42,584
decode.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-base64-20201016-git/decode.lisp
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: encode.lisp ;;;; Purpose: cl-base64 encoding routines ;;;; Programmer: Kevin M. Rosenberg ;;;; Date Started: Dec 2002 ;;;; ;;;; $Id$ ;;;; ;;;; This file implements the Base64 transfer encoding algorithm as ;;;; defined in RFC 1521 by Borensten & Freed, September 1993. ;;;; See: http://www.ietf.org/rfc/rfc1521.txt ;;;; ;;;; Based on initial public domain code by Juri Pakaste <[email protected]> ;;;; ;;;; Copyright 2002-2003 Kevin M. Rosenberg ;;;; Permission to use with BSD-style license included in the COPYING file ;;;; ************************************************************************* (in-package #:cl-base64) (define-condition base64-error (error) ((input :initarg :input :reader base64-error-input) (position :initarg :position :reader base64-error-position :type unsigned-byte))) (define-condition bad-base64-character (base64-error) ((code :initarg :code :reader bad-base64-character-code)) (:report (lambda (condition stream) (format stream "Bad character ~S at index ~D of ~S" (code-char (bad-base64-character-code condition)) (base64-error-position condition) (base64-error-input condition))))) (define-condition incomplete-base64-data (base64-error) () (:report (lambda (condition stream) (format stream "Unexpected end of Base64 data at index ~D of ~S" (base64-error-position condition) (base64-error-input condition))))) (deftype array-index (&optional (length array-dimension-limit)) `(integer 0 (,length))) (deftype array-length (&optional (length array-dimension-limit)) `(integer 0 ,length)) (deftype character-code () `(integer 0 (,char-code-limit))) (defmacro etypecase/unroll ((var &rest types) &body body) #+sbcl `(etypecase ,var ,@(loop for type in types collect `(,type ,@body))) #-sbcl `(locally (declare (type (or ,@types) ,var)) ,@body)) (defmacro let/typed ((&rest vars) &body body) `(let ,(loop for (var value) in vars collect (list var value)) (declare ,@(loop for (var nil type) in vars when type collect (list 'type type var))) ,@body)) (defmacro define-base64-decoder (hose sink) `(defun ,(intern (format nil "~A-~A-~A-~A" '#:base64 hose '#:to sink)) (input &key (table +decode-table+) (uri nil) ,@(when (eq sink :stream) `(stream)) (whitespace :ignore)) ,(format nil "~ Decode Base64 ~(~A~) to ~(~A~). TABLE is the decode table to use. Two decode tables are provided: +DECODE-TABLE+ (used by default) and +URI-DECODE-TABLE+. See MAKE-DECODE-TABLE. For backwards-compatibility the URI parameter is supported. If it is true, then +URI-DECODE-TABLE+ is used, and the value for TABLE parameter is ignored. WHITESPACE can be one of: :ignore - Whitespace characters are ignored (default). :signal - Signal a BAD-BASE64-CHARACTER condition using SIGNAL. :error - Signal a BAD-BASE64-CHARACTER condition using ERROR." hose sink) (declare (optimize (speed 3) (safety 1)) (type decode-table table) (type ,(ecase hose (:stream 'stream) (:string 'string)) input)) (let/typed ((decode-table (if uri +uri-decode-table+ table) decode-table) ,@(ecase sink (:stream) (:usb8-array (ecase hose (:stream `((result (make-array 1024 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0) (array (unsigned-byte 8) (*))))) (:string `((result (make-array (* 3 (ceiling (length input) 4)) :element-type '(unsigned-byte 8)) (simple-array (unsigned-byte 8) (*))) (rpos 0 array-index))))) (:string (case hose (:stream `((result (make-array 1024 :element-type 'character :adjustable t :fill-pointer 0) (array character (*))))) (:string `((result (make-array (* 3 (ceiling (length input) 4)) :element-type 'character) (simple-array character (*))) (rpos 0 array-index))))) (:integer `((result 0 unsigned-byte))))) (flet ((bad-char (pos code &optional (action :error)) (let ((args (list 'bad-base64-character :input input :position pos :code code))) (ecase action (:error (apply #'error args)) (:cerror (apply #'cerror "Ignore the error and continue." args)) (:signal (apply #'signal args))))) (incomplete-input (pos) (error 'incomplete-base64-data :input input :position pos))) ,(let ((body `(let/typed ((ipos 0 array-index) (bitstore 0 (unsigned-byte 24)) (bitcount 0 (integer 0 14)) (svalue -1 (signed-byte 8)) (padchar 0 (integer 0 3)) (code 0 fixnum)) (loop ,@(ecase hose (:string `((if (< ipos length) (setq code (char-code (aref input ipos))) (return)))) (:stream `((let ((char (read-char input nil nil))) (if char (setq code (char-code char)) (return)))))) (cond ((or (< 127 code) (= -1 (setq svalue (aref decode-table code)))) (bad-char ipos code)) ((= -2 svalue) (cond ((<= (incf padchar) 2) (unless (<= 2 bitcount) (bad-char ipos code)) (decf bitcount 2)) (t (bad-char ipos code)))) ((= -3 svalue) (ecase whitespace (:ignore ;; Do nothing. ) (:error (bad-char ipos code :error)) (:signal (bad-char ipos code :signal)))) ((not (zerop padchar)) (bad-char ipos code)) (t (setf bitstore (logior (the (unsigned-byte 24) (ash bitstore 6)) svalue)) (incf bitcount 6) (when (>= bitcount 8) (decf bitcount 8) (let ((byte (logand (the (unsigned-byte 24) (ash bitstore (- bitcount))) #xFF))) (declare (type (unsigned-byte 8) byte)) ,@(ecase sink (:usb8-array (ecase hose (:string `((setf (aref result rpos) byte) (incf rpos))) (:stream `((vector-push-extend byte result))))) (:string (ecase hose (:string `((setf (schar result rpos) (code-char byte)) (incf rpos))) (:stream `((vector-push-extend (code-char byte) result))))) (:integer `((setq result (logior (ash result 8) byte)))) (:stream '((write-char (code-char byte) stream))))) (setf bitstore (logand bitstore #xFF))))) (incf ipos)) (unless (zerop bitcount) (incomplete-input ipos)) ,(ecase sink ((:string :usb8-array) (ecase hose (:string `(if (= rpos (length result)) result (subseq result 0 rpos))) (:stream `(copy-seq result)))) (:integer 'result) (:stream 'stream))))) (ecase hose (:string `(let ((length (length input))) (declare (type array-length length)) (etypecase/unroll (input simple-base-string simple-string string) ,body))) (:stream body))))))) (define-base64-decoder :string :usb8-array) (define-base64-decoder :string :string) (define-base64-decoder :string :integer) (define-base64-decoder :string :stream) (define-base64-decoder :stream :usb8-array) (define-base64-decoder :stream :string) (define-base64-decoder :stream :integer) (define-base64-decoder :stream :stream) ;; input-mode can be :string or :stream ;; input-format can be :character or :usb8
11,324
Common Lisp
.lisp
243
25.946502
83
0.399855
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
77e850ac219adfe365bfbb04f31760d6908f0ff1317876c94d65a0b3de4b3540
42,584
[ 254678 ]
42,585
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/cl-base64-20201016-git/tests.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*- ;;;; ************************************************************************* ;;;; FILE IDENTIFICATION ;;;; ;;;; Name: test.lisp ;;;; Purpose: Regression tests for cl-base64 ;;;; Programmer: Kevin M. Rosenberg ;;;; Date Started: Jan 2003 ;;;; ;;;; $Id$ ;;;; ************************************************************************* (in-package #:cl-user) (defpackage #:cl-base64/test (:use #:cl #:kmrcl #:cl-base64 #:ptester)) (in-package #:cl-base64/test) (defun test-valid-input (exp input) (test exp (base64-string-to-usb8-array input) :test #'equalp)) (defun test-broken-input (arg) (let ((.hole. (make-broadcast-stream))) (test-error (base64-string-to-usb8-array arg) :condition-type 'base64-error :include-subtypes t) (test-error (base64-string-to-string arg) :condition-type 'base64-error :include-subtypes t) (test-error (base64-string-to-integer arg) :condition-type 'base64-error :include-subtypes t) (test-error (base64-string-to-stream arg :stream .hole.) :condition-type 'base64-error :include-subtypes t) (test-error (with-input-from-string (in arg) (base64-stream-to-usb8-array in)) :condition-type 'base64-error :include-subtypes t) (test-error (with-input-from-string (in arg) (base64-stream-to-string in)) :condition-type 'base64-error :include-subtypes t) (test-error (with-input-from-string (in arg) (base64-stream-to-stream in :stream .hole.)) :condition-type 'base64-error :include-subtypes t) (test-error (with-input-from-string (in arg) (base64-stream-to-integer in)) :condition-type 'base64-error :include-subtypes t))) (defun test-valid () (test-valid-input #(0) "AA==") (test-valid-input #(0 0) "AAA=") (test-valid-input #(0 0 0) "AAAA") (test-valid-input #(0) " A A = = ") (test-valid-input #(0 0) " A A A = ") (test-valid-input #(0 0 0) " A A A A ")) (defun test-broken-1 () (test-broken-input "A") (test-broken-input "AA") (test-broken-input "AAA") (test-broken-input "AA=") (test-broken-input "A==") (test-broken-input "A===") (test-broken-input "AA===") (test-broken-input "AAA===") (test-broken-input "AAA==") (test-broken-input "A=A") (test-broken-input "AA=A") (test-broken-input "AAA=A") (test-broken-input "A==A")) (defun test-broken-2 () (flet ((test-invalid-char (char) (test-broken-input (format nil "~C" char)) (test-broken-input (format nil "A~C" char)) (test-broken-input (format nil "AA~C" char)) (test-broken-input (format nil "AAA~C" char)) (test-broken-input (format nil "AAAA~C" char)) (test-broken-input (format nil "AAA=~C" char)) (test-broken-input (format nil "AA==~C" char)))) (test-invalid-char #\$) (test-invalid-char (code-char 0)) (test-invalid-char (code-char 256)))) (defun do-tests (&key ((:break-on-failures *break-on-test-failures*) nil)) (with-tests (:name "cl-base64 tests") (test-valid) (test-broken-1) (test-broken-2) (do* ((length 0 (+ 3 length)) (string (make-string length) (make-string length)) (usb8 (make-usb8-array length) (make-usb8-array length)) (integer (random (expt 10 length)) (random (expt 10 length)))) ((>= length 300)) (dotimes (i length) (declare (fixnum i)) (let ((code (random 256))) (setf (schar string i) (code-char code)) (setf (aref usb8 i) code))) (do* ((columns 0 (+ columns 4))) ((> columns length)) ;; Test against cl-base64 routines (test integer (base64-string-to-integer (integer-to-base64-string integer :columns columns))) (test string (base64-string-to-string (string-to-base64-string string :columns columns)) :test #'string=) (test usb8 (base64-string-to-usb8-array (usb8-array-to-base64-string usb8)) :test #'equalp) ;; Test against AllegroCL built-in routines #+allegro (progn (test integer (excl:base64-string-to-integer (integer-to-base64-string integer :columns columns))) (test integer (base64-string-to-integer (excl:integer-to-base64-string integer))) (test (string-to-base64-string string :columns columns) (excl:usb8-array-to-base64-string usb8 (if (zerop columns) nil columns)) :test #'string=) (test string (base64-string-to-string (excl:usb8-array-to-base64-string usb8 (if (zerop columns) nil columns))) :test #'string=))))) t) (defun time-routines (&key (iterations nil) (length 256) (padding 0)) (assert (zerop (rem length 4)) (length)) (assert (<= 0 padding 2) (padding)) (let* ((str (make-string length :initial-element #\q)) (usb8 (map '(simple-array (unsigned-byte 8) (*)) #'char-code str)) (int 12345678901234567890) (n (or iterations (ceiling (* 32 1024 1024) length)))) (loop for i downfrom (1- length) repeat padding do (setf (aref str i) #\=)) (time-iterations 50000 (integer-to-base64-string int)) (time-iterations n (string-to-base64-string str)) (time-iterations n (usb8-array-to-base64-string usb8)) (let ((displaced (make-array (length str) :displaced-to str :element-type (array-element-type str))) (base (coerce str 'simple-base-string))) (time-iterations n (base64-string-to-usb8-array displaced)) (time-iterations n (base64-string-to-usb8-array str)) (time-iterations n (base64-string-to-usb8-array base))) #+allegro (progn (time-iterations n (excl:integer-to-base64-string int)) (time-iterations n (excl:usb8-array-to-base64-string usb8))))) ;;#+run-test (test-base64)
6,673
Common Lisp
.lisp
154
32.681818
78
0.540295
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
16befb8cd6a2702f91a3c3346c8cdb00fa5ce394e180369cb973967e108169c0
42,585
[ -1 ]
42,586
mime-types.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-mimes-20221106-git/mime-types.lisp
#| This file is a part of Trivial-Mimes (c) 2014 Shirakumo http://tymoon.eu ([email protected]) Author: Nicolas Hafner <[email protected]> |# (defpackage #:trivial-mimes (:nicknames #:mimes #:org.tymoonnext.trivial-mimes) (:use #:cl) (:export #:*mime-db* #:find-mime.types #:mime-probe #:mime-lookup #:mime #:mime-file-type #:mime-equal #:mime-case)) (in-package #:org.tymoonnext.trivial-mimes) (defun find-mime.types () "Attempts to find a usable MIME.TYPES file. If none can be found, an error is signalled." (or (loop for file in (list #p"/etc/mime.types" #+asdf (merge-pathnames "mime.types" (asdf:system-source-directory :trivial-mimes))) thereis (probe-file file)) (error "No MIME.TYPES file found anywhere!"))) (defvar *mime-db* (make-hash-table :test 'equalp) "An EQUALP hash-table with file-extensions as keys and the mime-types as values.") (defvar *reverse-mime-db* (make-hash-table :test 'equalp) "An EQUALP hash-table with mime-types as keys and the file-extensions as values.") (defun whitespace-p (char) (find char '(#\Space #\Newline #\Backspace #\Tab #\Linefeed #\Page #\Return #\Rubout))) (defun %read-tokens (line) (let ((tokens) (start)) (dotimes (i (length line)) (let ((char (aref line i))) (cond ((and start (whitespace-p char)) (push (subseq line start i) tokens) (setf start NIL)) ((not (or start (whitespace-p char))) (setf start i))))) (when start (push (subseq line start) tokens)) (nreverse tokens))) (defun valid-name-p (name) "According to RFC6838 type names MUST start with an alphanumeric character This also conveniently skips comments" (and name (alphanumericp (elt name 0)))) (defun build-mime-db (&optional (file (find-mime.types))) "Populates the *MIME-DB* with data gathered from the file. The file should have the following structure: MIME-TYPE FILE-EXTENSION*" (with-open-file (stream file :direction :input) (loop for line = (read-line stream NIL) while line for tokens = (%read-tokens line) when (valid-name-p (first tokens)) do (dolist (ending (cdr tokens)) (setf (gethash ending *mime-db*) (car tokens))) (setf (gethash (first tokens) *reverse-mime-db*) (second tokens))))) (build-mime-db) (defun mime-probe (pathname) "Attempts to get the mime-type through a call to the FILE shell utility. If the file does not exist or the platform is not unix, NIL is returned." #+unix (when (probe-file pathname) (let ((output (uiop:run-program (list "file" #+darwin "-bI" #-darwin "-bi" (uiop:native-namestring pathname)) :output :string))) (with-output-to-string (mime) (loop for c across output for char = (char-downcase c) ;; Allowed characters as per RFC6383 while (find char "abcdefghijklmnopqrstuvwxyz0123456789!#$&-^_.+/") do (write-char char mime))))) #-unix NIL) (defun mime-lookup (pathname) "Attempts to get the mime-type by file extension comparison. If none can be found, NIL is returned." (gethash (pathname-type pathname) *mime-db*)) (defun mime (pathname &optional (default "application/octet-stream")) "Attempts to detect the mime-type of the given pathname. First uses MIME-LOOKUP, then MIME-PROBE and lastly returns the DEFAULT if both fail." (or (mime-lookup pathname) (mime-probe pathname) default)) (defun mime-file-type (mime-type) "Returns a matching file-extension for the given mime-type. If the given mime-type cannot be found, NIL is returned." (gethash mime-type *reverse-mime-db*)) (defun mime-equal (m1 m2) "Checks whether M1 and M2 are matching. In particular, checks the match of type and subtype (any of which can be asterisks), discarding any parameters there might be. \(mime-equal \"text/*\" \"text/html\") T \(mime-equal \"text/html\" \"text/html;charset=utf8\") T \(mime-equal \"*/*\" \"application/octet-stream\") T \(mime-equal \"text/*\" \"application/octet-stream\") NIL" (or (equal "*" m1) (equal "*" m2) (equal "*/*" m1) (equal "*/*" m2) (destructuring-bind (type1 subtype1 &rest parameters1) (uiop:split-string m1 :separator '(#\/ #\;)) (declare (ignorable parameters1)) (destructuring-bind (type2 subtype2 &rest parameters2) (uiop:split-string m2 :separator '(#\/ #\;)) (declare (ignorable parameters2)) (cond ((or (equal "*" subtype1) (equal "*" subtype2) (equal "" subtype1) (equal "" subtype2)) (string-equal type1 type2)) ((string-equal type1 type2) (string-equal subtype1 subtype2)) (t nil)))))) (defmacro mime-case (file &body cases) "A case-like macro that works with MIME type of FILE. Otherwise clause is the last clause that starts with T or OTHERWISE,. Example: \(mime-case #p\"~/CHANGES.txt\" ((\"application/json\" \"application/*\") \"Something opaque...\") (\"text/plain\" \"That's a plaintext file :D\") (t \"I don't know this type!\"))" (let ((mime (gensym "mime"))) `(let ((,mime (mime ,file))) (cond ,@(loop for ((mimes . body) . rest) on cases when (member mimes '(T OTHERWISE)) collect `(t ,@body) into clauses and do (if rest (warn "Clauses after T and OTHERWISE are not reachable.") (return clauses)) collect `((member ,mime (list ,@(uiop:ensure-list mimes)) :test #'mime-equal) ,@body) into clauses finally (return clauses))))))
5,936
Common Lisp
.lisp
143
34.216783
114
0.620797
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
fb5313422142f261e031e2f1b236159ac25db6c6c98407aa6bbf8f683eacb207
42,586
[ -1 ]
42,588
tf-xcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-xcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-xcl.lisp --- XCL trivial-features implementation. ;;; ;;; Copyright (C) 2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; XCL already pushes :LITTLE-ENDIAN. ;;;; OS ;;; XCL already pushes :LINUX, :UNIX, :FREEBSD, :NETBSD, :BSD and :WINDOWS. ;;;; CPU ;;; XCL already pushes :X86 and :X86-64. (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,609
Common Lisp
.lisp
35
44.542857
75
0.731334
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
82f77568e1a61278d83f168bc4d7ac85537040b019cd19376b06ca887e17d314
42,588
[ 197592 ]
42,589
tf-abcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-abcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-abcl.lisp --- ABCL trivial-features implementation. ;;; ;;; Copyright (C) 2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (let ((order (jcall "toString" (jstatic "nativeOrder" "java.nio.ByteOrder")))) (cond ((string-equal order "LITTLE_ENDIAN") :little-endian) ((string-equal order "BIG_ENDIAN") :big-endian) (t (error "Byte order ~A unknown" order)))) *features*) ;;;; OS ;;; ABCL already pushes :LINUX and :UNIX. ;;;; CPU ;;; ABCL already pushes :x86-64 (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,900
Common Lisp
.lisp
42
41.047619
76
0.685575
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e860e429452e78e8289662730e9d52f366d67e2bcb2558dc704386daecfb09be
42,589
[ 3376 ]
42,590
tf-clasp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-clasp.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-clasp.lisp --- CLASP implementation of trivial-features. ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; - Set by CLASP directly. Sets :LITTLE-ENDIAN or :BIG-ENDIAN ;;;; OS ;;; - Set by CLASP directly. Already pushes :DARWIN, :LINUX, :UNIX, :BSD ;;;; CPU ;;; - Set by CLASP directly. Already pushes :X86-64 (currently the only ;;; supported platform) - More will be added directly in CLASP as soon as ;;; porting is done.
1,591
Common Lisp
.lisp
32
48.53125
77
0.734405
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5102d7a4e695835ecffe38365dfd83992ccf9c01a35e142d3b7a9e78f0beb15b
42,590
[ 416599 ]
42,591
tf-mezzano.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-mezzano.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mezzano.lisp --- Mezzano trivial-features implementation. ;;; ;;; Copyright (C) 2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; Mezzano already pushes :LITTLE-ENDIAN. ;;;; OS ;;; Mezzano already pushes :MEZZANO. ;;;; CPU ;;; Mezzano already pushes :X86-64. (pushnew :64-bit *features*)
1,496
Common Lisp
.lisp
33
44.121212
70
0.743132
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
bbee4ded595a91e3d2a3d90d7eb64db57177b5c17436e8dfd85cc1f35e3b2d7f
42,591
[ 439607 ]
42,592
tf-mcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-mcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mcl.lisp --- Digitool MCL trivial-features implementation. ;;; ;;; Copyright (C) 2010, Chun Tian (binghe) <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew :big-endian *features*) ;;;; OS ;;; MCL already pushes :UNIX and :DARWIN. (pushnew :bsd *features*) ;;;; CPU #+ppc-target (pushnew :ppc *features*) (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,603
Common Lisp
.lisp
36
43.083333
70
0.733804
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a654e84d83c236bbf6c7c8fa2ab9bb312a76f4ba5d37cb50f54935788abdbbd2
42,592
[ 96341 ]
42,593
tf-openmcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-openmcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-openmcl.lisp --- OpenMCL trivial-features implementation. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew #+big-endian-target :big-endian #+little-endian-target :little-endian *features*) ;;;; OS ;;; OpenMCL already pushes :UNIX and :DARWIN. #+linux-target (pushnew :linux *features*) #+darwin (pushnew :bsd *features*) #+solaris (pushnew :sunos *features*) ;;;; CPU ;;; what about ppc64? #+ppc-target (pushnew :ppc *features*) #+x8664-target (pushnew :x86-64 *features*) #+64-bit-host (pushnew :64-bit *features*) #+32-bit-host (pushnew :32-bit *features*)
1,817
Common Lisp
.lisp
41
42.609756
70
0.732011
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
9bc1db94b3b1e2b1a993aefecc3865daf8d8539432e0b4cb39fdec167b0bce69
42,593
[ 460782 ]
42,594
tf-corman.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-corman.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-corman.lisp --- Corman Lisp implementation of trivial-features. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew :little-endian *features*) ;;;; OS (pushnew :windows *features*) ;;;; CPU (pushnew :x86 *features*) ;; Not sure about this, iiuc corman can run under 64bit windows... (pushnew :32-bit *features*)
1,545
Common Lisp
.lisp
34
44.235294
70
0.743351
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
3d36e8da78e9a2bcc354574570b8fa611697c2ba1952f49410faa8e75c70741b
42,594
[ 415918 ]
42,595
tf-scl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-scl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-scl.lisp --- SCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2))) (setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff) (ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0) (#xfe (intern (symbol-name '#:big-endian) '#:keyword)) (#xff (intern (symbol-name '#:little-endian) '#:keyword)))) *features*) ;;;; OS ;;; SCL already pushes :unix, :bsd, :linux, :hpux, and :solaris ;;;; CPU ;;; SCL already pushes :amd64, :x86, :sparc, :sparc64, :hppa and :hppa64. ;;; For 64 bit CPUs the SCL pushes: :64bit #+amd64 (pushnew :x86-64 *features*) #+64bit (pushnew :64-bit *features*) #-64bit (pushnew :32-bit *features*)
1,989
Common Lisp
.lisp
41
45.926829
73
0.701546
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
30acb12b5fd436c01bf7724baabee27b383e5a08428d7946223b3b6d954a0e28
42,595
[ 419272 ]
42,596
tf-genera.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-genera.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: CL-USER; Base: 10; -*- ;;; ;;; tf-genera.lisp --- Genera trivial-features implementation. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;; Endianness (pushnew :little-endian *features*) ;;; Operating System ;; #+Genera is already on *features* ;;; CPU #+(or IMach VLM) (pushnew :Ivory *features*) ;; #+3600 for L-machines is already on *features* ;;; Register Size (pushnew :32-bit *features*)
1,610
Common Lisp
.lisp
35
44.742857
79
0.740741
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d50641813a406c879cfac0c36f6d76f198f9305e91eb8efd3091e5a2ff888beb
42,596
[ 315264 ]
42,597
tf-mocl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-mocl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mocl.lisp --- MOCL trivial-features implementation. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; MOCL already pushes :LITTLE-ENDIAN. ;;;; OS ;;; MOCL already pushes :IOS, :DARWIN, :BSD, and :UNIX for iOS, ;;; and :ANDROID, :LINUX, and :UNIX for Android. ;;;; CPU ;;; MOCL already pushes :ARM. (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,638
Common Lisp
.lisp
36
44.083333
70
0.730408
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
c5a220da0131c5189d36b0ef64cfb764f1a1859b7baa196a11b74531718a0fc5
42,597
[ 369918 ]
42,598
tf-sbcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-sbcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-sbcl.lisp --- SBCL trivial-features implementation. ;;; ;;; Copyright (C) 2007-2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (sb-alien:with-alien ((ptr (array (sb-alien:unsigned 8) 2))) (setf (sb-sys:sap-ref-16 (sb-alien:alien-sap ptr) 0) #xfeff) (ecase (sb-sys:sap-ref-8 (sb-alien:alien-sap ptr) 0) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword)))) *features*) ;;;; OS ;;; SBCL already pushes :DARWIN, :LINUX, :BSD and :UNIX. #+win32 (progn ;; note: as of 2008 or so, SBCL doesn't push :UNIX and :WIN32 ;; simultaneously anymore. (setq *features* (remove :unix *features*)) (pushnew :windows *features*)) ;;;; CPU ;;; SBCL already pushes: :X86, :X86-64, :PPC, and :64-BIT #-64-bit (pushnew :32-bit *features*)
2,025
Common Lisp
.lisp
44
43.363636
71
0.702484
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
27a56b6257ed0037bd4d32716bd36a994241676f262e5c66e8acbc2b0688faea
42,598
[ 434372 ]
42,599
tf-ecl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-ecl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-ecl.lisp --- ECL implementation of trivial-features. ;;; ;;; Copyright (C) 2007-2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (let ((ptr (ffi:allocate-foreign-object :unsigned-short))) (unwind-protect (progn (setf (ffi:deref-pointer ptr :unsigned-short) #xfeff) (ecase (ffi:deref-pointer ptr :unsigned-byte) (#xfe (intern "BIG-ENDIAN" "KEYWORD")) (#xff (intern "LITTLE-ENDIAN" "KEYWORD")))) (ffi:free-foreign-object ptr))) *features*) ;;;; OS ;;; ECL already pushes :DARWIN, :LINUX, :UNIX (except on Darwin) and :BSD. #+darwin (pushnew :unix *features*) #+win32 (pushnew :windows *features*) #+sun4sol2 (pushnew :sunos *features*) ;;;; CPU ;;; FIXME: add more #+powerpc7450 (pushnew :ppc *features*) #+x86_64 (pushnew :x86-64 *features*) #+(or i386 i486 i586 i686) (pushnew :x86 *features*) #+(or armv5l armv6l armv7l) (pushnew :arm *features*) #+(or aarch64 armv8l armv8b aarch64_be) (pushnew :arm64 *features*) #+mipsel (pushnew :mips *features*) #+uint64-t (pushnew :64-bit *features*) #+(and uint32-t (not uint64-t)) (pushnew :32-bit *features*)
2,393
Common Lisp
.lisp
51
43.313725
74
0.692374
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
566139142ea132b4a226ae5f45cba4204d6dfd78ee0b69b2290ffc67447f5eb1
42,599
[ 291413 ]
42,600
tf-mkcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-mkcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mkcl.lisp --- MKCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007-2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness #-(or :little-endian :big-endian) (pushnew (let ((ptr (ffi:allocate-foreign-object :unsigned-short))) (unwind-protect (progn (setf (ffi:deref-pointer ptr :unsigned-short) #xfeff) (ecase (ffi:deref-pointer ptr :unsigned-byte) (#xfe (intern "BIG-ENDIAN" "KEYWORD")) (#xff (intern "LITTLE-ENDIAN" "KEYWORD")))) (ffi:free-foreign-object ptr))) *features*) ;;;; OS ;;; MKCL conforms to SPEC ;;;; CPU ;;; MKCL conforms to SPEC (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,992
Common Lisp
.lisp
44
41.090909
71
0.687275
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
c68686a5f70605dfede7e50ba66e50000602f827f7efd32c26364e6cefd4618e
42,600
[ 479994 ]
42,601
tf-lispworks.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-lispworks.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-lispworks.lisp --- Lispworks implementation of trivial-features. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; Lispworks pushes :LITTLE-ENDIAN. #-little-endian (pushnew :big-endian *features*) #-(and) (pushnew (fli:with-dynamic-foreign-objects () (let ((ptr (fli:alloca :type :byte :nelems 2))) (setf (fli:dereference ptr :type '(:unsigned :short)) #xfeff) (ecase (fli:dereference ptr :type '(:unsigned :byte)) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword))))) *features*) ;;;; OS ;;; Lispworks already pushes :DARWIN, :LINUX and :UNIX. #+win32 (pushnew :windows *features*) ;;; Pushing :BSD. (Make sure this list is complete.) #+(or darwin freebsd netbsd openbsd) (pushnew :bsd *features*) #+solaris2 (pushnew :sunos *features*) ;;;; CPU ;;; Lispworks already pushes :X86. #+powerpc (pushnew :ppc *features*) #+lispworks-64bit (pushnew :64-bit *features*) #+lispworks-32bit (pushnew :32-bit *features*)
2,252
Common Lisp
.lisp
49
43.142857
74
0.708676
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d8bdcecc86c01dcec978fbd7fc93bc5890be71995eabb2762ffdc50fb43fb949
42,601
[ 29940 ]
42,602
tf-clisp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-clisp.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-clisp.lisp --- CLISP trivial-features implementation. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (intern (symbol-name (if sys::*big-endian* '#:big-endian '#:little-endian)) '#:keyword) *features*) ;;;; OS ;;; CLISP already exports :UNIX. #+win32 (pushnew :windows *features*) #-win32 (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (with-standard-io-syntax (read-from-string (format nil ":~(~A~)" (posix:uname-sysname (posix:uname))))) *features*)) #+(or darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; FIXME: not complete (let ((cpu (cond ((or (member :pc386 *features*) (member (machine-type) '("x86" "x86_64") :test #'string-equal)) (if (member :word-size=64 *features*) '#:x86-64 '#:x86)) ((string= (machine-type) "POWER MACINTOSH") '#:ppc) ((or (member (machine-type) '("SPARC" "SPARC64") :test #'string-equal)) (if (member :word-size=64 *features*) '#:sparc64 '#:sparc))))) (when cpu (pushnew (intern (symbol-name cpu) '#:keyword) *features*))) #+word-size=64 (pushnew :64-bit *features*) #-word-size=64 (pushnew :32-bit *features*)
2,699
Common Lisp
.lisp
64
35.125
74
0.618521
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d6207e8b42c951baeef5a956ada944251edb851fe32b578601de6b12bd590ca0
42,602
[ 309817 ]
42,603
tf-allegro.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-allegro.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-allegro.lisp --- Allegro implementation of trivial-features. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness ;;; Allegro already pushes :LITTLE-ENDIAN and :BIG-ENDIAN. ;;;; OS ;;; Allegro already pushes :LINUX and :UNIX. #+mswindows (pushnew :windows *features*) #+macosx (pushnew :darwin *features*) ;;; Pushing :BSD. (Make sure this list is complete.) #+(or macosx darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; Allegro already pushes :X86 and :X86-64. ;;; what about PPC64? #+powerpc (pushnew :ppc *features*) (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,878
Common Lisp
.lisp
42
43.285714
70
0.73494
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
27d3bb69aa6c67512049ad21952f677140211b33c636dd21df1ee44a9e75a26a
42,603
[ 2054 ]
42,604
tf-cmucl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/src/tf-cmucl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-cmucl.lisp --- CMUCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :cl-user) ;;;; Endianness (pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2))) (setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff) (ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword)))) *features*) ;;;; OS ;;; CMUCL already pushes :UNIX, :BSD, :LINUX and :DARWIN. ;;;; CPU ;;; CMUCL already pushes :PPC and :X86. (if (< 32 (logcount most-positive-fixnum)) (pushnew :64-bit *features*) (pushnew :32-bit *features*))
1,874
Common Lisp
.lisp
40
44.05
70
0.703886
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
16bcab2dfa005eb6d52754083a6e46c65c6b16a54be4dd70a4601fccb6686d84
42,604
[ 126877 ]
42,607
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-features-20211209-git/tests/tests.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tests.lisp --- trivial-features tests. ;;; ;;; Copyright (C) 2007, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package :trivial-features-tests) (defun run () (let ((*package* (find-package :trivial-features-tests))) (do-tests) (null (regression-test:pending-tests)))) ;;;; Support Code #-windows (progn ;; Hmm, why not just use OSICAT-POSIX:UNAME? (defcfun ("uname" %uname) :int (buf :pointer)) ;; Get system identification. (defun uname () (with-foreign-object (buf '(:struct utsname)) (when (= (%uname buf) -1) (error "uname() returned -1")) (macrolet ((utsname-slot (name) `(foreign-string-to-lisp (foreign-slot-pointer buf 'utsname ',name)))) (values (utsname-slot sysname) ;; (utsname-slot nodename) ;; (utsname-slot release) ;; (utsname-slot version) (utsname-slot machine)))))) (defun mutually-exclusive-p (features) (= 1 (loop for feature in features when (featurep feature) count 1))) ;;;; Tests (deftest endianness.1 (with-foreign-object (p :uint16) (setf (mem-ref p :uint16) #xfeff) (ecase (mem-ref p :uint8) (#xfe (featurep :big-endian)) (#xff (featurep :little-endian)))) t) (defparameter *bsds* '(:darwin :netbsd :openbsd :freebsd)) (defparameter *unices* (list* :linux *bsds*)) #+windows (deftest os.1 (featurep (list* :or :unix *unices*)) nil) #-windows (deftest os.1 (featurep (make-keyword (string-upcase (uname)))) t) (deftest os.2 (if (featurep :bsd) (mutually-exclusive-p *bsds*) (featurep `(:not (:or ,@*bsds*)))) t) (deftest os.3 (if (featurep `(:or ,@*unices*)) (featurep :unix) t) t) (deftest os.4 (if (featurep :windows) (not (featurep :unix)) t) t) (deftest cpu.1 (mutually-exclusive-p '(:ppc :ppc64 :x86 :x86-64 :alpha :mips :arm :arm64)) t) #+windows (deftest cpu.2 (case (get-system-info) (:intel (featurep :x86)) (:amd64 (featurep :x86-64)) (:ia64 nil) ; add this feature later! (t t)) t) #-windows (deftest cpu.2 (let ((machine (nth-value 1 (uname)))) (cond ((member machine '("x86" "x86_64") :test #'string=) (ecase (foreign-type-size :pointer) (4 (featurep :x86)) (8 (featurep :x86-64)))) (t (format *debug-io* "~&; NOTE: unhandled machine type, ~a, in CPU.2 test.~%" machine) t))) t) (deftest cpu.3 (ecase (foreign-type-size :pointer) (4 (featurep :32-bit)) (8 (featurep :64-bit))) t) ;; regression test: sometimes, silly logic leads to pushing nil to ;; *features*. (deftest nil.1 (featurep nil) nil) (deftest nil.2 (featurep :nil) nil)
4,013
Common Lisp
.lisp
117
29.196581
79
0.632964
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
34346cc9820ba056e6926e6f6daaf61368181ab8736e02ae742266e576db3af9
42,607
[ 44916 ]
42,609
usocket.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/usocket.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET -*- ;;;; See LICENSE for licensing information. (in-package :usocket) (defvar *ipv6-only-p* nil "When enabled, all USOCKET functions assume IPv6 addresses only.") (defparameter *wildcard-host* #(0 0 0 0) "Hostname to pass when all interfaces in the current system are to be bound. If this variable is passed to socket-listen, IPv6 capable systems will also listen for IPv6 connections.") (defparameter *auto-port* 0 "Port number to pass when an auto-assigned port number is wanted.") (defparameter *version* "0.8.2" "usocket version string") (defconstant +max-datagram-packet-size+ 65507 "The theoretical maximum amount of data in a UDP datagram. The IPv4 UDP packets have a 16-bit length constraint, and IP+UDP header has 28-byte. IP_MAXPACKET = 65535, /* netinet/ip.h */ sizeof(struct ip) = 20, /* netinet/ip.h */ sizeof(struct udphdr) = 8, /* netinet/udp.h */ 65535 - 20 - 8 = 65507 (But for UDP broadcast, the maximum message size is limited by the MTU size of the underlying link)") (defclass usocket () ((socket :initarg :socket :accessor socket :documentation "Implementation specific socket object instance.'") (wait-list :initform nil :accessor wait-list :documentation "WAIT-LIST the object is associated with.") (state :initform nil :accessor state :documentation "Per-socket return value for the `wait-for-input' function. The value stored in this slot can be any of NIL - not ready :READ - ready to read :READ-WRITE - ready to read and write :WRITE - ready to write The last two remain unused in the current version. ") #+(and win32 (or sbcl ecl lispworks)) (%ready-p :initform nil :accessor %ready-p :documentation "Indicates whether the socket has been signalled as ready for reading a new connection. The value will be set to T by `wait-for-input-internal' (given the right conditions) and reset to NIL by `socket-accept'. Don't modify this slot or depend on it as it is really intended to be internal only. Note: Accessed, but not used for 'stream-usocket'. " )) (:documentation "The main socket class. Sockets should be closed using the `socket-close' method.")) (defgeneric socket-state (socket) (:documentation "NIL - not ready :READ - ready to read :READ-WRITE - ready to read and write :WRITE - ready to write")) (defmethod socket-state ((socket usocket)) (state socket)) (defclass stream-usocket (usocket) ((stream :initarg :stream :accessor socket-stream :documentation "Stream instance associated with the socket." ;; ;;Iff an external-format was passed to `socket-connect' or `socket-listen' ;;the stream is a flexi-stream. Otherwise the stream is implementation ;;specific." )) (:documentation "Stream socket class. ' Contrary to other sockets, these sockets may be closed either with the `socket-close' method or by closing the associated stream (which can be retrieved with the `socket-stream' accessor).")) (defclass stream-server-usocket (usocket) ((element-type :initarg :element-type :initform #-lispworks 'character #+lispworks 'base-char :reader element-type :documentation "Default element type for streams created by `socket-accept'.")) (:documentation "Socket which listens for stream connections to be initiated from remote sockets.")) (defclass datagram-usocket (usocket) ((connected-p :type boolean :accessor connected-p :initarg :connected-p) #+(or cmu scl lispworks mcl (and clisp ffi (not rawsock))) (%open-p :type boolean :accessor %open-p :initform t :documentation "Flag to indicate if usocket is open, for GC on implementions operate on raw socket fd.") #+(or lispworks mcl (and clisp ffi (not rawsock))) (recv-buffer :documentation "Private RECV buffer.") #+(or lispworks mcl) (send-buffer :documentation "Private SEND buffer.")) (:documentation "UDP (inet-datagram) socket")) (defun usocket-p (socket) (typep socket 'usocket)) (defun stream-usocket-p (socket) (typep socket 'stream-usocket)) (defun stream-server-usocket-p (socket) (typep socket 'stream-server-usocket)) (defun datagram-usocket-p (socket) (typep socket 'datagram-usocket)) (defun make-socket (&key socket) "Create a usocket socket type from implementation specific socket." (unless socket (error 'invalid-socket-error)) (make-stream-socket :socket socket)) (defun make-stream-socket (&key socket stream) "Create a usocket socket type from implementation specific socket and stream objects. Sockets returned should be closed using the `socket-close' method or by closing the stream associated with the socket. " (unless socket (error 'invalid-socket-error)) (unless stream (error 'invalid-socket-stream-error)) (make-instance 'stream-usocket :socket socket :stream stream)) (defun make-stream-server-socket (socket &key (element-type #-lispworks 'character #+lispworks 'base-char)) "Create a usocket-server socket type from an implementation-specific socket object. The returned value is a subtype of `stream-server-usocket'. " (unless socket (error 'invalid-socket-error)) (make-instance 'stream-server-usocket :socket socket :element-type element-type)) (defun make-datagram-socket (socket &key connected-p) (unless socket (error 'invalid-socket-error)) (make-instance 'datagram-usocket :socket socket :connected-p connected-p)) (defgeneric socket-accept (socket &key element-type) (:documentation "Accepts a connection from `socket', returning a `stream-socket'. The stream associated with the socket returned has `element-type' when explicitly specified, or the element-type passed to `socket-listen' otherwise.")) (defgeneric socket-close (usocket) (:documentation "Close a previously opened `usocket'.")) (defmethod socket-close :before ((usocket usocket)) (when (wait-list usocket) (remove-waiter (wait-list usocket) usocket))) ;; also see http://stackoverflow.com/questions/4160347/close-vs-shutdown-socket (defgeneric socket-shutdown (usocket direction) (:documentation "Shutdown communication on the socket in DIRECTION. After a shutdown no input and/or output of the indicated DIRECTION can be performed on the `usocket'. DIRECTION should be either :INPUT or :OUTPUT or :IO")) (defgeneric socket-send (usocket buffer length &key host port) (:documentation "Send packets through a previously opend `usocket'.")) (defgeneric socket-receive (usocket buffer length &key) (:documentation "Receive packets from a previously opend `usocket'. Returns 4 values: (values buffer size host port)")) (defgeneric get-local-address (socket) (:documentation "Returns the IP address of the socket.")) (defgeneric get-peer-address (socket) (:documentation "Returns the IP address of the peer the socket is connected to.")) (defgeneric get-local-port (socket) (:documentation "Returns the IP port of the socket. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-port (socket) (:documentation "Returns the IP port of the peer the socket to.")) (defgeneric get-local-name (socket) (:documentation "Returns the IP address and port of the socket as values. This function applies to both `stream-usocket' and `server-stream-usocket' type objects.")) (defgeneric get-peer-name (socket) (:documentation "Returns the IP address and port of the peer the socket is connected to as values.")) (defmacro with-connected-socket ((var socket) &body body) "Bind `socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(let ((,var ,socket)) (unwind-protect (when ,var (with-mapped-conditions (,var) ,@body)) (when ,var (socket-close ,var))))) (defmacro with-client-socket ((socket-var stream-var &rest socket-connect-args) &body body) "Bind the socket resulting from a call to `socket-connect' with the arguments `socket-connect-args' to `socket-var' and if `stream-var' is non-nil, bind the associated socket stream to it." `(with-connected-socket (,socket-var (socket-connect ,@socket-connect-args)) ,(if (null stream-var) `(progn ,@body) `(let ((,stream-var (socket-stream ,socket-var))) ,@body)))) (defmacro with-server-socket ((var server-socket) &body body) "Bind `server-socket' to `var', ensuring socket destruction on exit. `body' is only evaluated when `var' is bound to a non-null value. The `body' is an implied progn form." `(with-connected-socket (,var ,server-socket) ,@body)) (defmacro with-socket-listener ((socket-var &rest socket-listen-args) &body body) "Bind the socket resulting from a call to `socket-listen' with arguments `socket-listen-args' to `socket-var'." `(with-server-socket (,socket-var (socket-listen ,@socket-listen-args)) ,@body)) (defstruct (wait-list (:constructor %make-wait-list)) %wait ;; implementation specific waiters ;; the list of all usockets map) ;; maps implementation sockets to usockets ;; Implementation specific: ;; ;; %setup-wait-list ;; %add-waiter ;; %remove-waiter (defun make-wait-list (waiters) (let ((wl (%make-wait-list))) (setf (wait-list-map wl) (make-hash-table)) (%setup-wait-list wl) (dolist (x waiters wl) ; wl is returned (add-waiter wl x)))) (defun add-waiter (wait-list input) (setf (gethash (socket input) (wait-list-map wait-list)) input (wait-list input) wait-list) (pushnew input (wait-list-waiters wait-list)) (%add-waiter wait-list input)) (defun remove-waiter (wait-list input) (%remove-waiter wait-list input) (setf (wait-list-waiters wait-list) (remove input (wait-list-waiters wait-list)) (wait-list input) nil) (remhash (socket input) (wait-list-map wait-list))) (defun remove-all-waiters (wait-list) (dolist (waiter (wait-list-waiters wait-list)) (%remove-waiter wait-list waiter)) (setf (wait-list-waiters wait-list) nil) (clrhash (wait-list-map wait-list))) (defun wait-for-input (socket-or-sockets &key timeout ready-only &aux (single-socket-p (usocket-p socket-or-sockets))) "Waits for one or more streams to become ready for reading from the socket. When `timeout' (a non-negative real number) is specified, wait `timeout' seconds, or wait indefinitely when it isn't specified. A `timeout' value of 0 (zero) means polling. Returns two values: the first value is the list of streams which are readable (or in case of server streams acceptable). NIL may be returned for this value either when waiting timed out or when it was interrupted (EINTR). The second value is a real number indicating the time remaining within the timeout period or NIL if none. Without the READY-ONLY arg, WAIT-FOR-INPUT will return all sockets in the original list you passed it. This prevents a new list from being consed up. Some users of USOCKET were reluctant to use it if it wouldn't behave that way, expecting it to cost significant performance to do the associated garbage collection. Without the READY-ONLY arg, you need to check the socket STATE slot for the values documented in usocket.lisp in the usocket class." ;; for NULL sockets, return NIL with respect of TIMEOUT. (when (null socket-or-sockets) (when timeout (sleep timeout)) (return-from wait-for-input nil)) ;; create a new wait-list if it's not created by the caller. (unless (wait-list-p socket-or-sockets) ;; OPTIMIZATION: in case socket-or-sockets is an atom, create the wait-list ;; only once and store it into the usocket itself. (let ((wl (if (and single-socket-p (wait-list socket-or-sockets)) (wait-list socket-or-sockets) ; reuse the per-usocket wait-list (make-wait-list (if (listp socket-or-sockets) socket-or-sockets (list socket-or-sockets)))))) (multiple-value-bind (sockets to-result) (wait-for-input wl :timeout timeout :ready-only ready-only) ;; in case of single socket, keep the wait-list (unless single-socket-p (remove-all-waiters wl)) (return-from wait-for-input (values (if ready-only sockets socket-or-sockets) to-result))))) (let* ((start (get-internal-real-time)) (sockets-ready 0)) (dolist (x (wait-list-waiters socket-or-sockets)) (when (setf (state x) #+(and win32 (or sbcl ecl)) nil ; they cannot rely on LISTEN #-(and win32 (or sbcl ecl)) (if (and (stream-usocket-p x) (listen (socket-stream x))) :read nil)) (incf sockets-ready))) ;; the internal routine is responsibe for ;; making sure the wait doesn't block on socket-streams of ;; which theready- socket isn't ready, but there's space left in the ;; buffer. socket-or-sockets is not destructed. (wait-for-input-internal socket-or-sockets :timeout (if (zerop sockets-ready) timeout 0)) (let ((to-result (when timeout (let ((elapsed (/ (- (get-internal-real-time) start) internal-time-units-per-second))) (when (< elapsed timeout) (- timeout elapsed)))))) ;; two return values: ;; 1) the original wait-list, or available sockets (ready-only) ;; 2) remaining timeout (values (cond (ready-only (cond (single-socket-p (if (null (state (car (wait-list-waiters socket-or-sockets)))) nil ; nothing left if the only socket is not waiting (wait-list-waiters socket-or-sockets))) (t (remove-if #'null (wait-list-waiters socket-or-sockets) :key #'state)))) (t socket-or-sockets)) to-result)))) ;; ;; Data utility functions ;; (defun integer-to-octet-buffer (integer buffer octets &key (start 0)) (do ((b start (1+ b)) (i (ash (1- octets) 3) ;; * 8 (- i 8))) ((> 0 i) buffer) (setf (aref buffer b) (ldb (byte 8 i) integer)))) (defun octet-buffer-to-integer (buffer octets &key (start 0)) (let ((integer 0)) (do ((b start (1+ b)) (i (ash (1- octets) 3) ;; * 8 (- i 8))) ((> 0 i) integer) (setf (ldb (byte 8 i) integer) (aref buffer b))))) (defmacro port-to-octet-buffer (port buffer &key (start 0)) `(integer-to-octet-buffer ,port ,buffer 2 :start ,start)) (defmacro ip-to-octet-buffer (ip buffer &key (start 0)) `(integer-to-octet-buffer (host-byte-order ,ip) ,buffer 4 :start ,start)) (defmacro port-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 2 :start ,start)) (defmacro ip-from-octet-buffer (buffer &key (start 0)) `(octet-buffer-to-integer ,buffer 4 :start ,start)) ;; ;; IPv4 utility functions ;; (defun list-of-strings-to-integers (list) "Take a list of strings and return a new list of integers (from parse-integer) on each of the string elements." (let ((new-list nil)) (dolist (element (reverse list)) (push (parse-integer element) new-list)) new-list)) (defun ip-address-string-p (string) "Return a true value if the given string could be an IP address." (every (lambda (char) (or (digit-char-p char) (eql char #\.))) string)) (defun hbo-to-dotted-quad (integer) ; exported "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (format nil "~D.~D.~D.~D" first second third fourth))) (defun hbo-to-vector-quad (integer) ; exported "Host-byte-order integer to dotted-quad string conversion utility." (let ((first (ldb (byte 8 24) integer)) (second (ldb (byte 8 16) integer)) (third (ldb (byte 8 8) integer)) (fourth (ldb (byte 8 0) integer))) (vector first second third fourth))) (defun vector-quad-to-dotted-quad (vector) ; exported (format nil "~D.~D.~D.~D" (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3))) (defun dotted-quad-to-vector-quad (string) ; exported (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (vector (first list) (second list) (third list) (fourth list)))) (defgeneric host-byte-order (address)) ; exported (defmethod host-byte-order ((string string)) "Convert a string, such as 192.168.1.1, to host-byte-order, such as 3232235777." (let ((list (list-of-strings-to-integers (split-sequence #\. string)))) (+ (* (first list) 256 256 256) (* (second list) 256 256) (* (third list) 256) (fourth list)))) (defmethod host-byte-order ((vector vector)) ; IPv4 only "Convert a vector, such as #(192 168 1 1), to host-byte-order, such as 3232235777." (+ (* (aref vector 0) 256 256 256) (* (aref vector 1) 256 256) (* (aref vector 2) 256) (aref vector 3))) (defmethod host-byte-order ((int integer)) int) ; this assume input integer is already host-byte-order ;; ;; IPv6 utility functions ;; (defun vector-to-ipv6-host (vector) ; exported (with-output-to-string (*standard-output*) (loop with zeros-collapsed-p with collapsing-zeros-p for i below 16 by 2 for word = (+ (ash (aref vector i) 8) (aref vector (1+ i))) do (cond ((and (zerop word) (not collapsing-zeros-p) (not zeros-collapsed-p)) (setf collapsing-zeros-p t)) ((or (not (zerop word)) zeros-collapsed-p) (when collapsing-zeros-p (write-string ":") (setf collapsing-zeros-p nil zeros-collapsed-p t)) (format t "~:[~;:~]~X" (plusp i) word))) finally (when collapsing-zeros-p (write-string "::"))))) (defun split-ipv6-address (string) (let ((pos 0) (word nil) (double-colon-seen-p nil) (words-before-double-colon nil) (words-after-double-colon nil)) (loop (multiple-value-setq (word pos) (parse-integer string :radix 16 :junk-allowed t :start pos)) (labels ((at-end-p () (= pos (length string))) (looking-at-colon-p () (char= (char string pos) #\:)) (ensure-colon () (unless (looking-at-colon-p) (error "unsyntactic IPv6 address string ~S, expected a colon at position ~D" string pos)) (incf pos))) (cond ((null word) (when double-colon-seen-p (error "unsyntactic IPv6 address string ~S, can only have one double-colon filler mark" string)) (setf double-colon-seen-p t)) (double-colon-seen-p (push word words-after-double-colon)) (t (push word words-before-double-colon))) (if (at-end-p) (return (list (nreverse words-before-double-colon) (nreverse words-after-double-colon))) (ensure-colon)))))) (defun ipv6-host-to-vector (string) ; exported (assert (> (length string) 2) () "Unsyntactic IPv6 address literal ~S, expected at least three characters" string) (destructuring-bind (words-before-double-colon words-after-double-colon) (split-ipv6-address (concatenate 'string (when (eql (char string 0) #\:) "0") string (when (eql (char string (1- (length string))) #\:) "0"))) (let ((number-of-words-specified (+ (length words-before-double-colon) (length words-after-double-colon)))) (assert (<= number-of-words-specified 8) () "Unsyntactic IPv6 address literal ~S, too many colon separated address components" string) (assert (or (= number-of-words-specified 8) words-after-double-colon) () "Unsyntactic IPv6 address literal ~S, too few address components and no double-colon filler found" string) (loop with vector = (make-array 16 :element-type '(unsigned-byte 8)) for i below 16 by 2 for word in (append words-before-double-colon (make-list (- 8 number-of-words-specified) :initial-element 0) words-after-double-colon) do (setf (aref vector i) (ldb (byte 8 8) word) (aref vector (1+ i)) (ldb (byte 8 0) word)) finally (return vector))))) ;; exported since 0.8.0 (defun host-to-hostname (host) ; host -> string "Translate a string, vector quad or 16 byte IPv6 address to a stringified hostname." (etypecase host (string host) ; IPv4 or IPv6 ((or (vector t 4) ; IPv4 (array (unsigned-byte 8) (4))) (vector-quad-to-dotted-quad host)) ((or (vector t 16) ; IPv6 (array (unsigned-byte 8) (16))) (vector-to-ipv6-host host)) (integer (hbo-to-dotted-quad host)) ; integer input is IPv4 only (null (if *ipv6-only-p* "::" "0.0.0.0")))) ;; "::" is the IPv6 wildcard address (defun ip= (ip1 ip2) ; exported (etypecase ip1 (string (string= ip1 ; IPv4 or IPv6 (host-to-hostname ip2))) ((or (vector t 4) ; IPv4 (array (unsigned-byte 8) (4)) ; IPv4 (vector t 16) ; IPv6 (array (unsigned-byte 8) (16))) ; IPv6 (equalp ip1 ip2)) (integer (= ip1 ; IPv4 only (host-byte-order ip2))))) ; convert ip2 to integer (hbo) (defun ip/= (ip1 ip2) ; exported (not (ip= ip1 ip2))) ;; ;; DNS helper functions ;; (defun get-host-by-name (name) "0.7.1+: if there're IPv4 addresses, return the first IPv4 address. (unless in IPv6-only mode)" (let* ((hosts (get-hosts-by-name name)) (ipv4-hosts (remove-if-not #'(lambda (ip) (= 4 (length ip))) hosts)) (ipv6-hosts (remove-if #'(lambda (ip) (= 4 (length ip))) hosts))) (cond (*ipv6-only-p* (car ipv6-hosts)) (ipv4-hosts (car ipv4-hosts)) (t (car hosts))))) (defun get-random-host-by-name (name) "0.7.1+: if there're IPv4 addresses, only return a random IPv4 address. (unless in IPv6-only mode)" (let* ((hosts (get-hosts-by-name name)) (ipv4-hosts (remove-if-not #'(lambda (ip) (= 4 (length ip))) hosts)) (ipv6-hosts (remove-if #'(lambda (ip) (= 4 (length ip))) hosts))) (cond (*ipv6-only-p* (elt ipv6-hosts (random (length ipv6-hosts)))) (ipv4-hosts (elt ipv4-hosts (random (length ipv4-hosts)))) (hosts (elt hosts (random (length hosts))))))) (defun host-to-vector-quad (host) ; internal "Translate a host specification (vector quad, dotted quad or domain name) to a vector quad." (etypecase host (string (let ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) ;; valid IP dotted quad? not sure ip (get-random-host-by-name host)))) ((or (vector t 4) (array (unsigned-byte 8) (4))) host) (integer (hbo-to-vector-quad host)))) (defun host-to-hbo (host) ; internal (etypecase host (string (let ((ip (when (ip-address-string-p host) (dotted-quad-to-vector-quad host)))) (if (and ip (= 4 (length ip))) (host-byte-order ip) (host-to-hbo (get-host-by-name host))))) ((or (vector t 4) (array (unsigned-byte 8) (4))) (host-byte-order host)) (integer host))) ;; ;; Other utility functions ;; (defun split-timeout (timeout &optional (fractional 1000000)) "Split real value timeout into seconds and microseconds. Optionally, a different fractional part can be specified." (multiple-value-bind (secs sec-frac) (truncate timeout 1) (values secs (truncate (* fractional sec-frac) 1)))) ;; ;; Setting of documentation for backend defined functions ;; ;; Documentation for the function ;; ;; (defun SOCKET-CONNECT (host port &key element-type nodelay some-other-keys...) ..) ;; (setf (documentation 'socket-connect 'function) "Connect to `host' on `port'. `host' is assumed to be a string or an IP address represented in vector notation, such as #(192 168 1 1). `port' is assumed to be an integer. `element-type' specifies the element type to use when constructing the stream associated with the socket. The default is 'character. `nodelay' Allows to disable/enable Nagle's algorithm (http://en.wikipedia.org/wiki/Nagle%27s_algorithm). If this parameter is omitted, the behaviour is inherited from the CL implementation (in most cases, Nagle's algorithm is enabled by default, but for example in ACL it is disabled). If the parameter is specified, one of these three values is possible: T - Disable Nagle's algorithm; signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. NIL - Leave Nagle's algorithm enabled on the socket; signals an UNSUPPORTED condition if the implementation does not support explicit manipulation with that option. :IF-SUPPORTED - Disables Nagle's algorithm if the implementation allows this, otherwises just ignore this option. Returns a usocket object.") ;; Documentation for the function ;; ;; (defun SOCKET-LISTEN (host port &key reuseaddress backlog element-type) ..) ;;###FIXME: extend with default-element-type (setf (documentation 'socket-listen 'function) "Bind to interface `host' on `port'. `host' should be the representation of an ready-interface address. The implementation is not required to do an address lookup, making no guarantees that hostnames will be correctly resolved. If `*wildcard-host*' or NIL is passed for `host', the socket will be bound to all available interfaces for the system. `port' can be selected by the IP stack by passing `*auto-port*'. Returns an object of type `stream-server-usocket'. `reuse-address' and `backlog' are advisory parameters for setting socket options at creation time. `element-type' is the element type of the streams to be created by `socket-accept'. `reuseaddress' is supported for backward compatibility (but deprecated); when both `reuseaddress' and `reuse-address' have been specified, the latter takes precedence. ") ;;; Small utility functions mapping true/false to 1/0, moved here from option.lisp (proclaim '(inline bool->int int->bool)) (defun bool->int (bool) (if bool 1 0)) (defun int->bool (int) (= 1 int))
27,820
Common Lisp
.lisp
621
38.059581
120
0.650803
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
64ecc3a301c329239199037d5d8353f1a5802bd5da3b1be666f2260aa94ff7de
42,609
[ -1 ]
42,610
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/package.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: CL-USER -*- ;;;; See the LICENSE file for licensing information. (defpackage :usocket (:use #-genera :common-lisp #+genera :future-common-lisp #+abcl :java :split-sequence) (:export #:*version* #:*wildcard-host* #:*auto-port* #:+max-datagram-packet-size+ #:socket-connect ; socket constructors and methods #:socket-listen #:socket-accept #:socket-close #:socket-shutdown #:get-local-address #:get-peer-address #:get-local-port #:get-peer-port #:get-local-name #:get-peer-name #:socket-send ; udp function (send) #:socket-receive ; udp function (receive) #:wait-for-input ; waiting for input-ready state (select() like) #:make-wait-list #:add-waiter #:remove-waiter #:remove-all-waiters #:with-connected-socket ; convenience macros #:with-server-socket #:with-client-socket #:with-socket-listener #:usocket ; socket object and accessors #:stream-usocket #:stream-server-usocket #:socket #:socket-stream #:datagram-usocket #:socket-state ; 0.6.4 ;; predicates (for version 0.6 or 1.0 ?) #:usocket-p #:stream-usocket-p #:stream-server-usocket-p #:datagram-usocket-p #:host-byte-order ; IPv4 utility functions #:hbo-to-dotted-quad #:hbo-to-vector-quad #:vector-quad-to-dotted-quad #:dotted-quad-to-vector-quad #:vector-to-ipv6-host ; IPv6 utility functions #:ipv6-host-to-vector #:ip= ; IPv4+IPv6 utility function #:ip/= #:integer-to-octet-buffer ; Network utility functions #:octet-buffer-to-integer #:port-to-octet-buffer #:port-from-octet-buffer #:ip-to-octet-buffer #:ip-from-octet-buffer #:with-mapped-conditions #:socket-condition ; conditions #:ns-condition #:socket-error ; errors #:ns-error #:unknown-condition #:ns-unknown-condition #:unknown-error #:ns-unknown-error #:socket-warning ; warnings (udp) #:insufficient-implementation ; conditions regarding usocket support level #:unsupported #:unimplemented #:socket-server #:*remote-host* #:*remote-port* ;; added in 0.7.1 #:get-host-by-name #:get-hosts-by-name #:get-random-host-by-name #:ns-host-not-found-error #:ns-no-recovery-error #:ns-try-again-condition ; obsoleted #:ns-try-again-error #:default-udp-handler #:default-tcp-handler #:echo-tcp-handler ;; server handlers ;; added in 0.8.0 #:*backend* #:*default-event-base* #:host-to-hostname ;; socket-related conditions from IOlib #:ADDRESS-NOT-AVAILABLE-ERROR #:HOST-DOWN-ERROR #:OPERATION-NOT-SUPPORTED-ERROR #:SOCKET-OPTION #:NETWORK-DOWN-ERROR #:INVALID-SOCKET-ERROR #:SOCKET-TYPE-NOT-SUPPORTED-ERROR #:DEADLINE-TIMEOUT-ERROR #:SHUTDOWN-ERROR #:HOST-UNREACHABLE-ERROR #:NETWORK-UNREACHABLE-ERROR #:CONNECTION-ABORTED-ERROR #:BAD-FILE-DESCRIPTOR-ERROR #:PROTOCOL-NOT-SUPPORTED-ERROR #:CONNECTION-RESET-ERROR #:TIMEOUT-ERROR #:ADDRESS-IN-USE-ERROR #:NO-BUFFERS-ERROR #:INVALID-SOCKET-STREAM-ERROR #:INTERRUPTED-CONDITION #:INVALID-ARGUMENT-ERROR #:OPERATION-NOT-PERMITTED-ERROR #:NETWORK-RESET-ERROR #:CONNECTION-REFUSED-ERROR ;; added in 0.8.2 #:host-or-ip ;; added in 0.9.0 #:*ipv6-only-p* ))
4,316
Common Lisp
.lisp
109
26.357798
87
0.526517
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5b1a7049f5cff5ce43382ebd199fbc77e2e53a685d1c1dd09be1c33ff3da3b20
42,610
[ -1 ]
42,611
server.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/server.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (defvar *server*) (defun socket-server (host port function &optional arguments &key in-new-thread (protocol :stream) ;; for udp (timeout 1) (max-buffer-size +max-datagram-packet-size+) ;; for tcp element-type (reuse-address t) multi-threading name) (let* ((real-host (or host *wildcard-host*)) (socket (ecase protocol (:stream (apply #'socket-listen `(,real-host ,port ,@(when element-type `(:element-type ,element-type)) ,@(when reuse-address `(:reuse-address ,reuse-address))))) (:datagram (socket-connect nil nil :protocol :datagram :local-host real-host :local-port port))))) (labels ((real-call () (ecase protocol (:stream (tcp-event-loop socket function arguments :element-type element-type :multi-threading multi-threading)) (:datagram (udp-event-loop socket function arguments :timeout timeout :max-buffer-size max-buffer-size))))) (if in-new-thread (values (bt:make-thread #'real-call :name (or name "USOCKET Server")) socket) (progn (setq *server* socket) (real-call)))))) (defvar *remote-host*) (defvar *remote-port*) (defun default-udp-handler (buffer) ; echo (declare (type (simple-array (unsigned-byte 8) *) buffer)) buffer) (defun udp-event-loop (socket function &optional arguments &key timeout max-buffer-size) (let ((buffer (make-array max-buffer-size :element-type '(unsigned-byte 8) :initial-element 0)) (sockets (list socket))) (unwind-protect (loop do (multiple-value-bind (return-sockets real-time) (wait-for-input sockets :timeout timeout) (declare (ignore return-sockets)) (when real-time (multiple-value-bind (recv n *remote-host* *remote-port*) (socket-receive socket buffer max-buffer-size) (declare (ignore recv)) (if (plusp n) (progn (let ((reply (apply function (subseq buffer 0 n) arguments))) (when reply (replace buffer reply) (let ((n (socket-send socket buffer (length reply) :host *remote-host* :port *remote-port*))) (when (minusp n) (error "send error: ~A~%" n)))))) (error "receive error: ~A" n)))) #+scl (when thread:*quitting-lisp* (return)) #+(and cmu mp) (mp:process-yield))) (socket-close socket) (values)))) (defun default-tcp-handler (stream) ; null (declare (type stream stream)) (format stream "Hello world!~%")) (defun echo-tcp-handler (stream) (loop (when (listen stream) (let ((line (read-line stream nil))) (write-line line stream) (force-output stream))))) (defun tcp-event-loop (socket function &optional arguments &key element-type multi-threading) (let ((real-function #'(lambda (client-socket &rest arguments) (unwind-protect (multiple-value-bind (*remote-host* *remote-port*) (get-peer-name client-socket) (apply function (socket-stream client-socket) arguments)) (close (socket-stream client-socket)) (socket-close client-socket) nil)))) (unwind-protect (loop do (block continue (let* ((client-socket (apply #'socket-accept socket (when element-type (list :element-type element-type)))) (client-stream (socket-stream client-socket))) (if multi-threading (bt:make-thread (lambda () (handler-case (apply real-function client-socket arguments) #+sbcl (sb-bsd-sockets:invalid-argument-error ()))) :name "USOCKET Client") (unwind-protect (handler-case (apply real-function client-socket arguments) #+sbcl (sb-bsd-sockets:invalid-argument-error () (return-from continue))) (close client-stream) (socket-close client-socket))) #+scl (when thread:*quitting-lisp* (return)) #+(and cmu mp) (mp:process-yield)))) (socket-close socket) (values))))
5,512
Common Lisp
.lisp
114
29.368421
111
0.468361
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
df3dc4e29692901c03ebaf5f1cf59845a60896cf608bb38d3c9458cb764850b7
42,611
[ -1 ]
42,612
option.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/option.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET -*- ;;;; SOCKET-OPTION, a high-level socket option get/set framework ;;;; See LICENSE for licensing information. (in-package :usocket) ;; put here because option.lisp is for native backend only (defparameter *backend* :native) ;;; Interface definition (defgeneric socket-option (socket option &key) (:documentation "Get a socket's internal options")) (defgeneric (setf socket-option) (new-value socket option &key) (:documentation "Set a socket's internal options")) ;;; Handling of wrong type of arguments (defmethod socket-option ((socket usocket) (option t) &key) (error 'type-error :datum option :expected-type 'keyword)) (defmethod (setf socket-option) (new-value (socket usocket) (option t) &key) (declare (ignore new-value)) (socket-option socket option)) (defmethod socket-option ((socket usocket) (option symbol) &key) (if (keywordp option) (error 'unimplemented :feature option :context 'socket-option) (error 'type-error :datum option :expected-type 'keyword))) (defmethod (setf socket-option) (new-value (socket usocket) (option symbol) &key) (declare (ignore new-value)) (socket-option socket option)) ;;; Socket option: RECEIVE-TIMEOUT (SO_RCVTIMEO) (defmethod socket-option ((usocket stream-usocket) (option (eql :receive-timeout)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (socket:socket-options socket :so-rcvtimeo) #+clozure (ccl:stream-input-timeout socket) #+cmu (lisp::fd-stream-timeout (socket-stream usocket)) #+(or ecl clasp) (sb-bsd-sockets:sockopt-receive-timeout socket) #+lispworks (get-socket-receive-timeout socket) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (sb-impl::fd-stream-timeout (socket-stream usocket)) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket stream-usocket) (option (eql :receive-timeout)) &key) (declare (type number new-value) (ignorable new-value option)) (let ((socket (socket usocket)) (timeout new-value)) (declare (ignorable socket timeout)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (socket:socket-options socket :so-rcvtimeo timeout) #+clozure (setf (ccl:stream-input-timeout socket) timeout) #+cmu (setf (lisp::fd-stream-timeout (socket-stream usocket)) (coerce timeout 'integer)) #+(or ecl clasp) (setf (sb-bsd-sockets:sockopt-receive-timeout socket) timeout) #+lispworks (set-socket-receive-timeout socket timeout) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (setf (sb-impl::fd-stream-timeout (socket-stream usocket)) (coerce timeout 'single-float)) #+scl () ; TODO new-value)) ;;; Socket option: SEND-TIMEOUT (SO_SNDTIMEO) (defmethod socket-option ((usocket stream-usocket) (option (eql :send-timeout)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (socket:socket-options socket :so-sndtimeo) #+clozure (ccl:stream-output-timeout socket) #+cmu (lisp::fd-stream-timeout (socket-stream usocket)) #+(or ecl clasp) (sb-bsd-sockets:sockopt-send-timeout socket) #+lispworks (get-socket-send-timeout socket) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (sb-impl::fd-stream-timeout (socket-stream usocket)) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket stream-usocket) (option (eql :send-timeout)) &key) (declare (type number new-value) (ignorable new-value option)) (let ((socket (socket usocket)) (timeout new-value)) (declare (ignorable socket timeout)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (socket:socket-options socket :so-sndtimeo timeout) #+clozure (setf (ccl:stream-output-timeout socket) timeout) #+cmu (setf (lisp::fd-stream-timeout (socket-stream usocket)) (coerce timeout 'integer)) #+(or ecl clasp) (setf (sb-bsd-sockets:sockopt-send-timeout socket) timeout) #+lispworks (set-socket-send-timeout socket timeout) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (setf (sb-impl::fd-stream-timeout (socket-stream usocket)) (coerce timeout 'single-float)) #+scl () ; TODO new-value)) ;;; Socket option: REUSE-ADDRESS (SO_REUSEADDR), for TCP server (defmethod socket-option ((usocket stream-server-usocket) (option (eql :reuse-address)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (int->bool (socket:socket-options socket :so-reuseaddr)) #+clozure (int->bool (get-socket-option-reuseaddr socket)) #+cmu () ; TODO #+lispworks (get-socket-reuse-address socket) #+mcl () ; TODO #+mocl () ; unknown #+(or ecl sbcl clasp) (sb-bsd-sockets:sockopt-reuse-address socket) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket stream-server-usocket) (option (eql :reuse-address)) &key) (declare (type boolean new-value) (ignorable new-value option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro (socket:set-socket-options socket option new-value) #+clisp (socket:socket-options socket :so-reuseaddr (bool->int new-value)) #+clozure (set-socket-option-reuseaddr socket (bool->int new-value)) #+cmu () ; TODO #+lispworks (set-socket-reuse-address socket new-value) #+mcl () ; TODO #+mocl () ; unknown #+(or ecl sbcl clasp) (setf (sb-bsd-sockets:sockopt-reuse-address socket) new-value) #+scl () ; TODO new-value)) ;;; Socket option: BROADCAST (SO_BROADCAST), for UDP client (defmethod socket-option ((usocket datagram-usocket) (option (eql :broadcast)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (int->bool (socket:socket-options socket :so-broadcast)) #+clozure (int->bool (get-socket-option-broadcast socket)) #+cmu () ; TODO #+(or ecl clasp) () ; TODO #+lispworks (int->bool (get-socket-broadcast socket)) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (sb-bsd-sockets:sockopt-broadcast socket) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket datagram-usocket) (option (eql :broadcast)) &key) (declare (type boolean new-value) (ignorable new-value option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro (socket:set-socket-options socket option new-value) #+clisp (socket:socket-options socket :so-broadcast (bool->int new-value)) #+clozure (set-socket-option-broadcast socket (bool->int new-value)) #+cmu () ; TODO #+(or ecl clasp) () ; TODO #+lispworks (set-socket-broadcast socket (bool->int new-value)) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (setf (sb-bsd-sockets:sockopt-broadcast socket) new-value) #+scl () ; TODO new-value)) ;;; Socket option: TCP-NODELAY (TCP_NODELAY), for TCP client (defmethod socket-option ((usocket stream-usocket) (option (eql :tcp-no-delay)) &key) (declare (ignorable option)) (socket-option usocket :tcp-nodelay)) (defmethod socket-option ((usocket stream-usocket) (option (eql :tcp-nodelay)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp (int->bool (socket:socket-options socket :tcp-nodelay)) #+clozure (int->bool (get-socket-option-tcp-nodelay socket)) #+cmu () #+(or ecl clasp) (sb-bsd-sockets::sockopt-tcp-nodelay socket) #+lispworks (int->bool (get-socket-tcp-nodelay socket)) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (sb-bsd-sockets::sockopt-tcp-nodelay socket) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket stream-usocket) (option (eql :tcp-no-delay)) &key) (declare (ignorable option)) (setf (socket-option usocket :tcp-nodelay) new-value)) (defmethod (setf socket-option) (new-value (usocket stream-usocket) (option (eql :tcp-nodelay)) &key) (declare (type boolean new-value) (ignorable new-value option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro (socket:set-socket-options socket :no-delay new-value) #+clisp (socket:socket-options socket :tcp-nodelay (bool->int new-value)) #+clozure (set-socket-option-tcp-nodelay socket (bool->int new-value)) #+cmu () #+(or ecl clasp) (setf (sb-bsd-sockets::sockopt-tcp-nodelay socket) new-value) #+lispworks (progn #-(or lispworks4 lispworks5.0) (comm::set-socket-tcp-nodelay socket new-value) #+(or lispworks4 lispworks5.0) (set-socket-tcp-nodelay socket (bool->int new-value))) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (setf (sb-bsd-sockets::sockopt-tcp-nodelay socket) new-value) #+scl () ; TODO new-value)) ;;; Socket option: TCP-KEEPALIVE (SO_KEEPALIVE) (defmethod socket-option ((usocket stream-usocket) (option (eql :tcp-keepalive)) &key) (declare (ignorable option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp () ; TODO #+clozure () ; TODO #+cmu () #+(or ecl clasp) (sb-bsd-sockets::sockopt-keep-alive socket) #+lispworks (int->bool (get-socket-keepalive socket)) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (sb-bsd-sockets:sockopt-keep-alive socket) #+scl ())) ; TODO (defmethod (setf socket-option) (new-value (usocket stream-usocket) (option (eql :tcp-keepalive)) &key) (declare (type boolean new-value) (ignorable new-value option)) (let ((socket (socket usocket))) (declare (ignorable socket)) #+abcl () ; TODO #+allegro () ; TODO #+clisp () ; TODO #+clozure (ccl::set-socket-options socket :keepalive new-value) #+cmu () #+(or ecl clasp) (setf (sb-bsd-sockets::sockopt-keep-alive socket) new-value) #+lispworks (set-socket-keepalive socket (bool->int new-value)) #+mcl () ; TODO #+mocl () ; unknown #+sbcl (setf (sb-bsd-sockets:sockopt-keep-alive socket) new-value) #+scl () ; TODO new-value)) (eval-when (:load-toplevel :execute) (export 'socket-option))
11,506
Common Lisp
.lisp
381
24.401575
81
0.620121
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
51dd0fac48c716137ee19a5c9927c47cd8271e13fd38f28384dc4034c1d37b10
42,612
[ -1 ]
42,613
condition.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/condition.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET -*- ;;;; See LICENSE for licensing information. (in-package :usocket) ;; Condition signalled by operations with unsupported arguments ;; For trivial-sockets compatibility. (define-condition insufficient-implementation (error) ((feature :initarg :feature :reader feature) (context :initarg :context :reader context :documentation "String designator of the public API function which the feature belongs to.")) (:documentation "The ancestor of all errors usocket may generate because of insufficient support from the underlying implementation with respect to the arguments given to `function'. One call may signal several errors, if the caller allows processing to continue. ")) (define-condition unsupported (insufficient-implementation) ((minimum :initarg :minimum :reader minimum :documentation "Indicates the minimal version of the implementation required to support the requested feature.")) (:report (lambda (c stream) (format stream "~A in ~A is unsupported." (feature c) (context c)) (when (minimum c) (format stream " Minimum version (~A) is required." (minimum c))))) (:documentation "Signalled when the underlying implementation doesn't allow supporting the requested feature. When you see this error, go bug your vendor/implementation developer!")) (define-condition unimplemented (insufficient-implementation) () (:report (lambda (c stream) (format stream "~A in ~A is unimplemented." (feature c) (context c)))) (:documentation "Signalled if a certain feature might be implemented, based on the features of the underlying implementation, but hasn't been implemented yet.")) ;; Conditions raised by sockets operations (define-condition socket-condition (condition) ((socket :initarg :socket :accessor usocket-socket)) ;;###FIXME: no slots (yet); should at least be the affected usocket... (:documentation "Parent condition for all socket related conditions.")) (define-condition socket-error (socket-condition error) () ;; no slots (yet) (:documentation "Parent error for all socket related errors")) (define-condition ns-condition (condition) ((host-or-ip :initarg :host-or-ip :accessor host-or-ip)) (:documentation "Parent condition for all name resolution conditions.")) (define-condition ns-error (ns-condition error) (#+(or clasp ecl) (socket :initarg :socket :accessor usocket-socket)) (:documentation "Parent error for all name resolution errors.")) (eval-when (:compile-toplevel :load-toplevel :execute) (defun define-usocket-condition-class (class &rest parents) `(progn (define-condition ,class ,parents ()) (eval-when (:load-toplevel :execute) (export ',class))))) (defmacro define-usocket-condition-classes (class-list parents) `(progn ,@(mapcar #'(lambda (x) (apply #'define-usocket-condition-class x parents)) class-list))) ;; Mass define and export our conditions (define-usocket-condition-classes (interrupted-condition) (socket-condition)) (define-condition unknown-condition (socket-condition) ((real-condition :initarg :real-condition :accessor usocket-real-condition)) (:documentation "Condition raised when there's no other - more applicable - condition available.")) ;; Mass define and export our errors (define-usocket-condition-classes (address-in-use-error address-not-available-error already-shutdown-error bad-file-descriptor-error connection-refused-error connection-aborted-error connection-reset-error invalid-argument-error no-buffers-error operation-not-supported-error operation-not-permitted-error protocol-not-supported-error socket-type-not-supported-error network-unreachable-error network-down-error network-reset-error host-down-error host-unreachable-error out-of-memory-error shutdown-error timeout-error deadline-timeout-error invalid-socket-error invalid-socket-stream-error) (socket-error)) (define-condition unknown-error (socket-error) ((real-error :initarg :real-error :accessor usocket-real-error :initform nil) (errno :initarg :errno :reader usocket-errno :initform 0)) (:report (lambda (c stream) (typecase c (simple-condition (format stream (simple-condition-format-control (usocket-real-error c)) (simple-condition-format-arguments (usocket-real-error c)))) (otherwise (format stream "The condition ~A occurred with errno: ~D." (usocket-real-error c) (usocket-errno c)))))) (:documentation "Error raised when there's no other - more applicable - error available.")) (define-usocket-condition-classes (ns-try-again-condition) ; obsoleted (socket-condition)) (define-condition ns-unknown-condition (ns-condition) ((real-condition :initarg :real-condition :accessor ns-real-condition :initform nil)) (:documentation "Condition raised when there's no other - more applicable - condition available.")) (define-usocket-condition-classes ;; the no-data error code in the Unix 98 api ;; isn't really an error: there's just no data to return. ;; with lisp, we just return NIL (indicating no data) instead of ;; raising an exception... (ns-host-not-found-error ns-no-recovery-error ns-try-again-error) (ns-error)) (define-condition ns-unknown-error (ns-error) ((real-error :initarg :real-error :accessor ns-real-error :initform nil)) (:report (lambda (c stream) (typecase c (simple-condition (format stream (simple-condition-format-control (usocket-real-error c)) (simple-condition-format-arguments (usocket-real-error c)))) (otherwise (format stream "The condition ~A occurred." (usocket-real-error c)))))) (:documentation "Error raised when there's no other - more applicable - error available.")) (defmacro with-mapped-conditions ((&optional socket host-or-ip) &body body) `(handler-bind ((condition #'(lambda (c) (handle-condition c ,socket ,host-or-ip)))) ,@body)) (defparameter +unix-errno-condition-map+ `(((11) . ns-try-again-error) ;; EAGAIN ((35) . ns-try-again-error) ;; EDEADLCK ((4) . interrupted-condition))) ;; EINTR (defparameter +unix-errno-error-map+ ;;### the first column is for non-(linux or srv4) systems ;; the second for linux ;; the third for srv4 ;;###FIXME: How do I determine on which Unix we're running ;; (at least in clisp and sbcl; I know about cmucl...) ;; The table below works under the assumption we'll *only* see ;; socket associated errors... `(((48 98) . address-in-use-error) ((49 99) . address-not-available-error) ((9) . bad-file-descriptor-error) ((61 111) . connection-refused-error) ((54 104) . connection-reset-error) ((53 103) . connection-aborted-error) ((22) . invalid-argument-error) ((55 105) . no-buffers-error) ((12) . out-of-memory-error) ((45 95) . operation-not-supported-error) ((1 13) . operation-not-permitted-error) ((43 92) . protocol-not-supported-error) ((44 93) . socket-type-not-supported-error) ((51 101) . network-unreachable-error) ((50 100) . network-down-error) ((52 102) . network-reset-error) ((58 108) . already-shutdown-error) ((60 110) . timeout-error) ((64 112) . host-down-error) ((65 113) . host-unreachable-error))) (defun map-errno-condition (errno) (cdr (assoc errno +unix-errno-error-map+ :test #'member))) (defun map-errno-error (errno) (cdr (assoc errno +unix-errno-error-map+ :test #'member))) (defparameter +unix-ns-error-map+ `((1 . ns-host-not-found-error) (2 . ns-try-again-error) (3 . ns-no-recovery-error))) (defmacro unsupported (feature context &key minimum) `(cerror "Ignore it and continue" 'unsupported :feature ,feature :context ,context :minimum ,minimum)) (defmacro unimplemented (feature context) `(signal 'unimplemented :feature ,feature :context ,context)) ;;; People may want to ignore all unsupported warnings, here it is. (defmacro ignore-unsupported-warnings (&body body) `(handler-bind ((unsupported #'(lambda (c) (declare (ignore c)) (continue)))) (progn ,@body)))
8,860
Common Lisp
.lisp
210
35.761905
87
0.673396
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e631a95fc1e671fa25e44e3c26d1d36b7e1ed9f587bb45667d5f402302476ed8
42,613
[ -1 ]
42,614
mcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/mcl.lisp
;; MCL backend for USOCKET 0.4.1 ;; Terje Norderhaug <[email protected]>, January 1, 2009 (in-package :usocket) (defun handle-condition (condition &optional socket (host-or-ip nil)) ; incomplete, needs to handle additional conditions (flet ((raise-error (&optional socket-condition host-or-ip) (if socket-condition (cond ((typep socket-condition ns-error) (error socket-condition :socket socket :host-or-ip host-or-ip)) (t (error socket-condition :socket socket))) (error 'unknown-error :socket socket :real-error condition)))) (typecase condition (ccl:host-stopped-responding (raise-error 'host-down-error host-or-ip)) (ccl:host-not-responding (raise-error 'host-unreachable-error host-or-ip)) (ccl:connection-reset (raise-error 'connection-reset-error)) (ccl:connection-timed-out (raise-error 'timeout-error)) (ccl:opentransport-protocol-error (raise-error 'protocol-not-supported-error)) (otherwise (raise-error condition host-or-ip))))) (defun socket-connect (host port &key (element-type 'character) timeout deadline nodelay local-host local-port (protocol :stream)) (when (eq nodelay :if-supported) (setf nodelay t)) (ecase protocol (:stream (with-mapped-conditions (nil host) (let* ((socket (make-instance 'active-socket :remote-host (when host (host-to-hostname host)) :remote-port port :local-host (when local-host (host-to-hostname local-host)) :local-port local-port :deadline deadline :nodelay nodelay :connect-timeout (and timeout (round (* timeout 60))) :element-type element-type)) (stream (socket-open-stream socket))) (make-stream-socket :socket socket :stream stream)))) (:datagram (with-mapped-conditions (nil (or host local-host)) (make-datagram-socket (ccl::open-udp-socket :local-address (and local-host (host-to-hbo local-host)) :local-port local-port)))))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (socket (with-mapped-conditions () (make-instance 'passive-socket :local-port port :local-host (host-to-hbo host) :reuse-address reuseaddress :backlog backlog)))) (make-stream-server-socket socket :element-type element-type))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (let* ((socket (socket usocket)) (stream (with-mapped-conditions (usocket) (socket-accept socket :element-type element-type)))) (make-stream-socket :socket socket :stream stream))) (defmethod socket-close ((usocket usocket)) (with-mapped-conditions (usocket) (socket-close (socket usocket)))) (defmethod socket-shutdown ((usocket usocket) direction) (declare (ignore usocket direction)) ;; As far as I can tell there isn't a way to shutdown a socket in mcl. (unsupported "shutdown" 'socket-shutdown)) (defmethod ccl::stream-close ((usocket usocket)) (socket-close usocket)) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (list (hbo-to-vector-quad (ccl::get-host-address (host-to-hostname name)))))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) (ccl::inet-host-name (host-to-hbo address)))) (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defmethod get-local-address ((usocket usocket)) (hbo-to-vector-quad (ccl::get-host-address (or (local-host (socket usocket)) "")))) (defmethod get-local-port ((usocket usocket)) (local-port (socket usocket))) (defmethod get-peer-address ((usocket stream-usocket)) (hbo-to-vector-quad (ccl::get-host-address (remote-host (socket usocket))))) (defmethod get-peer-port ((usocket stream-usocket)) (remote-port (socket usocket))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BASIC MCL SOCKET IMPLEMENTATION (defclass socket () ((local-port :reader local-port :initarg :local-port) (local-host :reader local-host :initarg :local-host) (element-type :reader element-type :initform 'ccl::base-character :initarg :element-type))) (defclass active-socket (socket) ((remote-host :reader remote-host :initarg :remote-host) (remote-port :reader remote-port :initarg :remote-port) (deadline :initarg :deadline) (nodelay :initarg :nodelay) (connect-timeout :reader connect-timeout :initform NIL :initarg :connect-timeout :type (or null fixnum) :documentation "ticks (60th of a second)"))) (defmethod socket-open-stream ((socket active-socket)) (ccl::open-tcp-stream (or (remote-host socket)(ccl::local-interface-ip-address)) (remote-port socket) :element-type (if (subtypep (element-type socket) 'character) 'ccl::base-character 'unsigned-byte) :connect-timeout (connect-timeout socket))) (defmethod socket-close ((socket active-socket)) NIL) (defclass passive-socket (socket) ((streams :accessor socket-streams :type list :initform NIL :documentation "Circular list of streams with first element the next to open") (reuse-address :reader reuse-address :initarg :reuse-address) (lock :reader socket-lock :initform (ccl:make-lock "Socket")))) (defmethod initialize-instance :after ((socket passive-socket) &key backlog) (loop repeat backlog collect (socket-open-listener socket) into streams finally (setf (socket-streams socket) (cdr (rplacd (last streams) streams)))) (when (zerop (local-port socket)) (setf (slot-value socket 'local-port) (or (ccl::process-wait-with-timeout "binding port" (* 10 60) #'ccl::stream-local-port (car (socket-streams socket))) (error "timeout"))))) (defmethod socket-accept ((socket passive-socket) &key element-type &aux (lock (socket-lock socket))) (flet ((connection-established-p (stream) (ccl::with-io-buffer-locked ((ccl::stream-io-buffer stream nil)) (let ((state (ccl::opentransport-stream-connection-state stream))) (not (eq :unbnd state)))))) (with-mapped-conditions () (ccl:with-lock-grabbed (lock nil "Socket Lock") (let ((connection (shiftf (car (socket-streams socket)) (socket-open-listener socket element-type)))) (pop (socket-streams socket)) (ccl:process-wait "Accepting" #'connection-established-p connection) connection))))) (defmethod socket-close ((socket passive-socket)) (loop with streams = (socket-streams socket) for (stream tail) on streams do (close stream :abort T) until (eq tail streams) finally (setf (socket-streams socket) NIL))) (defmethod socket-open-listener (socket &optional element-type) ; see http://code.google.com/p/mcl/issues/detail?id=28 (let* ((ccl::*passive-interface-address* (local-host socket)) (new (ccl::open-tcp-stream NIL (or (local-port socket) #$kOTAnyInetAddress) :reuse-local-port-p (reuse-address socket) :element-type (if (subtypep (or element-type (element-type socket)) 'character) 'ccl::base-character 'unsigned-byte)))) (declare (special ccl::*passive-interface-address*)) new)) (defmethod input-available-p ((stream ccl::opentransport-stream)) (macrolet ((when-io-buffer-lock-grabbed ((lock &optional multiple-value-p) &body body) "Evaluates the body if and only if the lock is successfully grabbed" ;; like with-io-buffer-lock-grabbed but returns immediately instead of polling the lock (let ((needs-unlocking-p (gensym)) (lock-var (gensym))) `(let* ((,lock-var ,lock) (ccl::*grabbed-io-buffer-locks* (cons ,lock-var ccl::*grabbed-io-buffer-locks*)) (,needs-unlocking-p (needs-unlocking-p ,lock-var))) (declare (dynamic-extent ccl::*grabbed-io-buffer-locks*)) (when ,needs-unlocking-p (,(if multiple-value-p 'multiple-value-prog1 'prog1) (progn ,@body) (ccl::%release-io-buffer-lock ,lock-var))))))) (labels ((needs-unlocking-p (lock) (declare (type ccl::lock lock)) ;; crucial - clears bogus lock.value as in grab-io-buffer-lock-out-of-line: (ccl::%io-buffer-lock-really-grabbed-p lock) (ccl:store-conditional lock nil ccl:*current-process*))) "similar to stream-listen on buffered-input-stream-mixin but without waiting for lock" (let ((io-buffer (ccl::stream-io-buffer stream))) (or (not (eql 0 (ccl::io-buffer-incount io-buffer))) (ccl::io-buffer-untyi-char io-buffer) (locally (declare (optimize (speed 3) (safety 0))) (when-io-buffer-lock-grabbed ((ccl::io-buffer-lock io-buffer)) (funcall (ccl::io-buffer-listen-function io-buffer) stream io-buffer)))))))) (defmethod connection-established-p ((stream ccl::opentransport-stream)) (ccl::with-io-buffer-locked ((ccl::stream-io-buffer stream nil)) (let ((state (ccl::opentransport-stream-connection-state stream))) (not (eq :unbnd state))))) (defun wait-for-input-internal (wait-list &key timeout &aux result) (labels ((ready-sockets (sockets) (dolist (sock sockets result) (when (cond ((stream-usocket-p sock) (input-available-p (socket-stream sock))) ((stream-server-usocket-p sock) (let ((ot-stream (first (socket-streams (socket sock))))) (or (input-available-p ot-stream) (connection-established-p ot-stream))))) (push sock result))))) (with-mapped-conditions () (ccl:process-wait-with-timeout "socket input" (when timeout (truncate (* timeout 60))) #'ready-sockets (wait-list-waiters wait-list))) (nreverse result))) ;;; datagram socket methods (defmethod initialize-instance :after ((usocket datagram-usocket) &key) (with-slots (socket send-buffer recv-buffer) usocket (setq send-buffer (ccl::make-TUnitData (ccl::ot-conn-endpoint socket))) (setq recv-buffer (ccl::make-TUnitData (ccl::ot-conn-endpoint socket))))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (with-mapped-conditions (usocket host) (with-slots (socket send-buffer) usocket (unless (and host port) (unsupported 'host 'socket-send)) (ccl::send-message socket send-buffer buffer size host port offset)))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key) (with-mapped-conditions (usocket) (with-slots (socket recv-buffer) usocket (ccl::receive-message socket recv-buffer buffer length)))) (defmethod socket-close ((socket datagram-usocket)) nil) ; TODO
11,738
Common Lisp
.lisp
233
42.549356
103
0.656754
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
4b7afd2ca3556cb0e57c7e3ae66fb2934a4507b79155ccc2b81cca92b1fab92a
42,614
[ -1 ]
42,615
genera.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/genera.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: USOCKET; Base: 10 -*- ;;;; See LICENSE for licensing information. (in-package :usocket) (defclass genera-socket () ((foreign-address :initform 0 :initarg :foreign-address :accessor gs-foreign-address) (foreign-port :initform 0 :initarg :foreign-port :accessor gs-foreign-port) (local-address :initform 0 :initarg :local-address :accessor gs-local-address) (local-port :initform 0 :initarg :local-port :accessor gs-local-port)) ) (defclass genera-stream-socket (genera-socket) ((stream :initform nil :initarg :stream :accessor gs-stream)) ) (defclass genera-stream-server-socket (genera-socket) ((backlog :initform nil :initarg :backlog :accessor gs-backlog) (element-type :initform nil :initarg :element-type :accessor gs-element-type) (pending-connections :initform nil :accessor gs-pending-connections)) ) (defclass genera-datagram-socket (genera-socket) ((connection :initform nil :initarg :connection :accessor gs-connection)) ) (defun host-to-host-object (host) (let ((host (host-to-hostname host))) (cond ((string-equal host "localhost") net:*local-host*) ((ip-address-string-p host) (let ((quad (dotted-quad-to-vector-quad host))) ;;---*** NOTE: This test is temporary until we have a loopback interface (if (= (aref quad 0) 127) net:*local-host* (net:parse-host (format nil "INTERNET|~A" host))))) (t (net:parse-host host))))) (defun element-type-to-format (element-type protocol) (cond ((null element-type) (ecase protocol (:stream :text) (:datagram :binary))) ((subtypep element-type 'character) :text) (t :binary))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) (typecase condition ;;---*** TODO: Add additional conditions as appropriate (sys:connection-refused (error 'connection-refused-error :socket socket)) ((or tcp::tcp-destination-unreachable-during-connection tcp::udp-destination-unreachable) (error 'host-unreachable-error :socket socket)) (sys:host-not-responding-during-connection (error 'timeout-error :socket socket)) (sys:unknown-host-name (error 'ns-host-not-found-error :host-or-ip host-or-ip)) (sys:network-error (error 'unknown-error :socket socket :real-error condition :errno -1)))) (defun socket-connect (host port &key (protocol :stream) element-type timeout deadline (nodelay nil nodelay-p) local-host local-port) (declare (ignore local-host)) (when deadline (unsupported 'deadline 'socket-connect)) (when (and nodelay-p (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (with-mapped-conditions (nil host) (ecase protocol (:stream (let* ((host-object (host-to-host-object host)) (format (element-type-to-format element-type protocol)) (characters (eq format :text)) (timeout (if timeout (* 60 timeout) tcp:*tcp-connect-timeout*)) (stream (tcp:open-tcp-stream host-object port local-port :characters characters :ascii-translation characters :timeout timeout)) (gs (make-instance 'genera-stream-socket :stream stream))) (setf (gs-foreign-address gs) (scl:send stream :foreign-address)) (setf (gs-foreign-port gs) (scl:send stream :foreign-port)) (setf (gs-local-address gs) (scl:send stream :local-address)) (setf (gs-local-port gs) (scl:send stream :local-port)) (make-stream-socket :socket gs :stream stream))) (:datagram ;;---*** TODO (unsupported 'datagram 'socket-connect))))) (defmethod socket-close ((usocket usocket)) (with-mapped-conditions (usocket) (socket-close (socket usocket)))) (defmethod socket-close ((socket genera-stream-socket)) (with-slots (stream) socket (when stream (scl:send (shiftf stream nil) :close nil)))) (defmethod socket-close ((socket genera-stream-server-socket)) (with-slots (local-port pending-connections) socket (when local-port (tcp:remove-tcp-port-listener local-port)) (dolist (tcb pending-connections) (tcp::reject-tcb tcb)))) (defmethod socket-close ((socket genera-datagram-socket)) (with-slots (connection) socket (when connection (scl:send (shiftf connection nil) :close nil)) ;;---*** TODO: listening? )) ;;; Cribbed from TCP::MAKE-TCB (defun gensym-tcp-port () (loop as number = (incf tcp::*last-gensym-port-number*) then tcp::*last-gensym-port-number* do (cond ((loop for existing-tcb in tcp::*tcb-list* thereis (= number (tcp::tcb-local-port existing-tcb)))) ((and (<= #.(expt 2 10) number) (< number #.(expt 2 16))) (return number)) (t (setq tcp::*last-gensym-port-number* #.(expt 2 10)))))) (defun socket-listen (host port &key (reuse-address nil reuse-address-p) (reuseaddress nil reuseaddress-p) (backlog 5) (element-type 'character)) (let ((host-object (host-to-host-object host)) (port (if (zerop port) (gensym-tcp-port) port)) (reuse-address (cond (reuse-address-p reuse-address) (reuseaddress-p reuseaddress) (t nil)))) (when (<= port 1024) ;; Don't allow listening on "privileged" ports to mimic Unix/Linux semantics (error 'operation-not-permitted-error :socket nil)) (when (tcp:tcp-port-protocol-name port) ;; Can't replace a Genera server (error 'address-in-use-error :socket nil)) (when (tcp:tcp-port-listener port) (unless reuse-address (error 'address-in-use-error :socket nil))) (let ((gs (make-instance 'genera-stream-server-socket :backlog backlog :element-type element-type))) (setf (gs-local-address gs) (loop for (network address) in (scl:send host-object :network-addresses) when (typep network 'tcp:internet-network) return address)) (setf (gs-local-port gs) port) (flet ((add-to-queue (tcb) (cond ((and (not (zerop (gs-local-address gs))) (not (= (gs-local-address gs) (tcp::tcb-local-address tcb)))) ;; Reject if not destined for the proper address (tcp::reject-tcb tcb)) ((<= (length (gs-pending-connections gs)) (gs-backlog gs)) (tcp::accept-tcb tcb) (tcp::tcb-travel-through-states tcb "Accept" nil :listen :syn-received) (setf (gs-pending-connections gs) (append (gs-pending-connections gs) (list tcb)))) (t ;; Reject if backlog is full (tcp::reject-tcb tcb))))) (tcp:add-tcp-port-listener port #'add-to-queue)) (make-stream-server-socket gs :element-type element-type)))) (defmethod socket-accept ((socket stream-server-usocket) &key element-type) (with-slots (pending-connections) (socket socket) (loop (process:process-block "Wait for connection" #'(lambda () (not (null pending-connections)))) (let ((tcb (pop pending-connections))) (when tcb (let* ((format (element-type-to-format (or element-type (element-type socket)) :stream)) (characters (eq format :text)) (stream (tcp::make-tcp-stream tcb :characters characters :ascii-translation characters)) (gs (make-instance 'genera-stream-socket :stream stream))) (setf (gs-foreign-address gs) (scl:send stream :foreign-address)) (setf (gs-foreign-port gs) (scl:send stream :foreign-port)) (setf (gs-local-address gs) (scl:send stream :local-address)) (setf (gs-local-port gs) (scl:send stream :local-port)) (return (make-stream-socket :socket gs :stream stream)))))))) (defmethod get-local-address ((usocket usocket)) (hbo-to-vector-quad (gs-local-address (socket usocket)))) (defmethod get-peer-address ((usocket stream-usocket)) (hbo-to-vector-quad (gs-foreign-address (socket usocket)))) (defmethod get-local-port ((usocket usocket)) (gs-local-port (socket usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (gs-foreign-port (socket usocket))) (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) ;;---*** TODO (unsupported 'datagram 'socket-send)) (defmethod socket-receive ((socket datagram-usocket) buffer length &key) ;;---*** TODO (unsupported 'datagram 'socket-receive)) (defun get-host-by-address (address) ) ;; TODO (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (let ((host-object (host-to-host-object name))) (loop for (network address) in (scl:send host-object :network-addresses) when (typep network 'tcp:internet-network) collect (hbo-to-vector-quad address))))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () (process:process-block-with-timeout timeout "Wait for input" #'(lambda (wait-list) (let ((ready-sockets nil)) (dolist (waiter (wait-list-waiters wait-list) ready-sockets) (setf (state waiter) (cond ((stream-usocket-p waiter) (if (listen (socket-stream waiter)) :read nil)) ((datagram-usocket-p waiter) (let ((connection (gs-connection (socket waiter)))) (if (and connection (not (scl:send connection :connection-pending-p))) :read nil))) ((stream-server-usocket-p waiter) (if (gs-pending-connections (socket waiter)) :read nil)))) (when (not (null (state waiter))) (setf ready-sockets t))))) wait-list) wait-list))
9,940
Common Lisp
.lisp
231
37.796537
93
0.679413
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
0c1609521a79e660ea00e5ea22cafd3a44b1e6ee8a8a212817551f2a21a019ef
42,615
[ -1 ]
42,616
iolib.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/iolib.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter *backend* :iolib) (export 'socket-option) (defparameter +iolib-error-map+ `((iolib/sockets:socket-address-in-use-error . address-in-use-error) (iolib/sockets:socket-address-family-not-supported-error . socket-type-not-supported-error) (iolib/sockets:socket-address-not-available-error . address-not-available-error) (iolib/sockets:socket-network-down-error . network-down-error) (iolib/sockets:socket-network-reset-error . network-reset-error) (iolib/sockets:socket-network-unreachable-error . network-unreachable-error) ;; (iolib/sockets:socket-no-network-error . ?) (iolib/sockets:socket-connection-aborted-error . connection-aborted-error) (iolib/sockets:socket-connection-reset-error . connection-reset-error) (iolib/sockets:socket-connection-refused-error . connection-refused-error) (iolib/sockets:socket-connection-timeout-error . timeout-error) ;; (iolib/sockets:socket-connection-in-progress-error . ?) (iolib/sockets:socket-endpoint-shutdown-error . network-down-error) (iolib/sockets:socket-no-buffer-space-error . no-buffers-error) (iolib/sockets:socket-host-down-error . host-down-error) (iolib/sockets:socket-host-unreachable-error . host-unreachable-error) ;; (iolib/sockets:socket-already-connected-error . ?) (iolib/sockets:socket-not-connected-error . connection-refused-error) (iolib/sockets:socket-option-not-supported-error . operation-not-permitted-error) (iolib/syscalls:eacces . operation-not-permitted-error) (iolib/sockets:socket-operation-not-supported-error . operation-not-supported-error) (iolib/sockets:unknown-protocol . protocol-not-supported-error) ;; (iolib/sockets:unknown-interface . ?) (iolib/sockets:unknown-service . protocol-not-supported-error) (iolib/sockets:socket-error . socket-error) ;; Nameservice errors (src/sockets/dns/conditions.lisp) (iolib/sockets:resolver-error . ns-error) (iolib/sockets:resolver-fail-error . ns-host-not-found-error) (iolib/sockets:resolver-again-error . ns-try-again-error) (iolib/sockets:resolver-no-name-error . ns-no-recovery-error) (iolib/sockets:resolver-unknown-error . ns-unknown-error) )) ;; IOlib uses (SIMPLE-ARRAY (UNSIGNED-BYTE 16) (8)) to represent IPv6 addresses, ;; while USOCKET shared code uses (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (16)). Here we do the ;; conversion. (defun iolib-vector-to-vector-quad (host) (etypecase host ((or (vector t 4) ; IPv4 (array (unsigned-byte 8) (4))) host) ((or (vector t 8) ; IPv6 (array (unsigned-byte 16) (8))) (loop with vector = (make-array 16 :element-type '(unsigned-byte 8)) for i below 16 by 2 for word = (aref host (/ i 2)) do (setf (aref vector i) (ldb (byte 8 8) word) (aref vector (1+ i)) (ldb (byte 8 0) word)) finally (return vector))))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (let* ((usock-error (cdr (assoc (type-of condition) +iolib-error-map+))) (usock-error (if (functionp usock-error) (funcall usock-error condition) usock-error))) (if usock-error (if (typep usock-error 'socket-error) (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (cond ((subtypep usock-error 'ns-condition) (signal usock-error :socket socket :host-or-ip host-or-ip)) (t (signal usock-error :socket socket)))) (error 'unknown-error :real-error condition :socket socket)))) (defun ipv6-address-p (host) (iolib/sockets:ipv6-address-p (iolib/sockets:ensure-hostname host))) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t) ;; nodelay == t is the ACL default local-host local-port) (declare (ignore element-type deadline nodelay)) (with-mapped-conditions (nil host) (let* ((remote (when (and host port) (iolib/sockets:ensure-hostname host))) (local (when (and local-host local-port) (iolib/sockets:ensure-hostname local-host))) (ipv6-p (or (and remote (ipv6-address-p remote) (and local (ipv6-address-p local))))) (socket (apply #'iolib/sockets:make-socket `(:type ,protocol :address-family :internet :ipv6 ,ipv6-p :connect ,(cond ((eq protocol :stream) :active) ((and host port) :active) (t :passive)) ,@(when local `(:local-host ,local :local-port ,local-port)) :nodelay nodelay)))) (when remote (apply #'iolib/sockets:connect `(,socket ,remote :port ,port ,@(when timeout `(:wait ,timeout)))) (unless (iolib/sockets:socket-connected-p socket) (close socket) (error 'iolib/sockets:socket-error))) (ecase protocol (:stream (make-stream-socket :stream socket :socket socket)) (:datagram (make-datagram-socket socket :connected-p (and remote t))))))) (defmethod socket-close ((usocket usocket)) (close (socket usocket))) (defmethod socket-shutdown ((usocket stream-usocket) direction) (with-mapped-conditions () (case direction (:input (iolib/sockets:shutdown (socket usocket) :read t)) (:output (iolib/sockets:shutdown (socket usocket) :write t)) (t ; :io by default (iolib/sockets:shutdown (socket usocket) :read t :write t))))) (defun socket-listen (host port &key reuseaddress reuse-address (backlog 5) (element-type 'character)) (declare (ignore element-type)) (with-mapped-conditions (nil host) (make-stream-server-socket (iolib/sockets:make-socket :connect :passive :address-family :internet :local-host (iolib/sockets:ensure-hostname host) :local-port port :backlog backlog :reuse-address (or reuse-address reuseaddress))))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (declare (ignore element-type)) (with-mapped-conditions (usocket) (let ((socket (iolib/sockets:accept-connection (socket usocket)))) (make-stream-socket :socket socket :stream socket)))) (defmethod get-local-address ((usocket usocket)) (iolib-vector-to-vector-quad (iolib/sockets:address-to-vector (iolib/sockets:local-host (socket usocket))))) (defmethod get-peer-address ((usocket stream-usocket)) (iolib-vector-to-vector-quad (iolib/sockets:address-to-vector (iolib/sockets:remote-host (socket usocket))))) (defmethod get-local-port ((usocket usocket)) (iolib/sockets:local-port (socket usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (iolib/sockets:remote-port (socket usocket))) (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (apply #'iolib/sockets:send-to `(,(socket usocket) ,buffer :start ,offset :end ,(+ offset size) ,@(when (and host port) `(:remote-host ,(iolib/sockets:ensure-hostname host) :remote-port ,port))))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key start end) (multiple-value-bind (buffer size host port) (iolib/sockets:receive-from (socket usocket) :buffer buffer :size length :start start :end end) (values buffer size (iolib-vector-to-vector-quad host) port))) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (multiple-value-bind (address more-addresses) (iolib/sockets:lookup-hostname name :ipv6 iolib/sockets:*ipv6*) (mapcar #'(lambda (x) (iolib-vector-to-vector-quad (iolib/sockets:address-name x))) (cons address more-addresses))))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) nil)) ;; TODO (defvar *event-base* (make-instance 'iolib/multiplex:event-base)) (defun %setup-wait-list (wait-list) (setf (wait-list-%wait wait-list) (or *event-base* ;; iolib/multiplex:*default-multiplexer* is used here (make-instance 'iolib/multiplex:event-base)))) (defun make-usocket-read-handler (usocket disconnector) (lambda (fd event exception) (declare (ignore fd event exception)) (handler-case (if (eq (state usocket) :write) (setf (state usocket) :read-write) (setf (state usocket) :read)) (end-of-file () (funcall disconnector :close))))) (defun make-usocket-write-handler (usocket disconnector) (lambda (fd event exception) (declare (ignore fd event exception)) (handler-case (if (eq (state usocket) :read) (setf (state usocket) :read-write) (setf (state usocket) :write)) (end-of-file () (funcall disconnector :close)) (iolib/streams:hangup () (funcall disconnector :close))))) #|| Too few arguments in call to #<Compiled-function (:internal usocket::make-usocket-error-handler) (Non-Global) #x3020018C678F>: 2 arguments provided, at least 3 required. Backtrace: 0: ((:internal usocket::make-usocket-error-handler) 17511955605035 2) 1: (iolib/multiplex::%handle-one-fd #<event base, 1 FDs monitored, using: #<epoll(4) multiplexer> #x3020018C963D> (8 (:error :read :write)) 54337.518855526D0 nil 0.0D0) ||# (defun make-usocket-error-handler (usocket disconnector) (lambda (fd event &optional exception) (declare (ignore fd event exception)) (handler-case (setf (state usocket) nil) (end-of-file () (funcall disconnector :close)) (iolib/streams:hangup () (funcall disconnector :close))))) (defun make-usocket-disconnector (event-base usocket) (declare (ignore event-base)) (lambda (&rest events) (let ((socket (socket usocket))) ;; if were asked to close the socket, we do so here (when (member :close events) (close socket :abort t))))) (defun %add-waiter (wait-list waiter) (let ((event-base (wait-list-%wait wait-list)) (fd (iolib/sockets:socket-os-fd (socket waiter)))) ;; reset socket state (setf (state waiter) nil) ;; set read handler (unless (iolib/multiplex::fd-monitored-p event-base fd :read) (iolib/multiplex:set-io-handler event-base fd :read (make-usocket-read-handler waiter (make-usocket-disconnector event-base waiter)))) ;; set write handler #+ignore (unless (iolib/multiplex::fd-monitored-p event-base fd :write) (iolib/multiplex:set-io-handler event-base fd :write (make-usocket-write-handler waiter (make-usocket-disconnector event-base waiter)))) ;; set error handler (unless (iolib/multiplex::fd-has-error-handler-p event-base fd) (iolib/multiplex:set-error-handler event-base fd (make-usocket-error-handler waiter (make-usocket-disconnector event-base waiter)))))) (defun %remove-waiter (wait-list waiter) (let ((event-base (wait-list-%wait wait-list))) (iolib/multiplex:remove-fd-handlers event-base (iolib/sockets:socket-os-fd (socket waiter)) :read t :write nil :error t))) ;; NOTE: `wait-list-waiters` returns all usockets (defun wait-for-input-internal (wait-list &key timeout) (let ((event-base (wait-list-%wait wait-list))) (handler-case (iolib/multiplex:event-dispatch event-base :timeout timeout) (iolib/streams:hangup ()) (end-of-file ())) ;; close the event-base after use (unless (eq event-base *event-base*) (close event-base)))) (defmethod socket-option ((socket usocket) option) (iolib/sockets:socket-option (socket-stream socket) option)) (defmethod (setf socket-option) (new-value (socket usocket) option) (let ((form `(setf (iolib/sockets:socket-option ,(socket-stream socket) ,option) ,new-value))) (eval (macroexpand-1 form))))
12,526
Common Lisp
.lisp
268
40.940299
170
0.671985
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
777149f5c453865ca189459ae7cebc0bda2a3d7d87066615eeb483599d68a0a7
42,616
[ -1 ]
42,617
allegro.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/allegro.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) #+cormanlisp (eval-when (:compile-toplevel :load-toplevel :execute) (require :acl-socket)) #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (require :sock) ;; for wait-for-input: (require :process) ;; note: the line below requires ACL 6.2+ (require :osi)) (defun get-host-name () ;; note: the line below requires ACL 7.0+ to actually *work* on windows #+allegro (excl.osi:gethostname) #+cormanlisp "") (defparameter +allegro-identifier-error-map+ '((:address-in-use . address-in-use-error) (:address-not-available . address-not-available-error) (:network-down . network-down-error) (:network-reset . network-reset-error) (:network-unreachable . network-unreachable-error) (:connection-aborted . connection-aborted-error) (:connection-reset . connection-reset-error) (:no-buffer-space . no-buffers-error) (:shutdown . shutdown-error) (:connection-timed-out . timeout-error) (:connection-refused . connection-refused-error) (:host-down . host-down-error) (:host-unreachable . host-unreachable-error))) ;; TODO: what's the error class of Corman Lisp? (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (typecase condition #+allegro (excl:socket-error (let ((usock-error (cdr (assoc (excl:stream-error-identifier condition) +allegro-identifier-error-map+)))) (declare (type symbol usock-error)) (if usock-error (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (error 'unknown-error :real-error condition :socket socket)))))) (defun to-format (element-type) (if (subtypep element-type 'character) :text :binary)) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t) ;; nodelay == t is the ACL default local-host local-port) (when timeout (unsupported 'timeout 'socket-connect)) (when deadline (unsupported 'deadline 'socket-connect)) (when (eq nodelay :if-supported) (setf nodelay t)) (let ((socket)) (setf socket (with-mapped-conditions (socket (or host local-host)) (ecase protocol (:stream (labels ((make-socket () (socket:make-socket :remote-host (host-to-hostname host) :remote-port port :local-host (when local-host (host-to-hostname local-host)) :local-port local-port :format (to-format element-type) :nodelay nodelay))) #+allegro (if timeout (mp:with-timeout (timeout nil) (make-socket)) (make-socket)) #+cormanlisp (make-socket))) (:datagram (apply #'socket:make-socket (nconc (list :type protocol :address-family :internet :local-host (when local-host (host-to-hostname local-host)) :local-port local-port :format (to-format element-type)) (if (and host port) (list :connect :active :remote-host (host-to-hostname host) :remote-port port) (list :connect :passive)))))))) (ecase protocol (:stream (make-stream-socket :socket socket :stream socket)) (:datagram (make-datagram-socket socket :connected-p (and host port t)))))) ;; One socket close method is sufficient, ;; because socket-streams are also sockets. (defmethod socket-close ((usocket usocket)) "Close socket." (with-mapped-conditions (usocket) (close (socket usocket) :abort t))) ; see "sbcl.lisp" for (:abort t) (defmethod socket-shutdown ((usocket stream-usocket) direction) (with-mapped-conditions (usocket) (if (eq :io direction) (progn (socket:shutdown (socket usocket) :direction :input) (socket:shutdown (socket usocket) :direction :output)) (socket:shutdown (socket usocket) :direction direction)))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) ;; Allegro and OpenMCL socket interfaces bear very strong resemblence ;; whatever you change here, change it also for OpenMCL (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (sock (with-mapped-conditions (nil host) (apply #'socket:make-socket (append (list :connect :passive :reuse-address reuseaddress :local-port port :backlog backlog :format (to-format element-type) ;; allegro now ignores :format ) (when (ip/= host *wildcard-host*) (list :local-host host))))))) (make-stream-server-socket sock :element-type element-type))) (defmethod socket-accept ((socket stream-server-usocket) &key element-type) (declare (ignore element-type)) ;; allegro streams are multivalent (let ((stream-sock (with-mapped-conditions (socket) (socket:accept-connection (socket socket))))) (make-stream-socket :socket stream-sock :stream stream-sock))) (defmethod get-local-address ((usocket usocket)) (hbo-to-vector-quad (socket:local-host (socket usocket)))) (defmethod get-peer-address ((usocket stream-usocket)) (hbo-to-vector-quad (socket:remote-host (socket usocket)))) (defmethod get-local-port ((usocket usocket)) (socket:local-port (socket usocket))) (defmethod get-peer-port ((usocket stream-usocket)) #+allegro (socket:remote-port (socket usocket))) (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) #+allegro (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (with-mapped-conditions (usocket host) (let ((s (socket usocket))) (socket:send-to s (if (zerop offset) buffer (subseq buffer offset (+ offset size))) size :remote-host host :remote-port port)))) #+allegro (defmethod socket-receive ((usocket datagram-usocket) buffer length &key) (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (unsigned-byte 32) ; host (unsigned-byte 16))) ; port (with-mapped-conditions (usocket) (let ((s (socket usocket))) (socket:receive-from s length :buffer buffer :extract t)))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) (socket:ipaddr-to-hostname (host-to-hbo address)))) (defun get-hosts-by-name (name) ;;###FIXME: ACL has the acldns module which returns all A records ;; only problem: it doesn't fall back to tcp (from udp) if the returned ;; structure is too long. (with-mapped-conditions (nil name) (list (hbo-to-vector-quad (socket:lookup-hostname (host-to-hostname name)))))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (push (socket waiter) (wait-list-%wait wait-list))) (defun %remove-waiter (wait-list waiter) (setf (wait-list-%wait wait-list) (remove (socket waiter) (wait-list-%wait wait-list)))) #+allegro (defun wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () (let ((active-internal-sockets (if timeout (mp:wait-for-input-available (wait-list-%wait wait-list) :timeout timeout) (mp:wait-for-input-available (wait-list-%wait wait-list))))) ;; this is quadratic, but hey, the active-internal-sockets ;; list is very short and it's only quadratic in the length of that one. ;; When I have more time I could recode it to something of linear ;; complexity. ;; [Same code is also used in openmcl.lisp] (dolist (x active-internal-sockets) (setf (state (gethash x (wait-list-map wait-list))) :read)) wait-list)))
8,808
Common Lisp
.lisp
205
34.385366
89
0.622435
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
4aae7888c9000291f35575619acc6cde34aa15cfa12b6b68a266c9c0c5e29f50
42,617
[ -1 ]
42,618
mocl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/mocl.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (declare (ignore socket)) (signal condition)) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-specified) (local-host nil local-host-p) (local-port nil local-port-p)) (when (and nodelay-specified (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (when deadline (unsupported 'deadline 'socket-connect)) (when timeout (unimplemented 'timeout 'socket-connect)) (when local-host-p (unimplemented 'local-host 'socket-connect)) (when local-port-p (unimplemented 'local-port 'socket-connect)) (let (socket) (ecase protocol (:stream (setf socket (rt::socket-connect host port)) (let ((stream (rt::make-socket-stream socket :binaryp (not (eq element-type 'character))))) (make-stream-socket :socket socket :stream stream))) (:datagram (error 'unsupported :feature '(protocol :datagram) :context 'socket-connect))))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (unimplemented 'socket-listen 'mocl)) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (unimplemented 'socket-accept 'mocl)) ;; Sockets and their associated streams are modelled as ;; different objects. Be sure to close the socket stream ;; when closing stream-sockets; it makes sure buffers ;; are flushed and the socket is closed correctly afterwards. (defmethod socket-close ((usocket usocket)) "Close socket." (rt::socket-shutdown usocket) (rt::c-fclose usocket)) (defmethod socket-close ((usocket stream-usocket)) "Close socket." (close (socket-stream usocket))) ;; (defmethod socket-close :after ((socket datagram-usocket)) ;; (setf (%open-p socket) nil)) (defmethod socket-shutdown ((usocket stream-usocket) direction) (declare (ignore usocket direction)) ;; sure would be nice if there was some documentation for mocl... (unimplemented "shutdown" 'socket-shutdown)) ;; (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port) ;; (let ((s (socket usocket)) ;; (host (if host (host-to-hbo host))) ;; (real-buffer (if (zerop offset) ;; buffer ;; (subseq buffer offset (+ offset size))))) ;; (multiple-value-bind (result errno) ;; (ext:inet-socket-send-to s real-buffer size ;; :remote-host host :remote-port port) ;; (or result ;; (mocl-map-socket-error errno :socket usocket))))) ;; (defmethod socket-receive ((socket datagram-usocket) buffer length &key) ;; (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer ;; (integer 0) ; size ;; (unsigned-byte 32) ; host ;; (unsigned-byte 16))) ; port ;; (let ((s (socket socket))) ;; (let ((real-buffer (or buffer ;; (make-array length :element-type '(unsigned-byte 8)))) ;; (real-length (or length ;; (length buffer)))) ;; (multiple-value-bind (result errno remote-host remote-port) ;; (ext:inet-socket-receive-from s real-buffer real-length) ;; (if result ;; (values real-buffer result remote-host remote-port) ;; (mocl-map-socket-error errno :socket socket)))))) ;; (defmethod get-local-name ((usocket usocket)) ;; (multiple-value-bind (address port) ;; (with-mapped-conditions (usocket) ;; (ext:get-socket-host-and-port (socket usocket))) ;; (values (hbo-to-vector-quad address) port))) ;; (defmethod get-peer-name ((usocket stream-usocket)) ;; (multiple-value-bind (address port) ;; (with-mapped-conditions (usocket) ;; (ext:get-peer-host-and-port (socket usocket))) ;; (values (hbo-to-vector-quad address) port))) ;; (defmethod get-local-address ((usocket usocket)) ;; (nth-value 0 (get-local-name usocket))) ;; (defmethod get-peer-address ((usocket stream-usocket)) ;; (nth-value 0 (get-peer-name usocket))) ;; (defmethod get-local-port ((usocket usocket)) ;; (nth-value 1 (get-local-name usocket))) ;; (defmethod get-peer-port ((usocket stream-usocket)) ;; (nth-value 1 (get-peer-name usocket))) ;; (defun get-host-by-address (address) ;; (multiple-value-bind (host errno) ;; (ext:lookup-host-entry (host-byte-order address)) ;; (cond (host ;; (ext:host-entry-name host)) ;; (t ;; (let ((condition (cdr (assoc errno +unix-ns-error-map+)))) ;; (cond (condition ;; (error condition :host-or-ip address)) ;; (t ;; (error 'ns-unknown-error :host-or-ip address ;; :real-error errno)))))))) (defun get-hosts-by-name (name) (rt::lookup-host name)) ;; (defun get-host-name () ;; (unix:unix-gethostname)) ;; ;; ;; WAIT-LIST part ;; (defun %add-waiter (wl waiter) (declare (ignore wl waiter))) (defun %remove-waiter (wl waiter) (declare (ignore wl waiter))) (defun %setup-wait-list (wl) (declare (ignore wl))) (defun wait-for-input-internal (wait-list &key timeout) (unimplemented 'wait-for-input-internal 'mocl))
5,501
Common Lisp
.lisp
126
40.111111
98
0.646465
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
4f6c15b3ac99a23e5f81073af09734d9ba296046215b52b94c2d7cfc4277f245
42,618
[ -1 ]
42,619
clozure.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/clozure.lisp
;;;; See LICENSE for licensing information. ;;;; Functions for CCL 1.11 (IPv6) only, see openmcl.lisp for rest of functions. (in-package :usocket) #+ipv6 (defun socket-connect (host port &key (protocol :stream) element-type timeout deadline nodelay local-host local-port) (when (eq nodelay :if-supported) (setf nodelay t)) (with-mapped-conditions (nil host) (let (remote local mcl-sock) (loop :for address-family :in '(:internet6 :internet) :do (tagbody (setq remote (when (and host port) (openmcl-socket:resolve-address :host (host-to-hostname host) :port port :socket-type protocol :address-family address-family)) local (when (and local-host local-port) (openmcl-socket:resolve-address :host (host-to-hostname local-host) :port local-port :socket-type protocol :address-family address-family)) mcl-sock (handler-bind ((ccl:socket-creation-error (lambda (err) (if (eq address-family :internet6) ; the first try, let's ignore the error (go :continue)) (signal err)))) (apply #'openmcl-socket:make-socket `(:type ,protocol ,@(when (or remote local) `(:address-family ,(openmcl-socket:socket-address-family (or remote local)))) ,@(when remote `(:remote-address ,remote)) ,@(when local `(:local-address ,local)) :format ,(to-format element-type protocol) :external-format ,ccl:*default-external-format* :deadline ,deadline :nodelay ,nodelay :connect-timeout ,timeout :input-timeout ,timeout)))) (loop-finish) :continue)) (ecase protocol (:stream (make-stream-socket :stream mcl-sock :socket mcl-sock)) (:datagram (make-datagram-socket mcl-sock :connected-p (and remote t))))))) #+ipv6 (defun socket-listen (host port &key (reuse-address nil reuse-address-supplied-p) (reuseaddress (when reuse-address-supplied-p reuse-address)) (backlog 5) (element-type 'character)) (let ((local-address (openmcl-socket:resolve-address :host (host-to-hostname host) :port port :connect :passive))) (with-mapped-conditions (nil host) (make-stream-server-socket (openmcl-socket:make-socket :connect :passive :address-family (openmcl-socket:socket-address-family local-address) :local-address local-address :reuse-address reuseaddress :backlog backlog :format (to-format element-type :stream)) :element-type element-type)))) #+ipv6 (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (let* ((ccl-socket (socket usocket)) (socket-keys (ccl::socket-keys ccl-socket))) (with-mapped-conditions (usocket host) (if (and host port) (openmcl-socket:send-to ccl-socket buffer size :remote-host (host-to-hostname host) :remote-port port :offset offset) (openmcl-socket:send-to ccl-socket buffer size :remote-address (getf socket-keys :remote-address) :offset offset)))))
4,597
Common Lisp
.lisp
85
30.505882
104
0.447082
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
9a86af9d1a83763d45bcf5ae3bcbf2c029052d6c52eea3a00161e24c40f2303a
42,619
[ -1 ]
42,620
lispworks.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/lispworks.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (eval-when (:compile-toplevel :load-toplevel :execute) (require "comm") #+lispworks3 (error "LispWorks 3 is not supported")) ;;; --------------------------------------------------------------------------- ;;; Warn if multiprocessing is not running on Lispworks (defun check-for-multiprocessing-started (&optional errorp) (unless mp:*current-process* (funcall (if errorp 'error 'warn) "You must start multiprocessing on Lispworks by calling~ ~%~3t(~s)~ ~%for ~s function properly." 'mp:initialize-multiprocessing 'wait-for-input))) (eval-when (:load-toplevel :execute) (check-for-multiprocessing-started)) #+win32 (eval-when (:load-toplevel :execute) (fli:register-module "ws2_32")) (fli:define-foreign-function (get-host-name-internal "gethostname" :source) ((return-string (:reference-return (:ef-mb-string :limit 257))) (namelen :int)) :lambda-list (&aux (namelen 256) return-string) :result-type :int #+win32 :module #+win32 "ws2_32") (defun get-host-name () (multiple-value-bind (return-code name) (get-host-name-internal) (when (zerop return-code) name))) #+win32 (defun remap-maybe-for-win32 (z) (mapcar #'(lambda (x) (cons (mapcar #'(lambda (y) (+ 10000 y)) (car x)) (cdr x))) z)) (defparameter +lispworks-error-map+ #+win32 (append (remap-maybe-for-win32 +unix-errno-condition-map+) (remap-maybe-for-win32 +unix-errno-error-map+)) #-win32 (append +unix-errno-condition-map+ +unix-errno-error-map+)) (defun raise-usock-err (errno socket &optional condition (host-or-ip nil)) (let ((usock-error (cdr (assoc errno +lispworks-error-map+ :test #'member)))) (if usock-error (if (subtypep usock-error 'error) (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (cond ((subtypep usock-error 'ns-condition) (signal usock-error :socket socket :host-or-ip host-or-ip)) (t (signal usock-error :socket socket)))) (error 'unknown-error :socket socket :real-error condition :errno errno)))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (typecase condition (condition (let ((errno #-win32 (lw:errno-value) #+win32 (wsa-get-last-error))) (unless (zerop errno) (raise-usock-err errno socket condition host-or-ip)))))) (defconstant *socket_sock_dgram* 2 "Connectionless, unreliable datagrams of fixed maximum length.") (defconstant *socket_ip_proto_udp* 17) (defconstant *sockopt_so_rcvtimeo* #-linux #x1006 #+linux 20 "Socket receive timeout") (defconstant *sockopt_so_sndtimeo* #-linux #x1007 #+linux 21 "Socket send timeout") (fli:define-c-struct timeval (tv-sec :long) (tv-usec :long)) (defconstant *sockopt_so_broadcast* #-linux #x0020 #+linux 6 "Socket broadcast") (defconstant *sockopt_so_keepalive* #-linux #x0008 #+linux 9 "Socket keepalive") ;;; ssize_t ;;; recvfrom(int socket, void *restrict buffer, size_t length, int flags, ;;; struct sockaddr *restrict address, socklen_t *restrict address_len); (fli:define-foreign-function (%recvfrom "recvfrom" :source) ((socket :int) (buffer (:pointer (:unsigned :byte))) (length :int) (flags :int) (address (:pointer (:struct comm::sockaddr))) (address-len (:pointer :int))) :result-type :int #+win32 :module #+win32 "ws2_32") ;;; ssize_t ;;; sendto(int socket, const void *buffer, size_t length, int flags, ;;; const struct sockaddr *dest_addr, socklen_t dest_len); (fli:define-foreign-function (%sendto "sendto" :source) ((socket :int) (buffer (:pointer (:unsigned :byte))) (length :int) (flags :int) (address (:pointer (:struct comm::sockaddr))) (address-len :int)) :result-type :int #+win32 :module #+win32 "ws2_32") #-win32 (defun set-socket-receive-timeout (socket-fd seconds) "Set socket option: RCVTIMEO, argument seconds can be a float number" (declare (type integer socket-fd) (type number seconds)) (multiple-value-bind (sec usec) (truncate seconds) (fli:with-dynamic-foreign-objects ((timeout (:struct timeval))) (fli:with-foreign-slots (tv-sec tv-usec) timeout (setf tv-sec sec tv-usec (truncate (* 1000000 usec))) (if (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) (fli:size-of '(:struct timeval)))) seconds))))) #-win32 (defun set-socket-send-timeout (socket-fd seconds) "Set socket option: SNDTIMEO, argument seconds can be a float number" (declare (type integer socket-fd) (type number seconds)) (multiple-value-bind (sec usec) (truncate seconds) (fli:with-dynamic-foreign-objects ((timeout (:struct timeval))) (fli:with-foreign-slots (tv-sec tv-usec) timeout (setf tv-sec sec tv-usec (truncate (* 1000000 usec))) (if (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_sndtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) (fli:size-of '(:struct timeval)))) seconds))))) #+win32 (defun set-socket-receive-timeout (socket-fd seconds) "Set socket option: RCVTIMEO, argument seconds can be a float number. On win32, you must bind the socket before use this function." (declare (type integer socket-fd) (type number seconds)) (fli:with-dynamic-foreign-objects ((timeout :int)) (setf (fli:dereference timeout) (truncate (* 1000 seconds))) (if (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :char)) (fli:size-of :int))) seconds))) #+win32 (defun set-socket-send-timeout (socket-fd seconds) "Set socket option: SNDTIMEO, argument seconds can be a float number. On win32, you must bind the socket before use this function." (declare (type integer socket-fd) (type number seconds)) (fli:with-dynamic-foreign-objects ((timeout :int)) (setf (fli:dereference timeout) (truncate (* 1000 seconds))) (if (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_sndtimeo* (fli:copy-pointer timeout :type '(:pointer :char)) (fli:size-of :int))) seconds))) #-win32 (defun get-socket-receive-timeout (socket-fd) "Get socket option: RCVTIMEO, return value is a float number" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((timeout (:struct timeval)) (len :int)) (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (fli:with-foreign-slots (tv-sec tv-usec) timeout (float (+ tv-sec (/ tv-usec 1000000)))))) #-win32 (defun get-socket-send-timeout (socket-fd) "Get socket option: SNDTIMEO, return value is a float number" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((timeout (:struct timeval)) (len :int)) (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_sndtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (fli:with-foreign-slots (tv-sec tv-usec) timeout (float (+ tv-sec (/ tv-usec 1000000)))))) #+win32 (defun get-socket-receive-timeout (socket-fd) "Get socket option: RCVTIMEO, return value is a float number" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((timeout :int) (len :int)) (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_rcvtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (float (/ (fli:dereference timeout) 1000)))) #+win32 (defun get-socket-send-timeout (socket-fd) "Get socket option: SNDTIMEO, return value is a float number" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((timeout :int) (len :int)) (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_sndtimeo* (fli:copy-pointer timeout :type '(:pointer :void)) len) (float (/ (fli:dereference timeout) 1000)))) #+(or lispworks4 lispworks5.0) (defun set-socket-tcp-nodelay (socket-fd new-value) "Set socket option: TCP_NODELAY, argument is a fixnum (0 or 1)" (declare (type integer socket-fd) (type (integer 0 1) new-value)) (fli:with-dynamic-foreign-objects ((zero-or-one :int)) (setf (fli:dereference zero-or-one) new-value) (when (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* comm::*sockopt_tcp_nodelay* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) (fli:size-of :int))) new-value))) (defun get-socket-tcp-nodelay (socket-fd) "Get socket option: TCP_NODELAY, return value is a fixnum (0 or 1)" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((zero-or-one :int) (len :int)) (if (zerop (comm::getsockopt socket-fd comm::*sockopt_sol_socket* comm::*sockopt_tcp_nodelay* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) len)) zero-or-one 0))) ; on error, return 0 (defun get-socket-broadcast (socket-fd) "Get socket option: SO_BROADCAST, return value is a fixnum (0 or 1)" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((zero-or-one :int) (len :int)) (if (zerop (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_broadcast* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) len)) zero-or-one 0))) (defun set-socket-broadcast (socket-fd new-value) "Set socket option: SO_BROADCAST, argument is a fixnum (0 or 1)" (declare (type integer socket-fd) (type (integer 0 1) new-value)) (fli:with-dynamic-foreign-objects ((zero-or-one :int)) (setf (fli:dereference zero-or-one) new-value) (when (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_broadcast* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) (fli:size-of :int))) new-value))) (defun get-socket-keepalive (socket-fd) "Get socket option: SO_KEEPALIVE, return value is a fixnum (0 or 1)" (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((zero-or-one :int) (len :int)) (if (zerop (comm::getsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_keepalive* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) len)) zero-or-one 0))) (defun set-socket-keepalive (socket-fd new-value) "Set socket option: SO_KEEPALIVE, argument is a fixnum (0 or 1)" (declare (type integer socket-fd) (type (integer 0 1) new-value)) (fli:with-dynamic-foreign-objects ((zero-or-one :int)) (setf (fli:dereference zero-or-one) new-value) (when (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* *sockopt_so_keepalive* (fli:copy-pointer zero-or-one :type '(:pointer #+win32 :char #-win32 :void)) (fli:size-of :int))) new-value))) (defun initialize-dynamic-sockaddr (hostname service protocol &aux (original-hostname hostname)) (declare (ignorable original-hostname)) #+(or lispworks4 lispworks5 lispworks6.0) (let ((server-addr (fli:allocate-dynamic-foreign-object :type '(:struct comm::sockaddr_in)))) (values (comm::initialize-sockaddr_in server-addr comm::*socket_af_inet* hostname service protocol) comm::*socket_af_inet* server-addr (fli:pointer-element-size server-addr))) #-(or lispworks4 lispworks5 lispworks6.0) ; version>=6.1 (progn (when (stringp hostname) (setq hostname (comm:string-ip-address hostname)) (unless hostname (let ((resolved-hostname (comm:get-host-entry original-hostname :fields '(:address)))) (unless resolved-hostname (return-from initialize-dynamic-sockaddr :unknown-host)) (setq hostname resolved-hostname)))) (if (or (null hostname) (integerp hostname) (comm:ipv6-address-p hostname)) (let ((server-addr (fli:allocate-dynamic-foreign-object :type '(:struct comm::lw-sockaddr)))) (multiple-value-bind (error family) (comm::initialize-sockaddr_in server-addr hostname service protocol) (values error family server-addr (if (eql family comm::*socket_af_inet*) (fli:size-of '(:struct comm::sockaddr_in)) (fli:size-of '(:struct comm::sockaddr_in6)))))) :bad-host))) (defun open-udp-socket (&key local-address local-port read-timeout (address-family comm::*socket_af_inet*)) "Open a unconnected UDP socket. For binding on address ANY(*), just not set LOCAL-ADDRESS (NIL), for binding on random free unused port, set LOCAL-PORT to 0." ;; Note: move (ensure-sockets) here to make sure delivered applications ;; correctly have networking support initialized. ;; ;; Following words was from Martin Simmons, forwarded by Camille Troillard: ;; Calling comm::ensure-sockets at load time looks like a bug in Lispworks-udp ;; (it is too early and also unnecessary). ;; The LispWorks comm package calls comm::ensure-sockets when it is needed, so I ;; think open-udp-socket should probably do it too. Calling it more than once is ;; safe and it will be very fast after the first time. #+win32 (comm::ensure-sockets) (let ((socket-fd (comm::socket address-family *socket_sock_dgram* *socket_ip_proto_udp*))) (if socket-fd (progn (when read-timeout (set-socket-receive-timeout socket-fd read-timeout)) (if local-port (fli:with-dynamic-foreign-objects () (multiple-value-bind (error local-address-family client-addr client-addr-length) (initialize-dynamic-sockaddr local-address local-port "udp") (if (or error (not (eql address-family local-address-family))) (progn (comm::close-socket socket-fd) (error "cannot resolve hostname ~S, service ~S: ~A" local-address local-port (or error "address family mismatch"))) (if (comm::bind socket-fd client-addr client-addr-length) ;; success, return socket fd socket-fd (progn (comm::close-socket socket-fd) (error "cannot bind")))))) socket-fd)) (error "cannot create socket")))) (defun connect-to-udp-server (hostname service &key local-address local-port read-timeout) "Something like CONNECT-TO-TCP-SERVER" (fli:with-dynamic-foreign-objects () (multiple-value-bind (error address-family server-addr server-addr-length) (initialize-dynamic-sockaddr hostname service "udp") (when error (error "cannot resolve hostname ~S, service ~S: ~A" hostname service error)) (let ((socket-fd (open-udp-socket :local-address local-address :local-port local-port :read-timeout read-timeout :address-family address-family))) (when (string= hostname "255.255.255.255") ;; LispWorks fails on connect if the broadcast option for broadcast ;; address is not set in advance (set-socket-broadcast socket-fd 1)) (if socket-fd (if (comm::connect socket-fd server-addr server-addr-length) ;; success, return socket fd socket-fd ;; fail, close socket and return nil (progn (comm::close-socket socket-fd) (error "cannot connect"))) (error "cannot create socket")))))) (defun socket-connect (host port &key (protocol :stream) (element-type 'base-char) timeout deadline (nodelay t) local-host local-port) ;; What's the meaning of this keyword? (when deadline (unimplemented 'deadline 'socket-connect)) #+(and lispworks4 (not lispworks4.4)) ; < 4.4.5 (when timeout (unsupported 'timeout 'socket-connect :minimum "LispWorks 4.4.5")) #+lispworks4 (when local-host (unsupported 'local-host 'socket-connect :minimum "LispWorks 5.0")) #+lispworks4 (when local-port (unsupported 'local-port 'socket-connect :minimum "LispWorks 5.0")) (ecase protocol (:stream (let ((hostname (host-to-hostname host)) (stream)) (setq stream (with-mapped-conditions (nil host) (comm:open-tcp-stream hostname port :element-type element-type #-(and lispworks4 (not lispworks4.4)) ; >= 4.4.5 #-(and lispworks4 (not lispworks4.4)) :timeout timeout #-lispworks4 #-lispworks4 #-lispworks4 #-lispworks4 :local-address (when local-host (host-to-hostname local-host)) :local-port local-port #-(or lispworks4 lispworks5.0) ; >= 5.1 #-(or lispworks4 lispworks5.0) :nodelay nodelay))) ;; Then handle `nodelay' separately for older versions <= 5.0 #+(or lispworks4 lispworks5.0) (when (and stream nodelay) (set-socket-tcp-nodelay (comm:socket-stream-socket stream) (bool->int nodelay))) ; ":if-supported" maps to 1 too. (if stream (make-stream-socket :socket (comm:socket-stream-socket stream) :stream stream) ;; if no other error catched by above with-mapped-conditions and still fails, then it's a timeout (error 'timeout-error)))) (:datagram (let ((usocket (make-datagram-socket (if (and host port) (with-mapped-conditions (nil host) (connect-to-udp-server (host-to-hostname host) port :local-address (and local-host (host-to-hostname local-host)) :local-port local-port :read-timeout timeout)) (with-mapped-conditions (nil local-host) (open-udp-socket :local-address (and local-host (host-to-hostname local-host)) :local-port local-port :read-timeout timeout))) :connected-p (and host port t)))) usocket)))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'base-char)) #+lispworks4.1 (unsupported 'host 'socket-listen :minimum "LispWorks 4.0 or newer than 4.1") #+lispworks4.1 (unsupported 'backlog 'socket-listen :minimum "LispWorks 4.0 or newer than 4.1") (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (comm::*use_so_reuseaddr* reuseaddress) (hostname (host-to-hostname host)) (socket-res-list (with-mapped-conditions (nil host) (multiple-value-list #-lispworks4.1 (comm::create-tcp-socket-for-service port :address hostname :backlog backlog) #+lispworks4.1 (comm::create-tcp-socket-for-service port)))) (sock (if (not (or (second socket-res-list) (third socket-res-list))) (first socket-res-list) (when (eq (second socket-res-list) :bind) (error 'address-in-use-error))))) (make-stream-server-socket sock :element-type element-type))) ;; Note: COMM::GET-FD-FROM-SOCKET contains additional socket-wait operations, which ;; should NOT be applied to socket FDs which has already been called on W-F-I, ;; so we have to check the %READY-P slot to decide if this waiting is necessary, ;; or SOCKET-ACCEPT will just hang. -- Chun Tian (binghe), May 1, 2011 (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (let* ((socket (with-mapped-conditions (usocket) #+win32 (if (%ready-p usocket) (comm::accept-connection-to-socket (socket usocket)) (comm::get-fd-from-socket (socket usocket))) #-win32 (comm::get-fd-from-socket (socket usocket)))) (stream (when socket (make-instance 'comm:socket-stream :socket socket :direction :io :element-type (or element-type (element-type usocket)))))) #+win32 (when socket (setf (%ready-p usocket) nil)) ;; It is possible that socket is NIL. Previously the call of make-stream-socket ;; raised a usocket:invalid-socket-error (when socket (make-stream-socket :socket socket :stream stream)))) ;; Sockets and their streams are different objects ;; close the stream in order to make sure buffers ;; are correctly flushed and the socket closed. (defmethod socket-close ((usocket stream-usocket)) "Close socket." (close (socket-stream usocket) :abort t)) ; see "sbcl.lisp" for (:abort t) (defmethod socket-close ((usocket usocket)) (with-mapped-conditions (usocket) (comm::close-socket (socket usocket)))) (defmethod socket-close :after ((socket datagram-usocket)) "Additional socket-close method for datagram-usocket" (setf (%open-p socket) nil)) (defconstant +shutdown-read+ 0) (defconstant +shutdown-write+ 1) (defconstant +shutdown-read-write+ 2) ;;; int ;;; shutdown(int socket, int what); (fli:define-foreign-function (%shutdown "shutdown" :source) ((socket :int) (what :int)) :result-type :int #+win32 :module #+win32 "ws2_32") (defmethod socket-shutdown ((usocket datagram-usocket) direction) (unless (member direction '(:input :output :io)) (error 'invalid-argument-error)) (let ((what (case direction (:input +shutdown-read+) (:output +shutdown-write+) (:io +shutdown-read-write+)))) (with-mapped-conditions (usocket) #-(or lispworks4 lispworks5 lispworks6) ; lispworks 7.0+ (comm::shutdown (socket usocket) what) #+(or lispworks4 lispworks5 lispworks6) (= 0 (%shutdown (socket usocket) what))))) (defmethod socket-shutdown ((usocket stream-usocket) direction) (unless (member direction '(:input :output :io)) (error 'invalid-argument-error)) (with-mapped-conditions (usocket) #-(or lispworks4 lispworks5 lispworks6) ; lispworks 7+ (comm:socket-stream-shutdown (socket-stream usocket) direction) #+(or lispworks4 lispworks5 lispworks6) (let ((what (case direction (:input +shutdown-read+) (:output +shutdown-write+) (:io +shutdown-read-write+)))) (= 0 (%shutdown (comm:socket-stream-socket (socket usocket)) what))))) (defmethod initialize-instance :after ((socket datagram-usocket) &key) (setf (slot-value socket 'send-buffer) (make-array +max-datagram-packet-size+ :element-type '(unsigned-byte 8) :allocation :static)) (setf (slot-value socket 'recv-buffer) (make-array +max-datagram-packet-size+ :element-type '(unsigned-byte 8) :allocation :static))) (defvar *length-of-sockaddr_in* (fli:size-of '(:struct comm::sockaddr_in))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0) &aux (socket-fd (socket usocket)) (message (slot-value usocket 'send-buffer))) ; TODO: multiple threads send together? "Send message to a socket, using sendto()/send()" (declare (type integer socket-fd) (type sequence buffer)) (when host (setq host (host-to-hostname host))) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) (replace message buffer :start2 offset :end2 (+ offset size)) (let ((n (if (and host port) (fli:with-dynamic-foreign-objects () (multiple-value-bind (error family client-addr client-addr-length) (initialize-dynamic-sockaddr host port "udp") (declare (ignore family)) (when error (error "cannot resolve hostname ~S, port ~S: ~A" host port error)) (%sendto socket-fd ptr (min size +max-datagram-packet-size+) 0 (fli:copy-pointer client-addr :type '(:struct comm::sockaddr)) client-addr-length))) (comm::%send socket-fd ptr (min size +max-datagram-packet-size+) 0)))) (declare (type fixnum n)) (if (plusp n) n (let ((errno #-win32 (lw:errno-value) #+win32 (wsa-get-last-error))) (unless (zerop errno) (raise-usock-err errno socket-fd host)) 0))))) (defmethod socket-receive ((socket datagram-usocket) buffer length &key timeout (max-buffer-size +max-datagram-packet-size+)) "Receive message from socket, read-timeout is a float number in seconds. This function will return 4 values: 1. receive buffer 2. number of receive bytes 3. remote address 4. remote port" (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (unsigned-byte 32) ; host (unsigned-byte 16)) ; port (type sequence buffer)) (let ((socket-fd (socket socket)) (message (slot-value socket 'recv-buffer)) ; TODO: how multiple threads do this in parallel? (read-timeout timeout) old-timeout) (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((client-addr (:struct comm::sockaddr_in)) (len :int #-(or lispworks4 lispworks5.0) ; <= 5.0 :initial-element *length-of-sockaddr_in*)) #+(or lispworks4 lispworks5.0) ; <= 5.0 (setf (fli:dereference len) *length-of-sockaddr_in*) (fli:with-dynamic-lisp-array-pointer (ptr message :type '(:unsigned :byte)) ;; setup new read timeout (when read-timeout (setf old-timeout (get-socket-receive-timeout socket-fd)) (set-socket-receive-timeout socket-fd read-timeout)) (let ((n (%recvfrom socket-fd ptr max-buffer-size 0 (fli:copy-pointer client-addr :type '(:struct comm::sockaddr)) len))) (declare (type fixnum n)) ;; restore old read timeout (when (and read-timeout (/= old-timeout read-timeout)) (set-socket-receive-timeout socket-fd old-timeout)) ;; Frank James' patch: reset the %read-p for WAIT-FOR-INPUT #+win32 (setf (%ready-p socket) nil) (if (plusp n) (values (if buffer (replace buffer message :end1 (min length max-buffer-size) :end2 (min n max-buffer-size)) (subseq message 0 (min n max-buffer-size))) (min n max-buffer-size) (comm::ntohl (fli:foreign-slot-value (fli:foreign-slot-value client-addr 'comm::sin_addr :object-type '(:struct comm::sockaddr_in) :type '(:struct comm::in_addr) :copy-foreign-object nil) 'comm::s_addr :object-type '(:struct comm::in_addr))) (comm::ntohs (fli:foreign-slot-value client-addr 'comm::sin_port :object-type '(:struct comm::sockaddr_in) :type '(:unsigned :short) :copy-foreign-object nil))) (let ((errno #-win32 (lw:errno-value) #+win32 (wsa-get-last-error))) (unless (zerop errno) (raise-usock-err errno socket-fd)) (values nil n 0 0)))))))) (defmethod get-local-name ((usocket usocket)) (multiple-value-bind (address port) (comm:get-socket-address (socket usocket)) (values (hbo-to-vector-quad address) port))) (defmethod get-peer-name ((usocket stream-usocket)) (multiple-value-bind (address port) (comm:get-socket-peer-address (socket usocket)) (values (hbo-to-vector-quad address) port))) (defmethod get-local-address ((usocket usocket)) (nth-value 0 (get-local-name usocket))) (defmethod get-peer-address ((usocket stream-usocket)) (nth-value 0 (get-peer-name usocket))) (defmethod get-local-port ((usocket usocket)) (nth-value 1 (get-local-name usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (nth-value 1 (get-peer-name usocket))) #-(or lispworks4 lispworks5 lispworks6.0) ; version>= 6.1 (defun ipv6-address-p (hostname) (when (stringp hostname) (setq hostname (comm:string-ip-address hostname)) (unless hostname (let ((resolved-hostname (comm:get-host-entry hostname :fields '(:address)))) (unless resolved-hostname (return-from ipv6-address-p nil)) (setq hostname resolved-hostname)))) (comm:ipv6-address-p hostname)) (defun lw-hbo-to-vector-quad (hbo) #+(or lispworks4 lispworks5 lispworks6.0) (hbo-to-vector-quad hbo) #-(or lispworks4 lispworks5 lispworks6.0) ; version>= 6.1 (if (comm:ipv6-address-p hbo) (ipv6-host-to-vector (comm:ipv6-address-string hbo)) (hbo-to-vector-quad hbo))) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (mapcar #'lw-hbo-to-vector-quad (comm:get-host-entry name :fields '(:addresses))))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) nil)) ;; TODO (defun os-socket-handle (usocket) (socket usocket)) (defun usocket-listen (usocket) (if (stream-usocket-p usocket) (when (listen (socket-stream usocket)) usocket) (when (comm::socket-listen (socket usocket)) usocket))) ;;; ;;; Non Windows implementation ;;; The Windows implementation needs to resort to the Windows API in order ;;; to achieve what we want (what we want is waiting without busy-looping) ;;; #-win32 (progn (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () ;; unfortunately, it's impossible to share code between ;; non-win32 and win32 platforms... ;; Can we have a sane -pref. complete [UDP!?]- API next time, please? (dolist (x (wait-list-waiters wait-list)) (mp:notice-fd (os-socket-handle x))) (labels ((wait-function (socks) (let (rv) (dolist (x socks rv) (when (usocket-listen x) (setf (state x) :READ rv t)))))) (if timeout (mp:process-wait-with-timeout "Waiting for a socket to become active" (truncate timeout) #'wait-function (wait-list-waiters wait-list)) (mp:process-wait "Waiting for a socket to become active" #'wait-function (wait-list-waiters wait-list)))) (dolist (x (wait-list-waiters wait-list)) (mp:unnotice-fd (os-socket-handle x))) wait-list)) ) ; end of block ;;; ;;; The Windows side of the story ;;; We want to wait without busy looping ;;; This code only works in threads which don't have (hidden) ;;; windows which need to receive messages. There are workarounds in the Windows API ;;; but are those available to 'us'. ;;; #+win32 (progn ;; LispWorks doesn't provide an interface to wait for a socket ;; to become ready (under Win32, that is) meaning that we need ;; to resort to system calls to achieve the same thing. ;; Luckily, it provides us access to the raw socket handles (as we ;; wrote the code above. (defconstant fd-read 1) (defconstant fd-read-bit 0) (defconstant fd-write 2) (defconstant fd-write-bit 1) (defconstant fd-oob 4) (defconstant fd-oob-bit 2) (defconstant fd-accept 8) (defconstant fd-accept-bit 3) (defconstant fd-connect 16) (defconstant fd-connect-bit 4) (defconstant fd-close 32) (defconstant fd-close-bit 5) (defconstant fd-qos 64) (defconstant fd-qos-bit 6) (defconstant fd-group-qos 128) (defconstant fd-group-qos-bit 7) (defconstant fd-routing-interface 256) (defconstant fd-routing-interface-bit 8) (defconstant fd-address-list-change 512) (defconstant fd-address-list-change-bit 9) (defconstant fd-max-events 10) (defconstant fionread 1074030207) ;; Note: ;; ;; If special finalization has to occur for a given ;; system resource (handle), an associated object should ;; be created. A special cleanup action should be added ;; to the system and a special cleanup action should ;; be flagged on all objects created for resources like it ;; ;; We have 2 functions to do so: ;; * hcl:add-special-free-action (function-symbol) ;; * hcl:flag-special-free-action (object) ;; ;; Note that the special free action will be called on all ;; objects which have been flagged for special free, so be ;; sure to check for the right argument type! (fli:define-foreign-type ws-socket () '(:unsigned :int)) (fli:define-foreign-type win32-handle () '(:unsigned :int)) (fli:define-c-struct wsa-network-events (network-events :long) (error-code (:c-array :int 10))) (fli:define-foreign-function (wsa-event-create "WSACreateEvent" :source) () :lambda-list nil :result-type :int :module "ws2_32") (fli:define-foreign-function (wsa-event-close "WSACloseEvent" :source) ((event-object win32-handle)) :result-type :int :module "ws2_32") ;; not used (fli:define-foreign-function (wsa-reset-event "WSAResetEvent" :source) ((event-object win32-handle)) :result-type :int :module "ws2_32") (fli:define-foreign-function (wsa-enum-network-events "WSAEnumNetworkEvents" :source) ((socket ws-socket) (event-object win32-handle) (network-events (:reference-return wsa-network-events))) :result-type :int :module "ws2_32") (fli:define-foreign-function (wsa-event-select "WSAEventSelect" :source) ((socket ws-socket) (event-object win32-handle) (network-events :long)) :result-type :int :module "ws2_32") (fli:define-foreign-function (wsa-get-last-error "WSAGetLastError" :source) () :result-type :int :module "ws2_32") (fli:define-foreign-function (wsa-ioctlsocket "ioctlsocket" :source) ((socket :long) (cmd :long) (argp (:ptr :long))) :result-type :int :module "ws2_32") ;; The Windows system ;; Now that we have access to the system calls, this is the plan: ;; 1. Receive a wait-list with associated sockets to wait for ;; 2. Add all those sockets to an event handle ;; 3. Listen for an event on that handle (we have a LispWorks system:: internal for that) ;; 4. After listening, detect if there are errors ;; (this step is different from Unix, where we can have only one error) ;; 5. If so, raise one of them ;; 6. If not so, return the sockets which have input waiting for them (defun maybe-wsa-error (rv &optional socket) (unless (zerop rv) (raise-usock-err (wsa-get-last-error) socket))) (defun bytes-available-for-read (socket) (fli:with-dynamic-foreign-objects ((int-ptr :long)) (let ((rv (wsa-ioctlsocket (os-socket-handle socket) fionread int-ptr))) (if (= 0 rv) (fli:dereference int-ptr) 0)))) (defun socket-ready-p (socket) (if (typep socket 'stream-usocket) (< 0 (bytes-available-for-read socket)) (%ready-p socket))) (defun waiting-required (sockets) (notany #'socket-ready-p sockets)) (defun wait-for-input-internal (wait-list &key timeout) (when (waiting-required (wait-list-waiters wait-list)) (system:wait-for-single-object (wait-list-%wait wait-list) "Waiting for socket activity" timeout)) (update-ready-and-state-slots wait-list)) (defun map-network-events (func network-events) (let ((event-map (fli:foreign-slot-value network-events 'network-events)) (error-array (fli:foreign-slot-pointer network-events 'error-code))) (unless (zerop event-map) (dotimes (i fd-max-events) (unless (zerop (ldb (byte 1 i) event-map)) ;;### could be faster with ash and logand? (funcall func (fli:foreign-aref error-array i))))))) (defun update-ready-and-state-slots (wait-list) (loop with sockets = (wait-list-waiters wait-list) for socket in sockets do (if (or (and (stream-usocket-p socket) (listen (socket-stream socket))) (%ready-p socket)) (setf (state socket) :READ) (multiple-value-bind (rv network-events) (wsa-enum-network-events (os-socket-handle socket) (wait-list-%wait wait-list) t) (if (zerop rv) (map-network-events #'(lambda (err-code) (if (zerop err-code) (setf (%ready-p socket) t (state socket) :READ) (raise-usock-err err-code socket))) network-events) (maybe-wsa-error rv socket)))))) ;; The wait-list part (defun free-wait-list (wl) (when (wait-list-p wl) (unless (null (wait-list-%wait wl)) (wsa-event-close (wait-list-%wait wl)) (setf (wait-list-%wait wl) nil)))) (eval-when (:load-toplevel :execute) (hcl:add-special-free-action 'free-wait-list)) (defun %setup-wait-list (wait-list) (hcl:flag-special-free-action wait-list) (setf (wait-list-%wait wait-list) (wsa-event-create))) (defun %add-waiter (wait-list waiter) (let ((events (etypecase waiter (stream-server-usocket (logior fd-connect fd-accept fd-close)) (stream-usocket (logior fd-connect fd-read fd-oob fd-close)) (datagram-usocket (logior fd-read))))) (maybe-wsa-error (wsa-event-select (os-socket-handle waiter) (wait-list-%wait wait-list) events) waiter))) (defun %remove-waiter (wait-list waiter) (maybe-wsa-error (wsa-event-select (os-socket-handle waiter) (wait-list-%wait wait-list) 0) waiter)) ) ; end of WIN32-block (defun set-socket-reuse-address (socket-fd reuse-address-p) (declare (type integer socket-fd) (type boolean reuse-address-p)) (fli:with-dynamic-foreign-objects ((value :int)) (setf (fli:dereference value) (if reuse-address-p 1 0)) (if (zerop (comm::setsockopt socket-fd comm::*sockopt_sol_socket* comm::*sockopt_so_reuseaddr* (fli:copy-pointer value :type '(:pointer :void)) (fli:size-of :int))) reuse-address-p))) (defun get-socket-reuse-address (socket-fd) (declare (type integer socket-fd)) (fli:with-dynamic-foreign-objects ((value :int) (len :int)) (if (zerop (comm::getsockopt socket-fd comm::*sockopt_sol_socket* comm::*sockopt_so_reuseaddr* (fli:copy-pointer value :type '(:pointer :void)) len)) (= 1 (fli:dereference value)))))
44,628
Common Lisp
.lisp
949
34.87039
125
0.570277
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
9bda4ce186f8e25c58f6ff40d0f6e21bab65ad5723ecfc665f7e4ea44f44bc1d
42,620
[ -1 ]
42,621
clisp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/clisp.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (eval-when (:compile-toplevel :load-toplevel :execute) #-ffi (warn "This image doesn't contain FFI package, GET-HOST-NAME won't work.") #-(or ffi rawsock) (warn "This image doesn't contain either FFI or RAWSOCK package, no UDP support.")) ;; utility routine for looking up the current host name #+ffi (ffi:def-call-out get-host-name-internal (:name "gethostname") (:arguments (name (FFI:C-PTR (FFI:C-ARRAY-MAX ffi:character 256)) :OUT :ALLOCA) (len ffi:int)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (defun get-host-name () #+ffi (multiple-value-bind (retcode name) (get-host-name-internal 256) (when (= retcode 0) name)) #-ffi "localhost") (defun get-host-by-address (address) (with-mapped-conditions (nil address) (let ((hostent (posix:resolve-host-ipaddr (host-to-hostname address)))) (posix:hostent-name hostent)))) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (let ((hostent (posix:resolve-host-ipaddr name))) (mapcar #'host-to-vector-quad (posix:hostent-addr-list hostent))))) ;; Format: ((UNIX Windows) . CONDITION) (defparameter +clisp-error-map+ #-win32 `((:EADDRINUSE . address-in-use-error) (:EADDRNOTAVAIL . address-not-available-error) (:EBADF . bad-file-descriptor-error) (:ECONNREFUSED . connection-refused-error) (:ECONNRESET . connection-reset-error) (:ECONNABORTED . connection-aborted-error) (:EINVAL . invalid-argument-error) (:ENOBUFS . no-buffers-error) (:ENOMEM . out-of-memory-error) (:ENOTSUP . operation-not-supported-error) (:EPERM . operation-not-permitted-error) (:EPROTONOSUPPORT . protocol-not-supported-error) (:ESOCKTNOSUPPORT . socket-type-not-supported-error) (:ENETUNREACH . network-unreachable-error) (:ENETDOWN . network-down-error) (:ENETRESET . network-reset-error) (:ESHUTDOWN . already-shutdown-error) (:ETIMEDOUT . timeout-error) (:EHOSTDOWN . host-down-error) (:EHOSTUNREACH . host-unreachable-error) ;; when blocked reading, and we close our socket due to a timeout. ;; POSIX.1 says that EAGAIN and EWOULDBLOCK may have the same values. (:EAGAIN . timeout-error) (:EWOULDBLOCK . timeout-error)) ;linux #+win32 `((:WSAEADDRINUSE . address-in-use-error) (:WSAEADDRNOTAVAIL . address-not-available-error) (:WSAEBADF . bad-file-descriptor-error) (:WSAECONNREFUSED . connection-refused-error) (:WSAECONNRESET . connection-reset-error) (:WSAECONNABORTED . connection-aborted-error) (:WSAEINVAL . invalid-argument-error) (:WSAENOBUFS . no-buffers-error) (:WSAENOMEM . out-of-memory-error) (:WSAENOTSUP . operation-not-supported-error) (:WSAEPERM . operation-not-permitted-error) (:WSAEPROTONOSUPPORT . protocol-not-supported-error) (:WSAESOCKTNOSUPPORT . socket-type-not-supported-error) (:WSAENETUNREACH . network-unreachable-error) (:WSAENETDOWN . network-down-error) (:WSAENETRESET . network-reset-error) (:WSAESHUTDOWN . already-shutdown-error) (:WSAETIMEDOUT . timeout-error) (:WSAEHOSTDOWN . host-down-error) (:WSAEHOSTUNREACH . host-unreachable-error))) (defun parse-errno (condition) "Returns a number or keyword if it can parse what is within parens, else NIL" (let ((s (princ-to-string condition))) (let ((pos1 (position #\( s)) (pos2 (position #\) s))) ;mac: number, linux: keyword (ignore-errors (if (digit-char-p (char s (1+ pos1))) (parse-integer s :start (1+ pos1) :end pos2) (let ((*package* (find-package "KEYWORD"))) (car (read-from-string s t nil :start pos1 :end (1+ pos2))))))))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch a usocket condition instead of a CLISP specific one, if we can." (let ((errno (cond ;clisp 2.49+ ((typep condition (find-symbol "OS-STREAM-ERROR" "EXT")) (parse-errno condition)) ;clisp 2.49 ((typep condition (find-symbol "SIMPLE-STREAM-ERROR" "SYSTEM")) (car (simple-condition-format-arguments condition)))))) (when errno (let ((error-keyword (if (keywordp errno) errno #+ffi(os:errno errno)))) (let ((usock-error (cdr (assoc error-keyword +clisp-error-map+)))) (when usock-error (if (subtypep usock-error 'error) (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (cond ((subtypep usock-error 'ns-condition) (signal usock-error :socket socket :host-or-ip host-or-ip)) (t (signal usock-error :socket socket)))))))))) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-specified) local-host local-port) (declare (ignorable timeout local-host local-port)) (when deadline (unsupported 'deadline 'socket-connect)) (when (and nodelay-specified (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (case protocol (:stream (let ((socket) (hostname (host-to-hostname host))) (with-mapped-conditions (socket host) (setf socket (if timeout (socket:socket-connect port hostname :element-type element-type :buffered t :timeout timeout) (socket:socket-connect port hostname :element-type element-type :buffered t)))) (make-stream-socket :socket socket :stream socket))) ;; the socket is a stream too (:datagram #+(or rawsock ffi) (with-mapped-conditions (nil (or host local-host)) (socket-create-datagram (or local-port *auto-port*) :local-host (or local-host *wildcard-host*) :remote-host (and host (host-to-vector-quad host)) :remote-port port)) #-(or rawsock ffi) (unsupported '(protocol :datagram) 'socket-connect)))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) ;; clisp 2.39 sets SO_REUSEADDRESS to 1 by default; no need to ;; to explicitly turn it on; unfortunately, there's no way to turn it off... (declare (ignore reuseaddress reuse-address reuse-address-supplied-p)) (let ((sock (apply #'socket:socket-server (append (list port :backlog backlog) (when (ip/= host *wildcard-host*) (list :interface host)))))) (with-mapped-conditions (nil host) (make-stream-server-socket sock :element-type element-type)))) (defmethod socket-accept ((socket stream-server-usocket) &key element-type) (let ((stream (with-mapped-conditions (socket) (socket:socket-accept (socket socket) :element-type (or element-type (element-type socket)))))) (make-stream-socket :socket stream :stream stream))) ;; Only one close method required: ;; sockets and their associated streams ;; are the same object (defmethod socket-close ((usocket usocket)) "Close socket." (with-mapped-conditions (usocket) (close (socket usocket) :abort t))) ; see "sbcl.lisp" for (:abort t) (defmethod socket-close ((usocket stream-server-usocket)) (socket:socket-server-close (socket usocket))) (defmethod socket-shutdown ((usocket stream-usocket) direction) (with-mapped-conditions (usocket) (if (eq :io direction) (progn (socket:socket-stream-shutdown (socket usocket) :input) (socket:socket-stream-shutdown (socket usocket) :output)) (socket:socket-stream-shutdown (socket usocket) direction)))) (defmethod get-local-name ((usocket stream-usocket)) (multiple-value-bind (address port) (socket:socket-stream-local (socket usocket) t) (values (dotted-quad-to-vector-quad address) port))) (defmethod get-local-name ((usocket stream-server-usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (multiple-value-bind (address port) (socket:socket-stream-peer (socket usocket) t) (values (dotted-quad-to-vector-quad address) port))) (defmethod get-local-address ((usocket usocket)) (nth-value 0 (get-local-name usocket))) (defmethod get-local-address ((usocket stream-server-usocket)) (dotted-quad-to-vector-quad (socket:socket-server-host (socket usocket)))) (defmethod get-peer-address ((usocket usocket)) (nth-value 0 (get-peer-name usocket))) (defmethod get-local-port ((usocket usocket)) (nth-value 1 (get-local-name usocket))) (defmethod get-local-port ((usocket stream-server-usocket)) (socket:socket-server-port (socket usocket))) (defmethod get-peer-port ((usocket usocket)) (nth-value 1 (get-peer-name usocket))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) ;; clisp's #'socket-status takes a list whose elts look either like, ;; (socket-stream direction . x) or like, ;; (socket-server . x) ;; and it replaces the x's. (push (cons (socket waiter) (cond ((stream-usocket-p waiter) (cons NIL NIL)) (t NIL))) (wait-list-%wait wait-list))) (defun %remove-waiter (wait-list waiter) (setf (wait-list-%wait wait-list) (remove (socket waiter) (wait-list-%wait wait-list) :key #'car))) (defmethod wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () (multiple-value-bind (secs musecs) (split-timeout (or timeout 1)) (dolist (x (wait-list-%wait wait-list)) (when (consp (cdr x)) ;it's a socket-stream not socket-server (setf (cadr x) :INPUT))) (let* ((request-list (wait-list-%wait wait-list)) (status-list (if timeout (socket:socket-status request-list secs musecs) (socket:socket-status request-list))) (sockets (wait-list-waiters wait-list))) (do* ((x (pop sockets) (pop sockets)) (y (cdr (last (pop status-list))) (cdr (last (pop status-list))))) ((null x)) (when (member y '(T :INPUT :EOF)) (setf (state x) :READ))) wait-list)))) ;;; ;;; UDP/Datagram sockets (RAWSOCK version) ;;; #+rawsock (progn (defun make-sockaddr_in () (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0)) (declaim (inline fill-sockaddr_in)) (defun fill-sockaddr_in (sockaddr_in ip port) (port-to-octet-buffer port sockaddr_in) (ip-to-octet-buffer ip sockaddr_in :start 2) sockaddr_in) (defun socket-create-datagram (local-port &key (local-host *wildcard-host*) remote-host remote-port) (let ((sock (rawsock:socket :inet :dgram 0)) (lsock_addr (fill-sockaddr_in (make-sockaddr_in) local-host local-port)) (rsock_addr (when remote-host (fill-sockaddr_in (make-sockaddr_in) remote-host (or remote-port local-port))))) (rawsock:bind sock (rawsock:make-sockaddr :inet lsock_addr)) (when rsock_addr (rawsock:connect sock (rawsock:make-sockaddr :inet rsock_addr))) (make-datagram-socket sock :connected-p (if rsock_addr t nil)))) (defmethod socket-receive ((socket datagram-usocket) buffer length &key) "Returns the buffer, the number of octets copied into the buffer (received) and the address of the sender as values." (let* ((sock (socket socket)) (sockaddr (rawsock:make-sockaddr :inet)) (real-length (or length +max-datagram-packet-size+)) (real-buffer (or buffer (make-array real-length :element-type '(unsigned-byte 8))))) (let ((rv (rawsock:recvfrom sock real-buffer sockaddr :start 0 :end real-length)) (host 0) (port 0)) (unless (connected-p socket) (let ((data (rawsock:sockaddr-data sockaddr))) (setq host (ip-from-octet-buffer data :start 4) port (port-from-octet-buffer data :start 2)))) (values (if buffer real-buffer (subseq real-buffer 0 rv)) rv host port)))) (defmethod socket-send ((socket datagram-usocket) buffer size &key host port (offset 0)) "Returns the number of octets sent." (let* ((sock (socket socket)) (sockaddr (when (and host port) (rawsock:make-sockaddr :inet (fill-sockaddr_in (make-sockaddr_in) (host-byte-order host) port)))) (real-size (min size +max-datagram-packet-size+)) (real-buffer (if (typep buffer '(simple-array (unsigned-byte 8) (*))) buffer (make-array real-size :element-type '(unsigned-byte 8) :initial-contents (subseq buffer 0 real-size)))) (rv (if (and host port) (rawsock:sendto sock real-buffer sockaddr :start offset :end (+ offset real-size)) (rawsock:send sock real-buffer :start offset :end (+ offset real-size))))) rv)) (defmethod socket-close ((usocket datagram-usocket)) (rawsock:sock-close (socket usocket))) (declaim (inline get-socket-name)) (defun get-socket-name (socket function) (let ((sockaddr (rawsock:make-sockaddr :inet (make-sockaddr_in)))) (funcall function socket sockaddr) (let ((data (rawsock:sockaddr-data sockaddr))) (values (hbo-to-vector-quad (ip-from-octet-buffer data :start 2)) (port-from-octet-buffer data :start 0))))) (defmethod get-local-name ((usocket datagram-usocket)) (get-socket-name (socket usocket) 'rawsock:getsockname)) (defmethod get-peer-name ((usocket datagram-usocket)) (get-socket-name (socket usocket) 'rawsock:getpeername)) ) ; progn ;;; ;;; UDP/Datagram sockets (FFI version) ;;; #+(and ffi (not rawsock)) (progn ;; C primitive types (ffi:def-c-type socklen_t ffi:uint32) ;; C structures (ffi:def-c-struct sockaddr #+macos (sa_len ffi:uint8) (sa_family #-macos ffi:ushort #+macos ffi:uint8) (sa_data (ffi:c-array ffi:char 14))) (ffi:def-c-struct sockaddr_in #+macos (sin_len ffi:uint8) (sin_family #-macos ffi:short #+macos ffi:uint8) (sin_port #-macos ffi:ushort #+macos ffi:uint16) (sin_addr ffi:uint32) (sin_zero (ffi:c-array ffi:char 8))) (ffi:def-c-struct timeval (tv_sec ffi:long) (tv_usec ffi:long)) ;; foreign functions (ffi:def-call-out %sendto (:name "sendto") (:arguments (socket ffi:int) (buffer ffi:c-pointer) (length ffi:int) (flags ffi:int) (address (ffi:c-ptr sockaddr)) (address-len ffi:int)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %send (:name "send") (:arguments (socket ffi:int) (buffer ffi:c-pointer) (length ffi:int) (flags ffi:int)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %recvfrom (:name "recvfrom") (:arguments (socket ffi:int) (buffer ffi:c-pointer) (length ffi:int) (flags ffi:int) (address (ffi:c-ptr sockaddr) :in-out) (address-len (ffi:c-ptr ffi:int) :in-out)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %socket (:name "socket") (:arguments (family ffi:int) (type ffi:int) (protocol ffi:int)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %connect (:name "connect") (:arguments (socket ffi:int) (address (ffi:c-ptr sockaddr) :in) (address_len socklen_t)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %bind (:name "bind") (:arguments (socket ffi:int) (address (ffi:c-ptr sockaddr) :in) (address_len socklen_t)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %close (:name #-win32 "close" #+win32 "closesocket") (:arguments (socket ffi:int)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %getsockopt (:name "getsockopt") (:arguments (sockfd ffi:int) (level ffi:int) (optname ffi:int) (optval ffi:c-pointer) (optlen (ffi:c-ptr socklen_t) :out)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %setsockopt (:name "setsockopt") (:arguments (sockfd ffi:int) (level ffi:int) (optname ffi:int) (optval ffi:c-pointer) (optlen socklen_t)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %htonl (:name "htonl") (:arguments (hostlong ffi:uint32)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:uint32)) (ffi:def-call-out %htons (:name "htons") (:arguments (hostshort ffi:uint16)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:uint16)) (ffi:def-call-out %ntohl (:name "ntohl") (:arguments (netlong ffi:uint32)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:uint32)) (ffi:def-call-out %ntohs (:name "ntohs") (:arguments (netshort ffi:uint16)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:uint16)) (ffi:def-call-out %getsockname (:name "getsockname") (:arguments (sockfd ffi:int) (localaddr (ffi:c-ptr sockaddr) :in-out) (addrlen (ffi:c-ptr socklen_t) :in-out)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) (ffi:def-call-out %getpeername (:name "getpeername") (:arguments (sockfd ffi:int) (peeraddr (ffi:c-ptr sockaddr) :in-out) (addrlen (ffi:c-ptr socklen_t) :in-out)) #+win32 (:library "WS2_32") #-win32 (:library :default) (:language #-win32 :stdc #+win32 :stdc-stdcall) (:return-type ffi:int)) ;; socket constants (defconstant +socket-af-inet+ 2) (defconstant +socket-sock-dgram+ 2) (defconstant +socket-ip-proto-udp+ 17) (defconstant +sockopt-so-rcvtimeo+ #-linux #x1006 #+linux 20 "Socket receive timeout") (defparameter *length-of-sockaddr_in* (ffi:sizeof 'sockaddr_in)) (declaim (inline fill-sockaddr_in)) (defun fill-sockaddr_in (sockaddr host port) (let ((hbo (host-to-hbo host))) (ffi:with-c-place (place sockaddr) #+macos (setf (ffi:slot place 'sin_len) *length-of-sockaddr_in*) (setf (ffi:slot place 'sin_family) +socket-af-inet+ (ffi:slot place 'sin_port) (%htons port) (ffi:slot place 'sin_addr) (%htonl hbo))) sockaddr)) (defun socket-create-datagram (local-port &key (local-host *wildcard-host*) remote-host remote-port) (let ((sock (%socket +socket-af-inet+ +socket-sock-dgram+ +socket-ip-proto-udp+)) (lsock_addr (fill-sockaddr_in (ffi:allocate-shallow 'sockaddr_in) local-host local-port)) (rsock_addr (when remote-host (fill-sockaddr_in (ffi:allocate-shallow 'sockaddr_in) remote-host (or remote-port local-port))))) (unless (plusp sock) (error "SOCKET-CREATE-DATAGRAM ERROR (socket): ~A" (os:errno))) (unwind-protect (let ((rv (%bind sock (ffi:cast (ffi:foreign-value lsock_addr) 'sockaddr) *length-of-sockaddr_in*))) (unless (zerop rv) (error "SOCKET-CREATE-DATAGRAM ERROR (bind): ~A" (os:errno))) (when rsock_addr (let ((rv (%connect sock (ffi:cast (ffi:foreign-value rsock_addr) 'sockaddr) *length-of-sockaddr_in*))) (unless (zerop rv) (error "SOCKET-CREATE-DATAGRAM ERROR (connect): ~A" (os:errno)))))) (ffi:foreign-free lsock_addr) (when remote-host (ffi:foreign-free rsock_addr))) (make-datagram-socket sock :connected-p (if rsock_addr t nil)))) (defun finalize-datagram-usocket (object) (when (datagram-usocket-p object) (socket-close object))) (defmethod initialize-instance :after ((usocket datagram-usocket) &key) (setf (slot-value usocket 'recv-buffer) (ffi:allocate-shallow 'ffi:uint8 :count +max-datagram-packet-size+)) ;; finalize the object (ext:finalize usocket 'finalize-datagram-usocket)) (defmethod socket-close ((usocket datagram-usocket)) (with-slots (recv-buffer socket) usocket (ffi:foreign-free recv-buffer) (zerop (%close socket)))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key) (let ((remote-address (ffi:allocate-shallow 'sockaddr_in)) (remote-address-length (ffi:allocate-shallow 'ffi:int)) nbytes (host 0) (port 0)) (setf (ffi:foreign-value remote-address-length) *length-of-sockaddr_in*) (unwind-protect (multiple-value-bind (n address address-length) (%recvfrom (socket usocket) (ffi:foreign-address (slot-value usocket 'recv-buffer)) +max-datagram-packet-size+ 0 ; flags (ffi:cast (ffi:foreign-value remote-address) 'sockaddr) (ffi:foreign-value remote-address-length)) (when (minusp n) (error "SOCKET-RECEIVE ERROR: ~A" (os:errno))) (setq nbytes n) (when (= address-length *length-of-sockaddr_in*) (let ((data (sockaddr-sa_data address))) (setq host (ip-from-octet-buffer data :start 2) port (port-from-octet-buffer data)))) (cond ((plusp n) (let ((return-buffer (ffi:foreign-value (slot-value usocket 'recv-buffer)))) (if buffer ; replace exist buffer of create new return buffer (let ((end-1 (min (or length (length buffer)) +max-datagram-packet-size+)) (end-2 (min n +max-datagram-packet-size+))) (replace buffer return-buffer :end1 end-1 :end2 end-2)) (setq buffer (subseq return-buffer 0 (min n +max-datagram-packet-size+)))))) ((zerop n)))) (ffi:foreign-free remote-address) (ffi:foreign-free remote-address-length)) (values buffer nbytes host port))) ;; implementation note: different from socket-receive, we know how many bytes we want to send everytime, ;; so, a send buffer will not needed, and if there is a buffer, it's hard to fill its content like those ;; in LispWorks. So, we allocate new foreign buffer for holding data (unknown sequence subtype) every time. ;; ;; I don't know if anyone is watching my coding work, but I think this design is reasonable for CLISP. (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (declare (type sequence buffer) (type (integer 0 *) size offset)) (let ((remote-address (when (and host port) (fill-sockaddr_in (ffi:allocate-shallow 'sockaddr_in) host port))) (send-buffer (ffi:allocate-deep 'ffi:uint8 (if (zerop offset) buffer (subseq buffer offset (+ offset size))) :count size :read-only t)) (real-size (min size +max-datagram-packet-size+)) (nbytes 0)) (unwind-protect (let ((n (if remote-address (%sendto (socket usocket) (ffi:foreign-address send-buffer) real-size 0 ; flags (ffi:cast (ffi:foreign-value remote-address) 'sockaddr) *length-of-sockaddr_in*) (%send (socket usocket) (ffi:foreign-address send-buffer) real-size 0)))) (cond ((plusp n) (setq nbytes n)) ((zerop n) (setq nbytes n)) (t (error "SOCKET-SEND ERROR: ~A" (os:errno))))) (ffi:foreign-free send-buffer) (when remote-address (ffi:foreign-free remote-address)) nbytes))) (declaim (inline get-socket-name)) (defun get-socket-name (socket function) (let ((address (ffi:allocate-shallow 'sockaddr_in)) (address-length (ffi:allocate-shallow 'ffi:int)) (host 0) (port 0)) (setf (ffi:foreign-value address-length) *length-of-sockaddr_in*) (unwind-protect (multiple-value-bind (rv return-address return-address-length) (funcall function socket (ffi:cast (ffi:foreign-value address) 'sockaddr) (ffi:foreign-value address-length)) (declare (ignore return-address-length)) (if (zerop rv) (let ((data (sockaddr-sa_data return-address))) (setq host (ip-from-octet-buffer data :start 2) port (port-from-octet-buffer data))) (error "GET-SOCKET-NAME ERROR: ~A" (os:errno)))) (ffi:foreign-free address) (ffi:foreign-free address-length)) (values (hbo-to-vector-quad host) port))) (defmethod get-local-name ((usocket datagram-usocket)) (get-socket-name (socket usocket) '%getsockname)) (defmethod get-peer-name ((usocket datagram-usocket)) (get-socket-name (socket usocket) '%getpeername)) ) ; progn
27,059
Common Lisp
.lisp
646
34.171827
109
0.624829
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
657eb2659f8438f023ec47b2b180e2100c384e0a774d75e19eff87bbb5bd6272
42,621
[ -1 ]
42,622
scl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/scl.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (defparameter +scl-error-map+ (append +unix-errno-condition-map+ +unix-errno-error-map+)) (defun scl-map-socket-error (err &key condition socket) (let ((usock-err (cdr (assoc err +scl-error-map+ :test #'member)))) (cond (usock-err (if (subtypep usock-err 'error) (error usock-err :socket socket) (signal usock-err :socket socket))) (t (error 'unknown-error :socket socket :real-error condition))))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (typecase condition (ext::socket-error (scl-map-socket-error (ext::socket-errno condition) :socket socket :condition condition)))) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-specified) (local-host nil local-host-p) (local-port nil local-port-p) &aux (patch-udp-p (fboundp 'ext::inet-socket-send-to))) (when (and nodelay-specified (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (when deadline (unsupported 'deadline 'socket-connect)) (when timeout (unsupported 'timeout 'socket-connect)) (when (and local-host-p (not patch-udp-p)) (unsupported 'local-host 'socket-connect :minimum "1.3.9")) (when (and local-port-p (not patch-udp-p)) (unsupported 'local-port 'socket-connect :minimum "1.3.9")) (let ((socket)) (ecase protocol (:stream (setf socket (let ((args (list (host-to-hbo host) port :kind protocol))) (when (and patch-udp-p (or local-host-p local-port-p)) (nconc args (list :local-host (when local-host (host-to-hbo local-host)) :local-port local-port))) (with-mapped-conditions (socket) (apply #'ext:connect-to-inet-socket args)))) (let ((stream (sys:make-fd-stream socket :input t :output t :element-type element-type :buffering :full))) (make-stream-socket :socket socket :stream stream))) (:datagram (when (not patch-udp-p) (error 'unsupported :feature '(protocol :datagram) :context 'socket-connect :minumum "1.3.9")) (setf socket (if (and host port) (let ((args (list (host-to-hbo host) port :kind protocol))) (when (and patch-udp-p (or local-host-p local-port-p)) (nconc args (list :local-host (when local-host (host-to-hbo local-host)) :local-port local-port))) (with-mapped-conditions (socket) (apply #'ext:connect-to-inet-socket args))) (if (or local-host-p local-port-p) (with-mapped-conditions () (ext:create-inet-listener (or local-port 0) protocol :host (when local-host (if (ip= local-host *wildcard-host*) 0 (host-to-hbo local-host))))) (with-mapped-conditions () (ext:create-inet-socket protocol))))) (let ((usocket (make-datagram-socket socket :connected-p (and host port t)))) (ext:finalize usocket #'(lambda () (when (%open-p usocket) (ext:close-socket socket)))) usocket))))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (host (if (ip= host *wildcard-host*) 0 (host-to-hbo host))) (server-sock (with-mapped-conditions () (ext:create-inet-listener port :stream :host host :reuse-address reuseaddress :backlog backlog)))) (make-stream-server-socket server-sock :element-type element-type))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (with-mapped-conditions (usocket) (let* ((sock (ext:accept-tcp-connection (socket usocket))) (stream (sys:make-fd-stream sock :input t :output t :element-type (or element-type (element-type usocket)) :buffering :full))) (make-stream-socket :socket sock :stream stream)))) ;; Sockets and their associated streams are modelled as ;; different objects. Be sure to close the socket stream ;; when closing stream-sockets; it makes sure buffers ;; are flushed and the socket is closed correctly afterwards. (defmethod socket-close ((usocket usocket)) "Close socket." (with-mapped-conditions (usocket) (ext:close-socket (socket usocket)))) (defmethod socket-close ((usocket stream-usocket)) "Close socket." (with-mapped-conditions (usocket) (close (socket-stream usocket) :abort t))) (defmethod socket-close :after ((socket datagram-usocket)) (setf (%open-p socket) nil)) (defmethod socket-shutdown ((usocket usocket) direction) (declare (ignore usocket direction)) (unsupported "shutdown" 'socket-shutdown)) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port) (let ((s (socket usocket)) (host (if host (host-to-hbo host))) (real-buffer (if (zerop offset) buffer (subseq buffer offset (+ offset size))))) (multiple-value-bind (result errno) (ext:inet-socket-send-to s real-buffer size :remote-host host :remote-port port) (or result (scl-map-socket-error errno :socket usocket))))) (defmethod socket-receive ((socket datagram-usocket) buffer length &key) (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (unsigned-byte 32) ; host (unsigned-byte 16))) ; port (let ((s (socket socket))) (let ((real-buffer (or buffer (make-array length :element-type '(unsigned-byte 8)))) (real-length (or length (length buffer)))) (multiple-value-bind (result errno remote-host remote-port) (ext:inet-socket-receive-from s real-buffer real-length) (if result (values real-buffer result remote-host remote-port) (scl-map-socket-error errno :socket socket)))))) (defmethod get-local-name ((usocket usocket)) (multiple-value-bind (address port) (with-mapped-conditions (usocket) (ext:get-socket-host-and-port (socket usocket))) (values (hbo-to-vector-quad address) port))) (defmethod get-peer-name ((usocket stream-usocket)) (multiple-value-bind (address port) (with-mapped-conditions (usocket) (ext:get-peer-host-and-port (socket usocket))) (values (hbo-to-vector-quad address) port))) (defmethod get-local-address ((usocket usocket)) (nth-value 0 (get-local-name usocket))) (defmethod get-peer-address ((usocket stream-usocket)) (nth-value 0 (get-peer-name usocket))) (defmethod get-local-port ((usocket usocket)) (nth-value 1 (get-local-name usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (nth-value 1 (get-peer-name usocket))) (defun get-host-by-address (address) (multiple-value-bind (host errno) (ext:lookup-host-entry (host-byte-order address)) (cond (host (ext:host-entry-name host)) (t (let ((condition (cdr (assoc errno +unix-ns-error-map+)))) (cond (condition (error condition :host-or-ip address)) (t (error 'ns-unknown-error :host-or-ip address :real-error errno)))))))) (defun get-hosts-by-name (name) (multiple-value-bind (host errno) (ext:lookup-host-entry name) (cond (host (mapcar #'hbo-to-vector-quad (ext:host-entry-addr-list host))) (t (let ((condition (cdr (assoc errno +unix-ns-error-map+)))) (cond (condition (error condition :host-or-ip name)) (t (error 'ns-unknown-error :host-or-ip name :real-error errno)))))))) (defun get-host-name () (unix:unix-gethostname)) ;; ;; ;; WAIT-LIST part ;; (defun %add-waiter (wl waiter) (declare (ignore wl waiter))) (defun %remove-waiter (wl waiter) (declare (ignore wl waiter))) (defun %setup-wait-list (wl) (declare (ignore wl))) (defun wait-for-input-internal (wait-list &key timeout) (let* ((sockets (wait-list-waiters wait-list)) (pollfd-size (alien:alien-size (alien:struct unix::pollfd) :bytes)) (nfds (length sockets)) (bytes (* nfds pollfd-size))) (alien:with-bytes (fds-sap bytes) (do ((sockets sockets (rest sockets)) (base 0 (+ base 8))) ((endp sockets)) (let ((fd (socket (first sockets)))) (setf (sys:sap-ref-32 fds-sap base) fd) (setf (sys:sap-ref-16 fds-sap (+ base 4)) unix::pollin))) (multiple-value-bind (result errno) (let ((thread:*thread-whostate* "Poll wait") (timeout (if timeout (truncate (* timeout 1000)) -1))) (declare (inline unix:unix-poll)) (unix:unix-poll (alien:sap-alien fds-sap (* (alien:struct unix::pollfd))) nfds timeout)) (cond ((not result) (error "~@<Polling error: ~A~:@>" (unix:get-unix-error-msg errno))) (t (do ((sockets sockets (rest sockets)) (base 0 (+ base 8))) ((endp sockets)) (let ((flags (sys:sap-ref-16 fds-sap (+ base 6)))) (unless (zerop (logand flags unix::pollin)) (setf (state (first sockets)) :READ))))))))))
10,034
Common Lisp
.lisp
234
33.961538
84
0.601556
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
8ee69637780f26162a783b06c9819abfd50b1055a678932d13b71177722d7350
42,622
[ -1 ]
42,623
clasp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/clasp.lisp
(in-package :usocket) #-clasp (progn #-:wsock (ffi:clines "#include <errno.h>" "#include <sys/socket.h>" "#include <unistd.h>") #+:wsock (ffi:clines "#ifndef FD_SETSIZE" "#define FD_SETSIZE 1024" "#endif" "#include <winsock2.h>") (ffi:clines #+:msvc "#include <time.h>" #-:msvc "#include <sys/time.h>" "#include <ecl/ecl-inl.h>")) (progn #-clasp (defun cerrno () (ffi:c-inline () () :int "errno" :one-liner t)) #+clasp (defun cerrno () (sockets-internal:errno)) #-clasp (defun fd-setsize () (ffi:c-inline () () :fixnum "FD_SETSIZE" :one-liner t)) #+clasp (defun fd-setsize () (sockets-internal:fd-setsize)) #-clasp (defun fdset-alloc () (ffi:c-inline () () :pointer-void "ecl_alloc_atomic(sizeof(fd_set))" :one-liner t)) #+clasp (defun fdset-alloc () (sockets-internal::alloc-atomic-sizeof-fd-set)) #-clasp (defun fdset-zero (fdset) (ffi:c-inline (fdset) (:pointer-void) :void "FD_ZERO((fd_set*)#0)" :one-liner t)) #+clasp(defun fdset-zero (fdset) (sockets-internal:fdset-zero fdset)) #-clasp (defun fdset-set (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :void "FD_SET(#1,(fd_set*)#0)" :one-liner t)) #+clasp(defun fdset-set (fdset fd) (sockets-internal:fdset-set fd fdset)) #-clasp (defun fdset-clr (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :void "FD_CLR(#1,(fd_set*)#0)" :one-liner t)) #+clasp(defun fdset-clr (fdset fd) (sockets-internal:fdset-clr fd fdset)) #-clasp (defun fdset-fd-isset (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :bool "FD_ISSET(#1,(fd_set*)#0)" :one-liner t)) #+clasp(defun fdset-fd-isset (fdset fd) (sockets-internal:fdset-isset fd fdset)) (declaim (inline cerrno fd-setsize fdset-alloc fdset-zero fdset-set fdset-clr fdset-fd-isset)) #-clasp (defun get-host-name () (ffi:c-inline () () :object "{ char *buf = (char *) ecl_alloc_atomic(257); if (gethostname(buf,256) == 0) @(return) = make_simple_base_string(buf); else @(return) = Cnil; }" :one-liner nil :side-effects nil)) #+clasp (defun get-host-name () (sockets-internal:get-host-name)) #-clasp (defun read-select (wl to-secs &optional (to-musecs 0)) (let* ((sockets (wait-list-waiters wl)) (rfds (wait-list-%wait wl)) (max-fd (reduce #'(lambda (x y) (let ((sy (sb-bsd-sockets:socket-file-descriptor (socket y)))) (if (< x sy) sy x))) (cdr sockets) :initial-value (sb-bsd-sockets:socket-file-descriptor (socket (car sockets)))))) (fdset-zero rfds) (dolist (sock sockets) (fdset-set rfds (sb-bsd-sockets:socket-file-descriptor (socket sock)))) (let ((count (ffi:c-inline (to-secs to-musecs rfds max-fd) (t :unsigned-int :pointer-void :int) :int " int count; struct timeval tv; if (#0 != Cnil) { tv.tv_sec = fixnnint(#0); tv.tv_usec = #1; } @(return) = select(#3 + 1, (fd_set*)#2, NULL, NULL, (#0 != Cnil) ? &tv : NULL); " :one-liner nil))) (cond ((= 0 count) (values nil nil)) ((< count 0) ;; check for EINTR and EAGAIN; these should not err (values nil (cerrno))) (t (dolist (sock sockets) (when (fdset-fd-isset rfds (sb-bsd-sockets:socket-file-descriptor (socket sock))) (setf (state sock) :READ)))))))) #+clasp (defun read-select (wl to-secs &optional (to-musecs 0)) (let* ((sockets (wait-list-waiters wl)) (rfds (wait-list-%wait wl)) (max-fd (reduce #'(lambda (x y) (let ((sy (sb-bsd-sockets:socket-file-descriptor (socket y)))) (if (< x sy) sy x))) (cdr sockets) :initial-value (sb-bsd-sockets:socket-file-descriptor (socket (car sockets)))))) (fdset-zero rfds) (dolist (sock sockets) (fdset-set rfds (sb-bsd-sockets:socket-file-descriptor (socket sock)))) (let ((count (sockets-internal:do-select to-secs to-musecs rfds max-fd))) (cond ((= 0 count) (values nil nil)) ((< count 0) ;; check for EINTR and EAGAIN; these should not err (values nil (cerrno))) (t (dolist (sock sockets) (when (fdset-fd-isset rfds (sb-bsd-sockets:socket-file-descriptor (socket sock))) (setf (state sock) :READ)))))))) )
5,221
Common Lisp
.lisp
145
25.427586
82
0.508793
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
9999ec7ce881df39ef2ff30fd78740c1f1fd7883034993dc92454b10646f0d68
42,623
[ 480117 ]
42,624
mezzano.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/mezzano.lisp
;;;; -*- Mode: Common-Lisp -*- ;;;; See LICENSE for licensing information. (in-package :usocket) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) (typecase condition ;; TODO: Add additional conditions as appropriate (mezzano.network.tcp:connection-timed-out (error 'timeout-error :socket socket)))) (defun socket-connect (host port &key (protocol :stream) element-type timeout deadline (nodelay nil nodelay-p) local-host local-port) (declare (ignore local-host local-port)) (when deadline (unsupported 'deadline 'socket-connect)) (when (and nodelay-p (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (when timeout (unsupported 'timeout 'socket-connect)) (with-mapped-conditions () (ecase protocol (:stream (let ((s (mezzano.network.tcp:tcp-stream-connect host port :element-type element-type))) (make-stream-socket :socket s :stream s))) (:datagram ;; TODO: (unsupported 'datagram 'socket-connect))))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (declare (ignore reuseaddress reuse-address reuse-address-supplied-p)) (let ((ip (mezzano.network.ip:make-ipv4-address host))) (make-stream-server-socket (mezzano.network.tcp:tcp-listen ip port :backlog backlog) :element-type element-type))) (defun get-hosts-by-name (name) (declare (ignore name))) (defun get-host-by-address (address) (declare (ignore address))) (defmethod mezzano.sync:get-object-event ((object usocket)) (mezzano.sync:get-object-event (socket object))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun wait-for-input-internal (wait-list &key timeout) (dolist (waiter (apply #'mezzano.sync:wait-for-objects-with-timeout timeout (wait-list-waiters wait-list))) (setf (state waiter) :read)) wait-list) (defmethod socket-close ((usocket stream-usocket)) (with-mapped-conditions () (close (socket-stream usocket)))) (defmethod socket-close ((usocket stream-server-usocket)) (with-mapped-conditions () (mezzano.network.tcp:close-tcp-listener (socket usocket)))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (with-mapped-conditions (usocket) (let ((s (mezzano.network.tcp:tcp-accept (socket usocket) :element-type element-type))) (make-stream-socket :socket s :stream s)))) (defmethod get-local-name ((usocket stream-usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defmethod get-local-address ((usocket stream-usocket)) (mezzano.network.ip:ipv4-address-to-string (mezzano.network.tcp:tcp-connection-local-ip (mezzano.network.tcp:tcp-stream-connection (socket usocket))))) (defmethod get-local-port ((usocket stream-usocket)) (mezzano.network.tcp:tcp-connection-local-port (mezzano.network.tcp:tcp-stream-connection (socket usocket)))) (defmethod get-peer-address ((usocket stream-usocket)) (mezzano.network.ip:ipv4-address-to-string (mezzano.network.tcp:tcp-connection-remote-ip (mezzano.network.tcp:tcp-stream-connection (socket usocket))))) (defmethod get-peer-port ((usocket stream-usocket)) (mezzano.network.tcp:tcp-connection-remote-port (mezzano.network.tcp:tcp-stream-connection (socket usocket))))
3,936
Common Lisp
.lisp
82
41.134146
109
0.685886
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e5dce93da7d4060c8123ad520a12b0fec210eb33022dbacd15b7d9f728c4fb5f
42,624
[ -1 ]
42,625
openmcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/openmcl.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) (defun get-host-name () (ccl::%stack-block ((resultbuf 256)) (when (zerop (#_gethostname resultbuf 256)) (ccl::%get-cstring resultbuf)))) (defparameter +openmcl-error-map+ '((:address-in-use . address-in-use-error) (:connection-aborted . connection-aborted-error) (:no-buffer-space . no-buffers-error) (:connection-timed-out . timeout-error) (:connection-refused . connection-refused-error) (:host-unreachable . host-unreachable-error) (:host-down . host-down-error) (:network-down . network-down-error) (:address-not-available . address-not-available-error) (:network-reset . network-reset-error) (:connection-reset . connection-reset-error) (:shutdown . shutdown-error) (:access-denied . operation-not-permitted-error))) (defparameter +openmcl-nameserver-error-map+ '((:no-recovery . ns-no-recovery-error) (:try-again . ns-try-again-error) (:host-not-found . ns-host-not-found-error))) ;; we need something which the openmcl implementors 'forgot' to do: ;; wait for more than one socket-or-fd (defun input-available-p (sockets &optional ticks-to-wait) (ccl::rletz ((tv :timeval)) (ccl::ticks-to-timeval ticks-to-wait tv) ;;### The trickery below can be moved to the wait-list now... (ccl::%stack-block ((infds ccl::*fd-set-size*)) (ccl::fd-zero infds) (let ((max-fd -1)) (dolist (sock sockets) (let ((fd (openmcl-socket:socket-os-fd (socket sock)))) (when fd ;; may be NIL if closed (setf max-fd (max max-fd fd)) (ccl::fd-set fd infds)))) (let ((res (#_select (1+ max-fd) infds (ccl::%null-ptr) (ccl::%null-ptr) (if ticks-to-wait tv (ccl::%null-ptr))))) (when (> res 0) (dolist (sock sockets) (let ((fd (openmcl-socket:socket-os-fd (socket sock)))) (when (and fd (ccl::fd-is-set fd infds)) (setf (state sock) :READ))))) sockets))))) (defun raise-error-from-id (condition-id socket real-condition) (let ((usock-err (cdr (assoc condition-id +openmcl-error-map+)))) (if usock-err (error usock-err :socket socket) (error 'unknown-error :socket socket :real-error real-condition)))) (defun handle-condition (condition &optional socket (host-or-ip nil)) (typecase condition (openmcl-socket:socket-error (raise-error-from-id (openmcl-socket:socket-error-identifier condition) socket condition)) (ccl:input-timeout (error 'timeout-error :socket socket)) (ccl:communication-deadline-expired (error 'deadline-timeout-error :socket socket)) (ccl::socket-creation-error #| ugh! |# (let* ((condition-id (ccl::socket-creation-error-identifier condition)) (nameserver-error (cdr (assoc condition-id +openmcl-nameserver-error-map+)))) (if nameserver-error (if (typep nameserver-error 'serious-condition) (error nameserver-error :host-or-ip host-or-ip) (signal nameserver-error :host-or-ip host-or-ip)) (raise-error-from-id condition-id socket condition)))))) (defun to-format (element-type protocol) (cond ((null element-type) (ecase protocol ; default value of different protocol (:stream ;;:text :bivalent) (:datagram :binary))) ((subtypep element-type 'character) :text) (t ;; :binary :bivalent))) #-ipv6 (defun socket-connect (host port &key (protocol :stream) element-type timeout deadline nodelay local-host local-port) (when (eq nodelay :if-supported) (setf nodelay t)) (with-mapped-conditions (nil host) (ecase protocol (:stream (let ((mcl-sock (openmcl-socket:make-socket :remote-host (host-to-hostname host) :remote-port port :local-host local-host :local-port local-port :format (to-format element-type protocol) :external-format ccl:*default-external-format* :deadline deadline :nodelay nodelay :connect-timeout timeout))) (make-stream-socket :stream mcl-sock :socket mcl-sock))) (:datagram (let* ((mcl-sock (openmcl-socket:make-socket :address-family :internet :type :datagram :local-host local-host :local-port local-port :input-timeout timeout :format (to-format element-type protocol) :external-format ccl:*default-external-format*)) (usocket (make-datagram-socket mcl-sock))) (when (and host port) (ccl::inet-connect (ccl::socket-device mcl-sock) (ccl::host-as-inet-host host) (ccl::port-as-inet-port port "udp"))) (setf (connected-p usocket) t) usocket))))) #-ipv6 (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (real-host (host-to-hostname host)) (sock (with-mapped-conditions (nil host) (apply #'openmcl-socket:make-socket (append (list :connect :passive :reuse-address reuseaddress :local-port port :backlog backlog :format (to-format element-type :stream)) (unless (eq host *wildcard-host*) (list :local-host real-host))))))) (make-stream-server-socket sock :element-type element-type))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (declare (ignore element-type)) ;; openmcl streams are bi/multivalent (let ((sock (with-mapped-conditions (usocket) (openmcl-socket:accept-connection (socket usocket))))) (make-stream-socket :socket sock :stream sock))) ;; One close method is sufficient because sockets ;; and their associated objects are represented ;; by the same object. (defmethod socket-close ((usocket usocket)) (with-mapped-conditions (usocket) (close (socket usocket) :abort t))) ; see "sbcl.lisp" for (:abort t) (defmethod socket-shutdown ((usocket usocket) direction) (let ((ccl-direction (case direction (:io :both) (otherwise direction)))) (with-mapped-conditions (usocket) (if (and (eq ccl-direction :both) ;; The :BOTH support was introduced in CCL 1.11.5, ;; and CCL's *FEATURES* allow to distignguish only major version, ;; so we use it starting with 1.12. (not (member :ccl-1.12 *features*))) (progn (openmcl-socket:shutdown (socket usocket) :direction :input) (openmcl-socket:shutdown (socket usocket) :direction :output)) (openmcl-socket:shutdown (socket usocket) :direction ccl-direction))))) #-ipv6 (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (with-mapped-conditions (usocket host) (if (and host port) (openmcl-socket:send-to (socket usocket) buffer size :remote-host (host-to-hbo host) :remote-port port :offset offset) ;; Clozure CL's socket function SEND-TO doesn't support operations on connected UDP sockets, ;; so we have to define our own. (let* ((socket (socket usocket)) (fd (ccl::socket-device socket))) (multiple-value-setq (buffer offset) (ccl::verify-socket-buffer buffer offset size)) (ccl::%stack-block ((bufptr size)) (ccl::%copy-ivector-to-ptr buffer offset bufptr 0 size) (ccl::socket-call socket "send" (ccl::with-eagain fd :output (ccl::ignoring-eintr (ccl::check-socket-error (#_send fd bufptr size 0)))))))))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key) (with-mapped-conditions (usocket) (openmcl-socket:receive-from (socket usocket) length :buffer buffer))) (defun usocket-host-address (address) (cond ((integerp address) (hbo-to-vector-quad address)) ((and (arrayp address) (= (length address) 16) (every #'= address #(0 0 0 0 0 0 0 0 0 0 #xff #xff))) (make-array 4 :displaced-to address :displaced-index-offset 12)) (t address))) (defmethod get-local-address ((usocket usocket)) (usocket-host-address (openmcl-socket:local-host (socket usocket)))) (defmethod get-peer-address ((usocket stream-usocket)) (usocket-host-address (openmcl-socket:remote-host (socket usocket)))) (defmethod get-local-port ((usocket usocket)) (openmcl-socket:local-port (socket usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (openmcl-socket:remote-port (socket usocket))) (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) (openmcl-socket:ipaddr-to-hostname (host-to-hbo address)))) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (list (hbo-to-vector-quad (openmcl-socket:lookup-hostname (host-to-hostname name)))))) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun %remove-waiter (wait-list waiter) (declare (ignore wait-list waiter))) (defun wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () (let* ((ticks-timeout (truncate (* (or timeout 1) ccl::*ticks-per-second*)))) (input-available-p (wait-list-waiters wait-list) (when timeout ticks-timeout)) wait-list))) ;;; Helper functions for option.lisp (defun get-socket-option-reuseaddr (socket) (ccl::int-getsockopt (ccl::socket-device socket) #$SOL_SOCKET #$SO_REUSEADDR)) (defun set-socket-option-reuseaddr (socket value) (ccl::int-setsockopt (ccl::socket-device socket) #$SOL_SOCKET #$SO_REUSEADDR value)) (defun get-socket-option-broadcast (socket) (ccl::int-getsockopt (ccl::socket-device socket) #$SOL_SOCKET #$SO_BROADCAST)) (defun set-socket-option-broadcast (socket value) (ccl::int-setsockopt (ccl::socket-device socket) #$SOL_SOCKET #$SO_BROADCAST value)) (defun get-socket-option-tcp-nodelay (socket) (ccl::int-getsockopt (ccl::socket-device socket) #$IPPROTO_TCP #$TCP_NODELAY)) (defun set-socket-option-tcp-nodelay (socket value) (ccl::int-setsockopt (ccl::socket-device socket) #$IPPROTO_TCP #$TCP_NODELAY value))
11,157
Common Lisp
.lisp
245
37.187755
93
0.635804
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
fb92b0d70f82b7a20c9f77169a43dc4b6cbe85d7ccf688798ce71e8df2cdd3d2
42,625
[ -1 ]
42,626
sbcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/sbcl.lisp
;;;; -*- Mode: Common-Lisp -*- ;;;; See LICENSE for licensing information. (in-package :usocket) #+sbcl (progn #-win32 (defun get-host-name () (sb-unix:unix-gethostname)) ;; we assume winsock has already been loaded, after all, ;; we already loaded sb-bsd-sockets and sb-alien #+win32 (defun get-host-name () (sb-alien:with-alien ((buf (sb-alien:array sb-alien:char 256))) (let ((result (sb-alien:alien-funcall (sb-alien:extern-alien "gethostname" (sb-alien:function sb-alien:int (* sb-alien:char) sb-alien:int)) (sb-alien:cast buf (* sb-alien:char)) 256))) (when (= result 0) (sb-alien:cast buf sb-alien:c-string)))))) #+(or mkcl (and ecl (not ecl-bytecmp))) (progn #-:wsock (ffi:clines "#include <errno.h>" "#include <sys/socket.h>" "#include <unistd.h>") #+:wsock (ffi:clines "#ifndef FD_SETSIZE" "#define FD_SETSIZE 1024" "#endif" "#include <winsock2.h>") (ffi:clines #+:msvc "#include <time.h>" #-:msvc "#include <sys/time.h>" "#include <ecl/ecl-inl.h>") #| #+:prefixed-api (ffi:clines "#define CONS(x, y) ecl_cons((x), (y))" "#define MAKE_INTEGER(x) ecl_make_integer((x))") #-:prefixed-api (ffi:clines "#define CONS(x, y) make_cons((x), (y))" "#define MAKE_INTEGER(x) make_integer((x))") |# (defun cerrno () (ffi:c-inline () () :int "errno" :one-liner t)) (defun fd-setsize () (ffi:c-inline () () :fixnum "FD_SETSIZE" :one-liner t)) #+ecl (defun fdset-alloc () (ffi:c-inline () () :pointer-void "ecl_alloc_atomic(sizeof(fd_set))" :one-liner t)) #+mkcl (defun fdset-alloc () (ffi:c-inline () () :pointer-void "mkcl_alloc_atomic(MKCL_ENV(), sizeof(fd_set))" :one-liner t)) (defun fdset-zero (fdset) (ffi:c-inline (fdset) (:pointer-void) :void "FD_ZERO((fd_set*)#0)" :one-liner t)) (defun fdset-set (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :void "FD_SET(#1,(fd_set*)#0)" :one-liner t)) (defun fdset-clr (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :void "FD_CLR(#1,(fd_set*)#0)" :one-liner t)) (defun fdset-fd-isset (fdset fd) (ffi:c-inline (fdset fd) (:pointer-void :fixnum) :bool "FD_ISSET(#1,(fd_set*)#0)" :one-liner t)) (declaim (inline cerrno fd-setsize fdset-alloc fdset-zero fdset-set fdset-clr fdset-fd-isset)) #+ecl (defun get-host-name () (ffi:c-inline () () :object "{ char *buf = (char *) ecl_alloc_atomic(257); if (gethostname(buf,256) == 0) @(return) = make_simple_base_string(buf); else @(return) = Cnil; }" :one-liner nil :side-effects nil)) #+mkcl (defun get-host-name () (ffi:c-inline () () :object "{ char *buf = (char *) mkcl_alloc_atomic(MKCL_ENV(),257); if (gethostname(buf,256) == 0) @(return) = mkcl_cstring_to_base_string(MKCL_ENV(), (buf)); else @(return) = mk_cl_Cnil; }" :one-liner nil :side-effects nil)) (defun read-select (wl to-secs &optional (to-musecs 0)) (let* ((sockets (wait-list-waiters wl)) (rfds (wait-list-%wait wl)) (max-fd (reduce #'(lambda (x y) (let ((sy (sb-bsd-sockets:socket-file-descriptor (socket y)))) (if (< x sy) sy x))) (cdr sockets) :initial-value (sb-bsd-sockets:socket-file-descriptor (socket (car sockets)))))) (fdset-zero rfds) (dolist (sock sockets) (fdset-set rfds (sb-bsd-sockets:socket-file-descriptor (socket sock)))) (let ((count (ffi:c-inline (to-secs to-musecs rfds max-fd) (t :unsigned-int :pointer-void :int) :int #+ecl " int count; struct timeval tv; struct timeval tvs; struct timeval tve; unsigned long elapsed; unsigned long remaining; int retval = -1; if (#0 != Cnil) { tv.tv_sec = fixnnint(#0); tv.tv_usec = #1; } remaining = ((tv.tv_sec*1000000) + tv.tv_usec); do { (void)gettimeofday(&tvs, NULL); // start time retval = select(#3 + 1, (fd_set*)#2, NULL, NULL, (#0 != Cnil) ? &tv : NULL); if ( (retval < 0) && (errno == EINTR) && (#0 != Cnil) ) { (void)gettimeofday(&tve, NULL); // end time elapsed = (tve.tv_sec - tvs.tv_sec)*1000000 + (tve.tv_usec - tvs.tv_usec); remaining = remaining - elapsed; if ( remaining < 0 ) { // already past timeout, just exit retval = 0; break; } tv.tv_sec = remaining / 1000000; tv.tv_usec = remaining - (tv.tv_sec * 1000000); } } while ((retval < 0) && (errno == EINTR)); @(return) = retval; " #+mkcl " int count; struct timeval tv; struct timeval tvs; struct timeval tve; unsigned long elapsed; unsigned long remaining; int retval = -1; if (#0 != mk_cl_Cnil) { tv.tv_sec = mkcl_integer_to_word(MKCL_ENV(), #0); tv.tv_usec = #1; } remaining = ((tv.tv_sec*1000000) + tv.tv_usec); do { (void)gettimeofday(&tvs, NULL); // start time retval = select(#3 + 1, (fd_set*)#2, NULL, NULL, (#0 != mk_cl_Cnil) ? &tv : NULL); if ( (retval < 0) && (errno == EINTR) && (#0 != mk_cl_Cnil) ) { (void)gettimeofday(&tve, NULL); // end time elapsed = (tve.tv_sec - tvs.tv_sec)*1000000 + (tve.tv_usec - tvs.tv_usec); remaining = remaining - elapsed; if ( remaining < 0 ) { // already past timeout, just exit retval = 0; break; } tv.tv_sec = remaining / 1000000; tv.tv_usec = remaining - (tv.tv_sec * 1000000); } } while ((retval < 0) && (errno == EINTR)); @(return) = retval; " :one-liner nil))) (cond ((= 0 count) (values nil nil)) ((< count 0) ;; check for EAGAIN; these should not err (values nil (cerrno))) (t (dolist (sock sockets) (when (fdset-fd-isset rfds (sb-bsd-sockets:socket-file-descriptor (socket sock))) (setf (state sock) :READ)))))))) ) ; progn (defun map-socket-error (sock-err) (map-errno-error (sb-bsd-sockets::socket-error-errno sock-err))) (defparameter +sbcl-condition-map+ '((interrupted-error . interrupted-condition) #+(or ecl mkcl clasp) (sb-bsd-sockets::host-not-found-error . ns-host-not-found-error))) (defparameter +sbcl-error-map+ `((sb-bsd-sockets:address-in-use-error . address-in-use-error) (sb-bsd-sockets::no-address-error . address-not-available-error) (sb-bsd-sockets:bad-file-descriptor-error . bad-file-descriptor-error) (sb-bsd-sockets:connection-refused-error . connection-refused-error) (sb-bsd-sockets:invalid-argument-error . invalid-argument-error) (sb-bsd-sockets:no-buffers-error . no-buffers-error) (sb-bsd-sockets:operation-not-supported-error . operation-not-supported-error) (sb-bsd-sockets:operation-not-permitted-error . operation-not-permitted-error) (sb-bsd-sockets:protocol-not-supported-error . protocol-not-supported-error) #-(or ecl mkcl clasp) (sb-bsd-sockets:unknown-protocol . protocol-not-supported-error) (sb-bsd-sockets:socket-type-not-supported-error . socket-type-not-supported-error) (sb-bsd-sockets:network-unreachable-error . network-unreachable-error) (sb-bsd-sockets:operation-timeout-error . timeout-error) #-(or ecl mkcl clasp) (sb-sys:io-timeout . timeout-error) #+sbcl (sb-ext:timeout . timeout-error) ;; learnt from fiveam (suggested by Anton Vodonosov) for early SBCL versions #+#.(cl:if (cl:ignore-errors (cl:find-symbol "BROKEN-PIPE" "SB-INT")) '(and) '(or)) (sb-int:broken-pipe . connection-aborted-error) (sb-bsd-sockets:socket-error . ,#'map-socket-error) ;; Nameservice errors: mapped to unknown-error #-(or ecl mkcl clasp) (sb-bsd-sockets:no-recovery-error . ns-no-recovery-error) #-(or ecl mkcl clasp) (sb-bsd-sockets:try-again-error . ns-try-again-error) #-(or ecl mkcl clasp) (sb-bsd-sockets:host-not-found-error . ns-host-not-found-error))) ;; this function servers as a general template for other backends (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (typecase condition (serious-condition (let* ((usock-error (cdr (assoc (type-of condition) +sbcl-error-map+))) (usock-error (if (functionp usock-error) (funcall usock-error condition) usock-error))) (declare (type symbol usock-error)) (if usock-error (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (error 'unknown-error :real-error condition :socket socket)))) (condition (let* ((usock-cond (cdr (assoc (type-of condition) +sbcl-condition-map+))) (usock-cond (if (functionp usock-cond) (funcall usock-cond condition) usock-cond))) (if usock-cond (cond ((subtypep usock-cond 'ns-condition) (signal usock-cond :socket socket :host-or-ip host-or-ip)) (t (signal usock-cond :socket socket))) (signal 'unknown-condition :real-condition condition :socket socket)))))) ;;; "The socket stream ends up with a bogus name as it is created before ;;; the socket is connected, making things harder to debug than they need ;;; to be." -- Nikodemus Siivola <[email protected]> (defvar *dummy-stream* (let ((stream (make-broadcast-stream))) (close stream) stream)) ;;; Amusingly, neither SBCL's own, nor GBBopen's WITH-TIMEOUT is asynch ;;; unwind safe. The one I posted is -- that's what the WITHOUT-INTERRUPTS ;;; and WITH-LOCAL-INTERRUPTS were for. :) But yeah, it's miles saner than ;;; the SB-EXT:WITH-TIMEOUT. -- Nikodemus Siivola <[email protected]> #+(and sbcl (not win32)) (defmacro %with-timeout ((seconds timeout-form) &body body) "Runs BODY as an implicit PROGN with timeout of SECONDS. If timeout occurs before BODY has finished, BODY is unwound and TIMEOUT-FORM is executed with its values returned instead. Note that BODY is unwound asynchronously when a timeout occurs, so unless all code executed during it -- including anything down the call chain -- is asynch unwind safe, bad things will happen. Use with care." (let ((exec (gensym)) (unwind (gensym)) (timer (gensym)) (timeout (gensym)) (block (gensym))) `(block ,block (tagbody (flet ((,unwind () (go ,timeout)) (,exec () ,@body)) (declare (dynamic-extent #',exec #',unwind)) (let ((,timer (sb-ext:make-timer #',unwind))) (declare (dynamic-extent ,timer)) (sb-sys:without-interrupts (unwind-protect (progn (sb-ext:schedule-timer ,timer ,seconds) (return-from ,block (sb-sys:with-local-interrupts (,exec)))) (sb-ext:unschedule-timer ,timer))))) ,timeout (return-from ,block ,timeout-form))))) (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (multiple-value-bind (host4 host6) (sb-bsd-sockets:get-host-by-name name) (let ((addr4 (when host4 (sb-bsd-sockets::host-ent-addresses host4))) (addr6 (when host6 (sb-bsd-sockets::host-ent-addresses host6)))) (append addr4 addr6))))) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-specified) local-host local-port &aux (sockopt-tcp-nodelay-p (fboundp 'sb-bsd-sockets::sockopt-tcp-nodelay))) (when deadline (unsupported 'deadline 'socket-connect)) #+(or ecl mkcl clasp) (when timeout (unsupported 'timeout 'socket-connect)) (when (and nodelay-specified ;; 20080802: ECL added this function to its sockets ;; package today. There's no guarantee the functions ;; we need are available, but we can make sure not to ;; call them if they aren't (not (eq nodelay :if-supported)) (not sockopt-tcp-nodelay-p)) (unsupported 'nodelay 'socket-connect)) (when (eq nodelay :if-supported) (setf nodelay t)) (let* ((remote (when host (car (get-hosts-by-name (host-to-hostname host))))) (local (when local-host (car (get-hosts-by-name (host-to-hostname local-host))))) (ipv6 (or (and remote (= 16 (length remote))) (and local (= 16 (length local))))) (socket (make-instance #+sbcl (if ipv6 'sb-bsd-sockets::inet6-socket 'sb-bsd-sockets:inet-socket) #+(or ecl mkcl clasp) 'sb-bsd-sockets:inet-socket :type protocol :protocol (case protocol (:stream :tcp) (:datagram :udp)))) usocket ok) (unwind-protect (progn (ecase protocol (:stream ;; If make a real socket stream before the socket is ;; connected, it gets a misleading name so supply a ;; dummy value to start with. (setf usocket (make-stream-socket :socket socket :stream *dummy-stream*)) ;; binghe: use SOCKOPT-TCP-NODELAY as internal symbol ;; to pass compilation on ECL without it. (when (and nodelay-specified sockopt-tcp-nodelay-p) (setf (sb-bsd-sockets::sockopt-tcp-nodelay socket) nodelay)) (when (or local-host local-port) (sb-bsd-sockets:socket-bind socket (if ipv6 (or local (ipv6-host-to-vector "::0")) (or local (host-to-vector-quad *wildcard-host*))) (or local-port *auto-port*))) (with-mapped-conditions (usocket host) #+(and sbcl (not win32)) (labels ((connect () (sb-bsd-sockets:socket-connect socket remote port))) (if timeout (%with-timeout (timeout (error 'sb-ext:timeout)) (connect)) (connect))) #+(or ecl mkcl clasp (and sbcl win32)) (sb-bsd-sockets:socket-connect socket remote port) ;; Now that we're connected make the stream. (setf (socket-stream usocket) (sb-bsd-sockets:socket-make-stream socket :input t :output t :buffering :full :element-type element-type ;; Robert Brown <[email protected]> said on Aug 4, 2011: ;; ... This means that SBCL streams created by usocket have a true ;; serve-events property. When writing large amounts of data to several ;; streams, the kernel will eventually stop accepting data from SBCL. ;; When this happens, SBCL either waits for I/O to be possible on ;; the file descriptor it's writing to or queues the data to be flushed later. ;; Because usocket streams specify serve-events as true, SBCL ;; always queues. Instead, it should wait for I/O to be available and ;; write the remaining data to the socket. That's what serve-events ;; equal to NIL gets you. ;; ;; Nikodemus Siivola <[email protected]> said on Aug 8, 2011: ;; It's set to T for purely historical reasons, and will soon change to ;; NIL in SBCL. (The docstring has warned of T being a temporary default ;; for as long as the :SERVE-EVENTS keyword argument has existed.) :serve-events nil)))) (:datagram (when (or local-host local-port) (sb-bsd-sockets:socket-bind socket (if ipv6 (or local (ipv6-host-to-vector "::0")) (or local (host-to-vector-quad *wildcard-host*))) (or local-port *auto-port*))) (setf usocket (make-datagram-socket socket)) (when (and host port) (with-mapped-conditions (usocket) (sb-bsd-sockets:socket-connect socket remote port) (setf (connected-p usocket) t))))) (setf ok t)) ;; Clean up in case of an error. (unless ok (sb-bsd-sockets:socket-close socket :abort t))) usocket)) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (let* (#+sbcl (local (when host (car (get-hosts-by-name (host-to-hostname host))))) #+sbcl (ipv6 (and local (= 16 (length local)))) (reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (ip #+sbcl (if (and local (not (eq host *wildcard-host*))) local (hbo-to-vector-quad sb-bsd-sockets-internal::inaddr-any)) #+(or ecl mkcl clasp) (host-to-vector-quad host)) (sock (make-instance #+sbcl (if ipv6 'sb-bsd-sockets::inet6-socket 'sb-bsd-sockets:inet-socket) #+(or ecl mkcl clasp) 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (handler-case (with-mapped-conditions (nil host) (setf (sb-bsd-sockets:sockopt-reuse-address sock) reuseaddress) (sb-bsd-sockets:socket-bind sock ip port) (sb-bsd-sockets:socket-listen sock backlog) (make-stream-server-socket sock :element-type element-type)) (t (c) ;; Make sure we don't leak filedescriptors (sb-bsd-sockets:socket-close sock) (error c))))) ;;; "2. SB-BSD-SOCKETS:SOCKET-ACCEPT method returns NIL for EAGAIN/EINTR, ;;; instead of raising a condition. It's always possible for ;;; SOCKET-ACCEPT on non-blocking socket to fail, even after the socket ;;; was detected to be ready: connection might be reset, for example. ;;; ;;; "I had to redefine SOCKET-ACCEPT method of STREAM-SERVER-USOCKET to ;;; handle this situation. Here is the redefinition:" -- Anton Kovalenko <[email protected]> (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (with-mapped-conditions (usocket) (let ((socket (sb-bsd-sockets:socket-accept (socket usocket)))) (when socket (prog1 (make-stream-socket :socket socket :stream (sb-bsd-sockets:socket-make-stream socket :input t :output t :buffering :full :element-type (or element-type (element-type usocket)))) ;; next time wait for event again if we had EAGAIN/EINTR ;; or else we'd enter a tight loop of failed accepts #+win32 (setf (%ready-p usocket) nil)))))) ;; Sockets and their associated streams are modelled as ;; different objects. Be sure to close the stream (which ;; closes the socket too) when closing a stream-socket. (defmethod socket-close ((usocket usocket)) (with-mapped-conditions (usocket) (sb-bsd-sockets:socket-close (socket usocket)))) ;; usocket leaks file descriptors on sb-int:broken-pipe conditions (#64) ;; ;; "If abort is true, an attempt is made to clean up any side effects of having ;; created stream. If stream performs output to a file that was created when ;; the stream was created, the file is deleted and any previously existing file ;; is not superseded. ... If abort is true and the stream is an output file stream, ;; its associated file might be deleted." (ANSI) ;; ;; adding (:abort t) fixes the potential leaks of socket fds. (defmethod socket-close ((usocket stream-usocket)) (with-mapped-conditions (usocket) (close (socket-stream usocket) :abort t))) #+sbcl (defmethod socket-shutdown ((usocket stream-usocket) direction) (with-mapped-conditions (usocket) (sb-bsd-sockets::socket-shutdown (socket usocket) :direction direction))) #+(or ecl mkcl) (defmethod socket-shutdown ((usocket stream-usocket) direction) (let ((sock-fd (sb-bsd-sockets:socket-file-descriptor (socket usocket))) (direction-flag (ecase direction (:input 0) (:output 1) (:io 2)))) (unless (zerop (ffi:c-inline (sock-fd direction-flag) (:int :int) :int "shutdown(#0, #1)" :one-liner t)) (error (map-errno-error (cerrno)))))) #+clasp (defmethod socket-shutdown ((usocket stream-usocket) direction) (let ((sock-fd (sb-bsd-sockets:socket-file-descriptor (socket usocket))) (direction-flag (ecase direction (:input 0) (:output 1) (:io 2)))) (unless (zerop (sockets-internal:shutdown sock-fd direction-flag)) (error (map-errno-error (cerrno)))))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (let ((remote (when host (car (get-hosts-by-name (host-to-hostname host)))))) (with-mapped-conditions (usocket host) (let* ((s (socket usocket)) (dest (if (and host port) (list remote port) nil)) (real-buffer (if (zerop offset) buffer (subseq buffer offset (+ offset size))))) (sb-bsd-sockets:socket-send s real-buffer size :address dest))))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key (element-type '(unsigned-byte 8))) #+sbcl (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (simple-array (unsigned-byte 8) (*)) ; host (unsigned-byte 16) ; port &optional)) (with-mapped-conditions (usocket) (let ((s (socket usocket))) (sb-bsd-sockets:socket-receive s buffer length :element-type element-type)))) (defmethod get-local-name ((usocket usocket)) (sb-bsd-sockets:socket-name (socket usocket))) (defmethod get-peer-name ((usocket stream-usocket)) (sb-bsd-sockets:socket-peername (socket usocket))) (defmethod get-local-address ((usocket usocket)) (nth-value 0 (get-local-name usocket))) (defmethod get-peer-address ((usocket stream-usocket)) (nth-value 0 (get-peer-name usocket))) (defmethod get-local-port ((usocket usocket)) (nth-value 1 (get-local-name usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (nth-value 1 (get-peer-name usocket))) (defun get-host-by-address (address) (with-mapped-conditions (nil address) (sb-bsd-sockets::host-ent-name (sb-bsd-sockets:get-host-by-address address)))) #+(and sbcl (not win32)) (progn (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (push (socket waiter) (wait-list-%wait wait-list))) (defun %remove-waiter (wait-list waiter) (setf (wait-list-%wait wait-list) (remove (socket waiter) (wait-list-%wait wait-list)))) (defun wait-for-input-internal (sockets &key timeout) (with-mapped-conditions () (sb-alien:with-alien ((rfds (sb-alien:struct sb-unix:fd-set))) (sb-unix:fd-zero rfds) (dolist (socket (wait-list-%wait sockets)) (sb-unix:fd-set (sb-bsd-sockets:socket-file-descriptor socket) rfds)) (multiple-value-bind (secs musecs) (split-timeout (or timeout 1)) (let* ((wait-list (wait-list-%wait sockets)) count err) (if (null wait-list) (setq count 0) ;; no need to call (multiple-value-setq (count err) (sb-unix:unix-fast-select ;; "invalid number of arguments: 0" if wait-list is null. (1+ (reduce #'max wait-list :key #'sb-bsd-sockets:socket-file-descriptor)) (sb-alien:addr rfds) nil nil (when timeout secs) (when timeout musecs)))) (if (null count) ; something wrong in #'sb-unix:unix-fast-select (unless (= err sb-unix:eintr) (error (map-errno-error err))) (when (< 0 count) ; do nothing if count = 0 ;; process the result... (dolist (x (wait-list-waiters sockets)) (when (sb-unix:fd-isset (sb-bsd-sockets:socket-file-descriptor (socket x)) rfds) (setf (state x) :READ)))))))))) ) ; progn ;;; WAIT-FOR-INPUT support for SBCL on Windows platform (Chun Tian (binghe)) ;;; Based on LispWorks version written by Erik Huelsmann. #+win32 ; shared by ECL and SBCL (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +wsa-wait-failed+ #xffffffff) (defconstant +wsa-infinite+ #xffffffff) (defconstant +wsa-wait-event-0+ 0) (defconstant +wsa-wait-timeout+ 258)) #+win32 ; shared by ECL and SBCL (progn (defconstant fd-read 1) (defconstant fd-read-bit 0) (defconstant fd-write 2) (defconstant fd-write-bit 1) (defconstant fd-oob 4) (defconstant fd-oob-bit 2) (defconstant fd-accept 8) (defconstant fd-accept-bit 3) (defconstant fd-connect 16) (defconstant fd-connect-bit 4) (defconstant fd-close 32) (defconstant fd-close-bit 5) (defconstant fd-qos 64) (defconstant fd-qos-bit 6) (defconstant fd-group-qos 128) (defconstant fd-group-qos-bit 7) (defconstant fd-routing-interface 256) (defconstant fd-routing-interface-bit 8) (defconstant fd-address-list-change 512) (defconstant fd-address-list-change-bit 9) (defconstant fd-max-events 10) (defconstant fionread 1074030207) ;; Note: for ECL, socket-handle will return raw Windows Handle, ;; while SBCL returns OSF Handle instead. (defun socket-handle (usocket) (sb-bsd-sockets:socket-file-descriptor (socket usocket))) (defun socket-ready-p (socket) (if (typep socket 'stream-usocket) (plusp (bytes-available-for-read socket)) (%ready-p socket))) (defun waiting-required (sockets) (notany #'socket-ready-p sockets)) (defun raise-usock-err (errno &optional socket) (error 'unknown-error :socket socket :real-error errno)) (defun wait-for-input-internal (wait-list &key timeout) (when (waiting-required (wait-list-waiters wait-list)) (let ((rv (wsa-wait-for-multiple-events 1 (wait-list-%wait wait-list) nil (if timeout (truncate (* 1000 timeout)) +wsa-infinite+) nil))) (ecase rv ((#.+wsa-wait-event-0+) (update-ready-and-state-slots wait-list)) ((#.+wsa-wait-timeout+)) ; do nothing here ((#.+wsa-wait-failed+) (maybe-wsa-error rv)))))) (defun %add-waiter (wait-list waiter) (let ((events (etypecase waiter (stream-server-usocket (logior fd-connect fd-accept fd-close)) (stream-usocket (logior fd-read)) (datagram-usocket (logior fd-read))))) (maybe-wsa-error (wsa-event-select (os-socket-handle waiter) (os-wait-list-%wait wait-list) events) waiter))) (defun %remove-waiter (wait-list waiter) (maybe-wsa-error (wsa-event-select (os-socket-handle waiter) (os-wait-list-%wait wait-list) 0) waiter)) ) ; progn #+(and sbcl win32) (progn ;; "SOCKET is defined as intptr_t in Windows headers; however, WS-SOCKET ;; is defined as unsigned-int, i.e. 32-bit even on 64-bit platform. It ;; seems to be a good thing to redefine WS-SOCKET as SB-ALIEN:SIGNED, ;; which is always machine word-sized (exactly as intptr_t; ;; N.B. as of Windows/x64, long and signed-long are 32-bit, and thus not ;; enough -- potentially)." ;; -- Anton Kovalenko <[email protected]>, Mar 22, 2011 (sb-alien:define-alien-type ws-socket sb-alien:signed) (sb-alien:define-alien-type ws-dword sb-alien:unsigned-long) ;; WS-EVENT was formerly defined as [internal, now removed] SB-ALIEN::HINSTANCE (synonym for SIGNED) (sb-alien:define-alien-type ws-event sb-alien:signed) (sb-alien:define-alien-type nil (sb-alien:struct wsa-network-events (network-events sb-alien:long) (error-code (array sb-alien:int 10)))) ; 10 = fd-max-events (sb-alien:define-alien-routine ("WSACreateEvent" wsa-event-create) ws-event) ; return type only (sb-alien:define-alien-routine ("WSACloseEvent" wsa-event-close) (boolean #.sb-vm::n-machine-word-bits) (event-object ws-event)) ;; not used (sb-alien:define-alien-routine ("WSAResetEvent" wsa-reset-event) (boolean #.sb-vm::n-machine-word-bits) (event-object ws-event)) (sb-alien:define-alien-routine ("WSAEnumNetworkEvents" wsa-enum-network-events) sb-alien:int (socket ws-socket) (event-object ws-event) (network-events (* (sb-alien:struct wsa-network-events)))) (sb-alien:define-alien-routine ("WSAEventSelect" wsa-event-select) sb-alien:int (socket ws-socket) (event-object ws-event) (network-events sb-alien:long)) (sb-alien:define-alien-routine ("WSAWaitForMultipleEvents" wsa-wait-for-multiple-events) ws-dword (number-of-events ws-dword) (events (* ws-event)) (wait-all-p (boolean #.sb-vm::n-machine-word-bits)) (timeout ws-dword) (alertable-p (boolean #.sb-vm::n-machine-word-bits))) (sb-alien:define-alien-routine ("ioctlsocket" wsa-ioctlsocket) sb-alien:int (socket ws-socket) (cmd sb-alien:long) (argp (* sb-alien:unsigned-long))) (defun maybe-wsa-error (rv &optional socket) (unless (zerop rv) (raise-usock-err (sockint::wsa-get-last-error) socket))) (defun os-socket-handle (usocket) (sb-bsd-sockets:socket-file-descriptor (socket usocket))) (defun bytes-available-for-read (socket) (sb-alien:with-alien ((int-ptr sb-alien:unsigned-long)) (maybe-wsa-error (wsa-ioctlsocket (os-socket-handle socket) fionread (sb-alien:addr int-ptr)) socket) (prog1 int-ptr (when (plusp int-ptr) (setf (state socket) :read))))) (defun map-network-events (func network-events) (let ((event-map (sb-alien:slot network-events 'network-events)) (error-array (sb-alien:slot network-events 'error-code))) (unless (zerop event-map) (dotimes (i fd-max-events) (unless (zerop (ldb (byte 1 i) event-map)) ;;### could be faster with ash and logand? (funcall func (sb-alien:deref error-array i))))))) (defun update-ready-and-state-slots (wait-list) (loop with sockets = (wait-list-waiters wait-list) for socket in sockets do (if (%ready-p socket) (progn (setf (state socket) :READ)) (sb-alien:with-alien ((network-events (sb-alien:struct wsa-network-events))) (let ((rv (wsa-enum-network-events (os-socket-handle socket) (os-wait-list-%wait wait-list) (sb-alien:addr network-events)))) (if (zerop rv) (map-network-events #'(lambda (err-code) (if (zerop err-code) (progn (setf (state socket) :READ) (when (stream-server-usocket-p socket) (setf (%ready-p socket) t))) (raise-usock-err err-code socket))) network-events) (maybe-wsa-error rv socket))))))) (defun os-wait-list-%wait (wait-list) (sb-alien:deref (wait-list-%wait wait-list))) (defun (setf os-wait-list-%wait) (value wait-list) (setf (sb-alien:deref (wait-list-%wait wait-list)) value)) ;; "Event handles are leaking in current SBCL backend implementation, ;; because of SBCL-unfriendly usage of finalizers. ;; ;; "SBCL never calls a finalizer that closes over a finalized object: a ;; reference from that closure prevents its collection forever. That's ;; the case with USOCKET in %SETUP-WAIT-LIST. ;; ;; "I use the following redefinition of %SETUP-WAIT-LIST: ;; ;; "Of course it may be rewritten with more clarity, but you can see the ;; core idea: I'm closing over those components of WAIT-LIST that I need ;; for finalization, not the wait-list itself. With the original ;; %SETUP-WAIT-LIST, hunchentoot stops working after ~100k accepted ;; connections; it doesn't happen with redefined %SETUP-WAIT-LIST." ;; ;; -- Anton Kovalenko <[email protected]>, Mar 22, 2011 (defun %setup-wait-list (wait-list) (setf (wait-list-%wait wait-list) (sb-alien:make-alien ws-event)) (setf (os-wait-list-%wait wait-list) (wsa-event-create)) (sb-ext:finalize wait-list (let ((event-handle (os-wait-list-%wait wait-list)) (alien (wait-list-%wait wait-list))) #'(lambda () (wsa-event-close event-handle) (unless (null alien) (sb-alien:free-alien alien)))))) ) ; progn #+(and (or ecl mkcl clasp) (not win32)) (progn (defun wait-for-input-internal (wl &key timeout) (with-mapped-conditions () (multiple-value-bind (secs usecs) (split-timeout (or timeout 1)) (multiple-value-bind (result-fds err) (read-select wl (when timeout secs) usecs) (declare (ignore result-fds)) (unless (null err) (error (map-errno-error err))))))) (defun %setup-wait-list (wl) (setf (wait-list-%wait wl) (fdset-alloc))) (defun %add-waiter (wl w) (declare (ignore wl w))) (defun %remove-waiter (wl w) (declare (ignore wl w))) ) ; progn #+(and (or ecl mkcl clasp) win32 (not ecl-bytecmp)) (progn (defun maybe-wsa-error (rv &optional syscall) (unless (zerop rv) (sb-bsd-sockets::socket-error syscall))) (defun %setup-wait-list (wl) (setf (wait-list-%wait wl) (ffi:c-inline () () :int "WSAEVENT event; event = WSACreateEvent(); @(return) = event;"))) (defun %add-waiter (wait-list waiter) (let ((events (etypecase waiter (stream-server-usocket (logior fd-connect fd-accept fd-close)) (stream-usocket (logior fd-read)) (datagram-usocket (logior fd-read))))) (maybe-wsa-error (ffi:c-inline ((socket-handle waiter) (wait-list-%wait wait-list) events) (:fixnum :fixnum :fixnum) :fixnum "int result; result = WSAEventSelect((SOCKET)#0, (WSAEVENT)#1, (long)#2); @(return) = result;") '%add-waiter))) (defun %remove-waiter (wait-list waiter) (maybe-wsa-error (ffi:c-inline ((socket-handle waiter) (wait-list-%wait wait-list)) (:fixnum :fixnum) :fixnum "int result; result = WSAEventSelect((SOCKET)#0, (WSAEVENT)#1, 0L); @(return) = result;") '%remove-waiter)) ;; TODO: how to handle error (result) in this call? (declaim (inline %bytes-available-for-read)) (defun %bytes-available-for-read (socket) (ffi:c-inline ((socket-handle socket)) (:fixnum) :fixnum "u_long nbytes; int result; nbytes = 0L; result = ioctlsocket((SOCKET)#0, FIONREAD, &nbytes); @(return) = nbytes;")) (defun bytes-available-for-read (socket) (let ((nbytes (%bytes-available-for-read socket))) (when (plusp nbytes) (setf (state socket) :read)) nbytes)) (defun update-ready-and-state-slots (wait-list) (loop with sockets = (wait-list-waiters wait-list) for socket in sockets do (if (%ready-p socket) (setf (state socket) :READ) (let ((events (etypecase socket (stream-server-usocket (logior fd-connect fd-accept fd-close)) (stream-usocket (logior fd-read)) (datagram-usocket (logior fd-read))))) ;; TODO: check the iErrorCode array (multiple-value-bind (valid-p ready-p) (ffi:c-inline ((socket-handle socket) events) (:fixnum :fixnum) (values :bool :bool) ;; TODO: replace 0 (2nd arg) with (wait-list-%wait wait-list) "WSANETWORKEVENTS network_events; int i, result; result = WSAEnumNetworkEvents((SOCKET)#0, 0, &network_events); if (!result) { @(return 0) = Ct; @(return 1) = (#1 & network_events.lNetworkEvents)? Ct : Cnil; } else { @(return 0) = Cnil; @(return 1) = Cnil; }") (if valid-p (when ready-p (setf (state socket) :READ) (when (stream-server-usocket-p socket) (setf (%ready-p socket) t))) (sb-bsd-sockets::socket-error 'update-ready-and-state-slots))))))) (defun wait-for-input-internal (wait-list &key timeout) (when (waiting-required (wait-list-waiters wait-list)) (let ((rv (ffi:c-inline ((wait-list-%wait wait-list) (if timeout (truncate (* 1000 timeout)) +wsa-infinite+)) (:fixnum :fixnum) :fixnum "DWORD result; WSAEVENT events[1]; events[0] = (WSAEVENT)#0; result = WSAWaitForMultipleEvents(1, events, NULL, #1, NULL); @(return) = result;"))) (ecase rv ((#.+wsa-wait-event-0+) (update-ready-and-state-slots (wait-list-waiters wait-list))) ((#.+wsa-wait-timeout+)) ; do nothing here ((#.+wsa-wait-failed+) (sb-bsd-sockets::socket-error 'wait-for-input-internal)))))) ) ; progn
40,135
Common Lisp
.lisp
899
34.291435
102
0.578397
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
75a17af43991b9be3f0bb9ace393b639b145327d5fbab467d0de2f56e80cf442
42,626
[ -1 ]
42,627
ecl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/ecl.lisp
;;;; -*- Mode: Lisp -*- ;;;; Foreign functions defined by ECL's DFFI, used for #+ecl-bytecmp only. ;;;; See LICENSE for licensing information. (in-package :usocket) #+(and ecl-bytecmp windows) (eval-when (:load-toplevel :execute) (ffi:load-foreign-library "ws2_32.dll" :module "ws2_32")) #+(and ecl-bytecmp windows) (progn (ffi:def-function ("gethostname" c-gethostname) ((name (* :unsigned-char)) (len :int)) :returning :int :module "ws2_32") (defun get-host-name () "Returns the hostname" (ffi:with-foreign-object (name '(:array :unsigned-char 256)) (when (zerop (c-gethostname (ffi:char-array-to-pointer name) 256)) (ffi:convert-from-foreign-string name)))) (ffi:def-foreign-type ws-socket :unsigned-int) (ffi:def-foreign-type ws-dword :unsigned-long) (ffi:def-foreign-type ws-event :unsigned-int) (ffi:def-struct wsa-network-events (network-events :long) (error-code (:array :int 10))) (ffi:def-function ("WSACreateEvent" wsa-event-create) () :returning ws-event :module "ws2_32") (ffi:def-function ("WSACloseEvent" c-wsa-event-close) ((event-object ws-event)) :returning :int :module "ws2_32") (defun wsa-event-close (ws-event) (not (zerop (c-wsa-event-close ws-event)))) (ffi:def-function ("WSAEnumNetworkEvents" wsa-enum-network-events) ((socket ws-socket) (event-object ws-event) (network-events (* wsa-network-events))) :returning :int :module "ws2_32") (ffi:def-function ("WSAEventSelect" wsa-event-select) ((socket ws-socket) (event-object ws-event) (network-events :long)) :returning :int :module "ws2_32") (ffi:def-function ("WSAWaitForMultipleEvents" c-wsa-wait-for-multiple-events) ((number-of-events ws-dword) (events (* ws-event)) (wait-all-p :int) (timeout ws-dword) (alertable-p :int)) :returning ws-dword :module "ws2_32") (defun wsa-wait-for-multiple-events (number-of-events events wait-all-p timeout alertable-p) (c-wsa-wait-for-multiple-events number-of-events events (if wait-all-p -1 0) timeout (if alertable-p -1 0))) (ffi:def-function ("ioctlsocket" wsa-ioctlsocket) ((socket ws-socket) (cmd :long) (argp (* :unsigned-long))) :returning :int :module "ws2_32") (ffi:def-function ("WSAGetLastError" wsa-get-last-error) () :returning :int :module "ws2_32") (defun maybe-wsa-error (rv &optional socket) (unless (zerop rv) (raise-usock-err (wsa-get-last-error) socket))) (defun bytes-available-for-read (socket) (ffi:with-foreign-object (int-ptr :unsigned-long) (maybe-wsa-error (wsa-ioctlsocket (socket-handle socket) fionread int-ptr) socket) (let ((int (ffi:deref-pointer int-ptr :unsigned-long))) (prog1 int (when (plusp int) (setf (state socket) :read)))))) (defun map-network-events (func network-events) (let ((event-map (ffi:get-slot-value network-events 'wsa-network-events 'network-events)) (error-array (ffi:get-slot-pointer network-events 'wsa-network-events 'error-code))) (unless (zerop event-map) (dotimes (i fd-max-events) (unless (zerop (ldb (byte 1 i) event-map)) (funcall func (ffi:deref-array error-array '(:array :int 10) i))))))) (defun update-ready-and-state-slots (sockets) (dolist (socket sockets) (if (%ready-p socket) (progn (setf (state socket) :READ)) (ffi:with-foreign-object (network-events 'wsa-network-events) (let ((rv (wsa-enum-network-events (socket-handle socket) 0 network-events))) (if (zerop rv) (map-network-events #'(lambda (err-code) (if (zerop err-code) (progn (setf (state socket) :READ) (when (stream-server-usocket-p socket) (setf (%ready-p socket) t))) (raise-usock-err err-code socket))) network-events) (maybe-wsa-error rv socket))))))) (defun os-wait-list-%wait (wait-list) (ffi:deref-pointer (wait-list-%wait wait-list) 'ws-event)) (defun (setf os-wait-list-%wait) (value wait-list) (setf (ffi:deref-pointer (wait-list-%wait wait-list) 'ws-event) value)) (defun free-wait-list (wl) (when (wait-list-p wl) (unless (null (wait-list-%wait wl)) (wsa-event-close (os-wait-list-%wait wl)) (ffi:free-foreign-object (wait-list-%wait wl)) (setf (wait-list-%wait wl) nil)))) (defun %setup-wait-list (wait-list) (setf (wait-list-%wait wait-list) (ffi:allocate-foreign-object 'ws-event)) (setf (os-wait-list-%wait wait-list) (wsa-event-create)) (ext:set-finalizer wait-list #'free-wait-list)) (defun os-socket-handle (usocket) (socket-handle usocket)) ) ; #+(and ecl-bytecmp windows)
5,141
Common Lisp
.lisp
126
32.706349
94
0.610944
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
ee31e462f25bcdb8a6cf44ade3125c0e5a11867d852851cafa62209720de4060
42,627
[ 428877 ]
42,628
abcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/abcl.lisp
;;;; New ABCL networking support (replacement to old armedbear.lisp) ;;;; Author: Chun Tian (binghe) ;;;; See LICENSE for licensing information. (in-package :usocket) ;;; Java Classes ($*...) (defvar $*boolean (jclass "boolean")) (defvar $*byte (jclass "byte")) (defvar $*byte[] (jclass "[B")) (defvar $*int (jclass "int")) (defvar $*long (jclass "long")) (defvar $*|Byte| (jclass "java.lang.Byte")) (defvar $*DatagramChannel (jclass "java.nio.channels.DatagramChannel")) (defvar $*DatagramPacket (jclass "java.net.DatagramPacket")) (defvar $*DatagramSocket (jclass "java.net.DatagramSocket")) (defvar $*Inet4Address (jclass "java.net.Inet4Address")) (defvar $*InetAddress (jclass "java.net.InetAddress")) (defvar $*InetSocketAddress (jclass "java.net.InetSocketAddress")) (defvar $*Iterator (jclass "java.util.Iterator")) (defvar $*SelectableChannel (jclass "java.nio.channels.SelectableChannel")) (defvar $*SelectionKey (jclass "java.nio.channels.SelectionKey")) (defvar $*Selector (jclass "java.nio.channels.Selector")) (defvar $*ServerSocket (jclass "java.net.ServerSocket")) (defvar $*ServerSocketChannel (jclass "java.nio.channels.ServerSocketChannel")) (defvar $*Set (jclass "java.util.Set")) (defvar $*Socket (jclass "java.net.Socket")) (defvar $*SocketAddress (jclass "java.net.SocketAddress")) (defvar $*SocketChannel (jclass "java.nio.channels.SocketChannel")) (defvar $*String (jclass "java.lang.String")) ;;; Java Constructor ($%.../n) (defvar $%Byte/0 (jconstructor $*|Byte| $*byte)) (defvar $%DatagramPacket/3 (jconstructor $*DatagramPacket $*byte[] $*int $*int)) (defvar $%DatagramPacket/5 (jconstructor $*DatagramPacket $*byte[] $*int $*int $*InetAddress $*int)) (defvar $%DatagramSocket/0 (jconstructor $*DatagramSocket)) (defvar $%DatagramSocket/1 (jconstructor $*DatagramSocket $*int)) (defvar $%DatagramSocket/2 (jconstructor $*DatagramSocket $*int $*InetAddress)) (defvar $%InetSocketAddress/1 (jconstructor $*InetSocketAddress $*int)) (defvar $%InetSocketAddress/2 (jconstructor $*InetSocketAddress $*InetAddress $*int)) (defvar $%ServerSocket/0 (jconstructor $*ServerSocket)) (defvar $%ServerSocket/1 (jconstructor $*ServerSocket $*int)) (defvar $%ServerSocket/2 (jconstructor $*ServerSocket $*int $*int)) (defvar $%ServerSocket/3 (jconstructor $*ServerSocket $*int $*int $*InetAddress)) (defvar $%Socket/0 (jconstructor $*Socket)) (defvar $%Socket/2 (jconstructor $*Socket $*InetAddress $*int)) (defvar $%Socket/4 (jconstructor $*Socket $*InetAddress $*int $*InetAddress $*int)) ;;; Java Methods ($@...[/Class]/n) (defvar $@accept/0 (jmethod $*ServerSocket "accept")) (defvar $@bind/DatagramSocket/1 (jmethod $*DatagramSocket "bind" $*SocketAddress)) (defvar $@bind/ServerSocket/1 (jmethod $*ServerSocket "bind" $*SocketAddress)) (defvar $@bind/ServerSocket/2 (jmethod $*ServerSocket "bind" $*SocketAddress $*int)) (defvar $@bind/Socket/1 (jmethod $*Socket "bind" $*SocketAddress)) (defvar $@byteValue/0 (jmethod $*|Byte| "byteValue")) (defvar $@channel/0 (jmethod $*SelectionKey "channel")) (defvar $@close/DatagramSocket/0 (jmethod $*DatagramSocket "close")) (defvar $@close/Selector/0 (jmethod $*Selector "close")) (defvar $@close/ServerSocket/0 (jmethod $*ServerSocket "close")) (defvar $@close/Socket/0 (jmethod $*Socket "close")) (defvar $@shutdownInput/Socket/0 (jmethod $*Socket "shutdownInput")) (defvar $@shutdownOutput/Socket/0 (jmethod $*Socket "shutdownOutput")) (defvar $@configureBlocking/1 (jmethod $*SelectableChannel "configureBlocking" $*boolean)) (defvar $@connect/DatagramChannel/1 (jmethod $*DatagramChannel "connect" $*SocketAddress)) (defvar $@connect/Socket/1 (jmethod $*Socket "connect" $*SocketAddress)) (defvar $@connect/Socket/2 (jmethod $*Socket "connect" $*SocketAddress $*int)) (defvar $@connect/SocketChannel/1 (jmethod $*SocketChannel "connect" $*SocketAddress)) (defvar $@getAddress/0 (jmethod $*InetAddress "getAddress")) (defvar $@getAllByName/1 (jmethod $*InetAddress "getAllByName" $*String)) (defvar $@getByName/1 (jmethod $*InetAddress "getByName" $*String)) (defvar $@getChannel/DatagramSocket/0 (jmethod $*DatagramSocket "getChannel")) (defvar $@getChannel/ServerSocket/0 (jmethod $*ServerSocket "getChannel")) (defvar $@getChannel/Socket/0 (jmethod $*Socket "getChannel")) (defvar $@getAddress/DatagramPacket/0 (jmethod $*DatagramPacket "getAddress")) (defvar $@getHostName/0 (jmethod $*InetAddress "getHostName")) (defvar $@getInetAddress/DatagramSocket/0 (jmethod $*DatagramSocket "getInetAddress")) (defvar $@getInetAddress/ServerSocket/0 (jmethod $*ServerSocket "getInetAddress")) (defvar $@getInetAddress/Socket/0 (jmethod $*Socket "getInetAddress")) (defvar $@getLength/DatagramPacket/0 (jmethod $*DatagramPacket "getLength")) (defvar $@getLocalAddress/DatagramSocket/0 (jmethod $*DatagramSocket "getLocalAddress")) (defvar $@getLocalAddress/Socket/0 (jmethod $*Socket "getLocalAddress")) (defvar $@getLocalPort/DatagramSocket/0 (jmethod $*DatagramSocket "getLocalPort")) (defvar $@getLocalPort/ServerSocket/0 (jmethod $*ServerSocket "getLocalPort")) (defvar $@getLocalPort/Socket/0 (jmethod $*Socket "getLocalPort")) (defvar $@getOffset/DatagramPacket/0 (jmethod $*DatagramPacket "getOffset")) (defvar $@getPort/DatagramPacket/0 (jmethod $*DatagramPacket "getPort")) (defvar $@getPort/DatagramSocket/0 (jmethod $*DatagramSocket "getPort")) (defvar $@getPort/Socket/0 (jmethod $*Socket "getPort")) (defvar $@hasNext/0 (jmethod $*Iterator "hasNext")) (defvar $@iterator/0 (jmethod $*Set "iterator")) (defvar $@next/0 (jmethod $*Iterator "next")) (defvar $@open/DatagramChannel/0 (jmethod $*DatagramChannel "open")) (defvar $@open/Selector/0 (jmethod $*Selector "open")) (defvar $@open/ServerSocketChannel/0 (jmethod $*ServerSocketChannel "open")) (defvar $@open/SocketChannel/0 (jmethod $*SocketChannel "open")) (defvar $@receive/1 (jmethod $*DatagramSocket "receive" $*DatagramPacket)) (defvar $@register/2 (jmethod $*SelectableChannel "register" $*Selector $*int)) (defvar $@select/0 (jmethod $*Selector "select")) (defvar $@select/1 (jmethod $*Selector "select" $*long)) (defvar $@selectedKeys/0 (jmethod $*Selector "selectedKeys")) (defvar $@send/1 (jmethod $*DatagramSocket "send" $*DatagramPacket)) (defvar $@setReuseAddress/1 (jmethod $*ServerSocket "setReuseAddress" $*boolean)) (defvar $@setSoTimeout/DatagramSocket/1 (jmethod $*DatagramSocket "setSoTimeout" $*int)) (defvar $@setSoTimeout/Socket/1 (jmethod $*Socket "setSoTimeout" $*int)) (defvar $@setTcpNoDelay/1 (jmethod $*Socket "setTcpNoDelay" $*boolean)) (defvar $@socket/DatagramChannel/0 (jmethod $*DatagramChannel "socket")) (defvar $@socket/ServerSocketChannel/0 (jmethod $*ServerSocketChannel "socket")) (defvar $@socket/SocketChannel/0 (jmethod $*SocketChannel "socket")) (defvar $@validOps/0 (jmethod $*SelectableChannel "validOps")) ;;; Java Field Variables ($+...) (defvar $+op-accept (jfield $*SelectionKey "OP_ACCEPT")) (defvar $+op-connect (jfield $*SelectionKey "OP_CONNECT")) (defvar $+op-read (jfield $*SelectionKey "OP_READ")) (defvar $+op-write (jfield $*SelectionKey "OP_WRITE")) ;;; Wrapper functions (return-type: java-object) (defun %get-address (address) (jcall $@getAddress/0 address)) (defun %get-all-by-name (string) ; return a simple vector (jstatic $@getAllByName/1 $*InetAddress string)) (defun %get-by-name (string) (jstatic $@getByName/1 $*InetAddress string)) (defun host-to-inet4 (host) "USOCKET host formats to Java Inet4Address, used internally." (%get-by-name (host-to-hostname host))) ;;; HANDLE-CONTITION (defparameter +abcl-error-map+ `(("java.net.BindException" . operation-not-permitted-error) ("java.net.ConnectException" . connection-refused-error) ("java.net.NoRouteToHostException" . network-unreachable-error) ; untested ("java.net.PortUnreachableException" . protocol-not-supported-error) ; untested ("java.net.ProtocolException" . protocol-not-supported-error) ; untested ("java.net.SocketException" . socket-type-not-supported-error) ; untested ("java.net.SocketTimeoutException" . timeout-error))) (defparameter +abcl-nameserver-error-map+ `(("java.net.UnknownHostException" . ns-host-not-found-error))) (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) (typecase condition (java-exception (let ((java-cause (java-exception-cause condition))) (let* ((usock-error (cdr (assoc (jclass-of java-cause) +abcl-error-map+ :test #'string=))) (usock-error (if (functionp usock-error) (funcall usock-error condition) usock-error)) (nameserver-error (cdr (assoc (jclass-of java-cause) +abcl-nameserver-error-map+ :test #'string=)))) (if nameserver-error (error nameserver-error :socket socket :host-or-ip host-or-ip) (when usock-error (error usock-error :socket socket)))))))) ;;; GET-HOSTS-BY-NAME (defun get-address (address) (when address (let* ((array (%get-address address)) (length (jarray-length array))) (labels ((jbyte (n) (let ((byte (jarray-ref array n))) (if (minusp byte) (+ 256 byte) byte)))) (cond ((= 4 length) (vector (jbyte 0) (jbyte 1) (jbyte 2) (jbyte 3))) ((= 16 length) (vector (jbyte 0) (jbyte 1) (jbyte 2) (jbyte 3) (jbyte 4) (jbyte 5) (jbyte 6) (jbyte 7) (jbyte 8) (jbyte 9) (jbyte 10) (jbyte 11) (jbyte 12) (jbyte 13) (jbyte 14) (jbyte 15))) (t nil)))))) ; neither a IPv4 nor IPv6 address?! (defun get-hosts-by-name (name) (with-mapped-conditions (nil name) (map 'list #'get-address (%get-all-by-name name)))) ;;; GET-HOST-BY-ADDRESS (defun get-host-by-address (host) (let ((inet4 (host-to-inet4 host))) (with-mapped-conditions (nil host) (jcall $@getHostName/0 inet4)))) ;;; SOCKET-CONNECT (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-supplied-p) local-host local-port) (when deadline (unsupported 'deadline 'socket-connect)) (let (socket stream usocket) (ecase protocol (:stream ; TCP (let ((channel (jstatic $@open/SocketChannel/0 $*SocketChannel)) (address (jnew $%InetSocketAddress/2 (host-to-inet4 host) port))) (setq socket (jcall $@socket/SocketChannel/0 channel)) ;; bind to local address if needed (when (or local-host local-port) (let ((local-address (jnew $%InetSocketAddress/2 (host-to-inet4 local-host) (or local-port 0)))) (with-mapped-conditions (nil host) (jcall $@bind/Socket/1 socket local-address)))) ;; connect to dest address (with-mapped-conditions (nil host) (jcall $@connect/SocketChannel/1 channel address)) (setq stream (ext:get-socket-stream socket :element-type element-type) usocket (make-stream-socket :stream stream :socket socket)) (when nodelay-supplied-p (jcall $@setTcpNoDelay/1 socket (if nodelay ;; both t and :if-supported mean java:+true+ java:+true+ java:+false+))) (when timeout (jcall $@setSoTimeout/Socket/1 socket (truncate (* 1000 timeout)))))) (:datagram ; UDP (let ((channel (jstatic $@open/DatagramChannel/0 $*DatagramChannel))) (setq socket (jcall $@socket/DatagramChannel/0 channel)) ;; bind to local address if needed (when (or local-host local-port) (let ((local-address (jnew $%InetSocketAddress/2 (host-to-inet4 local-host) (or local-port 0)))) (with-mapped-conditions (nil local-host) (jcall $@bind/DatagramSocket/1 socket local-address)))) ;; connect to dest address if needed (when (and host port) (let ((address (jnew $%InetSocketAddress/2 (host-to-inet4 host) port))) (with-mapped-conditions (nil host) (jcall $@connect/DatagramChannel/1 channel address)))) (setq usocket (make-datagram-socket socket :connected-p (if (and host port) t nil))) (when timeout (jcall $@setSoTimeout/DatagramSocket/1 socket (truncate (* 1000 timeout))))))) usocket)) ;;; SOCKET-LISTEN (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5 backlog-supplied-p) (element-type 'character)) (declare (type boolean reuse-address)) (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (channel (jstatic $@open/ServerSocketChannel/0 $*ServerSocketChannel)) (socket (jcall $@socket/ServerSocketChannel/0 channel)) (endpoint (jnew $%InetSocketAddress/2 (host-to-inet4 host) (or port 0)))) (jcall $@setReuseAddress/1 socket (if reuseaddress java:+true+ java:+false+)) (with-mapped-conditions (socket host) (if backlog-supplied-p (jcall $@bind/ServerSocket/2 socket endpoint backlog) (jcall $@bind/ServerSocket/1 socket endpoint))) (make-stream-server-socket socket :element-type element-type))) ;;; SOCKET-ACCEPT (defmethod socket-accept ((usocket stream-server-usocket) &key (element-type 'character element-type-p)) (with-mapped-conditions (usocket) (let* ((client-socket (jcall $@accept/0 (socket usocket))) (element-type (if element-type-p element-type (element-type usocket))) (stream (ext:get-socket-stream client-socket :element-type element-type))) (make-stream-socket :stream stream :socket client-socket)))) ;;; SOCKET-CLOSE (defmethod socket-close ((usocket stream-server-usocket)) (with-mapped-conditions (usocket) (jcall $@close/ServerSocket/0 (socket usocket)))) (defmethod socket-close ((usocket stream-usocket)) (with-mapped-conditions (usocket) (close (socket-stream usocket) :abort t) ; see "sbcl.lisp" for (:abort t) (jcall $@close/Socket/0 (socket usocket)))) (defmethod socket-close ((usocket datagram-usocket)) (with-mapped-conditions (usocket) (jcall $@close/DatagramSocket/0 (socket usocket)))) (defmethod socket-shutdown ((usocket stream-usocket) direction) (with-mapped-conditions (usocket) (ecase direction (:input (jcall $@shutdownInput/Socket/0 (socket usocket))) (:output (jcall $@shutdownOutput/Socket/0 (socket usocket))) (:io (jcall $@shutdownInput/Socket/0 (socket usocket)) (jcall $@shutdownOutput/Socket/0 (socket usocket)))))) ;;; GET-LOCAL/PEER-NAME/ADDRESS/PORT (defmethod get-local-name ((usocket usocket)) (values (get-local-address usocket) (get-local-port usocket))) (defmethod get-peer-name ((usocket usocket)) (values (get-peer-address usocket) (get-peer-port usocket))) (defmethod get-local-address ((usocket stream-usocket)) (get-address (jcall $@getLocalAddress/Socket/0 (socket usocket)))) (defmethod get-local-address ((usocket stream-server-usocket)) (get-address (jcall $@getInetAddress/ServerSocket/0 (socket usocket)))) (defmethod get-local-address ((usocket datagram-usocket)) (get-address (jcall $@getLocalAddress/DatagramSocket/0 (socket usocket)))) (defmethod get-peer-address ((usocket stream-usocket)) (get-address (jcall $@getInetAddress/Socket/0 (socket usocket)))) (defmethod get-peer-address ((usocket datagram-usocket)) (get-address (jcall $@getInetAddress/DatagramSocket/0 (socket usocket)))) (defmethod get-local-port ((usocket stream-usocket)) (jcall $@getLocalPort/Socket/0 (socket usocket))) (defmethod get-local-port ((usocket stream-server-usocket)) (jcall $@getLocalPort/ServerSocket/0 (socket usocket))) (defmethod get-local-port ((usocket datagram-usocket)) (jcall $@getLocalPort/DatagramSocket/0 (socket usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (jcall $@getPort/Socket/0 (socket usocket))) (defmethod get-peer-port ((usocket datagram-usocket)) (jcall $@getPort/DatagramSocket/0 (socket usocket))) ;;; SOCKET-SEND & SOCKET-RECEIVE (defun *->byte (data) (declare (type (unsigned-byte 8) data)) ; required by SOCKET-SEND (jnew $%Byte/0 (if (> data 127) (- data 256) data))) (defun byte->* (byte &optional (element-type '(unsigned-byte 8))) (let* ((ub8 (if (minusp byte) (+ 256 byte) byte))) (if (eq element-type 'character) (code-char ub8) ub8))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0)) (let* ((socket (socket usocket)) (byte-array (jnew-array $*byte size)) (packet (if (and host port) (jnew $%DatagramPacket/5 byte-array 0 size (host-to-inet4 host) port) (jnew $%DatagramPacket/3 byte-array 0 size)))) ;; prepare sending data (loop for i from offset below (+ size offset) do (setf (jarray-ref byte-array i) (*->byte (aref buffer i)))) (with-mapped-conditions (usocket host) (jcall $@send/1 socket packet) size))) ;;; TODO: return-host and return-port cannot be get ... (defmethod socket-receive ((usocket datagram-usocket) buffer length &key (element-type '(unsigned-byte 8))) (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (unsigned-byte 32) ; host (unsigned-byte 16))) ; port (let* ((socket (socket usocket)) (real-length (or length +max-datagram-packet-size+)) (byte-array (jnew-array $*byte real-length)) (packet (jnew $%DatagramPacket/3 byte-array 0 real-length))) (with-mapped-conditions (usocket) (jcall $@receive/1 socket packet)) (let* ((receive-length (jcall $@getLength/DatagramPacket/0 packet)) (return-buffer (or buffer (make-array receive-length :element-type element-type)))) (loop for i from 0 below receive-length do (setf (aref return-buffer i) (byte->* (jarray-ref byte-array i) element-type))) (let ((return-host (if (connected-p usocket) (get-peer-address usocket) (get-address (jcall $@getAddress/DatagramPacket/0 packet)))) (return-port (if (connected-p usocket) (get-peer-port usocket) (jcall $@getPort/DatagramPacket/0 packet)))) (values return-buffer receive-length return-host return-port))))) ;;; WAIT-FOR-INPUT (defun socket-channel-class (usocket) (cond ((stream-usocket-p usocket) $*SocketChannel) ((stream-server-usocket-p usocket) $*ServerSocketChannel) ((datagram-usocket-p usocket) $*DatagramChannel))) (defun get-socket-channel (usocket) (let ((method (cond ((stream-usocket-p usocket) $@getChannel/Socket/0) ((stream-server-usocket-p usocket) $@getChannel/ServerSocket/0) ((datagram-usocket-p usocket) $@getChannel/DatagramSocket/0)))) (jcall method (socket usocket)))) (defun wait-for-input-internal (wait-list &key timeout) (let* ((sockets (wait-list-waiters wait-list)) (ops (logior $+op-read $+op-accept)) (selector (jstatic $@open/Selector/0 $*Selector)) (channels (mapcar #'get-socket-channel sockets))) (unwind-protect (with-mapped-conditions () (dolist (channel channels) (jcall $@configureBlocking/1 channel java:+false+) (jcall $@register/2 channel selector (logand ops (jcall $@validOps/0 channel)))) (let ((ready-count (if timeout (jcall $@select/1 selector (truncate (* timeout 1000))) (jcall $@select/0 selector)))) (when (plusp ready-count) (let* ((keys (jcall $@selectedKeys/0 selector)) (iterator (jcall $@iterator/0 keys)) (%wait (wait-list-%wait wait-list))) (loop while (jcall $@hasNext/0 iterator) do (let* ((key (jcall $@next/0 iterator)) (channel (jcall $@channel/0 key))) (setf (state (gethash channel %wait)) :read))))))) (jcall $@close/Selector/0 selector) (dolist (channel channels) (jcall $@configureBlocking/1 channel java:+true+))))) ;;; WAIT-LIST ;;; NOTE from original worker (Erik): ;;; Note that even though Java has the concept of the Selector class, which ;;; remotely looks like a wait-list, it requires the sockets to be non-blocking. ;;; usocket however doesn't make any such guarantees and is therefore unable to ;;; use the concept outside of the waiting routine itself (blergh!). (defun %setup-wait-list (wl) (setf (wait-list-%wait wl) (make-hash-table :test #'equal :rehash-size 1.3d0))) (defun %add-waiter (wl w) (setf (gethash (get-socket-channel w) (wait-list-%wait wl)) w)) (defun %remove-waiter (wl w) (remhash (get-socket-channel w) (wait-list-%wait wl)))
20,392
Common Lisp
.lisp
384
48.979167
100
0.704842
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
1229115dbf8483cf14b0254ac02772ba1abecf0fad3a6b755d6209c1b76b38e1
42,628
[ -1 ]
42,629
cmucl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/backend/cmucl.lisp
;;;; See LICENSE for licensing information. (in-package :usocket) #+win32 (defun remap-for-win32 (z) (mapcar #'(lambda (x) (cons (mapcar #'(lambda (y) (+ 10000 y)) (car x)) (cdr x))) z)) (defparameter +cmucl-error-map+ #+win32 (append (remap-for-win32 +unix-errno-condition-map+) (remap-for-win32 +unix-errno-error-map+)) #-win32 (append +unix-errno-condition-map+ +unix-errno-error-map+)) (defun cmucl-map-socket-error (err &key condition socket host-or-ip) (let ((usock-error (cdr (assoc err +cmucl-error-map+ :test #'member)))) (if usock-error (if (subtypep usock-error 'error) (cond ((subtypep usock-error 'ns-error) (error usock-error :socket socket :host-or-ip host-or-ip)) (t (error usock-error :socket socket))) (cond ((subtypep usock-error 'ns-condition) (signal usock-error :socket socket :host-or-ip host-or-ip)) (t (signal usock-error :socket socket)))) (error 'unknown-error :socket socket :real-error condition)))) ;; CMUCL error handling is brain-dead: it doesn't preserve any ;; information other than the OS error string from which the ;; error can be determined. The OS error string isn't good enough ;; given that it may have been localized (l10n). ;; ;; The above applies to versions pre 19b; 19d and newer are expected to ;; contain even better error reporting. ;; ;; ;; Just catch the errors and encapsulate them in an unknown-error (defun handle-condition (condition &optional (socket nil) (host-or-ip nil)) "Dispatch correct usocket condition." (typecase condition (ext::socket-error (cmucl-map-socket-error (ext::socket-errno condition) :socket socket :condition condition :host-or-ip host-or-ip)))) (defun socket-connect (host port &key (protocol :stream) (element-type 'character) timeout deadline (nodelay t nodelay-specified) (local-host nil local-host-p) (local-port nil local-port-p) &aux (local-bind-p (fboundp 'ext::bind-inet-socket))) (when timeout (unsupported 'timeout 'socket-connect)) (when deadline (unsupported 'deadline 'socket-connect)) (when (and nodelay-specified (not (eq nodelay :if-supported))) (unsupported 'nodelay 'socket-connect)) (when (and local-host-p (not local-bind-p)) (unsupported 'local-host 'socket-connect :minimum "Snapshot 2008-08 (19E)")) (when (and local-port-p (not local-bind-p)) (unsupported 'local-port 'socket-connect :minimum "Snapshot 2008-08 (19E)")) (let ((socket)) (ecase protocol (:stream (setf socket (let ((args (list (host-to-hbo host) port protocol))) (when (and local-bind-p (or local-host-p local-port-p)) (nconc args (list :local-host (when local-host (host-to-hbo local-host)) :local-port local-port))) (with-mapped-conditions (socket host) (apply #'ext:connect-to-inet-socket args)))) (if socket (let* ((stream (sys:make-fd-stream socket :input t :output t :element-type element-type :buffering :full)) ;;###FIXME the above line probably needs an :external-format (usocket (make-stream-socket :socket socket :stream stream))) usocket) (let ((err (unix:unix-errno))) (when err (cmucl-map-socket-error err))))) (:datagram (setf socket (if (and host port) (let ((args (list (host-to-hbo host) port protocol))) (when (and local-bind-p (or local-host-p local-port-p)) (nconc args (list :local-host (when local-host (host-to-hbo local-host)) :local-port local-port))) (with-mapped-conditions (socket (or host local-host)) (apply #'ext:connect-to-inet-socket args))) (if (or local-host-p local-port-p) (with-mapped-conditions (socket (or host local-host)) (apply #'ext:create-inet-listener (nconc (list (or local-port 0) protocol) (when (and local-host-p (ip/= local-host *wildcard-host*)) (list :host (host-to-hbo local-host)))))) (with-mapped-conditions (socket (or host local-host)) (ext:create-inet-socket protocol))))) (if socket (let ((usocket (make-datagram-socket socket :connected-p (and host port t)))) (ext:finalize usocket #'(lambda () (when (%open-p usocket) (ext:close-socket socket)))) usocket) (let ((err (unix:unix-errno))) (when err (cmucl-map-socket-error err)))))))) (defun socket-listen (host port &key reuseaddress (reuse-address nil reuse-address-supplied-p) (backlog 5) (element-type 'character)) (let* ((reuseaddress (if reuse-address-supplied-p reuse-address reuseaddress)) (server-sock (with-mapped-conditions (nil host) (apply #'ext:create-inet-listener (nconc (list port :stream :backlog backlog :reuse-address reuseaddress) (when (ip/= host *wildcard-host*) (list :host (host-to-hbo host)))))))) (make-stream-server-socket server-sock :element-type element-type))) (defmethod socket-accept ((usocket stream-server-usocket) &key element-type) (with-mapped-conditions (usocket) (let* ((sock (ext:accept-tcp-connection (socket usocket))) (stream (sys:make-fd-stream sock :input t :output t :element-type (or element-type (element-type usocket)) :buffering :full))) (make-stream-socket :socket sock :stream stream)))) ;; Sockets and socket streams are represented ;; by different objects. Be sure to close the ;; socket stream when closing a stream socket. (defmethod socket-close ((usocket stream-usocket)) "Close socket." (with-mapped-conditions (usocket) (close (socket-stream usocket) :abort t))) ; see "sbcl.lisp" for (:abort t) (defmethod socket-close ((usocket usocket)) "Close socket." (with-mapped-conditions (usocket) (ext:close-socket (socket usocket)))) (defmethod socket-close :after ((socket datagram-usocket)) (setf (%open-p socket) nil)) #+unicode (defun %unix-send (fd buffer length flags) (alien:alien-funcall (alien:extern-alien "send" (function c-call:int c-call:int system:system-area-pointer c-call:int c-call:int)) fd (system:vector-sap buffer) length flags)) (defmethod socket-shutdown ((usocket usocket) direction) (with-mapped-conditions (usocket) (ext:inet-shutdown (socket usocket) (ecase direction (:input ext:shut-rd) (:output ext:shut-wr) (:io ext:shut-rdwr))))) (defmethod socket-send ((usocket datagram-usocket) buffer size &key host port (offset 0) &aux (real-buffer (if (zerop offset) buffer (subseq buffer offset (+ offset size))))) (with-mapped-conditions (usocket host) (if (and host port) (ext:inet-sendto (socket usocket) real-buffer size (host-to-hbo host) port) #-unicode (unix:unix-send (socket usocket) real-buffer size 0) #+unicode (%unix-send (socket usocket) real-buffer size 0)))) (defmethod socket-receive ((usocket datagram-usocket) buffer length &key) (declare (values (simple-array (unsigned-byte 8) (*)) ; buffer (integer 0) ; size (unsigned-byte 32) ; host (unsigned-byte 16))) ; port (let ((real-buffer (or buffer (make-array length :element-type '(unsigned-byte 8)))) (real-length (or length (length buffer)))) (multiple-value-bind (nbytes remote-host remote-port) (with-mapped-conditions (usocket) (ext:inet-recvfrom (socket usocket) real-buffer real-length)) (values real-buffer nbytes remote-host remote-port)))) (defmethod get-local-name ((usocket usocket)) (multiple-value-bind (address port) (ext:get-socket-host-and-port (socket usocket)) (values (hbo-to-vector-quad address) port))) (defmethod get-peer-name ((usocket stream-usocket)) (multiple-value-bind (address port) (ext:get-peer-host-and-port (socket usocket)) (values (hbo-to-vector-quad address) port))) (defmethod get-local-address ((usocket usocket)) (nth-value 0 (get-local-name usocket))) (defmethod get-peer-address ((usocket stream-usocket)) (nth-value 0 (get-peer-name usocket))) (defmethod get-local-port ((usocket usocket)) (nth-value 1 (get-local-name usocket))) (defmethod get-peer-port ((usocket stream-usocket)) (nth-value 1 (get-peer-name usocket))) (defun lookup-host-entry (host) (multiple-value-bind (entry errno) (ext:lookup-host-entry host) (if entry entry ;;###The constants below work on *most* OSes, but are defined as the ;; constants mentioned in C (let ((exception (second (assoc errno '((1 ns-host-not-found-error) ;; HOST_NOT_FOUND (2 ns-no-recovery-error) ;; NO_DATA (3 ns-no-recovery-error) ;; NO_RECOVERY (4 ns-try-again-error)))))) ;; TRY_AGAIN (when exception (error exception)))))) (defun get-host-by-address (address) (handler-case (ext:host-entry-name (lookup-host-entry (host-byte-order address))) (condition (condition) (handle-condition condition address)))) (defun get-hosts-by-name (name) (handler-case (mapcar #'hbo-to-vector-quad (ext:host-entry-addr-list (lookup-host-entry name))) (condition (condition) (handle-condition condition name)))) (defun get-host-name () (unix:unix-gethostname)) (defun %setup-wait-list (wait-list) (declare (ignore wait-list))) (defun %add-waiter (wait-list waiter) (push (socket waiter) (wait-list-%wait wait-list))) (defun %remove-waiter (wait-list waiter) (setf (wait-list-%wait wait-list) (remove (socket waiter) (wait-list-%wait wait-list)))) (defun wait-for-input-internal (wait-list &key timeout) (with-mapped-conditions () (alien:with-alien ((rfds (alien:struct unix:fd-set))) (unix:fd-zero rfds) (dolist (socket (wait-list-%wait wait-list)) (unix:fd-set socket rfds)) (multiple-value-bind (secs musecs) (split-timeout (or timeout 1)) (multiple-value-bind (count err) (unix:unix-fast-select (1+ (reduce #'max (wait-list-%wait wait-list))) (alien:addr rfds) nil nil (when timeout secs) musecs) (declare (ignore err)) (if (<= 0 count) ;; process the result... (dolist (x (wait-list-waiters wait-list)) (when (unix:fd-isset (socket x) rfds) (setf (state x) :READ))) (progn ;;###FIXME generate an error, except for EINTR )))))))
11,657
Common Lisp
.lisp
267
34.254682
88
0.598697
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
33a69c474af076ca72342c405f60fdef762bcd4955ca2d63f2c0fca42009d94e
42,629
[ -1 ]
42,630
clisp-sockets.txt
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/notes/clisp-sockets.txt
http://clisp.cons.org/impnotes.html#socket (SOCKET:SOCKET-SERVER &OPTIONAL [port-or-socket]) (SOCKET:SOCKET-SERVER-HOST socket-server) (SOCKET:SOCKET-SERVER-PORT socket-server) (SOCKET:SOCKET-WAIT socket-server &OPTIONAL [seconds [microseconds]]) (SOCKET:SOCKET-ACCEPT socket-server &KEY :ELEMENT-TYPE :EXTERNAL-FORMAT :BUFFERED :TIMEOUT) (SOCKET:SOCKET-CONNECT port &OPTIONAL [host] &KEY :ELEMENT-TYPE :EXTERNAL-FORMAT :BUFFERED :TIMEOUT) (SOCKET:SOCKET-STATUS socket-stream-or-list &OPTIONAL [seconds [microseconds]]) (SOCKET:SOCKET-STREAM-HOST socket-stream) (SOCKET:SOCKET-STREAM-PORT socket-stream) (SOCKET:SOCKET-SERVICE-PORT &OPTIONAL service-name (protocol "tcp")) (SOCKET:SOCKET-STREAM-PEER socket-stream [do-not-resolve-p]) (SOCKET:SOCKET-STREAM-LOCAL socket-stream [do-not-resolve-p]) (SOCKET:SOCKET-STREAM-SHUTDOWN socket-stream direction) (SOCKET:SOCKET-OPTIONS socket-server &REST {option}*) (posix:resolve-host-ipaddr &optional host) with the host-ent structure: name - host name aliases - LIST of aliases addr-list - LIST of IPs as dotted quads (IPv4) or coloned octets (IPv6) addrtype - INTEGER address type IPv4 or IPv6 Errors are of type SYSTEM::SIMPLE-OS-ERROR with a 1 element (integer) SYSTEM::$FORMAT-ARGUMENTS list This integer stores the OS error reported; meaning WSA* codes on Win32 and E* codes on *nix, only: unix.lisp in CMUCL shows BSD, Linux and SRV4 have different number assignments for the same E* constant names :-(
1,480
Common Lisp
.lisp
28
51.178571
100
0.786408
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
0a38ed8dd864a19e5080d4cec0efd1ef7fd6c081c0cb2ed219c0f97777b8b916
42,630
[ -1 ]
42,631
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/package.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: CL-USER -*- ;;;; See the LICENSE file for licensing information. (in-package :cl-user) (defpackage :usocket-test (:use :common-lisp :usocket :regression-test) (:export #:do-tests #:run-usocket-tests))
279
Common Lisp
.lisp
9
28.666667
77
0.690299
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a0caef1ec97cfc198515ab052085e0bdba01185da376f2257b5e0ca363d206e9
42,631
[ -1 ]
42,632
test-timeout.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/test-timeout.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- ;;;; See LICENSE for licensing information. (in-package :usocket-test) ;; echo server with binary protocol: ;; ;; msg = cmd-byte || length-byte || data* ;; tells server echo back the data bytes (defconstant +cmd-echo+ 0) ;; tells server to simply consume the data bytes (defconstant +cmd-read+ 1) ;; blocks server for n seconds before next echo / read (defconstant +cmd-setdelay+ 8) (defun tcp-echo-handler (client) (handler-bind ((error (lambda (c) (format *error-output* "Client handler error: ~A~%" c) (return-from tcp-echo-handler)))) (loop with delay = 0 do (let ((cmd (read-byte client nil nil))) (unless cmd (return)) ;; client disconnected (let* ((length (read-byte client))) (cond ((or (= cmd +cmd-echo+) (= cmd +cmd-read+)) (when (plusp delay) (sleep delay) (setf delay 0)) (let ((buffer (make-array length :element-type '(unsigned-byte 8)))) (read-sequence buffer client) (when (= cmd +cmd-echo+) (write-sequence buffer client)))) ((= cmd +cmd-setdelay+) (unless (= length 1) (error "Bad setdelay data length ~A, want 1 byte" length)) (setf delay (read-byte client))) (t (error "Unknown command ~A" cmd)))))))) (defun send-tcp-echo-command (socket command &optional data) (assert (< (length data) 256)) (let ((stream (socket-stream socket))) (write-byte command stream) (write-byte (length data) stream) (write-sequence data stream) (finish-output stream))) (defvar *tcp-echo-thread* nil) (defvar *tcp-echo-port* nil) (defun start-tcp-echo-server () (unless *tcp-echo-thread* (multiple-value-bind (thread socket) (socket-server "127.0.0.1" 0 'tcp-echo-handler nil :protocol :stream :in-new-thread t :multi-threading t :element-type '(unsigned-byte 8)) (setq *tcp-echo-thread* thread *tcp-echo-port* (get-local-port socket))))) (deftest tcp-timeout-in-read-sequence (progn (start-tcp-echo-server) (with-client-socket (s stream "127.0.0.1" *tcp-echo-port* :element-type '(unsigned-byte 8)) ;; Server will respond after 5s. (send-tcp-echo-command s +cmd-setdelay+ #(5)) (send-tcp-echo-command s +cmd-echo+ #(1 2 3 4)) ;; Our timeout is 1s. (setf (socket-option s :receive-timeout) 1) ;; So this read should fail. (with-caught-conditions (usocket:timeout-error :got-timeout) (with-mapped-conditions (s) (let ((response (make-array 4 :element-type '(unsigned-byte 8)))) (read-sequence response stream)))))) :got-timeout) (deftest tcp-timeout-in-write-sequence (progn (start-tcp-echo-server) (with-client-socket (s stream "127.0.0.1" *tcp-echo-port* :element-type '(unsigned-byte 8)) (with-caught-conditions (usocket:timeout-error :got-timeout) (with-mapped-conditions (s) ;; Server will unblock after 5s. (send-tcp-echo-command s +cmd-setdelay+ #(5)) ;; Our write timeout is 1s. (setf (socket-option s :send-timeout) 1) ;; So this write should fail. Actually, a single write won't ;; fail because the socket is buffering, but it should fail ;; eventually, so write ~50MB. (dotimes (i 200000) (send-tcp-echo-command s +cmd-read+ #(1 2 3 4))))))) :got-timeout)
3,730
Common Lisp
.lisp
88
33.659091
95
0.591247
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
24daecffb4e24a943c29b727f926a7dec025849328d7766a2d9368341dca9c96
42,632
[ -1 ]
42,633
test-condition.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/test-condition.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- ;;;; See LICENSE for licensing information. (in-package :usocket-test) (deftest ns-host-not-found-error.1 (with-caught-conditions (usocket:ns-host-not-found-error nil) (usocket:socket-connect "xxx" 123) t) nil) ;;; This test does not work, if timeout is ignored by the implementation ;;; Will get a connection-refused-error instead #-(or ecl clasp) (deftest timeout-error.1 (with-caught-conditions (usocket:timeout-error nil) (usocket:socket-connect "common-lisp.net" 81 :timeout 0) t) nil) (deftest connection-refused-error.1 (with-caught-conditions (usocket:connection-refused-error nil) (usocket:socket-connect "common-lisp.net" 81) t) nil) (deftest operation-not-permitted-error.1 (with-caught-conditions (usocket:operation-not-permitted-error nil) (usocket:socket-listen "127.0.0.1" 81) t) nil)
938
Common Lisp
.lisp
26
32.961538
82
0.733996
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5810e28871b04a7bf408d272c2360d0c35fb6ae8eab521857a4232eb24b4c22e
42,633
[ -1 ]
42,634
test-datagram.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/test-datagram.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- ;;;; See LICENSE for licensing information. (in-package :usocket-test) (defvar *echo-server* nil) (defvar *echo-server-port* nil) (defun start-server () (multiple-value-bind (thread socket) (socket-server "127.0.0.1" 0 #'identity nil :in-new-thread t :protocol :datagram) (setq *echo-server* thread *echo-server-port* (get-local-port socket)))) (defparameter *max-buffer-size* 32) (defvar *send-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defvar *receive-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defun clean-buffers () (fill *send-buffer* 0) (fill *receive-buffer* 0)) ;;; UDP Send Test #1: connected socket (deftest udp-send.1 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (socket-connect "127.0.0.1" *echo-server-port* :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (socket-send s *send-buffer* 5) (wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) ;;; UDP Send Test #2: unconnected socket (deftest udp-send.2 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (socket-connect nil nil :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (socket-send s *send-buffer* 5 :host "127.0.0.1" :port *echo-server-port*) (wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) (deftest mark-h-david ; Mark H. David's remarkable UDP test code (let* ((host "localhost") (port 1111) (server-sock (socket-connect nil nil :protocol ':datagram :local-host host :local-port port)) (client-sock (socket-connect host port :protocol ':datagram)) (octet-vector (make-array 2 :element-type '(unsigned-byte 8) :initial-contents `(,(char-code #\O) ,(char-code #\K)))) (recv-octet-vector (make-array 2 :element-type '(unsigned-byte 8)))) (socket-send client-sock octet-vector 2) (socket-receive server-sock recv-octet-vector 2) (prog1 (and (equalp octet-vector recv-octet-vector) recv-octet-vector) (socket-close server-sock) (socket-close client-sock))) #(79 75)) (deftest frank-james ; Frank James' test code for LispWorks/UDP (with-caught-conditions (#+win32 CONNECTION-RESET-ERROR #-win32 CONNECTION-REFUSED-ERROR nil) (let ((sock (socket-connect "localhost" 1234 :protocol ':datagram :element-type '(unsigned-byte 8)))) (unwind-protect (progn (socket-send sock (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0) 16) (let ((buffer (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0))) (socket-receive sock buffer 16))) (socket-close sock)))) nil) (defun frank-wfi-test () (let ((s (socket-connect nil nil :protocol :datagram :element-type '(unsigned-byte 8) :local-port 8001))) (unwind-protect (do ((i 0 (1+ i)) (buffer (make-array 1024 :element-type '(unsigned-byte 8) :initial-element 0)) (now (get-universal-time)) (done nil)) ((or done (= i 4)) nil) (format t "~Ds ~D Waiting state ~S~%" (- (get-universal-time) now) i (usocket::state s)) (when (wait-for-input s :ready-only t :timeout 5) (format t "~D state ~S~%" i (usocket::state s)) (handler-bind ((error (lambda (c) (format t "socket-receive error: ~A~%" c) (break) nil))) (multiple-value-bind (buffer count remote-host remote-port) (socket-receive s buffer 1024) (handler-bind ((error (lambda (c) (format t "socket-send error: ~A~%" c) (break)))) (when buffer (socket-send s (subseq buffer 0 count) count :host remote-host :port remote-port))))))) (socket-close s))))
4,823
Common Lisp
.lisp
112
33.6875
106
0.581826
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
f732f72b1e01195f3d10bac61017b75a33652785796a8c4bd98b14d864761a48
42,634
[ -1 ]
42,635
wait-for-input.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/wait-for-input.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- ;;;; See LICENSE for licensing information. (in-package :usocket-test) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *wait-for-input-timeout* 2)) (deftest wait-for-input.1 (with-caught-conditions (nil nil) (let ((sock (usocket:socket-connect *common-lisp-net* 80)) (time (get-universal-time))) (unwind-protect (progn (usocket:wait-for-input sock :timeout *wait-for-input-timeout*) (- (get-universal-time) time)) (usocket:socket-close sock)))) #.*wait-for-input-timeout*) (deftest wait-for-input.2 (with-caught-conditions (nil nil) (let ((sock (usocket:socket-connect *common-lisp-net* 80)) (time (get-universal-time))) (unwind-protect (progn (usocket:wait-for-input sock :timeout *wait-for-input-timeout* :ready-only t) (- (get-universal-time) time)) (usocket:socket-close sock)))) #.*wait-for-input-timeout*) (deftest wait-for-input.3 (with-caught-conditions (nil nil) (let ((sock (usocket:socket-connect *common-lisp-net* 80))) (unwind-protect (progn (format (usocket:socket-stream sock) "GET / HTTP/1.0~2%") (force-output (usocket:socket-stream sock)) (usocket:wait-for-input sock :timeout *wait-for-input-timeout*) (subseq (read-line (usocket:socket-stream sock)) 0 4)) (usocket:socket-close sock)))) "HTTP") ;;; Advanced W-F-I tests by Elliott Slaughter <[email protected]> (defvar *socket-server-port* 0) (defvar *socket-server-listen* nil) (defvar *socket-server-connection*) (defvar *socket-client-connection*) (defvar *output-p* t) (defun stage-1 () (unless *socket-server-listen* (setf *socket-server-listen* (socket-listen *wildcard-host* 0 :element-type '(unsigned-byte 8))) (setf *socket-server-port* (get-local-port *socket-server-listen*))) (setf *socket-server-connection* (when (wait-for-input *socket-server-listen* :timeout 0 :ready-only t) (socket-accept *socket-server-listen*))) (when *output-p* ; should be NIL (format t "First time (before client connects) is ~s.~%" *socket-server-connection*)) *socket-server-connection*) ;; TODO: original test code have addition (:TIMEOUT 0) when doing the SOCKET-CONNECT, ;; it seems cannot work on SBCL/Windows, need to investigate, but here we ignore it. (defun stage-2 () (setf *socket-client-connection* (socket-connect "localhost" *socket-server-port* :protocol :stream :element-type '(unsigned-byte 8))) (setf *socket-server-connection* (when (wait-for-input *socket-server-listen* :timeout 0 :ready-only t) #+(and win32 (or lispworks ecl sbcl)) (when *output-p* (format t "%READY-P: ~D~%" (usocket::%ready-p *socket-server-listen*))) (socket-accept *socket-server-listen*))) (when *output-p* ; should be a usocket object (format t "Second time (after client connects) is ~s.~%" *socket-server-connection*)) *socket-server-connection*) (defun stage-3 () (setf *socket-server-connection* (when (wait-for-input *socket-server-listen* :timeout 0 :ready-only t) #+(and win32 (or lispworks ecl sbcl)) (when *output-p* (format t "%READY-P: ~D~%" (usocket::%ready-p *socket-server-listen*))) (socket-accept *socket-server-listen*))) (when *output-p* ; should be NIL again (format t "Third time (before second client) is ~s.~%" *socket-server-connection*)) *socket-server-connection*) (deftest elliott-slaughter.1 (let ((*output-p* nil)) (let* ((s-1 (stage-1)) (s-2 (stage-2)) (s-3 (stage-3))) (prog1 (and (null s-1) (usocket::usocket-p s-2) (null s-3)) (socket-close *socket-server-listen*) (setf *socket-server-listen* nil)))) t) #| Issue elliott-slaughter.2 (WAIT-FOR-INPUT/win32 on TCP socket) W-F-I correctly found the inputs, but :READY-ONLY didn't work. |# (defun receive-each (connections) (let ((ready (usocket:wait-for-input connections :timeout 0 :ready-only t))) (loop for connection in ready collect (read-line (usocket:socket-stream connection))))) (defun receive-all (connections) (loop for messages = (receive-each connections) then (receive-each connections) while messages append messages)) (defun send (connection message) (format (usocket:socket-stream connection) "~a~%" message) (force-output (usocket:socket-stream connection))) (defun server () (let* ((listen (usocket:socket-listen usocket:*wildcard-host* 12345)) (connection (usocket:socket-accept listen))) (loop for messages = (receive-all connection) then (receive-all connection) do (format t "Got messages:~%~s~%" messages) do (sleep 1/50)))) (defun client () (let ((connection (usocket:socket-connect "localhost" 12345))) (loop for i from 0 do (send connection (format nil "This is message ~a." i)) do (sleep 1/100))))
5,046
Common Lisp
.lisp
113
39.495575
94
0.67394
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
1488fe39f6bcb2f637f68ebe821b5fc222e22b6d5124beaec2e79327b8dfa3c2
42,635
[ -1 ]
42,636
test-usocket.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/test-usocket.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- ;;;; See LICENSE for licensing information. ;;;; Usage: (usoct:run-usocket-tests) or (usoct:do-tests) (in-package :usocket-test) (defparameter +non-existing-host+ "1.2.3.4" "The stringified IP address of a host on the same subnet. No physical host may be present.") (defparameter +unused-local-port+ 15213) (defparameter *fake-usocket* (usocket::make-stream-socket :socket :my-socket :stream :my-stream)) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *common-lisp-net* (get-host-by-name "common-lisp.net"))) (defvar *local-ip*) (defmacro with-caught-conditions ((expect throw) &body body) `(catch 'caught-error (handler-case (handler-bind ((unsupported #'(lambda (c) (declare (ignore c)) (continue)))) (progn ,@body)) (unknown-error (c) (if (typep c ',expect) (throw 'caught-error ,throw) (progn (describe c) (describe (usocket::usocket-real-error c)) c))) (error (c) (if (typep c ',expect) (throw 'caught-error ,throw) (progn (describe c) c))) (unknown-condition (c) (if (typep c ',expect) (throw 'caught-error ,throw) (progn (describe c) (describe (usocket::usocket-real-condition c)) c))) (condition (c) (if (typep c ',expect) (throw 'caught-error ,throw) (progn (describe c) c)))))) (deftest make-socket.1 (socket *fake-usocket*) :my-socket) (deftest make-socket.2 (socket-stream *fake-usocket*) :my-stream) (deftest socket-no-connect.1 (with-caught-conditions (socket-error nil) (socket-connect "127.0.0.1" +unused-local-port+ :timeout 1) t) nil) (deftest socket-no-connect.2 (with-caught-conditions (socket-error nil) (socket-connect #(127 0 0 1) +unused-local-port+ :timeout 1) t) nil) (deftest socket-no-connect.3 (with-caught-conditions (socket-error nil) (socket-connect 2130706433 +unused-local-port+ :timeout 1) ;; == #(127 0 0 1) t) nil) (deftest socket-failure.1 (with-caught-conditions (#+(or :darwin :os-macosx) connection-refused-error #-(or :darwin :os-macosx) timeout-error nil) (socket-connect 2130706433 +unused-local-port+ :timeout 1) ;; == #(127 0 0 1) :unreach) nil) (deftest socket-failure.2 (with-caught-conditions (timeout-error nil) (socket-connect +non-existing-host+ 80 :timeout 1) ;; 80 = just a port :unreach) nil) ;; let's hope c-l.net doesn't move soon, or that people start to ;; test usocket like crazy.. (deftest socket-connect.1 (with-caught-conditions (nil nil) (let ((sock (socket-connect "common-lisp.net" 80))) (unwind-protect (when (typep sock 'usocket) t) (socket-close sock)))) t) (deftest socket-connect.2 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (when (typep sock 'usocket) t) (socket-close sock)))) t) (deftest socket-connect.3 (with-caught-conditions (nil nil) (let ((sock (socket-connect (usocket::host-byte-order *common-lisp-net*) 80))) (unwind-protect (when (typep sock 'usocket) t) (socket-close sock)))) t) ;; let's hope c-l.net doesn't change its software any time soon (deftest socket-stream.1 (with-caught-conditions (nil nil) (let ((sock (socket-connect "common-lisp.net" 80))) (unwind-protect (progn (format (socket-stream sock) "GET / HTTP/1.0~2%") (force-output (socket-stream sock)) (subseq (read-line (socket-stream sock)) 0 4)) (socket-close sock)))) "HTTP") (deftest socket-name.1 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (get-peer-address sock) (socket-close sock)))) #.*common-lisp-net*) (deftest socket-name.2 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (get-peer-port sock) (socket-close sock)))) 80) (deftest socket-name.3 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (get-peer-name sock) (socket-close sock)))) #.*common-lisp-net* 80) #+ignore (deftest socket-name.4 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (equal (get-local-address sock) *local-ip*) (socket-close sock)))) t) (deftest socket-shutdown.1 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (usocket::ignore-unsupported-warnings (socket-shutdown sock :input)) (socket-close sock)) t)) t) (deftest socket-shutdown.2 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (usocket::ignore-unsupported-warnings (socket-shutdown sock :output)) (socket-close sock)) t)) t) (deftest socket-shutdown.3 (with-caught-conditions (nil nil) (let ((sock (socket-connect *common-lisp-net* 80))) (unwind-protect (usocket::ignore-unsupported-warnings (socket-shutdown sock :io)) (socket-close sock)) t)) t) ;; Listening to localhost and connecting to localhost (by Pascal J. Bourguignon) (deftest socket-listen.1 (with-caught-conditions (nil nil) (usocket:with-socket-listener (listen "localhost" 9999 :element-type '(unsigned-byte 8) :reuseaddress t :backlog 1) (usocket:with-client-socket (client client-stream "localhost" 9999 :element-type '(unsigned-byte 8)) (usocket:with-server-socket (server (usocket:socket-accept listen)) (write-byte 42 client-stream) (force-output client-stream) (read-byte (usocket:socket server)))))) 42) ;; Listening on all the IPv4 addresses, and connecting to localhost (by Pascal J. Bourguignon) (deftest socket-listen.2 (with-caught-conditions (nil nil) (usocket:with-socket-listener (listen "0.0.0.0" 9999 :element-type '(unsigned-byte 8) :reuseaddress t :backlog 1) (usocket:with-client-socket (client client-stream "localhost" 9999 :element-type '(unsigned-byte 8)) (usocket:with-server-socket (server (usocket:socket-accept listen)) (write-byte 42 client-stream) (force-output client-stream) (read-byte (usocket:socket server)))))) 42) (defun run-usocket-tests () (do-tests))
7,493
Common Lisp
.lisp
189
29.883598
122
0.580814
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
3efab529113247db758062bca2f49d6fb3f05e97bbd71b1809aeae3c3e5867bd
42,636
[ 324085 ]
42,637
udp-one-shot.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/tests/udp-one-shot.lisp
;;;; -*- Mode: LISP; Base: 10; Syntax: ANSI-Common-lisp; Package: USOCKET-TEST -*- (in-package :usocket-test) ;; Test code from "INVALID-ARGUMENT-ERROR on socket-receive (#48)" ;; Author: @4lph4-Ph4un ;; Environment: SBCL 1.4.16, WSL on Windows 10 (defun UDP-one-shot-V1 (&optional (port 1232)) (let ((socket (usocket:socket-connect nil nil :protocol :datagram :element-type '(unsigned-byte 8) :local-host "127.0.0.1" :local-port port)) (buffer (make-array 8 :element-type '(unsigned-byte 8)))) (unwind-protect (multiple-value-bind (received size remote-host remote-port) ;; NOTE: An explicit buffer can be given. If the length ;; is nil buffer's length will be used. (usocket:socket-receive socket buffer 8) (format t "~A~%" received) (usocket:socket-send socket (reverse received) size :host remote-host :port remote-port)) (usocket:socket-close socket)))) #| Backtrace: 0: (USOCKET::HANDLE-CONDITION #<SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR {100375B833}> #<USOCKET:DATAGRAM-USOCKET {100375B773}>) Locals: CONDITION = #<SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR {100375B833}> SOCKET = #<USOCKET:DATAGRAM-USOCKET {100375B773}> 1: (SB-KERNEL::%SIGNAL #<SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR {100375B833}>) Locals: CONDITION = #<SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR {100375B833}> HANDLER-CLUSTERS = (((#<SB-KERNEL::CLASSOID-CELL SB-IMPL::EVAL-ERROR> . #<CLOSURE # {7F0C5FD9DE0B}>)) ((#<SB-KERNEL::CLASSOID-CELL SB-C:COMPILER-ERROR> . #<FUNCTION # {5222748B}>)) ..) 2: (ERROR SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR :ERRNO 22 :SYSCALL "recvfrom") Locals: CONDITION = #<SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR {100375B833}> #:G8039 = SB-BSD-SOCKETS:INVALID-ARGUMENT-ERROR SB-DEBUG::MORE = (:ERRNO 22 :SYSCALL "recvfrom") 3: (SB-BSD-SOCKETS:SOCKET-ERROR "recvfrom" 22) Locals: ERRNO = 22 WHERE = "recvfrom" 4: ((FLET SB-BSD-SOCKETS::WITH-SOCKET-ADDR-THUNK :IN SB-BSD-SOCKETS:SOCKET-RECEIVE) #<SB-ALIEN-INTERNALS:ALIEN-VALUE :SAP #X7F0C58001230 :TYPE (* (SB-ALIEN:STRUCT SB-BSD-SOCKETS-INTERNAL::SOCKADDR-IN (SB.. Locals: SB-BSD-SOCKETS::COPY-BUFFER = #<SB-ALIEN-INTERNALS:ALIEN-VALUE :SAP #X7F0C58001250 :TYPE (* (ARRAY (SB-ALIEN:UNSIGNED 8) 1))> SB-BSD-SOCKETS::SIZE = 16 SB-BSD-SOCKETS::SOCKADDR = #<SB-ALIEN-INTERNALS:ALIEN-VALUE :SAP #X7F0C58001230 :TYPE (* ..)> 5: (SB-BSD-SOCKETS::CALL-WITH-SOCKET-ADDR #<SB-BSD-SOCKETS:INET-SOCKET 127.0.0.1:1232, fd: 3 {100375B203}> NIL #<CLOSURE (FLET SB-BSD-SOCKETS::WITH-SOCKET-ADDR-THUNK :IN SB-BSD-SOCKETS:SOCKET-RECEIVE) {7.. Locals: SOCKADDR = #<SB-ALIEN-INTERNALS:ALIEN-VALUE :SAP #X7F0C58001230 :TYPE (* ..)> SOCKADDR-ARGS = NIL SOCKET = #<SB-BSD-SOCKETS:INET-SOCKET 127.0.0.1:1232, fd: 3 {100375B203}> THUNK = #<CLOSURE (FLET SB-BSD-SOCKETS::WITH-SOCKET-ADDR-THUNK :IN SB-BSD-SOCKETS:SOCKET-RECEIVE) {7F0C5FD9DB8B}> 6: ((:METHOD SB-BSD-SOCKETS:SOCKET-RECEIVE (SB-BSD-SOCKETS:SOCKET T T)) #<SB-BSD-SOCKETS:INET-SOCKET 127.0.0.1:1232, fd: 3 {100375B203}> #(0 0 0 0 0 0 ...) 8 :OOB NIL :PEEK NIL :WAITALL NIL :DONTWAIT NIL.. Locals: #:.DEFAULTING-TEMP. = (UNSIGNED-BYTE 8) SB-BSD-SOCKETS::BUFFER = #(0 0 0 0 0 0 ...) SB-BSD-SOCKETS::BUFFER#1 = #(0 0 0 0 0 0 ...) SB-BSD-SOCKETS::DONTWAIT = NIL SB-BSD-SOCKETS::ELEMENT-TYPE = (UNSIGNED-BYTE 8) LENGTH = 8 LENGTH#1 = 8 SB-BSD-SOCKETS::OOB = NIL SB-BSD-SOCKETS::PEEK = NIL SB-BSD-SOCKETS:SOCKET = #<SB-BSD-SOCKETS:INET-SOCKET 127.0.0.1:1232, fd: 3 {100375B203}> SB-BSD-SOCKETS::WAITALL = NIL 7: ((:METHOD USOCKET:SOCKET-RECEIVE (USOCKET:DATAGRAM-USOCKET T T)) #<USOCKET:DATAGRAM-USOCKET {100375B773}> #(0 0 0 0 0 0 ...) 8 :ELEMENT-TYPE (UNSIGNED-BYTE 8)) [fast-method] Locals: USOCKET::BUFFER = #(0 0 0 0 0 0 ...) USOCKET::ELEMENT-TYPE = (UNSIGNED-BYTE 8) LENGTH = 8 USOCKET:SOCKET = #<USOCKET:DATAGRAM-USOCKET {100375B773}> 8: (MASTER-CLASS/SRC/SERVER-03:UDP-ONE-SHOT-V1 1232) Locals: PORT = 1232 SOCKET = #<USOCKET:DATAGRAM-USOCKET {100375B773}> |#
4,259
Common Lisp
.lisp
80
47.025
207
0.655883
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
52792ddb999f3b0e902ab4537bfe32bec1a29cc12357f7c2216fe06a6251f8be
42,637
[ -1 ]
42,638
OpenTransportUDP.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/vendor/OpenTransportUDP.lisp
;;;-*-Mode: LISP; Package: CCL -*- ;; ;;; OpenTransportUDP.lisp ;;; Copyright 2012 Chun Tian (binghe) <[email protected]> ;;; UDP extension to OpenTransport.lisp (with some TCP patches) (in-package "CCL") (eval-when (:compile-toplevel :load-toplevel :execute) (require :opentransport)) ;; MCL Issue 28: Passive TCP streams should be able to listen to the loopback interface ;; see http://code.google.com/p/mcl/issues/detail?id=28 for details (defparameter *passive-interface-address* NIL "Address to use for passive connections - optionally bind to loopback address while opening a tcp stream") (advise local-interface-ip-address (or *passive-interface-address* (:do-it)) :when :around :name 'override-local-interface-ip-address) ;; MCL Issue 29: Passive TCP connections on OS assigned ports ;; see http://code.google.com/p/mcl/issues/detail?id=29 for details (advise ot-conn-tcp-passive-connect (destructuring-bind (conn port &optional (allow-reuse t)) arglist (declare (ignore allow-reuse)) (if (eql port #$kOTAnyInetAddress) ;; Avoids registering a proxy for port 0 but instead registers one for the true port: (multiple-value-bind (proxy result) (let* ((*opentransport-class-proxies* NIL) ; makes ot-find-proxy return NIL (result (:do-it)) ;; pushes onto *opentransport-class-proxies* (proxy (prog1 (pop *opentransport-class-proxies*) (assert (not *opentransport-class-proxies*)))) (context (cdr proxy)) (tmpconn (make-ot-conn :context context :endpoint (pref context :ot-context.ref))) (localaddress (ot-conn-tcp-get-addresses tmpconn))) (declare (dynamic-extent tmpconn)) ;; replace original set in body of function (setf (ot-conn-local-address conn) localaddress) (values (cons localaddress context) result)) ;; need to be outside local binding of *opentransport-class-proxies* (without-interrupts (push proxy *opentransport-class-proxies*)) result) (:do-it))) :when :around :name 'ot-conn-tcp-passive-connect-any-address) (defun open-udp-socket (&key local-address local-port) (init-opentransport) (let (endpoint ; TODO: opentransport-alloc-endpoint-from-freelist (err #$kOTNoError) (configptr (ot-cloned-configuration traps::$kUDPName))) (rlet ((errP :osstatus)) (setq endpoint #+carbon-compat (#_OTOpenEndpointInContext configptr 0 (%null-ptr) errP *null-ptr*) #-carbon-compat (#_OTOpenEndpoint configptr 0 (%null-ptr) errP) err (pref errP :osstatus)) (if (eql err #$kOTNoError) (let* ((context (ot-make-endpoint-context endpoint nil nil)) ; no notifier, not minimal (conn (make-ot-conn :context context :endpoint endpoint))) (macrolet ((check-ot-error-return (error-context) `(unless (eql (setq err (pref errP :osstatus)) #$kOTNoError) (values (ot-error err ,error-context))))) (setf (ot-conn-bindreq conn) #-carbon-compat (#_OTAlloc endpoint #$T_BIND #$T_ADDR errP) #+carbon-compat (#_OTAllocInContext endpoint #$T_BIND #$T_ADDR errP *null-ptr*) ) (check-ot-error-return :alloc) (setf (ot-conn-bindret conn) #-carbon-compat (#_OTAlloc endpoint #$T_BIND #$T_ADDR errP) #+carbon-compat (#_OTAllocInContext endpoint #$T_BIND #$T_ADDR errP *null-ptr*) ) (check-ot-error-return :alloc) (setf (ot-conn-options conn) #-carbon-compat (#_OTAlloc endpoint #$T_OPTMGMT #$T_OPT errP) #+carbon-compat (#_OTAllocInContext endpoint #$T_OPTMGMT #$T_OPT errP *null-ptr*) ) (check-ot-error-return :alloc)) ;; BIND to local address (for UDP server) (when local-port ; local-address (let* ((host (or local-address (local-interface-ip-address))) (port (tcp-service-port-number local-port)) (localaddress `(:tcp ,host ,port)) (bindreq (ot-conn-bindreq conn)) (bindret (ot-conn-bindret conn))) (let* ((netbuf (pref bindreq :tbind.addr))) (declare (dynamic-extent netbuf)) (setf (pref netbuf :tnetbuf.len) (record-length :inetaddress) (pref bindreq :tbind.qlen) 5) ; arbitrary qlen (#_OTInitInetAddress (pref netbuf :tnetbuf.buf) port host) (setf (pref context :ot-context.completed) nil) (unless (= (setq err (#_OTBind endpoint bindreq bindret)) #$kOTNoError) (ot-error err :bind))) (setf (ot-conn-local-address conn) localaddress))) conn) (ot-error err :create))))) (defun make-TUnitData (endpoint) "create the send/recv buffer for UDP sockets" (let ((err #$kOTNoError)) (rlet ((errP :osstatus)) (macrolet ((check-ot-error-return (error-context) `(unless (eql (setq err (pref errP :osstatus)) #$kOTNoError) (values (ot-error err ,error-context))))) (let ((udata #-carbon-compat (#_OTAlloc endpoint #$T_UNITDATA #$T_ALL errP) #+carbon-compat (#_OTAllocInContext endpoint #$T_UNITDATA #$T_ALL errP *null-ptr*))) (check-ot-error-return :alloc) udata))))) (defun send-message (conn data buffer size host port &optional (offset 0)) ;; prepare dest address (let ((addr (pref data :tunitdata.addr))) (declare (dynamic-extent addr)) (setf (pref addr :tnetbuf.len) (record-length :inetaddress)) (#_OTInitInetAddress (pref addr :tnetbuf.buf) port host)) ;; prepare data buffer (let* ((udata (pref data :tunitdata.udata)) (outptr (pref udata :tnetbuf.buf))) (declare (dynamic-extent udata)) (%copy-ivector-to-ptr buffer offset outptr 0 size) (setf (pref udata :tnetbuf.len) size)) ;; send the packet (let* ((endpoint (ot-conn-endpoint conn)) (result (#_OTSndUData endpoint data))) (the fixnum result))) (defun receive-message (conn data buffer length) (let* ((endpoint (ot-conn-endpoint conn)) (err (#_OTRcvUData endpoint data *null-ptr*))) (if (eql err #$kOTNoError) (let* (;(addr (pref data :tunitdata.addr)) (udata (pref data :tunitdata.udata)) (inptr (pref udata :tnetbuf.buf)) (read-bytes (pref udata :tnetbuf.len)) (buffer (or buffer (make-array read-bytes :element-type '(unsigned-byte 8)))) (length (or length (length buffer))) (actual-size (min read-bytes length))) (%copy-ptr-to-ivector inptr 0 buffer 0 actual-size) (values buffer actual-size 0 0)) ; TODO: retrieve address and port (ot-error err :receive)))) ; TODO: use OTRcvUDErr instead
6,398
Common Lisp
.lisp
135
42.266667
108
0.681862
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
475d77f9f344ab02fa9a88644b01eb1e4dc25bf713bd3d21a3a4a8e25ec8c862
42,638
[ 170825, 414085 ]
42,639
kqueue.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/usocket-0.8.5/vendor/kqueue.lisp
;;;-*-Mode: LISP; Package: CCL -*- ;; ;; KQUEUE.LISP ;; ;; KQUEUE - BSD kernel event notification mechanism support for Common LISP. ;; Copyright (C) 2007 Terje Norderhaug <[email protected]> ;; Released under LGPL - see <http://www.gnu.org>. ;; Alternative licensing available upon request. ;; ;; DISCLAIMER: The user of this module should understand that executing code is a potentially hazardous ;; activity, and that many dangers and obstacles, marked or unmarked, may exist within this code. ;; As a condition of your use of the module, you assume all risk of personal injury, death, or property ;; loss, and all other bad things that may happen, even if caused by negligence, ignorance or stupidity. ;; The author is is no way responsible, and besides, does not have "deep pockets" nor any spare change. ;; ;; Version: 0.20 alpha (July 26, 2009) - subject to major revisions, so consider yourself warned. ;; Tested with Macintosh Common LISP 5.1 and 5.2, but is intended to be platform and system independent in the future. ;; ;; Email feedback and improvements to <[email protected]>. ;; Updated versions will be available from <http://www.in-progress.com/src/>. ;; ;; RELATED IMPLEMENTATIONS ;; There is another kevent.lisp for other platforms by Risto Laakso (merge?). ;; Also a Scheme kevent.ss by Jose Antonio Ortega. ;; ;; SEE ALSO: ;; http://people.freebsd.org/~jlemon/papers/kqueue.pdf ;; http://developer.apple.com/samplecode/FileNotification/index.html ;; The Man page for kqueue() or kevent(). ;; PyKQueue - Python OO interface to KQueue. ;; LibEvent - an event notification library in C by Niels Provos. ;; Liboop - another abstract library in C on top of kevent or other kernel notification. #| HISTORY: 2007-Oct-18 terje version 0.1 released on the Info-MCL mailing list. 2008-Aug-21 terje load-framework-bundle is not needed under MCL 5.2 2008-Aug-21 terje rename get-addr to lookup-function-in-bundle (only for pre MCL 5.2) 2009-Jul-19 terje uses kevent-error condition and strerror. 2009-Jul-24 terje reports errors unless nil-if-not-found in lookup-function-in-bundle. 2009-Jul-24 terje kevent :variant for C's intptr_t type for 64bit (and osx 10.5) compatibility. 2009-Jul-25 terje 64bit support, dynamically determined for PPC. Kudos to Glen Foy for helping out. 2009-Jul-25 terje make-kevent function. |# #| IMPLEMENTATION NOTES: kevents are copied into and from the kernel, so the records don't have to be kept in the app! kevents does not work in OSX before 10.3. *kevent-record* has to be explcitly set to :kevent64 to work on 64bit intel macs. Consider using sysctlbyname() to test for 64bit, combining hw.cpu64bit_capable, hw.optional.x86_64 and hw.optional.64bitops |# (in-package :ccl) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #-ccl-5.2 ; has been added to MCL 5.2 (defmethod load-framework-bundle ((framework-name string) &key (load-executable t)) ;; FRAMWORK CALL FUNCTIONALITY FROM BSD.LISP ;; (C) 2003 Brendan Burns <[email protected]> ;; Released under LGPL. (with-cfstrs ((framework framework-name)) (let ((err 0) (baseURL nil) (bundleURL nil) (result nil)) (rlet ((folder :fsref)) ;; Find the folder holding the bundle (setf err (#_FSFindFolder #$kOnAppropriateDisk #$kFrameworksFolderType t folder)) ;; if everything's cool, make a URL for it (when (zerop err) (setf baseURL (#_CFURLCreateFromFSRef (%null-ptr) folder)) (if (%null-ptr-p baseURL) (setf err #$coreFoundationUnknownErr))) ;; if everything's cool, make a URL for the bundle (when (zerop err) (setf bundleURL (#_CFURLCreateCopyAppendingPathComponent (%null-ptr) baseURL framework nil)) (if (%null-ptr-p bundleURL) (setf err #$coreFoundationUnknownErr))) ;; if everything's cool, load it (when (zerop err) (setf result (#_CFBundleCreate (%null-ptr) bundleURL)) (if (%null-ptr-p result) (setf err #$coreFoundationUnknownErr))) ;; if everything's cool, and the user wants it loaded, load it (when (and load-executable (zerop err)) (if (not (#_CFBundleLoadExecutable result)) (setf err #$coreFoundationUnknownErr))) ;; if there's an error, but we've got a pointer, free it and clear result (when (and (not (zerop err)) (not (%null-ptr-p result))) (#_CFRelease result) (setf result nil)) ;; free the URLs if there non-null (when (not (%null-ptr-p bundleURL)) (#_CFRelease bundleURL)) (when (not (%null-ptr-p baseURL)) (#_CFRelease baseURL)) ;; return pointer + error value (values result err))))) #+ignore (defun get-addr (bundle name) (let* ((addr (#_CFBundleGetFunctionPointerForName bundle name))) (rlet ((buf :long)) (setf (%get-ptr buf) addr) (ash (%get-signed-long buf) -2)))) #-ccl-5.2 (defun lookup-function-in-bundle (name bundle &optional nil-if-not-found) (with-cfstrs ((str name)) (let* ((addr (#_CFBundleGetFunctionPointerForName bundle str))) (if (%null-ptr-p addr) (unless nil-if-not-found (error "Couldn't resolve address of foreign function ~s" name)) (rlet ((buf :long)) ;; mcl 5.2 uses %fixnum-from-macptr here (setf (%get-ptr buf) addr) (ash (%get-signed-long buf) -2)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Convenient way to declare BSD system calls #+ignore (defparameter *system-bundle* #+ccl-5.2 (get-bundle-for-framework-name "System.framework") #-ccl-5.2 (let ((bundle (load-framework-bundle "System.framework"))) (terminate-when-unreachable bundle (lambda (b)(#_CFRelease b))) bundle)) (defmacro declare-bundle-ff (name name-string &rest arglist &aux (fn (gensym (format nil "ff_~A_" (string name))))) ;; Is there an existing define-trap like macro for this? or could one be modified for use with bundles? `(progn (defloadvar ,fn (let* ((bundle #+ccl-5.2 (get-bundle-for-framework-name "System.framework") #-ccl-5.2 (let ((bundle (load-framework-bundle "System.framework"))) (terminate-when-unreachable bundle (lambda (b)(#_CFRelease b))) bundle))) (lookup-function-in-bundle ,name-string bundle))) ,(let ((args (do ((arglist arglist (cddr arglist)) (result)) ((not (cdr arglist)) (nreverse result)) (push (second arglist) result)))) `(defun ,name ,args (ppc-ff-call ,fn ,@arglist))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (declare-bundle-ff %system-kqueue "kqueue" :signed-fullword) ;; returns a file descriptor no! (defun system-kqueue () (let ((kq (%system-kqueue))) (if (= kq -1) (ecase (%system-errno) (12 (error "The kernel failed to allocate enough memory for the kernel queue")) ; ENOMEM (24 (error "The per-process descriptor table is full")) ; EMFILE (23 (error "The system file table is full"))) ; ENFILE kq))) (declare-bundle-ff %system-kevent "kevent" :unsigned-fullword kq :address ke :unsigned-fullword nke :address ko :unsigned-fullword nko :address timeout :signed-fullword) (declare-bundle-ff %system-open "open" :address name :unsigned-fullword mode :unsigned-fullword arg :signed-fullword) (declare-bundle-ff %system-close "close" :unsigned-fullword fd :signed-fullword) (declare-bundle-ff %system-errno* "__error" :signed-fullword) (declare-bundle-ff %system-strerror "strerror" :signed-fullword errno :address) (defun %system-errno () (%get-fixnum (%int-to-ptr (%system-errno*)))) ; (%system-errno) (defconstant $O-EVTONLY #x8000) ; (defconstant $O-NONBLOCK #x800 "Non blocking mode") (defun system-open (posix-namestring) "Low level open function, as in C, returns an fd number" (with-cstrs ((name posix-namestring)) (%system-open name $O-EVTONLY 0))) (defun system-close (fd) (%system-close fd)) (defrecord timespec (sec :unsigned-long) (usec :unsigned-long)) (defVar *kevent-record* nil) (def-ccl-pointers determine-64bit-kevents () (setf *kevent-record* (if (ccl::gestalt #$gestaltPowerPCProcessorFeatures #+ccl-5.2 #$gestaltPowerPCHas64BitSupport #-ccl-5.2 6) :kevent32 :kevent64))) (defrecord :kevent32 (ident :unsigned-long) ; uintptr_t (filter :short) (flags :unsigned-short) (fflags :unsigned-long) (data :long) ; intptr_t (udata :pointer)) (defrecord :kevent64 (:variant ; uintptr_t ((ident64 :uint64)) ((ident :unsigned-long))) (filter :short) (flags :unsigned-short) (fflags :unsigned-long) (:variant ; intptr_t ((data64 :sint64)) ((data :long))) (:variant ; RMCL :pointer is 32bit ((udata64 :uint64)) ((udata :pointer)))) (defun make-kevent (&key (ident 0) (filter 0) (flags 0) (fflags 0) (data 0) (udata *null-ptr*)) (ecase *kevent-record* (:kevent64 (make-record kevent64 :ident ident :filter filter :flags flags :fflags fflags :data data :udata udata)) (:kevent32 (make-record kevent32 :ident ident :filter filter :flags flags :fflags fflags :data data :udata udata)))) (defun kevent-rref (ke field) (ecase *kevent-record* (:kevent32 (ecase field (:ident (rref ke :kevent32.ident)) (:filter (rref ke :kevent32.filter)) (:flags (rref ke :kevent32.flags)) (:fflags (rref ke :kevent32.fflags)) (:data (rref ke :kevent32.data)) (:udata (rref ke :kevent32.udata)))) (:kevent64 (ecase field (:ident (rref ke :kevent64.ident)) (:filter (rref ke :kevent64.filter)) (:flags (rref ke :kevent64.flags)) (:fflags (rref ke :kevent64.fflags)) (:data (rref ke :kevent64.data)) (:udata (rref ke :kevent64.udata)))))) (defun kevent-filter (ke) (kevent-rref ke :filter)) (defun kevent-flags (ke) (kevent-rref ke :flags)) (defun kevent-data (ke) (kevent-rref ke :data)) ;; FILTER TYPES: (eval-when (:compile-toplevel :load-toplevel :execute) ; added by binghe (defconstant $kevent-read-filter -1 "Data available to read") (defconstant $kevent-write-filter -2 "Writing is possible") (defconstant $kevent-aio-filter -3 "AIO system call has been made") (defconstant $kevent-vnode-filter -4 "Event occured on a file descriptor") (defconstant $kevent-proc-filter -5 "Process performed one or more of the requested events") (defconstant $kevent-signal-filter -6 "Attempted to deliver a signal to a process") (defconstant $kevent-timer-filter -7 "Establishes an arbitrary timer") (defconstant $kevent-netdev-filter -8 "Event occured on a network device") (defconstant $kevent-filesystem-filter -9) ) ; eval-when ; FLAGS: (defconstant $kevent-add #x01) (defconstant $kevent-delete #x02) (defconstant $kevent-enable #x04) (defconstant $kevent-disable #x08) (defconstant $kevent-oneshot #x10) (defconstant $kevent-clear #x20) (defconstant $kevent-error #x4000) (defconstant $kevent-eof #x8000 "EV_EOF") ;; FFLAGS: (defconstant $kevent-file-delete #x01 "The file was unlinked from the file system") (defconstant $kevent-file-write #x02 "A write occurred on the file") (defconstant $kevent-file-extend #x04 "The file was extended") (defconstant $kevent-file-attrib #x08 "The file had its attributes changed") (defconstant $kevent-file-link #x10 "The link count on the file changed") (defconstant $kevent-file-rename #x20 "The file was renamed") (defconstant $kevent-file-revoke #x40 "Access to the file was revoked or the file system was unmounted") (defconstant $kevent-file-all (logior $kevent-file-delete $kevent-file-write $kevent-file-extend $kevent-file-attrib $kevent-file-link $kevent-file-rename $kevent-file-revoke)) (defconstant $kevent-net-linkup #x01 "Link is up") (defconstant $kevent-net-linkdown #x02 "Link is down") (defconstant $kevent-net-linkinvalid #x04 "Link state is invalid") (defconstant $kevent-net-added #x08 "IP adress added") (defconstant $kevent-net-deleted #x10 "IP adress deleted") (define-condition kevent-error (simple-error) ((errno :initform NIL :initarg :errno) (ko :initform nil :type (or null kevent) :initarg :ko) (syserr :initform (%system-errno))) (:report (lambda (c s) (with-slots (errno ko syserr) c (format s "kevent system call error ~A [~A]" errno syserr) (when errno (format s "(~A)" (%get-cstring (%system-strerror errno)))) (when ko (format s " for ") (let ((*standard-output* s)) (print-record ko *kevent-record*))))))) (defun %kevent (kq &optional ke ko (timeout 0)) (check-type kq integer) (rlet ((&timeout :timespec :sec timeout :usec 1)) (let ((num (with-timer ;; does not seem to make a difference... (%system-kevent kq (or ke (%null-ptr))(if ke 1 0)(or ko (%null-ptr))(if ko 1 0) &timeout)))) ; "If an error occurs while processing an element of the changelist and there ; is enough room in the eventlist, then the event will be placed in the eventlist with ; EV_ERROR set in flags and the system error in data." (when (and ko (plusp (logand $kevent-error (kevent-flags ko)))) (error 'kevent-error :errno (kevent-data ko) :ko ko)) ; "Otherwise, -1 will be returned, and errno will be set to indicate the error condition." (when (= num -1) ;; hack - opentransport provides the constants for the errors documented for the call (case (%system-errno) (0 (error "kevent system call failed with an unspecified error")) ;; should not happen! (13 (error "The process does not have permission to register a filter")) (14 (error "There was an error reading or writing the kevent structure")) ; EFAULT (9 (error "The specified descriptor is invalid")) ; EBADF (4 (error "A signal was delivered before the timeout expired and before any events were placed on the kqueue for return.")) ; EINTR (22 (error "The specified time limit or filter is invalid")) ; EINVAL (2 (error "The event could not be found to be modified or deleted")) ; ENOENT (12 (error "No memory was available to register the event")) ; ENOMEM (78 (error "The specified process to attach to does not exist"))) ; ESRCH ;; shouldn't get here... (errchk (%system-errno)) (error "error ~A" (%system-errno))) (unless (zerop num) (values ko num))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CLOS INTERFACE (defclass kqueue () ((kq :initform (system-kqueue) :documentation "file descriptor referencing the kqueue") (fds :initform NIL)) ;; ## better if kept on top level, perhaps as a hash table... (:documentation "A kernal event notification channel")) (defmethod initialize-instance :after ((q kqueue) &rest rest) (declare (ignore rest)) (terminate-when-unreachable q 'kqueue-close)) (defmethod kqueue-close ((q kqueue)) (with-slots (kq fds) q (when (or kq fds) ;; allow repeated close (system-close kq) (setf fds NIL) (setf kq NIL)))) (defmethod kqueue-poll ((q kqueue)) "Polls a kqueue for kevents" ;; may not have to be cleared, but just in case: (flet ((kqueue-poll2 (ko) (let ((result (with-slots (kq) q (without-interrupts (%kevent kq NIL ko))))) (when result (let ((type (kevent-filter result))) (ecase type (0 (values)) (#.$kevent-read-filter (values :read (kevent-rref result :ident) (kevent-rref result :flags) (kevent-rref result :fflags) (kevent-rref result :data) (kevent-rref result :udata))) (#.$kevent-write-filter :write) (#.$kevent-aio-filter :aio) (#.$kevent-vnode-filter (values :vnode (cdr (assoc (kevent-rref result :ident) (slot-value q 'fds))) (kevent-rref result :flags) (kevent-rref result :fflags) (kevent-rref result :data) (kevent-rref result :udata))) (#.$kevent-filesystem-filter :filesystem))))))) (ecase *kevent-record* (:kevent64 (rlet ((ko :kevent64 :ident 0 :filter 0 :flags 0 :fflags 0 :data 0 :udata (%null-ptr))) (kqueue-poll2 ko))) (:kevent32 (rlet ((ko :kevent32 :ident 0 :filter 0 :flags 0 :fflags 0 :data 0 :udata (%null-ptr))) (kqueue-poll2 ko)))))) (defmethod kqueue-subscribe ((q kqueue) &key ident filter (flags 0) (fflags 0) (data 0) (udata (%null-ptr))) (let ((ke (make-kevent :ident ident :filter filter :flags flags :fflags fflags :data data :udata udata))) (with-slots (kq) q (without-interrupts (%kevent kq ke))))) (defmethod kqueue-vnode-subscribe ((q kqueue) pathname) "Makes the queue report an event when there is a change to a directory or file" (let* ((namestring (posix-namestring (full-pathname pathname))) (fd (system-open namestring))) (with-slots (fds) q (push (cons fd pathname) fds)) (kqueue-subscribe q :ident fd :filter $kevent-vnode-filter :flags (logior $kevent-add $kevent-clear) :fflags $kevent-file-all) namestring)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #+test (defun kevent-d (pathname &optional (*standard-output* (fred))) "Report changes to a file or directory" (loop with kqueue = (make-instance 'kqueue) with sub = (kqueue-vnode-subscribe kqueue pathname) for i from 1 to 60 for result = (multiple-value-list (kqueue-poll kqueue)) unless (equal result '(NIL)) do (progn (format T "~A~%" result) (force-output)) ; do (process-allow-schedule) do (sleep 1) finally (write-line "Done") )) #| ; Report changes to this file in a fred window (save this document to see what happens): (process-run-function "kevent-d" #'kevent-d *loading-file-source-file* (fred)) ; Reports files added or removed from the directory of this file: (process-run-function "kevent-d" #'kevent-d (make-pathname :directory (pathname-directory *loading-file-source-file*)) (fred)) |#
19,988
Common Lisp
.lisp
433
37.632794
141
0.610296
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
aa70f8bdf3c449f442b31df96ef49f80ccbca65f9d8fc114a1031c7291a48fa5
42,639
[ 152419, 192570, 335290 ]
42,640
bordeaux-threads-test.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/test/bordeaux-threads-test.lisp
#| Copyright 2006,2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (defpackage bordeaux-threads/test (:use #:cl #:bordeaux-threads #:fiveam) (:shadow #:with-timeout)) (in-package #:bordeaux-threads/test) (def-suite :bordeaux-threads) (def-fixture using-lock () (let ((lock (make-lock))) (&body))) (in-suite :bordeaux-threads) (test should-have-current-thread (is (current-thread))) (test current-thread-identity (let* ((box (list nil)) (thread (make-thread (lambda () (setf (car box) (current-thread)))))) (join-thread thread) (is (eql (car box) thread)))) (test join-thread-return-value (is (eql 0 (join-thread (make-thread (lambda () 0)))))) (test should-identify-threads-correctly (is (threadp (current-thread))) (is (threadp (make-thread (lambda () t) :name "foo"))) (is (not (threadp (make-lock))))) (test should-retrieve-thread-name (is (equal "foo" (thread-name (make-thread (lambda () t) :name "foo"))))) (test interrupt-thread (let* ((box (list nil)) (thread (make-thread (lambda () (setf (car box) (catch 'new-thread (sleep 60) 'not-interrupted)))))) (sleep 1) (interrupt-thread thread (lambda () (throw 'new-thread 'interrupted))) (join-thread thread) (is (eql 'interrupted (car box))))) (test should-lock-without-contention (with-fixture using-lock () (is (acquire-lock lock t)) (release-lock lock) (is (acquire-lock lock nil)) (release-lock lock))) #-(or allegro sbcl) (def-test acquire-recursive-lock () (let ((test-lock (make-recursive-lock)) (results (make-array 4 :adjustable t :fill-pointer 0)) (results-lock (make-lock)) (threads ())) (flet ((add-result (r) (with-lock-held (results-lock) (vector-push-extend r results)))) (dotimes (i 2) (push (make-thread #'(lambda () (when (acquire-recursive-lock test-lock) (unwind-protect (progn (add-result :enter) (sleep 1) (add-result :leave)) (release-recursive-lock test-lock))))) threads))) (map 'nil #'join-thread threads) (is (equalp results #(:enter :leave :enter :leave))))) (defun set-equal (set-a set-b) (and (null (set-difference set-a set-b)) (null (set-difference set-b set-a)))) (test default-special-bindings (locally (declare (special *a* *c*)) (let* ((the-as 50) (the-bs 150) (*b* 42) some-a some-b some-other-a some-other-b (*default-special-bindings* `((*a* . (funcall ,(lambda () (incf the-as)))) (*b* . (funcall ,(lambda () (incf the-bs)))) ,@*default-special-bindings*)) (threads (list (make-thread (lambda () (setf some-a *a* some-b *b*))) (make-thread (lambda () (setf some-other-a *a* some-other-b *b*)))))) (declare (special *b*)) (thread-yield) (is (not (boundp '*a*))) (loop while (some #'thread-alive-p threads) do (thread-yield)) (is (set-equal (list some-a some-other-a) '(51 52))) (is (set-equal (list some-b some-other-b) '(151 152))) (is (not (boundp '*a*)))))) (defparameter *shared* 0) (defparameter *lock* (make-lock)) (test should-have-thread-interaction ;; this simple test generates N process. Each process grabs and ;; releases the lock until SHARED has some value, it then ;; increments SHARED. the outer code first sets shared 1 which ;; gets the thing running and then waits for SHARED to reach some ;; value. this should, i think, stress test locks. (setf *shared* 0) (flet ((worker (i) (loop do (with-lock-held (*lock*) (when (= i *shared*) (incf *shared*) (return))) (thread-yield) (sleep 0.001)))) (let* ((procs (loop for i from 1 upto 2 ;; create a new binding to protect against implementations that ;; mutate instead of binding the loop variable collect (let ((i i)) (make-thread (lambda () (funcall #'worker i)) :name (format nil "Proc #~D" i)))))) (with-lock-held (*lock*) (incf *shared*)) (block test (loop until (with-lock-held (*lock*) (= (1+ (length procs)) *shared*)) do (with-lock-held (*lock*) (is (>= (1+ (length procs)) *shared*))) (thread-yield) (sleep 0.001)))))) (defparameter *condition-variable* (make-condition-variable)) (test condition-variable (setf *shared* 0) (flet ((worker (i) (with-lock-held (*lock*) (loop until (= i *shared*) do (condition-wait *condition-variable* *lock*)) (incf *shared*)) (condition-notify *condition-variable*))) (let ((num-procs 100)) (dotimes (i num-procs) ;; create a new binding to protect against implementations that ;; mutate instead of binding the loop variable (let ((i i)) (make-thread (lambda () (funcall #'worker i)) :name (format nil "Proc #~D" i)))) (with-lock-held (*lock*) (loop until (= num-procs *shared*) do (condition-wait *condition-variable* *lock*))) (is (equal num-procs *shared*))))) ;; Generally safe sanity check for the locks and single-notify #+(and lispworks (or lispworks4 lispworks5)) (test condition-variable-lw (let ((condition-variable (make-condition-variable :name "Test")) (test-lock (make-lock)) (completed nil)) (dotimes (id 6) (let ((id id)) (make-thread (lambda () (with-lock-held (test-lock) (condition-wait condition-variable test-lock) (push id completed) (condition-notify condition-variable)))))) (sleep 2) (if completed (print "Failed: Premature passage through condition-wait") (print "Successfully waited on condition")) (condition-notify condition-variable) (sleep 2) (if (and completed (eql (length completed) 6) (equal (sort completed #'<) (loop for id from 0 to 5 collect id))) (print "Success: All elements notified") (print (format nil "Failed: Of 6 expected elements, only ~A proceeded" completed))) (bt::with-cv-access condition-variable (if (and (not (or (car wait-tlist) (cdr wait-tlist))) (zerop (hash-table-count wait-hash)) (zerop (hash-table-count unconsumed-notifications))) (print "Success: condition variable restored to initial state") (print "Error: condition variable retains residue from completed waiters"))) (setq completed nil) (dotimes (id 6) (let ((id id)) (make-thread (lambda () (with-lock-held (test-lock) (condition-wait condition-variable test-lock) (push id completed)))))) (sleep 2) (condition-notify condition-variable) (sleep 2) (if (= (length completed) 1) (print "Success: Notify-single only notified a single waiter to restart") (format t "Failure: Notify-single restarted ~A items" (length completed))) (condition-notify condition-variable) (sleep 2) (if (= (length completed) 2) (print "Success: second Notify-single only notified a single waiter to restart") (format t "Failure: Two Notify-singles restarted ~A items" (length completed))) (loop for i from 0 to 5 do (condition-notify condition-variable)) (print "Note: In the case of any failures, assume there are outstanding waiting threads") (values))) #+(or abcl allegro clisp clozure ecl genera lispworks6 mezzano sbcl scl) (test condition-wait-timeout (let ((lock (make-lock)) (cvar (make-condition-variable)) (flag nil)) (make-thread (lambda () (sleep 0.4) (setf flag t))) (with-lock-held (lock) (condition-wait cvar lock :timeout 0.2) (is (null flag)) (sleep 0.4) (is (eq t flag))))) (test semaphore-signal (let ((sem (make-semaphore))) (make-thread (lambda () (sleep 0.4) (signal-semaphore sem))) (is (not (null (wait-on-semaphore sem)))))) (test semaphore-signal-n-of-m (let* ((sem (make-semaphore :count 1)) (lock (make-lock)) (count 0) (waiter (lambda () (wait-on-semaphore sem) (with-lock-held (lock) (incf count))))) (make-thread (lambda () (sleep 0.2) (signal-semaphore sem :count 3))) (dotimes (v 5) (make-thread waiter)) (sleep 0.3) (is (= count 4)) ;; release other waiters (signal-semaphore sem :count 10) (sleep 0.1) (is (= count 5)))) (test semaphore-wait-timeout (let ((sem (make-semaphore)) (flag nil)) (make-thread (lambda () (sleep 0.4) (setf flag t))) (is (null (wait-on-semaphore sem :timeout 0.2))) (is (null flag)) (sleep 0.4) (is (eq t flag)))) (test semaphore-typed (is (typep (bt:make-semaphore) 'bt:semaphore)) (is (bt:semaphore-p (bt:make-semaphore))) (is (null (bt:semaphore-p (bt:make-lock))))) (test with-timeout-return-value (is (eql :foo (bt:with-timeout (5) :foo)))) (test with-timeout-signals (signals timeout (bt:with-timeout (1) (sleep 5)))) (test with-timeout-non-interference (flet ((sleep-with-timeout (s) (bt:with-timeout (4) (sleep s)))) (finishes (progn (sleep-with-timeout 3) (sleep-with-timeout 3)))))
10,373
Common Lisp
.lisp
259
30.181467
94
0.556569
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5914f91fded82783146d50e599042571394e17e34495f13f7d83c4a4c87041bb
42,640
[ -1 ]
42,641
impl-clisp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-clisp.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'mt:thread) ;;; Thread Creation (defun %make-thread (function name) (mt:make-thread function :name name :initial-bindings mt:*default-special-bindings*)) (defun current-thread () (mt:current-thread)) (defun threadp (object) (mt:threadp object)) (defun thread-name (thread) (mt:thread-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mt:mutex) (deftype recursive-lock () '(and mt:mutex (satisfies mt:mutex-recursive-p))) (defun lock-p (object) (typep object 'mt:mutex)) (defun recursive-lock-p (object) (and (typep object 'mt:mutex) (mt:mutex-recursive-p object))) (defun make-lock (&optional name) (mt:make-mutex :name (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (mt:mutex-lock lock :timeout (if wait-p nil 0))) (defun release-lock (lock) (mt:mutex-unlock lock)) (defmacro with-lock-held ((place) &body body) `(mt:with-mutex-lock (,place) ,@body)) (defun make-recursive-lock (&optional name) (mt:make-mutex :name (or name "Anonymous recursive lock") :recursive-p t)) (defun acquire-recursive-lock (lock &optional (wait-p t)) (acquire-lock lock wait-p)) (defun release-recursive-lock (lock) (release-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(mt:with-mutex-lock (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (mt:make-exemption :name (or name "Anonymous condition variable"))) (defun condition-wait (condition-variable lock &key timeout) (mt:exemption-wait condition-variable lock :timeout timeout) t) (defun condition-notify (condition-variable) (mt:exemption-signal condition-variable)) (defun thread-yield () (mt:thread-yield)) ;;; Timeouts (defmacro with-timeout ((timeout) &body body) (once-only (timeout) `(mt:with-timeout (,timeout (error 'timeout :length ,timeout)) ,@body))) ;;; Introspection/debugging ;;; VTZ: mt:list-threads returns all threads that are not garbage collected. (defun all-threads () (delete-if-not #'mt:thread-active-p (mt:list-threads))) (defun interrupt-thread (thread function &rest args) (mt:thread-interrupt thread :function function :arguments args)) (defun destroy-thread (thread) ;;; VTZ: actually we can kill ourselelf. ;;; suicide is part of our contemporary life :) (signal-error-if-current-thread thread) (mt:thread-interrupt thread :function t)) (defun thread-alive-p (thread) (mt:thread-active-p thread)) (defun join-thread (thread) (mt:thread-join thread)) (mark-supported)
2,812
Common Lisp
.lisp
76
33.815789
76
0.719733
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d61cdda99b7a03dd329d0ca947b25b82fca63ba5a4596d56f78a94c45feecd1c
42,641
[ 368805 ]
42,642
condition-variables.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/condition-variables.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; This file provides a portable implementation of condition ;;; variables (given a working WITH-LOCK-HELD and THREAD-YIELD), and ;;; should be used if there is no condition variable implementation in ;;; the host Lisp. (defstruct condition-var name lock active) (defun condition-wait (condition-variable lock &key timeout) (signal-error-if-condition-wait-timeout timeout) (check-type condition-variable condition-var) (setf (condition-var-active condition-variable) nil) (release-lock lock) (do () ((when (condition-var-active condition-variable) (acquire-lock lock) t)) (thread-yield)) t) (define-condition-wait-compiler-macro) (defun condition-notify (condition-variable) (check-type condition-variable condition-var) (with-lock-held ((condition-var-lock condition-variable)) (setf (condition-var-active condition-variable) t)))
1,053
Common Lisp
.lisp
30
32.033333
70
0.746798
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
795d2b0fdef7c7dde02900ee8dc565ade8896f06629dcde520f972d0ff3ea37c
42,642
[ 442028 ]
42,643
impl-lispworks.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-lispworks.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the LispWorks Multiprocessing interface can be found at ;;; http://www.lispworks.com/documentation/lw445/LWUG/html/lwuser-156.htm (deftype thread () 'mp:process) ;;; Thread Creation (defun start-multiprocessing () (mp:initialize-multiprocessing)) (defun %make-thread (function name) (mp:process-run-function name nil (lambda () (let ((return-values (multiple-value-list (funcall function)))) (setf (mp:process-property 'return-values) return-values) (values-list return-values))))) (defun current-thread () #-#.(cl:if (cl:find-symbol (cl:string '#:get-current-process) :mp) '(and) '(or)) mp:*current-process* ;; introduced in LispWorks 5.1 #+#.(cl:if (cl:find-symbol (cl:string '#:get-current-process) :mp) '(and) '(or)) (mp:get-current-process)) (defun threadp (object) (mp:process-p object)) (defun thread-name (thread) (mp:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mp:lock) #-(or lispworks4 lispworks5) (deftype recursive-lock () '(and mp:lock (satisfies mp:lock-recursive-p))) (defun lock-p (object) (typep object 'mp:lock)) (defun recursive-lock-p (object) #+(or lispworks4 lispworks5) nil #-(or lispworks4 lispworks5) ; version 6+ (and (typep object 'mp:lock) (mp:lock-recursive-p object))) (defun make-lock (&optional name) (mp:make-lock :name (or name "Anonymous lock") #-(or lispworks4 lispworks5) :recursivep #-(or lispworks4 lispworks5) nil)) (defun acquire-lock (lock &optional (wait-p t)) (mp:process-lock lock nil (cond ((null wait-p) 0) ((numberp wait-p) wait-p) (t nil)))) (defun release-lock (lock) (mp:process-unlock lock)) (defmacro with-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) (defun make-recursive-lock (&optional name) (mp:make-lock :name (or name "Anonymous recursive lock") #-(or lispworks4 lispworks5) :recursivep #-(or lispworks4 lispworks5) t)) (defun acquire-recursive-lock (lock &optional (wait-p t)) (acquire-lock lock wait-p)) (defun release-recursive-lock (lock) (release-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) ;;; Resource contention: condition variables #-(or lispworks4 lispworks5) (defun make-condition-variable (&key name) (mp:make-condition-variable :name (or name "Anonymous condition variable"))) #-(or lispworks4 lispworks5) (defun condition-wait (condition-variable lock &key timeout) (mp:condition-variable-wait condition-variable lock :timeout timeout) t) #-(or lispworks4 lispworks5) (defun condition-notify (condition-variable) (mp:condition-variable-signal condition-variable)) (defun thread-yield () (mp:process-allow-scheduling)) ;;; Introspection/debugging (defun all-threads () (mp:list-all-processes)) (defun interrupt-thread (thread function &rest args) (apply #'mp:process-interrupt thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mp:process-kill thread)) (defun thread-alive-p (thread) (mp:process-alive-p thread)) (declaim (inline %join-thread)) (defun %join-thread (thread) #-#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (mp:process-wait (format nil "Waiting for thread ~A to complete" thread) (complement #'mp:process-alive-p) thread) #+#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (mp:process-join thread)) (defun join-thread (thread) (%join-thread thread) (let ((return-values (mp:process-property 'return-values thread))) (values-list return-values))) (mark-supported)
4,032
Common Lisp
.lisp
105
33.961905
82
0.682181
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e7e69b9365b7e256b2738ec8629524bd5bebbcec77e03e1af7d50bd29c9b5959
42,643
[ 404988 ]
42,644
impl-ecl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-ecl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the ECL Multiprocessing interface can be found at ;;; http://ecls.sourceforge.net/cgi-bin/view/Main/MultiProcessing (deftype thread () 'mp:process) ;;; Thread Creation (defun %make-thread (function name) (mp:process-run-function name function)) (defun current-thread () mp::*current-process*) (defun threadp (object) (typep object 'mp:process)) (defun thread-name (thread) (mp:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mp:lock) (deftype recursive-lock () '(and mp:lock (satisfies mp:recursive-lock-p))) (defun lock-p (object) (typep object 'mp:lock)) (defun recursive-lock-p (object) (and (typep object 'mp:lock) (mp:recursive-lock-p object))) (defun make-lock (&optional name) (mp:make-lock :name (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (mp:get-lock lock wait-p)) (defun release-lock (lock) (mp:giveup-lock lock)) (defmacro with-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) (defun make-recursive-lock (&optional name) (mp:make-lock :name (or name "Anonymous recursive lock") :recursive t)) (defun acquire-recursive-lock (lock &optional (wait-p t)) (mp:get-lock lock wait-p)) (defun release-recursive-lock (lock) (mp:giveup-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (declare (ignore name)) (mp:make-condition-variable)) (defun condition-wait (condition-variable lock &key timeout) (if timeout (handler-case (with-timeout (timeout) (mp:condition-variable-wait condition-variable lock)) (timeout () nil)) (mp:condition-variable-wait condition-variable lock))) (defun condition-notify (condition-variable) (mp:condition-variable-signal condition-variable)) (defun thread-yield () (mp:process-yield)) ;;; Introspection/debugging (defun all-threads () (mp:all-processes)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (mp:interrupt-process thread (apply-function)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mp:process-kill thread)) (defun thread-alive-p (thread) (mp:process-active-p thread)) (defun join-thread (thread) (mp:process-join thread)) (mark-supported)
2,741
Common Lisp
.lisp
76
32.605263
75
0.714829
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
6c569394193f90fb001ff19bfe7927c68d9526a9097291491a3a5a9aa76d090a
42,644
[ 156330 ]
42,645
impl-sbcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-sbcl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the SBCL Threads interface can be found at ;;; http://www.sbcl.org/manual/Threading.html (deftype thread () 'sb-thread:thread) ;;; Thread Creation (defun %make-thread (function name) (sb-thread:make-thread function :name name)) (defun current-thread () sb-thread:*current-thread*) (defun threadp (object) (typep object 'sb-thread:thread)) (defun thread-name (thread) (sb-thread:thread-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'sb-thread:mutex) (deftype recursive-lock () 'sb-thread:mutex) (defun lock-p (object) (typep object 'sb-thread:mutex)) (defun recursive-lock-p (object) (typep object 'sb-thread:mutex)) (defun make-lock (&optional name) (sb-thread:make-mutex :name (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) #+#.(cl:if (cl:find-symbol (cl:string '#:grab-mutex) :sb-thread) '(and) '(or)) (sb-thread:grab-mutex lock :waitp wait-p) #-#.(cl:if (cl:find-symbol (cl:string '#:grab-mutex) :sb-thread) '(and) '(or)) (sb-thread:get-mutex lock nil wait-p)) (defun release-lock (lock) (sb-thread:release-mutex lock)) (defmacro with-lock-held ((place) &body body) `(sb-thread:with-mutex (,place) ,@body)) (defun make-recursive-lock (&optional name) (sb-thread:make-mutex :name (or name "Anonymous recursive lock"))) ;;; XXX acquire-recursive-lock and release-recursive-lock are actually ;;; complicated because we can't use control stack tricks. We need to ;;; actually count something to check that the acquire/releases are ;;; balanced (defmacro with-recursive-lock-held ((place) &body body) `(sb-thread:with-recursive-lock (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (sb-thread:make-waitqueue :name (or name "Anonymous condition variable"))) (defun condition-wait (condition-variable lock &key timeout) (let ((success (sb-thread:condition-wait condition-variable lock :timeout timeout))) (when (not success) (acquire-lock lock)) success)) (defun condition-notify (condition-variable) (sb-thread:condition-notify condition-variable)) (defun thread-yield () (sb-thread:thread-yield)) ;;; Timeouts (deftype timeout () 'sb-ext:timeout) (defmacro with-timeout ((timeout) &body body) `(sb-ext:with-timeout ,timeout ,@body)) ;;; Semaphores (deftype semaphore () 'sb-thread:semaphore) (defun make-semaphore (&key name (count 0)) (sb-thread:make-semaphore :name name :count count)) (defun signal-semaphore (semaphore &key (count 1)) (sb-thread:signal-semaphore semaphore count)) (defun wait-on-semaphore (semaphore &key timeout) (sb-thread:wait-on-semaphore semaphore :timeout timeout)) ;;; Introspection/debugging (defun all-threads () (sb-thread:list-all-threads)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (sb-thread:interrupt-thread thread (apply-function)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (sb-thread:terminate-thread thread)) (defun thread-alive-p (thread) (sb-thread:thread-alive-p thread)) (defun join-thread (thread) (sb-thread:join-thread thread)) (mark-supported)
3,547
Common Lisp
.lisp
92
35.5
80
0.723996
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
943c4cc0c605913cf52a004eda50cf5521fc1ac27f34e3d379eba5fa5679471d
42,645
[ 50725 ]
42,646
impl-lispworks-condition-variables.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-lispworks-condition-variables.lisp
;;;; -*- indent-tabs-mode: nil -*- (in-package #:bordeaux-threads) ;; Lispworks condition support is simulated, albeit via a lightweight wrapper over ;; its own polling-based wait primitive. Waiters register with the condition variable, ;; and use MP:process-wait which queries for permission to proceed at its own (usspecified) interval. ;; http://www.lispworks.com/documentation/lw51/LWRM/html/lwref-445.htm ;; A wakeup callback (on notify) is provided to lighten this query to not have to do a hash lookup ;; on every poll (or have to serialize on the condition variable) and a mechanism is put ;; in place to unregister any waiter that exits wait for other reasons, ;; and to resend any (single) notification that may have been consumed before this (corner ;; case). Much of the complexity present is to support single notification (as recommended in ;; the spec); but a distinct condition-notify-all is provided for reference. ;; Single-notification follows a first-in first-out ordering ;; ;; Performance: With 1000 threads waiting on one condition-variable, the steady-state hit (at least ;; as tested on a 3GHz Win32 box) is noise - hovering at 0% on Task manager. ;; While not true zero like a true native solution, the use of the Lispworks native checks appear ;; fast enough to be an equivalent substitute (thread count will cause issue before the ;; waiting overhead becomes significant) (defstruct (condition-variable (:constructor make-lw-condition (name))) name (lock (mp:make-lock :name "For condition-variable") :type mp:lock :read-only t) (wait-tlist (cons nil nil) :type cons :read-only t) (wait-hash (make-hash-table :test 'eq) :type hash-table :read-only t) ;; unconsumed-notifications is to track :remove-from-consideration ;; for entries that may have exited prematurely - notification is sent through ;; to someone else, and offender is removed from hash and list (unconsumed-notifications (make-hash-table :test 'eq) :type hash-table :read-only t)) (defun make-condition-variable (&key name) (make-lw-condition name)) (defmacro with-cv-access (condition-variable &body body) (let ((cv-sym (gensym)) (slots '(lock wait-tlist wait-hash unconsumed-notifications))) `(let ((,cv-sym ,condition-variable)) (with-slots ,slots ,cv-sym (macrolet ((locked (&body body) `(mp:with-lock (lock) ,@body))) (labels ((,(gensym) () ,@slots))) ; Trigger expansion of the symbol-macrolets to ignore ,@body))))) (defmacro defcvfun (function-name (condition-variable &rest args) &body body) `(defun ,function-name (,condition-variable ,@args) (with-cv-access ,condition-variable ,@body))) #+lispworks (editor:setup-indent "defcvfun" 2 2 7) ; indent defcvfun ; utility function thath assumes process is locked on condition-variable's lock. (defcvfun do-notify-single (condition-variable) ; assumes already locked (let ((id (caar wait-tlist))) (when id (pop (car wait-tlist)) (unless (car wait-tlist) ; check for empty (setf (cdr wait-tlist) nil)) (funcall (gethash id wait-hash)) ; call waiter-wakeup (remhash id wait-hash) ; absence of entry = permission to proceed (setf (gethash id unconsumed-notifications) t)))) ;; Added for completeness/to show how it's done in this paradigm; but ;; The symbol for this call is not exposed in the api (defcvfun condition-notify-all (condition-variable) (locked (loop for waiter-wakeup being the hash-values in wait-hash do (funcall waiter-wakeup)) (clrhash wait-hash) (clrhash unconsumed-notifications) ; don't care as everyone just got notified (setf (car wait-tlist) nil) (setf (cdr wait-tlist) nil))) ;; Currently implemented so as to notify only one waiting thread (defcvfun condition-notify (condition-variable) (locked (do-notify-single condition-variable))) (defun delete-from-tlist (tlist element) (let ((deleter (lambda () (setf (car tlist) (cdar tlist)) (unless (car tlist) (setf (cdr tlist) nil))))) (loop for cons in (car tlist) do (if (eq element (car cons)) (progn (funcall deleter) (return nil)) (let ((cons cons)) (setq deleter (lambda () (setf (cdr cons) (cddr cons)) (unless (cdr cons) (setf (cdr tlist) cons))))))))) (defun add-to-tlist-tail (tlist element) (let ((new-link (cons element nil))) (cond ((car tlist) (setf (cddr tlist) new-link) (setf (cdr tlist) new-link)) (t (setf (car tlist) new-link) (setf (cdr tlist) new-link))))) (defcvfun condition-wait (condition-variable lock- &key timeout) (signal-error-if-condition-wait-timeout timeout) (mp:process-unlock lock-) (unwind-protect ; for the re-taking of the lock. Guarding all of the code (let ((wakeup-allowed-to-proceed nil) (wakeup-lock (mp:make-lock :name "wakeup lock for condition-wait"))) ;; wakeup-allowed-to-proceed is an optimisation to avoid having to serialize all waiters and ;; search the hashtable. That it is locked is for safety/completeness, although ;; as wakeup-allowed-to-proceed only transitions nil -> t, and that missing it once or twice is ;; moot in this situation, it would be redundant even if ever a Lispworks implementation ever became ;; non-atomic in its assigments (let ((id (cons nil nil)) (clean-exit nil)) (locked (add-to-tlist-tail wait-tlist id) (setf (gethash id wait-hash) (lambda () (mp:with-lock (wakeup-lock) (setq wakeup-allowed-to-proceed t))))) (unwind-protect (progn (mp:process-wait "Waiting for notification" (lambda () (when (mp:with-lock (wakeup-lock) wakeup-allowed-to-proceed) (locked (not (gethash id wait-hash)))))) (locked (remhash id unconsumed-notifications)) (setq clean-exit t)) ; Notification was consumed ;; Have to call remove-from-consideration just in case process was interrupted ;; rather than having condition met (unless clean-exit ; clean-exit is just an optimization (locked (when (gethash id wait-hash) ; not notified - must have been interrupted ;; Have to unsubscribe (remhash id wait-hash) (delete-from-tlist wait-tlist id)) ;; note - it's possible to be removed from wait-hash/wait-tlist (in notify-single); but still have an unconsumed notification! (when (gethash id unconsumed-notifications) ; Must have exited for reasons unrelated to notification (remhash id unconsumed-notifications) ; Have to pass on the notification to an eligible waiter (do-notify-single condition-variable))))))) (mp:process-lock lock-)) t) (define-condition-wait-compiler-macro)
7,140
Common Lisp
.lisp
132
46.424242
141
0.668954
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
36a601416281cbc40bb43f76c8468441c9a1672023986987226e403e34fbc6bb
42,646
[ 69487 ]
42,648
impl-abcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-abcl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Reimplemented with java.util.concurrent.locks.ReentrantLock by Mark Evenson 2011. Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; the implementation of the Armed Bear thread interface can be found in ;;; src/org/armedbear/lisp/LispThread.java (deftype thread () 'threads:thread) ;;; Thread Creation (defun %make-thread (function name) (threads:make-thread function :name name)) (defun current-thread () (threads:current-thread)) (defun thread-name (thread) (threads:thread-name thread)) (defun threadp (object) (typep object 'thread)) ;;; Resource contention: locks and recursive locks (defstruct mutex name lock) (defstruct (mutex-recursive (:include mutex))) ;; Making methods constants in this manner avoids the runtime expense of ;; introspection involved in JCALL with string arguments. (defconstant +lock+ (jmethod "java.util.concurrent.locks.ReentrantLock" "lock")) (defconstant +try-lock+ (jmethod "java.util.concurrent.locks.ReentrantLock" "tryLock")) (defconstant +is-held-by-current-thread+ (jmethod "java.util.concurrent.locks.ReentrantLock" "isHeldByCurrentThread")) (defconstant +unlock+ (jmethod "java.util.concurrent.locks.ReentrantLock" "unlock")) (defconstant +get-hold-count+ (jmethod "java.util.concurrent.locks.ReentrantLock" "getHoldCount")) (deftype lock () 'mutex) (deftype recursive-lock () 'mutex-recursive) (defun lock-p (object) (typep object 'mutex)) (defun recursive-lock-p (object) (typep object 'mutex-recursive)) (defun make-lock (&optional name) (make-mutex :name (or name "Anonymous lock") :lock (jnew "java.util.concurrent.locks.ReentrantLock"))) (defun acquire-lock (lock &optional (wait-p t)) (check-type lock mutex) (when (jcall +is-held-by-current-thread+ (mutex-lock lock)) (error "Non-recursive lock being reacquired by owner.")) (cond (wait-p (jcall +lock+ (mutex-lock lock)) t) (t (jcall +try-lock+ (mutex-lock lock))))) (defun release-lock (lock) (check-type lock mutex) (unless (jcall +is-held-by-current-thread+ (mutex-lock lock)) (error "Attempt to release lock not held by calling thread.")) (jcall +unlock+ (mutex-lock lock)) (values)) (defun make-recursive-lock (&optional name) (make-mutex-recursive :name (or name "Anonymous lock") :lock (jnew "java.util.concurrent.locks.ReentrantLock"))) (defun acquire-recursive-lock (lock &optional (wait-p t)) (check-type lock mutex-recursive) (cond (wait-p (jcall +lock+ (mutex-recursive-lock lock)) t) (t (jcall +try-lock+ (mutex-recursive-lock lock))))) (defun release-recursive-lock (lock) (check-type lock mutex-recursive) (unless (jcall +is-held-by-current-thread+ (mutex-lock lock)) (error "Attempt to release lock not held by calling thread.")) (jcall +unlock+ (mutex-lock lock)) (values)) ;;; Resource contention: condition variables (defun thread-yield () (java:jstatic "yield" "java.lang.Thread")) (defstruct condition-variable (name "Anonymous condition variable")) (defun condition-wait (condition lock &key timeout) (threads:synchronized-on condition (release-lock lock) (if timeout ;; Since giving a zero time value to threads:object-wait means ;; an indefinite wait, use some arbitrary small number. (threads:object-wait condition (if (zerop timeout) least-positive-single-float timeout)) (threads:object-wait condition))) (acquire-lock lock) t) (defun condition-notify (condition) (threads:synchronized-on condition (threads:object-notify condition))) ;;; Introspection/debugging (defun all-threads () (let ((threads ())) (threads:mapcar-threads (lambda (thread) (push thread threads))) (reverse threads))) (defun interrupt-thread (thread function &rest args) (apply #'threads:interrupt-thread thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (threads:destroy-thread thread)) (defun thread-alive-p (thread) (threads:thread-alive-p thread)) (defun join-thread (thread) (threads:thread-join thread)) (mark-supported)
4,319
Common Lisp
.lisp
114
33.929825
81
0.720077
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
195a1bceb4ff5a46d75b537380bee535f5e453162ae6ff669a0e9a559a59fb3a
42,648
[ 304068, 366417 ]
42,649
impl-clasp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-clasp.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the ECL Multiprocessing interface can be found at ;;; http://ecls.sourceforge.net/cgi-bin/view/Main/MultiProcessing (deftype thread () 'mp:process) ;;; Thread Creation (defun %make-thread (function name) (mp:process-run-function name function bordeaux-threads:*default-special-bindings*)) (defun current-thread () mp:*current-process*) (defun threadp (object) (typep object 'mp:process)) (defun thread-name (thread) (mp:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mp:mutex) (deftype recursive-lock () '(and mp:mutex (satisfies mp:recursive-lock-p))) (defun lock-p (object) (typep object 'mp:mutex)) (defun recursive-lock-p (object) (and (typep object 'mp:mutex) (mp:recursive-lock-p object))) (defun make-lock (&optional name) (mp:make-lock :name (or name :anonymous))) (defun acquire-lock (lock &optional (wait-p t)) (mp:get-lock lock wait-p)) (defun release-lock (lock) (mp:giveup-lock lock)) (defmacro with-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) (defun make-recursive-lock (&optional name) (mp:make-recursive-mutex (or name :anonymous-recursive-lock))) (defun acquire-recursive-lock (lock &optional (wait-p t)) (mp:get-lock lock wait-p)) (defun release-recursive-lock (lock) (mp:giveup-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(mp:with-lock (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (declare (ignore name)) (mp:make-condition-variable)) (defun condition-wait (condition-variable lock &key timeout) (if timeout (mp:condition-variable-timedwait condition-variable lock timeout) (mp:condition-variable-wait condition-variable lock)) t) (defun condition-notify (condition-variable) (mp:condition-variable-signal condition-variable)) (defun thread-yield () (mp:process-yield)) ;;; Introspection/debugging (defun all-threads () (mp:all-processes)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (mp:interrupt-process thread (apply-function)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mp:process-kill thread)) (defun thread-alive-p (thread) (mp:process-active-p thread)) (defun join-thread (thread) (mp:process-join thread)) (mark-supported)
2,704
Common Lisp
.lisp
75
32.92
86
0.727728
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
0e3042c79e5b5fec48a16123a2564a13caedc6712df550a67d01fb946a98f411
42,649
[ 45473 ]
42,650
impl-scl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-scl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2008 Scieneer Pty Ltd Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'thread:thread) (defun %make-thread (function name) (thread:thread-create function :name name)) (defun current-thread () thread:*thread*) (defun threadp (object) (typep object 'thread:thread)) (defun thread-name (thread) (thread:thread-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'thread:lock) (deftype recursive-lock () 'thread:recursive-lock) (defun lock-p (object) (typep object 'thread:lock)) (defun recursive-lock-p (object) (typep object 'thread:recursive-lock)) (defun make-lock (&optional name) (thread:make-lock (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (thread::acquire-lock lock nil wait-p)) (defun release-lock (lock) (thread::release-lock lock)) (defmacro with-lock-held ((place) &body body) `(thread:with-lock-held (,place) ,@body)) (defun make-recursive-lock (&optional name) (thread:make-lock (or name "Anonymous recursive lock") :type :recursive)) ;;; XXX acquire-recursive-lock and release-recursive-lock are actually ;;; complicated because we can't use control stack tricks. We need to ;;; actually count something to check that the acquire/releases are ;;; balanced (defmacro with-recursive-lock-held ((place) &body body) `(thread:with-lock-held (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (thread:make-cond-var (or name "Anonymous condition variable"))) (defun condition-wait (condition-variable lock &key timeout) (if timeout (thread:cond-var-timedwait condition-variable lock timeout) (thread:cond-var-wait condition-variable lock)) t) (defun condition-notify (condition-variable) (thread:cond-var-broadcast condition-variable)) (defun thread-yield () (mp:process-yield)) ;;; Introspection/debugging (defun all-threads () (mp:all-processes)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (thread:thread-interrupt thread (apply-function)))) (defun destroy-thread (thread) (thread:destroy-thread thread)) (defun thread-alive-p (thread) (mp:process-alive-p thread)) (defun join-thread (thread) (mp:process-wait (format nil "Waiting for thread ~A to complete" thread) (lambda () (not (mp:process-alive-p thread))))) (mark-supported)
2,681
Common Lisp
.lisp
71
34.183099
74
0.720714
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
835f80113c16eba541c087d52b3a6f66818c92edda0702b99e047a8c2466b97e
42,650
[ 485412 ]
42,651
impl-genera.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-genera.lisp
;;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: BORDEAUX-THREADS; Base: 10; -*- #| Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'process:process) (defvar *thread-recursive-lock-key* 0) ;;; Thread Creation (defun %make-thread (function name) (flet ((top-level () (let* ((*thread-recursive-lock-key* 0) (return-values (multiple-value-list (funcall function)))) (setf (si:process-spare-slot-4 scl:*current-process*) return-values) (values-list return-values)))) (declare (dynamic-extent #'top-level)) (process:process-run-function name #'top-level))) (defun current-thread () scl:*current-process*) (defun threadp (object) (process:process-p object)) (defun thread-name (thread) (process:process-name thread)) ;;; Resource contention: locks and recursive locks (defstruct (lock (:constructor make-lock-internal)) lock lock-argument) (defun make-lock (&optional name) (let ((lock (process:make-lock (or name "Anonymous lock")))) (make-lock-internal :lock lock :lock-argument nil))) (defun acquire-lock (lock &optional (wait-p t)) (check-type lock lock) (let ((lock-argument (process:make-lock-argument (lock-lock lock)))) (cond (wait-p (process:lock (lock-lock lock) lock-argument) (setf (lock-lock-argument lock) lock-argument) t) (t (process:with-no-other-processes (when (process:lock-lockable-p (lock-lock lock)) (process:lock (lock-lock lock) lock-argument) (setf (lock-lock-argument lock) lock-argument) t)))))) (defun release-lock (lock) (check-type lock lock) (process:unlock (lock-lock lock) (scl:shiftf (lock-lock-argument lock) nil))) (defstruct (recursive-lock (:constructor make-recursive-lock-internal)) lock lock-arguments) (defun make-recursive-lock (&optional name) (make-recursive-lock-internal :lock (process:make-lock (or name "Anonymous recursive lock") :recursive t) :lock-arguments (make-hash-table :test #'equal))) (defun acquire-recursive-lock (lock) (check-type lock recursive-lock) (acquire-recursive-lock-internal lock)) (defun acquire-recursive-lock-internal (lock &optional timeout) (let ((key (cons (incf *thread-recursive-lock-key*) scl:*current-process*)) (lock-argument (process:make-lock-argument (recursive-lock-lock lock)))) (cond (timeout (process:with-no-other-processes (when (process:lock-lockable-p (recursive-lock-lock lock)) (process:lock (recursive-lock-lock lock) lock-argument) (setf (gethash key (recursive-lock-lock-arguments lock)) lock-argument) t))) (t (process:lock (recursive-lock-lock lock) lock-argument) (setf (gethash key (recursive-lock-lock-arguments lock)) lock-argument) t)))) (defun release-recursive-lock (lock) (check-type lock recursive-lock) (let* ((key (cons *thread-recursive-lock-key* scl:*current-process*)) (lock-argument (gethash key (recursive-lock-lock-arguments lock)))) (prog1 (process:unlock (recursive-lock-lock lock) lock-argument) (decf *thread-recursive-lock-key*) (remhash key (recursive-lock-lock-arguments lock))))) (defmacro with-recursive-lock-held ((place &key timeout) &body body) `(with-recursive-lock-held-internal ,place ,timeout #'(lambda () ,@body))) (defun with-recursive-lock-held-internal (lock timeout function) (check-type lock recursive-lock) (assert (typep timeout '(or null (satisfies zerop))) (timeout) 'bordeaux-mp-condition :message ":TIMEOUT value must be either NIL or 0") (when (acquire-recursive-lock-internal lock timeout) (unwind-protect (funcall function) (release-recursive-lock lock)))) ;;; Resource contention: condition variables (eval-when (:compile-toplevel :load-toplevel :execute) (defstruct (condition-variable (:constructor %make-condition-variable)) name (waiters nil)) ) (defun make-condition-variable (&key name) (%make-condition-variable :name name)) (defun condition-wait (condition-variable lock &key timeout) (check-type condition-variable condition-variable) (check-type lock lock) (process:with-no-other-processes (let ((waiter (cons scl:*current-process* nil))) (process:atomic-updatef (condition-variable-waiters condition-variable) #'(lambda (waiters) (append waiters (scl:ncons waiter)))) (let ((expired? t)) (unwind-protect (progn (release-lock lock) (process:block-with-timeout timeout (format nil "Waiting~@[ on ~A~]" (condition-variable-name condition-variable)) #'(lambda (waiter expired?-loc) (when (not (null (cdr waiter))) (setf (sys:location-contents expired?-loc) nil) t)) waiter (sys:value-cell-location 'expired?)) expired?) (unless expired? (acquire-lock lock))))))) (defun condition-notify (condition-variable) (check-type condition-variable condition-variable) (let ((waiter (process:atomic-pop (condition-variable-waiters condition-variable)))) (when waiter (setf (cdr waiter) t) (process:wakeup (car waiter)))) (values)) (defun thread-yield () (scl:process-allow-schedule)) ;;; Timeouts (defmacro with-timeout ((timeout) &body body) "Execute `BODY' and signal a condition of type TIMEOUT if the execution of BODY does not complete within `TIMEOUT' seconds." `(with-timeout-internal ,timeout #'(lambda () ,@body))) (defun with-timeout-internal (timeout function) ;; PROCESS:WITH-TIMEOUT either returns NIL on timeout or signals an error which, ;; unforutnately, does not have a distinguished type (i.e., it's a SYS:FATAL-ERROR). ;; So, rather than try to catch the error and signal our condition, we instead ;; ensure the return value from the PROCESS:WITH-TIMEOUT is never NIL if there is ;; no timeout. (Sigh) (let ((result (process:with-timeout (timeout) (cons 'success (multiple-value-list (funcall function)))))) (if result (values-list (cdr result)) (error 'timeout :length timeout)))) ;;; Introspection/debugging (defun all-threads () process:*all-processes*) (defun interrupt-thread (thread function &rest args) (declare (dynamic-extent args)) (apply #'process:process-interrupt thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (process:process-kill thread :without-aborts :force)) (defun thread-alive-p (thread) (process:process-active-p thread)) (defun join-thread (thread) (process:process-wait (format nil "Join ~S" thread) #'(lambda (thread) (not (process:process-active-p thread))) thread) (values-list (si:process-spare-slot-4 thread))) (mark-supported)
7,481
Common Lisp
.lisp
163
37.226994
95
0.639747
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
94e5d7c307c3df734d4220e2e790ce440765f6724f38634c6e7d3ea9794048c6
42,651
[ -1 ]
42,652
impl-clozure.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-clozure.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the OpenMCL Threads interface can be found at ;;; http://openmcl.clozure.com/Doc/Programming-with-Threads.html (deftype thread () 'ccl:process) ;;; Thread Creation (defun %make-thread (function name) (ccl:process-run-function name function)) (defun current-thread () ccl:*current-process*) (defun threadp (object) (typep object 'ccl:process)) (defun thread-name (thread) (ccl:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'ccl:lock) (deftype recursive-lock () 'ccl:lock) (defun lock-p (object) (typep object 'ccl:lock)) (defun recursive-lock-p (object) (typep object 'ccl:lock)) (defun make-lock (&optional name) (ccl:make-lock (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (if wait-p (ccl:grab-lock lock) (ccl:try-lock lock))) (defun release-lock (lock) (ccl:release-lock lock)) (defmacro with-lock-held ((place) &body body) `(ccl:with-lock-grabbed (,place) ,@body)) (defun make-recursive-lock (&optional name) (ccl:make-lock (or name "Anonymous recursive lock"))) (defun acquire-recursive-lock (lock) (ccl:grab-lock lock)) (defun release-recursive-lock (lock) (ccl:release-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(ccl:with-lock-grabbed (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (declare (ignore name)) (ccl:make-semaphore)) (defun condition-wait (condition-variable lock &key timeout) (release-lock lock) (unwind-protect (if timeout (ccl:timed-wait-on-semaphore condition-variable timeout) (ccl:wait-on-semaphore condition-variable)) (acquire-lock lock t)) t) (defun condition-notify (condition-variable) (ccl:signal-semaphore condition-variable)) (defun thread-yield () (ccl:process-allow-schedule)) ;;; Semaphores (deftype semaphore () 'ccl:semaphore) (defun make-semaphore (&key name (count 0)) (declare (ignore name)) (let ((semaphore (ccl:make-semaphore))) (dotimes (c count) (ccl:signal-semaphore semaphore)) semaphore)) (defun signal-semaphore (semaphore &key (count 1)) (dotimes (c count) (ccl:signal-semaphore semaphore))) (defun wait-on-semaphore (semaphore &key timeout) (if timeout (ccl:timed-wait-on-semaphore semaphore timeout) (ccl:wait-on-semaphore semaphore))) ;;; Introspection/debugging (defun all-threads () (ccl:all-processes)) (defun interrupt-thread (thread function &rest args) (declare (dynamic-extent args)) (apply #'ccl:process-interrupt thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (ccl:process-kill thread)) (defun thread-alive-p (thread) (not (ccl:process-exhausted-p thread))) (defun join-thread (thread) (ccl:join-process thread)) (mark-supported)
3,061
Common Lisp
.lisp
90
30.977778
67
0.729444
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a844a943a0dccfbb26debfd02f84736397d3a22781e2cc0bb9bb3b9390449e6c
42,652
[ 471966 ]
42,653
impl-allegro.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-allegro.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) ;;; documentation on the Allegro Multiprocessing interface can be found at ;;; http://www.franz.com/support/documentation/8.1/doc/multiprocessing.htm ;;; Resource contention: locks and recursive locks (deftype lock () 'mp:process-lock) (deftype recursive-lock () 'mp:process-lock) (defun lock-p (object) (typep object 'mp:process-lock)) (defun recursive-lock-p (object) (typep object 'mp:process-lock)) (defun make-lock (&optional name) (mp:make-process-lock :name (or name "Anonymous lock"))) (defun make-recursive-lock (&optional name) (mp:make-process-lock :name (or name "Anonymous recursive lock"))) (defun acquire-lock (lock &optional (wait-p t)) (mp:process-lock lock mp:*current-process* "Lock" (if wait-p nil 0))) (defun release-lock (lock) (mp:process-unlock lock)) (defmacro with-lock-held ((place) &body body) `(mp:with-process-lock (,place :norecursive t) ,@body)) (defmacro with-recursive-lock-held ((place &key timeout) &body body) `(mp:with-process-lock (,place :timeout ,timeout) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (declare (ignorable name)) #-(version>= 9) (mp:make-gate nil) #+(version>= 9) (mp:make-condition-variable :name name)) (defun condition-wait (condition-variable lock &key timeout) #-(version>= 9) (progn (release-lock lock) (if timeout (mp:process-wait-with-timeout "wait for message" timeout #'mp:gate-open-p condition-variable) (mp:process-wait "wait for message" #'mp:gate-open-p condition-variable)) (acquire-lock lock) (mp:close-gate condition-variable)) #+(version>= 9) (mp:condition-variable-wait condition-variable lock :timeout timeout) t) (defun condition-notify (condition-variable) #-(version>= 9) (mp:open-gate condition-variable) #+(version>= 9) (mp:condition-variable-signal condition-variable)) (defun thread-yield () (mp:process-allow-schedule)) (deftype thread () 'mp:process) ;;; Thread Creation (defun start-multiprocessing () (mp:start-scheduler)) (defun %make-thread (function name) #+smp (mp:process-run-function name function) #-smp (mp:process-run-function name (lambda () (let ((return-values (multiple-value-list (funcall function)))) (setf (getf (mp:process-property-list mp:*current-process*) 'return-values) return-values) (values-list return-values))))) (defun current-thread () mp:*current-process*) (defun threadp (object) (typep object 'mp:process)) (defun thread-name (thread) (mp:process-name thread)) ;;; Timeouts (defmacro with-timeout ((timeout) &body body) (once-only (timeout) `(mp:with-timeout (,timeout (error 'timeout :length ,timeout)) ,@body))) ;;; Introspection/debugging (defun all-threads () mp:*all-processes*) (defun interrupt-thread (thread function &rest args) (apply #'mp:process-interrupt thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mp:process-kill thread)) (defun thread-alive-p (thread) (mp:process-alive-p thread)) (defun join-thread (thread) #+smp (values-list (mp:process-join thread)) #-smp (progn (mp:process-wait (format nil "Waiting for thread ~A to complete" thread) (complement #'mp:process-alive-p) thread) (let ((return-values (getf (mp:process-property-list thread) 'return-values))) (values-list return-values)))) (mark-supported)
3,752
Common Lisp
.lisp
107
30.803738
81
0.69299
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
c6daafb10c656c28b72dd1167eb3e6f808e3b7cafc602056161458e0040b4a6c
42,653
[ 493570 ]
42,654
pkgdcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/pkgdcl.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10; Package: CL-USER -*- ;;;; The above modeline is required for Genera. Do not change. (cl:defpackage :bordeaux-threads (:nicknames #:bt) (:use #:cl #:alexandria) #+abcl (:import-from :java #:jnew #:jcall #:jmethod) (:export #:thread #:make-thread #:current-thread #:threadp #:thread-name #:start-multiprocessing #:*default-special-bindings* #:*standard-io-bindings* #:*supports-threads-p* #:lock #:make-lock #:lock-p #:acquire-lock #:release-lock #:with-lock-held #:recursive-lock #:make-recursive-lock #:recursive-lock-p #:acquire-recursive-lock #:release-recursive-lock #:with-recursive-lock-held #:make-condition-variable #:condition-wait #:condition-notify #:make-semaphore #:signal-semaphore #:wait-on-semaphore #:semaphore #:semaphore-p #:with-timeout #:timeout #:all-threads #:interrupt-thread #:destroy-thread #:thread-alive-p #:join-thread #:thread-yield) (:documentation "BORDEAUX-THREADS is a proposed standard for a minimal MP/threading interface. It is similar to the CLIM-SYS threading and lock support, but for the following broad differences: 1) Some behaviours are defined in additional detail: attention has been given to special variable interaction, whether and when cleanup forms are run. Some behaviours are defined in less detail: an implementation that does not support multiple threads is not required to use a new list (nil) for a lock, for example. 2) Many functions which would be difficult, dangerous or inefficient to provide on some implementations have been removed. Chiefly these are functions such as thread-wait which expect for efficiency that the thread scheduler is written in Lisp and 'hookable', which can't sensibly be done if the scheduler is external to the Lisp image, or the system has more than one CPU. 3) Unbalanced ACQUIRE-LOCK and RELEASE-LOCK functions have been added. 4) Posix-style condition variables have been added, as it's not otherwise possible to implement them correctly using the other operations that are specified. Threads may be implemented using whatever applicable techniques are provided by the operating system: user-space scheduling, kernel-based LWPs or anything else that does the job. Some parts of this specification can also be implemented in a Lisp that does not support multiple threads. Thread creation and some thread inspection operations will not work, but the locking functions are still present (though they may do nothing) so that thread-safe code can be compiled on both multithread and single-thread implementations without need of conditionals. To avoid conflict with existing MP/threading interfaces in implementations, these symbols live in the BORDEAUX-THREADS package. Implementations and/or users may also make them visible or exported in other more traditionally named packages."))
3,091
Common Lisp
.lisp
53
52.396226
92
0.737434
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
549f9608d251933bc0ea552d899da21a0b9221ede20e6b48c6e630acee57e2d3
42,654
[ 434426 ]
42,655
impl-mkcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-mkcl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Copyright 2010 Jean-Claude Beaudoin. Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'mt:thread) ;;; Thread Creation (defun %make-thread (function name) (mt:thread-run-function name function)) (defun current-thread () mt::*thread*) (defun threadp (object) (typep object 'mt:thread)) (defun thread-name (thread) (mt:thread-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mt:lock) (deftype recursive-lock () '(and mt:lock (satisfies mt:recursive-lock-p))) (defun lock-p (object) (typep object 'mt:lock)) (defun recursive-lock-p (object) (and (typep object 'mt:lock) (mt:recursive-lock-p object))) (defun make-lock (&optional name) (mt:make-lock :name (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (mt:get-lock lock wait-p)) (defun release-lock (lock) (mt:giveup-lock lock)) (defmacro with-lock-held ((place) &body body) `(mt:with-lock (,place) ,@body)) (defun make-recursive-lock (&optional name) (mt:make-lock :name (or name "Anonymous recursive lock") :recursive t)) (defun acquire-recursive-lock (lock &optional (wait-p t)) (mt:get-lock lock wait-p)) (defun release-recursive-lock (lock) (mt:giveup-lock lock)) (defmacro with-recursive-lock-held ((place) &body body) `(mt:with-lock (,place) ,@body)) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (declare (ignore name)) (mt:make-condition-variable)) (defun condition-wait (condition-variable lock &key timeout) (signal-error-if-condition-wait-timeout timeout) (mt:condition-wait condition-variable lock) t) (define-condition-wait-compiler-macro) (defun condition-notify (condition-variable) (mt:condition-signal condition-variable)) (defun thread-yield () (mt:thread-yield)) ;;; Introspection/debugging (defun all-threads () (mt:all-threads)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (mt:interrupt-thread thread (apply-function)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mt:thread-kill thread)) (defun thread-alive-p (thread) (mt:thread-active-p thread)) (defun join-thread (thread) (mt:thread-join thread)) (mark-supported)
2,532
Common Lisp
.lisp
74
31.202703
73
0.721832
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
6937face500d1c34393f7e834e1873c16ee1bce685840f9abe0431a92bef02e4
42,655
[ 426956 ]
42,656
bordeaux-threads.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/bordeaux-threads.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10; Package: BORDEAUX-THREADS -*- ;;;; The above modeline is required for Genera. Do not change. #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (defvar *supports-threads-p* nil "This should be set to T if the running instance has thread support.") (defun mark-supported () (setf *supports-threads-p* t) (pushnew :bordeaux-threads *features*)) (define-condition bordeaux-mp-condition (error) ((message :initarg :message :reader message)) (:report (lambda (condition stream) (format stream (message condition))))) (defgeneric make-threading-support-error () (:documentation "Creates a BORDEAUX-THREADS condition which specifies whether there is no BORDEAUX-THREADS support for the implementation, no threads enabled for the system, or no support for a particular function.") (:method () (make-condition 'bordeaux-mp-condition :message (if *supports-threads-p* "There is no support for this method on this implementation." "There is no thread support in this instance.")))) ;;; Timeouts #-sbcl (define-condition timeout (serious-condition) ((length :initform nil :initarg :length :reader timeout-length)) (:report (lambda (c s) (if (timeout-length c) (format s "A timeout set to ~A seconds occurred." (timeout-length c)) (format s "A timeout occurred."))))) #-sbcl (define-condition interrupt () ((tag :initarg :tag :reader interrupt-tag))) #-(or sbcl genera) (defmacro with-timeout ((timeout) &body body) "Execute `BODY' and signal a condition of type TIMEOUT if the execution of BODY does not complete within `TIMEOUT' seconds. On implementations which do not support WITH-TIMEOUT natively and don't support threads either it has no effect." (declare (ignorable timeout body)) #+thread-support (once-only (timeout) (with-gensyms (ok-tag interrupt-tag caller interrupt-thread c) `(let (,interrupt-thread) (unwind-protect-case () (catch ',ok-tag (let* ((,interrupt-tag (gensym "INTERRUPT-TAG-")) (,caller (current-thread))) (setf ,interrupt-thread (make-thread #'(lambda () (sleep ,timeout) (interrupt-thread ,caller #'(lambda () (signal 'interrupt :tag ,interrupt-tag)))) :name (format nil "WITH-TIMEOUT thread serving: ~S." (thread-name ,caller)))) (handler-bind ((interrupt #'(lambda (,c) (when (eql ,interrupt-tag (interrupt-tag ,c)) (error 'timeout :length ,timeout))))) (throw ',ok-tag (progn ,@body))))) (:normal (when (and ,interrupt-thread (thread-alive-p ,interrupt-thread)) ;; There's a potential race condition between THREAD-ALIVE-P ;; and DESTROY-THREAD but calling the latter when a thread already ;; terminated should not be a grave matter. (ignore-errors (destroy-thread ,interrupt-thread)))))))) #-thread-support `(error (make-threading-support-error))) ;;; Semaphores ;;; We provide this structure definition unconditionally regardless of the fact ;;; it may not be used not to prevent warnings from compiling default functions ;;; for semaphore in default-implementations.lisp. (defstruct %semaphore lock condition-variable counter) #-(or ccl sbcl) (deftype semaphore () '%semaphore) ;;; Thread Creation ;;; See default-implementations.lisp for MAKE-THREAD. ;; Forms are evaluated in the new thread or in the calling thread? (defvar *default-special-bindings* nil "This variable holds an alist associating special variable symbols to forms to evaluate. Special variables named in this list will be locally bound in the new thread before it begins executing user code. This variable may be rebound around calls to MAKE-THREAD to add/alter default bindings. The effect of mutating this list is undefined, but earlier forms take precedence over later forms for the same symbol, so defaults may be overridden by consing to the head of the list.") (defmacro defbindings (name docstring &body initforms) (check-type docstring string) `(defparameter ,name (list ,@(loop for (special form) in initforms collect `(cons ',special ',form))) ,docstring)) ;; Forms are evaluated in the new thread or in the calling thread? (defbindings *standard-io-bindings* "Standard bindings of printer/reader control variables as per CL:WITH-STANDARD-IO-SYNTAX." (*package* (find-package :common-lisp-user)) (*print-array* t) (*print-base* 10) (*print-case* :upcase) (*print-circle* nil) (*print-escape* t) (*print-gensym* t) (*print-length* nil) (*print-level* nil) (*print-lines* nil) (*print-miser-width* nil) (*print-pprint-dispatch* (copy-pprint-dispatch nil)) (*print-pretty* nil) (*print-radix* nil) (*print-readably* t) (*print-right-margin* nil) (*random-state* (make-random-state t)) (*read-base* 10) (*read-default-float-format* 'single-float) (*read-eval* t) (*read-suppress* nil) (*readtable* (copy-readtable nil))) (defun binding-default-specials (function special-bindings) "Return a closure that binds the symbols in SPECIAL-BINDINGS and calls FUNCTION." (let ((specials (remove-duplicates special-bindings :from-end t :key #'car))) (lambda () (progv (mapcar #'car specials) (loop for (nil . form) in specials collect (eval form)) (funcall function))))) ;;; FIXME: This test won't work if CURRENT-THREAD ;;; conses a new object each time (defun signal-error-if-current-thread (thread) (when (eq thread (current-thread)) (error 'bordeaux-mp-condition :message "Cannot destroy the current thread"))) (defparameter *no-condition-wait-timeout-message* "CONDITION-WAIT with :TIMEOUT is not available for this Lisp implementation.") (defun signal-error-if-condition-wait-timeout (timeout) (when timeout (error 'bordeaux-mp-condition :message *no-condition-wait-timeout-message*))) (defmacro define-condition-wait-compiler-macro () `(define-compiler-macro condition-wait (&whole whole condition-variable lock &key timeout) (declare (ignore condition-variable lock)) (when timeout (simple-style-warning *no-condition-wait-timeout-message*)) whole))
7,091
Common Lisp
.lisp
159
37.716981
92
0.637614
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
549406405b8741ca89c41cd7ec6ea280a22e2d74f623eaad9539d11af6a45a7f
42,656
[ -1 ]
42,657
impl-cmucl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-cmucl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'mp::process) ;;; Thread Creation (defun start-multiprocessing () (mp::startup-idle-and-top-level-loops)) (defun %make-thread (function name) #+#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (mp:make-process function :name name) #-#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (mp:make-process (lambda () (let ((return-values (multiple-value-list (funcall function)))) (setf (getf (mp:process-property-list mp:*current-process*) 'return-values) return-values) (values-list return-values))) :name name)) (defun current-thread () mp:*current-process*) (defmethod threadp (object) (mp:processp object)) (defun thread-name (thread) (mp:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mp::error-check-lock) (deftype recursive-lock () 'mp::recursive-lock) (defun lock-p (object) (typep object 'mp::error-check-lock)) (defun recursive-lock-p (object) (typep object 'mp::recursive-lock)) (defun make-lock (&optional name) (mp:make-lock (or name "Anonymous lock") :kind :error-check)) (defun acquire-lock (lock &optional (wait-p t)) (if wait-p (mp::lock-wait lock "Lock wait") (mp::lock-wait-with-timeout lock "Lock wait" 0))) (defun release-lock (lock) (setf (mp::lock-process lock) nil)) (defmacro with-lock-held ((place) &body body) `(mp:with-lock-held (,place "Lock wait") ,@body)) (defun make-recursive-lock (&optional name) (mp:make-lock (or name "Anonymous recursive lock") :kind :recursive)) (defun acquire-recursive-lock (lock &optional (wait-p t)) (acquire-lock lock)) (defun release-recursive-lock (lock) (release-lock lock)) (defmacro with-recursive-lock-held ((place &key timeout) &body body) `(mp:with-lock-held (,place "Lock Wait" :timeout ,timeout) ,@body)) ;;; Note that the locks _are_ recursive, but not "balanced", and only ;;; checked if they are being held by the same process by with-lock-held. ;;; The default with-lock-held in bordeaux-mp.lisp sort of works, in that ;;; it will wait for recursive locks by the same process as well. ;;; Resource contention: condition variables ;;; There's some stuff in x86-vm.lisp that might be worth investigating ;;; whether to build on. There's also process-wait and friends. (defstruct condition-var "CMUCL doesn't have conditions, so we need to create our own type." name lock active) (defun make-condition-variable (&key name) (make-condition-var :lock (make-lock) :name (or name "Anonymous condition variable"))) (defun condition-wait (condition-variable lock &key timeout) (signal-error-if-condition-wait-timeout timeout) (check-type condition-variable condition-var) (with-lock-held ((condition-var-lock condition-variable)) (setf (condition-var-active condition-variable) nil)) (release-lock lock) (mp:process-wait "Condition Wait" #'(lambda () (condition-var-active condition-variable))) (acquire-lock lock) t) (define-condition-wait-compiler-macro) (defun condition-notify (condition-variable) (check-type condition-variable condition-var) (with-lock-held ((condition-var-lock condition-variable)) (setf (condition-var-active condition-variable) t)) (thread-yield)) (defun thread-yield () (mp:process-yield)) ;;; Timeouts (defmacro with-timeout ((timeout) &body body) (once-only (timeout) `(mp:with-timeout (,timeout (error 'timeout :length ,timeout)) ,@body))) ;;; Introspection/debugging (defun all-threads () (mp:all-processes)) (defun interrupt-thread (thread function &rest args) (flet ((apply-function () (if args (lambda () (apply function args)) function))) (declare (dynamic-extent #'apply-function)) (mp:process-interrupt thread (apply-function)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mp:destroy-process thread)) (defun thread-alive-p (thread) (mp:process-active-p thread)) (defun join-thread (thread) #+#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (mp:process-join thread) #-#.(cl:if (cl:find-symbol (cl:string '#:process-join) :mp) '(and) '(or)) (progn (mp:process-wait (format nil "Waiting for thread ~A to complete" thread) (lambda () (not (mp:process-alive-p thread)))) (let ((return-values (getf (mp:process-property-list thread) 'return-values))) (values-list return-values)))) (mark-supported)
4,919
Common Lisp
.lisp
120
35.741667
82
0.671921
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
401dced616eb76b6e5f8447b9bdb9fda2c7e80c932fdb9a8b087790b34f4fdea
42,657
[ 83872 ]
42,658
impl-mezzano.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-mezzano.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Copyright 2016 Henry Harrington Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'mezzano.supervisor:thread) ;;; Thread Creation (defun %make-thread (function name) (mezzano.supervisor:make-thread function :name name)) (defun current-thread () (mezzano.supervisor:current-thread)) (defun threadp (object) (mezzano.supervisor:threadp object)) (defun thread-name (thread) (mezzano.supervisor:thread-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'mezzano.supervisor:mutex) (defun lock-p (object) (mezzano.supervisor:mutex-p object)) (defun make-lock (&optional name) (mezzano.supervisor:make-mutex name)) (defun acquire-lock (lock &optional (wait-p t)) (mezzano.supervisor:acquire-mutex lock wait-p)) (defun release-lock (lock) (mezzano.supervisor:release-mutex lock)) (defmacro with-lock-held ((place) &body body) `(mezzano.supervisor:with-mutex (,place) ,@body)) (defstruct (recursive-lock (:constructor make-recursive-lock (&optional name &aux (mutex (mezzano.supervisor:make-mutex name))))) mutex (depth 0)) (defun call-with-recursive-lock-held (lock function) (cond ((mezzano.supervisor:mutex-held-p (recursive-lock-mutex lock)) (unwind-protect (progn (incf (recursive-lock-depth lock)) (funcall function)) (decf (recursive-lock-depth lock)))) (t (mezzano.supervisor:with-mutex ((recursive-lock-mutex lock)) (multiple-value-prog1 (funcall function) (assert (zerop (recursive-lock-depth lock)))))))) (defmacro with-recursive-lock-held ((place) &body body) `(call-with-recursive-lock-held ,place (lambda () ,@body))) ;;; Resource contention: condition variables (defun make-condition-variable (&key name) (mezzano.supervisor:make-condition-variable name)) (defun condition-wait (condition-variable lock &key timeout) (mezzano.supervisor:condition-wait condition-variable lock timeout)) (defun condition-notify (condition-variable) (mezzano.supervisor:condition-notify condition-variable)) (defun thread-yield () (mezzano.supervisor:thread-yield)) ;;; Timeouts ;;; Semaphores (deftype semaphore () 'mezzano.sync:semaphore) (defun make-semaphore (&key name (count 0)) (mezzano.sync:make-semaphore :name name :value count)) (defun signal-semaphore (semaphore &key (count 1)) (dotimes (c count) (mezzano.sync:semaphore-up semaphore))) (defun wait-on-semaphore (semaphore &key timeout) (mezzano.supervisor:event-wait-for (semaphore :timeout timeout) (mezzano.sync:semaphore-down semaphore :wait-p nil))) ;;; Introspection/debugging (defun all-threads () (mezzano.supervisor:all-threads)) (defun interrupt-thread (thread function &rest args) (mezzano.supervisor:establish-thread-foothold thread (lambda () (apply function args)))) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (mezzano.supervisor:terminate-thread thread)) (defun thread-alive-p (thread) (not (eql (mezzano.supervisor:thread-state thread) :dead))) (defun join-thread (thread) (signal-error-if-current-thread thread) ;; THREAD-JOIN can return non-lists if the thread was destroyed. (let ((values (mezzano.supervisor:thread-join thread))) (if (listp values) (values-list values) nil))) (mark-supported)
3,581
Common Lisp
.lisp
91
34.714286
85
0.717347
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
076064af85642c7a3fe1c457394a5fdf4cb0ed6049caf1583e4202dcf8e13b6d
42,658
[ 84988 ]
42,659
default-implementations.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/default-implementations.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10; Package: BORDEAUX-THREADS -*- ;;;; The above modeline is required for Genera. Do not change. (in-package #:bordeaux-threads) ;;; Helper macros (defmacro defdfun (name args doc &body body) `(eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp ',name) (defun ,name ,args ,@body)) (setf (documentation ',name 'function) (or (documentation ',name 'function) ,doc)))) (defmacro defdmacro (name args doc &body body) `(eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp ',name) (defmacro ,name ,args ,@body)) (setf (documentation ',name 'function) (or (documentation ',name 'function) ,doc)))) ;;; Thread Creation (defdfun start-multiprocessing () "If the host implementation uses user-level threads, start the scheduler and multiprocessing, otherwise do nothing. It is safe to call repeatedly." nil) (defdfun make-thread (function &key name (initial-bindings *default-special-bindings*)) "Creates and returns a thread named NAME, which will call the function FUNCTION with no arguments: when FUNCTION returns, the thread terminates. NAME defaults to \"Anonymous thread\" if unsupplied. On systems that do not support multi-threading, MAKE-THREAD will signal an error. The interaction between threads and dynamic variables is in some cases complex, and depends on whether the variable has only a global binding (as established by e.g. DEFVAR/DEFPARAMETER/top-level SETQ) or has been bound locally (e.g. with LET or LET*) in the calling thread. - Global bindings are shared between threads: the initial value of a global variable in the new thread will be the same as in the parent, and an assignment to such a variable in any thread will be visible to all threads in which the global binding is visible. - Local bindings, such as the ones introduced by INITIAL-BINDINGS, are local to the thread they are introduced in, except that - Local bindings in the the caller of MAKE-THREAD may or may not be shared with the new thread that it creates: this is implementation-defined. Portable code should not depend on particular behaviour in this case, nor should it assign to such variables without first rebinding them in the new thread." (%make-thread (binding-default-specials function initial-bindings) (or name "Anonymous thread"))) (defdfun %make-thread (function name) "The actual implementation-dependent function that creates threads." (declare (ignore function name)) (error (make-threading-support-error))) (defdfun current-thread () "Returns the thread object for the calling thread. This is the same kind of object as would be returned by MAKE-THREAD." nil) (defdfun threadp (object) "Returns true if object is a thread, otherwise NIL." (declare (ignore object)) nil) (defdfun thread-name (thread) "Returns the name of the thread, as supplied to MAKE-THREAD." (declare (ignore thread)) "Main thread") ;;; Resource contention: locks and recursive locks (defdfun lock-p (object) "Returns T if OBJECT is a lock; returns NIL otherwise." (declare (ignore object)) nil) (defdfun recursive-lock-p (object) "Returns T if OBJECT is a recursive lock; returns NIL otherwise." (declare (ignore object)) nil) (defdfun make-lock (&optional name) "Creates a lock (a mutex) whose name is NAME. If the system does not support multiple threads this will still return some object, but it may not be used for very much." ;; In CLIM-SYS this is a freshly consed list (NIL). I don't know if ;; there's some good reason it should be said structure or that it ;; be freshly consed - EQ comparison of locks? (declare (ignore name)) (list nil)) (defdfun acquire-lock (lock &optional wait-p) "Acquire the lock LOCK for the calling thread. WAIT-P governs what happens if the lock is not available: if WAIT-P is true, the calling thread will wait until the lock is available and then acquire it; if WAIT-P is NIL, ACQUIRE-LOCK will return immediately. ACQUIRE-LOCK returns true if the lock was acquired and NIL otherwise. This specification does not define what happens if a thread attempts to acquire a lock that it already holds. For applications that require locks to be safe when acquired recursively, see instead MAKE-RECURSIVE-LOCK and friends." (declare (ignore lock wait-p)) t) (defdfun release-lock (lock) "Release LOCK. It is an error to call this unless the lock has previously been acquired (and not released) by the same thread. If other threads are waiting for the lock, the ACQUIRE-LOCK call in one of them will now be able to continue. This function has no interesting return value." (declare (ignore lock)) (values)) (defdmacro with-lock-held ((place) &body body) "Evaluates BODY with the lock named by PLACE, the value of which is a lock created by MAKE-LOCK. Before the forms in BODY are evaluated, the lock is acquired as if by using ACQUIRE-LOCK. After the forms in BODY have been evaluated, or if a non-local control transfer is caused (e.g. by THROW or SIGNAL), the lock is released as if by RELEASE-LOCK. Note that if the debugger is entered, it is unspecified whether the lock is released at debugger entry or at debugger exit when execution is restarted." `(when (acquire-lock ,place t) (unwind-protect (locally ,@body) (release-lock ,place)))) (defdfun make-recursive-lock (&optional name) "Create and return a recursive lock whose name is NAME. A recursive lock differs from an ordinary lock in that a thread that already holds the recursive lock can acquire it again without blocking. The thread must then release the lock twice before it becomes available for another thread." (declare (ignore name)) (list nil)) (defdfun acquire-recursive-lock (lock) "As for ACQUIRE-LOCK, but for recursive locks." (declare (ignore lock)) t) (defdfun release-recursive-lock (lock) "Release the recursive LOCK. The lock will only become free after as many Release operations as there have been Acquire operations. See RELEASE-LOCK for other information." (declare (ignore lock)) (values)) (defdmacro with-recursive-lock-held ((place &key timeout) &body body) "Evaluates BODY with the recursive lock named by PLACE, which is a reference to a recursive lock created by MAKE-RECURSIVE-LOCK. See WITH-LOCK-HELD etc etc" (declare (ignore timeout)) `(when (acquire-recursive-lock ,place) (unwind-protect (locally ,@body) (release-recursive-lock ,place)))) ;;; Resource contention: condition variables ;;; A condition variable provides a mechanism for threads to put ;;; themselves to sleep while waiting for the state of something to ;;; change, then to be subsequently woken by another thread which has ;;; changed the state. ;;; ;;; A condition variable must be used in conjunction with a lock to ;;; protect access to the state of the object of interest. The ;;; procedure is as follows: ;;; ;;; Suppose two threads A and B, and some kind of notional event ;;; channel C. A is consuming events in C, and B is producing them. ;;; CV is a condition-variable ;;; ;;; 1) A acquires the lock that safeguards access to C ;;; 2) A threads and removes all events that are available in C ;;; 3) When C is empty, A calls CONDITION-WAIT, which atomically ;;; releases the lock and puts A to sleep on CV ;;; 4) Wait to be notified; CONDITION-WAIT will acquire the lock again ;;; before returning ;;; 5) Loop back to step 2, for as long as threading should continue ;;; ;;; When B generates an event E, it ;;; 1) acquires the lock guarding C ;;; 2) adds E to the channel ;;; 3) calls CONDITION-NOTIFY on CV to wake any sleeping thread ;;; 4) releases the lock ;;; ;;; To avoid the "lost wakeup" problem, the implementation must ;;; guarantee that CONDITION-WAIT in thread A atomically releases the ;;; lock and sleeps. If this is not guaranteed there is the ;;; possibility that thread B can add an event and call ;;; CONDITION-NOTIFY between the lock release and the sleep - in this ;;; case the notify call would not see A, which would be left sleeping ;;; despite there being an event available. (defdfun thread-yield () "Allows other threads to run. It may be necessary or desirable to call this periodically in some implementations; others may schedule threads automatically. On systems that do not support multi-threading, this does nothing." (values)) (defdfun make-condition-variable (&key name) "Returns a new condition-variable object for use with CONDITION-WAIT and CONDITION-NOTIFY." (declare (ignore name)) nil) (defdfun condition-wait (condition-variable lock &key timeout) "Atomically release LOCK and enqueue the calling thread waiting for CONDITION-VARIABLE. The thread will resume when another thread has notified it using CONDITION-NOTIFY; it may also resume if interrupted by some external event or in other implementation-dependent circumstances: the caller must always test on waking that there is threading to be done, instead of assuming that it can go ahead. It is an error to call function this unless from the thread that holds LOCK. If TIMEOUT is nil or not provided, the system always reacquires LOCK before returning to the caller. In this case T is returned. If TIMEOUT is non-nil, the call will return after at most TIMEOUT seconds (approximately), whether or not a notification has occurred. Either NIL or T will be returned. A return of NIL indicates that the lock is no longer held and that the timeout has expired. A return of T indicates that the lock is held, in which case the timeout may or may not have expired. **NOTE**: The behavior of CONDITION-WAIT with TIMEOUT diverges from the POSIX function pthread_cond_timedwait. The former may return without the lock being held while the latter always returns with the lock held. In an implementation that does not support multiple threads, this function signals an error." (declare (ignore condition-variable lock timeout)) (error (make-threading-support-error))) (defdfun condition-notify (condition-variable) "Notify at least one of the threads waiting for CONDITION-VARIABLE. It is implementation-dependent whether one or more than one (and possibly all) threads are woken, but if the implementation is capable of waking only a single thread (not all are) this is probably preferable for efficiency reasons. The order of wakeup is unspecified and does not necessarily relate to the order that the threads went to sleep in. CONDITION-NOTIFY has no useful return value. In an implementation that does not support multiple threads, it has no effect." (declare (ignore condition-variable)) (values)) ;;; Resource contention: semaphores (defdfun make-semaphore (&key name (count 0)) "Create a semaphore with the supplied NAME and initial counter value COUNT." (make-%semaphore :lock (make-lock name) :condition-variable (make-condition-variable :name name) :counter count)) (defdfun signal-semaphore (semaphore &key (count 1)) "Increment SEMAPHORE by COUNT. If there are threads waiting on this semaphore, then COUNT of them are woken up." (with-lock-held ((%semaphore-lock semaphore)) (incf (%semaphore-counter semaphore) count) (dotimes (v count) (condition-notify (%semaphore-condition-variable semaphore)))) (values)) (defdfun wait-on-semaphore (semaphore &key timeout) "Decrement the count of SEMAPHORE by 1 if the count would not be negative. Else blocks until the semaphore can be decremented. Returns generalized boolean T on success. If TIMEOUT is given, it is the maximum number of seconds to wait. If the count cannot be decremented in that time, returns NIL without decrementing the count." (with-lock-held ((%semaphore-lock semaphore)) (if (>= (%semaphore-counter semaphore) 1) (decf (%semaphore-counter semaphore)) (let ((deadline (when timeout (+ (get-internal-real-time) (* timeout internal-time-units-per-second))))) ;; we need this loop because of a spurious wakeup possibility (loop until (>= (%semaphore-counter semaphore) 1) do (cond ((null (condition-wait (%semaphore-condition-variable semaphore) (%semaphore-lock semaphore) :timeout timeout)) (return-from wait-on-semaphore)) ;; unfortunately cv-wait may return T on timeout too ((and deadline (>= (get-internal-real-time) deadline)) (return-from wait-on-semaphore)) (timeout (setf timeout (/ (- deadline (get-internal-real-time)) internal-time-units-per-second))))) (decf (%semaphore-counter semaphore)))))) (defdfun semaphore-p (object) "Returns T if OBJECT is a semaphore; returns NIL otherwise." (typep object 'semaphore)) ;;; Introspection/debugging ;;; The following functions may be provided for debugging purposes, ;;; but are not advised to be called from normal user code. (defdfun all-threads () "Returns a sequence of all of the threads. This may not be freshly-allocated, so the caller should not modify it." (error (make-threading-support-error))) (defdfun interrupt-thread (thread function) "Interrupt THREAD and cause it to evaluate FUNCTION before continuing with the interrupted path of execution. This may not be a good idea if THREAD is holding locks or doing anything important. On systems that do not support multiple threads, this function signals an error." (declare (ignore thread function)) (error (make-threading-support-error))) (defdfun destroy-thread (thread) "Terminates the thread THREAD, which is an object as returned by MAKE-THREAD. This should be used with caution: it is implementation-defined whether the thread runs cleanup forms or releases its locks first. Destroying the calling thread is an error." (declare (ignore thread)) (error (make-threading-support-error))) (defdfun thread-alive-p (thread) "Returns true if THREAD is alive, that is, if DESTROY-THREAD has not been called on it." (declare (ignore thread)) (error (make-threading-support-error))) (defdfun join-thread (thread) "Wait until THREAD terminates. If THREAD has already terminated, return immediately. The return values of the thread function are returned." (declare (ignore thread)) (error (make-threading-support-error)))
14,854
Common Lisp
.lisp
305
44.44918
86
0.737648
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e3705fa7611639bafad202a3e1136f8fb389d78b713fdb0f55f819fbe34b0243
42,659
[ 228690 ]
42,660
impl-mcl.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/bordeaux-threads-v0.8.8/src/impl-mcl.lisp
;;;; -*- indent-tabs-mode: nil -*- #| Copyright 2006, 2007 Greg Pfeil Distributed under the MIT license (see LICENSE file) |# (in-package #:bordeaux-threads) (deftype thread () 'ccl::process) ;;; Thread Creation (defun %make-thread (function name) (ccl:process-run-function name function)) (defun current-thread () ccl:*current-process*) (defun threadp (object) (ccl::processp object)) (defun thread-name (thread) (ccl:process-name thread)) ;;; Resource contention: locks and recursive locks (deftype lock () 'ccl:lock) (defun lock-p (object) (typep object 'ccl:lock)) (defun make-lock (&optional name) (ccl:make-lock (or name "Anonymous lock"))) (defun acquire-lock (lock &optional (wait-p t)) (if wait-p (ccl:process-lock lock ccl:*current-process*) ;; this is broken, but it's better than a no-op (ccl:without-interrupts (when (null (ccl::lock.value lock)) (ccl:process-lock lock ccl:*current-process*))))) (defun release-lock (lock) (ccl:process-unlock lock)) (defmacro with-lock-held ((place) &body body) `(ccl:with-lock-grabbed (,place) ,@body)) (defun thread-yield () (ccl:process-allow-schedule)) ;;; Introspection/debugging (defun all-threads () ccl:*all-processes*) (defun interrupt-thread (thread function &rest args) (declare (dynamic-extent args)) (apply #'ccl:process-interrupt thread function args)) (defun destroy-thread (thread) (signal-error-if-current-thread thread) (ccl:process-kill thread)) (mark-supported)
1,508
Common Lisp
.lisp
46
30.086957
56
0.722917
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
78016f5c728e429badcbd00b9c5ae16bf2c657c864ff97460c51160bc5113b2d
42,660
[ 323536 ]
42,661
encoding.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/encoding.lisp
(in-package :cl-user) (defpackage dexador.encoding (:use :cl) (:import-from :babel :list-character-encodings :*default-character-encoding*) (:import-from :ppcre :scan-to-strings) (:export :detect-charset)) (in-package :dexador.encoding) (defun parse-content-type (content-type) (let ((types (nth-value 1 (ppcre:scan-to-strings "^\\s*?(\\w+)/([^;\\s]+)(?:\\s*;\\s*charset=([A-Za-z0-9_-]+))?" content-type)))) (when types (values (aref types 0) (aref types 1) (aref types 2))))) (defun charset-to-encoding (charset &optional (default babel:*default-character-encoding*)) (cond ((null charset) default) ((string-equal charset "utf-8") :utf-8) ((string-equal charset "euc-jp") :eucjp) ((or (string-equal charset "shift_jis") (string-equal charset "shift-jis")) :cp932) ((string-equal charset "windows-31j") :cp932) (t (or (find charset (babel:list-character-encodings) :test #'string-equal) default)))) (defun detect-charset (content-type body) (multiple-value-bind (type subtype charset) (parse-content-type content-type) (cond ((charset-to-encoding charset nil)) ((string-equal type "text") (or (charset-to-encoding charset nil) (if (and (string-equal subtype "html") (typep body '(array (unsigned-byte 8) (*)))) (charset-to-encoding (detect-charset-from-html body) nil) nil) :utf-8)) ((and (string-equal type "application") (string-equal subtype "json")) ;; According to RFC4627 (http://www.ietf.org/rfc/rfc4627.txt), ;; JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. ;; It's possible to determine if the encoding is UTF-16 or UTF-36 ;; by looking at the first four octets, however, I leave it to the future. (charset-to-encoding charset :utf-8)) ((and (string-equal type "application") (ppcre:scan "(?:[^+]+\\+)?xml" subtype)) (charset-to-encoding charset))))) (defun detect-charset-from-html (body) "Detect the body's charset by (roughly) searching meta tags which has \"charset\" attribute." (labels ((find-meta (start) (search #.(babel:string-to-octets "<meta ") body :start2 start)) (main (start) (let ((start (find-meta start))) (unless start (return-from main nil)) (let ((end (position (char-code #\>) body :start start :test #'=))) (unless end (return-from main nil)) (incf end) (let ((match (nth-value 1 (ppcre:scan-to-strings "charset=[\"']?([^\\s\"'>]+)[\"']?" (babel:octets-to-string body :start start :end end :errorp nil))))) (if match (aref match 0) (main end))))))) (main 0)))
3,213
Common Lisp
.lisp
77
30.376623
111
0.533844
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
cf00cc24dfcc19456e97db048c6725453b59edf49e6a08d2a5c20dc1663c4c30
42,661
[ 360574 ]
42,662
dexador.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/dexador.lisp
(in-package :cl-user) (uiop:define-package dexador (:nicknames :dex) (:use :cl #-windows #:dexador.backend.usocket #+windows #:dexador.backend.winhttp) (:shadow :get :delete) (:import-from :dexador.connection-cache :*connection-pool* :*use-connection-pool* :make-connection-pool :clear-connection-pool) (:import-from :dexador.util :*default-connect-timeout* :*default-read-timeout* :*default-proxy* :*verbose* :*not-verify-ssl*) (:import-from :alexandria :copy-stream :remove-from-plist) (:export :request :get :post :head :put :patch :delete :fetch :*default-connect-timeout* :*default-read-timeout* :*default-proxy* :*verbose* :*not-verify-ssl* :*connection-pool* :*use-connection-pool* :make-connection-pool :clear-connection-pool ;; Restarts :retry-request :ignore-and-continue) (:use-reexport :dexador.error)) (in-package :dexador) (defun get (uri &rest args &key version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout max-redirects force-binary force-string want-stream content ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) "Make a GET request to URI and return (values body-or-stream status response-headers uri &optional opaque-socket-stream) You may pass a real stream in as STREAM if you want us to communicate with the server via it -- though if any errors occur, we will open a new connection to the server. If you have a previous OPAQUE-SOCKET-STREAM you can pass that in as STREAM as well and we will re-use that connection. OPAQUE-SOCKET-STREAM is not returned if USE-CONNECTION-POOL is T, instead we keep track of it and re-use it when needed. If WANT-STREAM is T, then a STREAM is returned as the first value. You may read this as needed to get the body of the response. If KEEP-ALIVE and USE-CONNECTION-POOL are T, then the stream will be returned to the connection pool when you have read all the data or closed the stream. If KEEP-ALIVE is NIL then you are responsible for closing the stream when done. If KEEP-ALIVE is T and USE-CONNECTION-POOL is NIL, then the fifth value returned is a stream which you can then pass in again using the STREAM option to re-use the active connection. If you ignore the stream, it will get closed during garbage collection. If KEEP-ALIVE is T and USE-CONNECTION-POOL is T, then there is no fifth value (OPAQUE-SOCKET-STREAM) returned, but the active connection to the host/port may be reused in subsequent calls. This removes the need for the caller to keep track of the active socket-stream for subsequent calls. While CONTENT is allowed in a GET request the results are ill-defined and not advised." (declare (ignore version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout max-redirects force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path content)) (apply #'request uri :method :get args)) (defun post (uri &rest args &key version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path)) (apply #'request uri :method :post args)) (defun head (uri &rest args &key version headers basic-auth cookie-jar connect-timeout read-timeout max-redirects ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version headers basic-auth cookie-jar connect-timeout read-timeout max-redirects ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path)) (apply #'request uri :method :head :use-connection-pool nil args)) (defun put (uri &rest args &key version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path)) (apply #'request uri :method :put args)) (defun patch (uri &rest args &key version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version content headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path)) (apply #'request uri :method :patch args)) (defun delete (uri &rest args &key version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream content ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout force-binary force-string want-stream ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path content)) (apply #'request uri :method :delete args)) (defun fetch (uri destination &rest args &key (if-exists :error) version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout max-redirects ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path) (declare (ignore version headers basic-auth cookie-jar keep-alive use-connection-pool connect-timeout read-timeout max-redirects ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy insecure ca-path)) (unless (and (eql if-exists nil) (probe-file destination)) (with-open-file (out destination :direction :output :element-type '(unsigned-byte 8) :if-exists if-exists :if-does-not-exist :create) (let ((body (apply #'dex:get uri :want-stream t :force-binary t (remove-from-plist args :if-exists)))) (alexandria:copy-stream body out) ;; Nominally the body gets closed, but if keep-alive is nil we need to explicitly do it. (when (open-stream-p body) (close body)))))) (defun ignore-and-continue (e) (let ((restart (find-restart 'ignore-and-continue e))) (when restart (invoke-restart restart)))) (defun retry-request (times &key (interval 3)) (declare (type (or function integer) interval)) (etypecase times (condition (let ((restart (find-restart 'retry-request times))) (when restart (invoke-restart restart)))) (integer (retry-request-ntimes times :interval interval)))) (defun retry-request-ntimes (n &key (interval 3)) (declare (type integer n) (type (or function integer) interval)) (let ((retries 0)) (declare (type integer retries)) (lambda (e) (declare (type condition e)) (let ((restart (find-restart 'retry-request e))) (when restart (when (< retries n) (incf retries) (etypecase interval (function (funcall interval retries)) (integer (sleep interval))) (invoke-restart restart)))))))
8,488
Common Lisp
.lisp
143
50.363636
260
0.690322
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
84b5705959da776b5af9b416490c683bab4ce553c310b790f501569f6df333f2
42,662
[ -1 ]
42,663
util.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/util.lisp
(in-package :cl-user) (defpackage dexador.util (:use :cl) (:import-from :fast-io :with-fast-output :fast-write-byte :fast-write-sequence) (:import-from :quri :uri-path :uri-query :uri-host :uri-port :render-uri) (:export :*default-connect-timeout* :*default-read-timeout* :*verbose* :*default-proxy* :*not-verify-ssl* :defun-speedy :defun-careful :octets :ascii-string-to-octets :+crlf+ :*default-user-agent* :write-first-line :write-header :with-header-output :write-connect-header :make-random-string)) (in-package :dexador.util) (defvar *default-connect-timeout* 10) (defvar *default-read-timeout* 10) (defvar *verbose* nil) (defvar *not-verify-ssl* nil) (defvar *default-proxy* (or #-windows (uiop:getenv "HTTPS_PROXY") #-windows (uiop:getenv "HTTP_PROXY")) "If specified will be used as the default value of PROXY in calls to dexador. Defaults to the value of the environment variable HTTPS_PROXY or HTTP_PROXY if not on Windows.") (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *speedy-declaration* '(declare (optimize (speed 3) (safety 0) (space 0) (compilation-speed 0)))) (defvar *careful-declaration* '(declare (optimize (speed 3) (safety 2))))) (defmacro defun-speedy (name lambda-list &body body) `(progn (declaim (notinline ,name)) (defun ,name ,lambda-list ,*speedy-declaration* ,@body))) (defmacro defun-careful (name lambda-list &body body) `(progn (declaim (notinline ,name)) (defun ,name ,lambda-list ,*careful-declaration* ,@body))) (deftype octets (&optional (len '*)) `(simple-array (unsigned-byte 8) (,len))) (declaim (ftype (function (simple-string) octets) ascii-string-to-octets)) (eval-when (:compile-toplevel :load-toplevel :execute) (defun-speedy %ascii-string-to-octets (string) (let ((result (make-array (length string) :element-type '(unsigned-byte 8)))) (declare (type octets result)) (dotimes (i (length string) result) (declare (type fixnum i)) (setf (aref result i) (char-code (aref string i)))))) (defun-speedy ascii-string-to-octets (string) (%ascii-string-to-octets string)) (define-compiler-macro ascii-string-to-octets (&whole form string) (if (constantp string) (%ascii-string-to-octets string) form)) (declaim (type octets +crlf+)) (defvar +crlf+ (ascii-string-to-octets (format nil "~C~C" #\Return #\Newline)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *dexador-version* (asdf:component-version (asdf:find-system :dexador))) (defparameter *default-user-agent* (format nil "Dexador/~A (~A~@[ ~A~]); ~A;~@[ ~A~]" *dexador-version* (or (lisp-implementation-type) "Common Lisp") (or (lisp-implementation-version) "") (or #-clisp (software-type) #+(or win32 mswindows) "Windows" #-(or win32 mswindows) "Unix") (or #-clisp (software-version))))) (defparameter *header-buffer* nil) (defun write-first-line (method uri version &optional (buffer *header-buffer*)) (fast-write-sequence (ascii-string-to-octets (string method)) buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ascii-string-to-octets (format nil "~A~:[~;~:*?~A~]" (or (uri-path uri) "/") (uri-query uri))) buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ecase version (1.1 (ascii-string-to-octets "HTTP/1.1")) (1.0 (ascii-string-to-octets "HTTP/1.0"))) buffer) (fast-write-sequence +crlf+ buffer)) (defun write-header-field (name buffer) (fast-write-sequence (if (typep name 'octets) name (ascii-string-to-octets (string-capitalize name))) buffer)) (defun write-header-value (value buffer) (fast-write-sequence (if (typep value 'octets) value (ascii-string-to-octets (princ-to-string value))) buffer)) (defun write-header (name value &optional (buffer *header-buffer*)) (write-header-field name buffer) (fast-write-sequence (ascii-string-to-octets ": ") buffer) (write-header-value value buffer) (fast-write-sequence +crlf+ buffer)) (define-compiler-macro write-header (name value &optional (buffer '*header-buffer*)) `(progn ,(if (and (constantp name) (typep name '(or keyword string))) `(fast-write-sequence (ascii-string-to-octets ,(string-capitalize name)) ,buffer) `(write-header-field ,name ,buffer)) (fast-write-sequence (ascii-string-to-octets ": ") ,buffer) ,(if (constantp value) `(fast-write-sequence (ascii-string-to-octets ,(string value)) ,buffer) `(write-header-value ,value ,buffer)) (fast-write-sequence +crlf+ ,buffer))) (defmacro with-header-output ((buffer &optional output) &body body) `(with-fast-output (,buffer ,output) (declare (ignorable ,buffer)) (let ((*header-buffer* ,buffer)) ,@body))) (defun write-connect-header (uri version buffer &optional proxy-auth) (fast-write-sequence (ascii-string-to-octets "CONNECT") buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ascii-string-to-octets (format nil "~A:~A" (uri-host uri) (uri-port uri))) buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ecase version (1.1 (ascii-string-to-octets "HTTP/1.1")) (1.0 (ascii-string-to-octets "HTTP/1.0"))) buffer) (fast-write-sequence +crlf+ buffer) (fast-write-sequence (ascii-string-to-octets "Host:") buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ascii-string-to-octets (format nil "~A:~A" (uri-host uri) (uri-port uri))) buffer) (when proxy-auth (fast-write-sequence +crlf+ buffer) (fast-write-sequence (ascii-string-to-octets "Proxy-Authorization:") buffer) (fast-write-byte #.(char-code #\Space) buffer) (fast-write-sequence (ascii-string-to-octets proxy-auth) buffer)) (fast-write-sequence +crlf+ buffer) (fast-write-sequence +crlf+ buffer)) (defun-speedy make-random-string (&optional (length 12)) (declare (type fixnum length)) (let ((result (make-string length))) (declare (type simple-string result)) (dotimes (i length result) (setf (aref result i) (ecase (random 5) ((0 1) (code-char (+ #.(char-code #\a) (random 26)))) ((2 3) (code-char (+ #.(char-code #\A) (random 26)))) ((4) (code-char (+ #.(char-code #\0) (random 10)))))))))
7,444
Common Lisp
.lisp
165
35
106
0.585756
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a3df0726df9686219b542fa4f0949684a96ccd9f510221243e3a8d512754bd07
42,663
[ -1 ]
42,664
error.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/error.lisp
(in-package :cl-user) (defpackage dexador.error (:use :cl) (:import-from :quri :render-uri) (:export :http-request-failed ;; 4xx :http-request-bad-request :http-request-unauthorized :http-request-payment-required :http-request-forbidden :http-request-not-found :http-request-method-not-allowed :http-request-not-acceptable :http-request-proxy-authentication-required :http-request-request-timeout :http-request-conflict :http-request-gone :http-request-length-required :http-request-precondition-failed :http-request-payload-too-large :http-request-uri-too-long :http-request-unsupported-media-type :http-request-range-not-satisfiable :http-request-expectation-failed :http-request-misdirected-request :http-request-upgrade-required :http-request-too-many-requests ;; 5xx :http-request-internal-server-error :http-request-not-implemented :http-request-bad-gateway :http-request-service-unavailable :http-request-gateway-timeout :http-request-http-version-not-supported ;; accessors :response-body :response-status :response-headers :request-uri :request-method ;; Proxy errors :socks5-proxy-request-failed)) (in-package :dexador.error) (define-condition http-request-failed (error) ((body :initarg :body :reader response-body) (status :initarg :status :reader response-status) (headers :initarg :headers :reader response-headers) (uri :initarg :uri :reader request-uri) (method :initarg :method :reader request-method)) (:report (lambda (condition stream) (with-slots (uri status) condition (format stream "An HTTP request to ~S has failed (status=~D)." (quri:render-uri uri) status))))) (defmacro define-request-failed-condition (name code) `(define-condition ,(intern (format nil "~A-~A" :http-request name)) (http-request-failed) () (:report (lambda (condition stream) (with-slots (body uri) condition (format stream ,(format nil "An HTTP request to ~~S returned ~D ~A.~~2%~~A" code (substitute #\Space #\- (string-downcase name))) (quri:render-uri uri) body)))))) (defvar *request-failed-error* (make-hash-table :test 'eql)) #.`(progn ,@(loop for (name . code) in '(;; 4xx (Client Errors) (bad-request . 400) (unauthorized . 401) (payment-required . 402) (forbidden . 403) (not-found . 404) (method-not-allowed . 405) (not-acceptable . 406) (proxy-authentication-required . 407) (request-timeout . 408) (conflict . 409) (gone . 410) (length-required . 411) (precondition-failed . 412) (payload-too-large . 413) (uri-too-long . 414) (unsupported-media-type . 415) (range-not-satisfiable . 416) (expectation-failed . 417) (misdirected-request . 421) (upgrade-required . 426) (too-many-requests . 429) ;; 5xx (Server Errors) (internal-server-error . 500) (not-implemented . 501) (bad-gateway . 502) (service-unavailable . 503) (gateway-timeout . 504) (http-version-not-supported . 505)) collect `(define-request-failed-condition ,name ,code) collect `(setf (gethash ,code *request-failed-error*) ',(intern (format nil "~A-~A" :http-request name))))) (defun http-request-failed (status &key body headers uri method) (error (gethash status *request-failed-error* 'http-request-failed) :body body :status status :headers headers :uri uri :method method)) (define-condition socks5-proxy-request-failed (http-request-failed) ((reason :initarg :reason)) (:report (lambda (condition stream) (with-slots (uri reason) condition (format stream "An HTTP request to ~S via SOCKS5 has failed (reason=~S)." (quri:render-uri uri) reason)))))
5,721
Common Lisp
.lisp
118
30.90678
93
0.458952
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
3f080bb69b29afcb7750c8d4e4a272404261c3371711d8a08df031b28c69a8da
42,664
[ -1 ]
42,665
body.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/body.lisp
(defpackage #:dexador.body (:use #:cl) (:import-from #:dexador.encoding #:detect-charset) (:import-from #:dexador.decoding-stream #:make-decoding-stream) (:import-from #:dexador.util #:ascii-string-to-octets #:+crlf+) (:import-from #:babel #:octets-to-string #:character-decoding-error) (:import-from #:babel-encodings #:*suppress-character-coding-errors*) (:import-from :trivial-mimes :mime) (:import-from #:quri #:url-encode) (:import-from #:chipz #:make-decompressing-stream #:decompress #:make-dstate) (:export #:decode-body #:write-multipart-content #:decompress-body)) (in-package #:dexador.body) (defun decode-body (content-type body &key default-charset on-close) (let ((charset (or (and content-type (detect-charset content-type body)) default-charset)) (babel-encodings:*suppress-character-coding-errors* t)) (if charset (handler-case (if (streamp body) (make-decoding-stream body :encoding charset :on-close on-close) (babel:octets-to-string body :encoding charset)) (babel:character-decoding-error (e) (warn (format nil "Failed to decode the body to ~S due to the following error (falling back to binary):~% ~A" charset e)) (return-from decode-body body))) body))) (defun content-disposition (key val) (if (pathnamep val) (let* ((filename (file-namestring val)) (utf8-filename-p (find-if (lambda (char) (< 127 (char-code char))) filename))) (format nil "Content-Disposition: form-data; name=\"~A\"; ~:[filename=\"~A\"~;filename*=UTF-8''~A~]~C~C" key utf8-filename-p (if utf8-filename-p (url-encode filename :encoding :utf-8) filename) #\Return #\Newline)) (format nil "Content-Disposition: form-data; name=\"~A\"~C~C" key #\Return #\Newline))) (defun write-multipart-content (content boundary stream) (let ((boundary (ascii-string-to-octets boundary))) (labels ((boundary-line (&optional endp) (write-sequence (ascii-string-to-octets "--") stream) (write-sequence boundary stream) (when endp (write-sequence (ascii-string-to-octets "--") stream)) (crlf)) (crlf () (write-sequence +crlf+ stream))) (loop for (key . val) in content do (boundary-line) (write-sequence (ascii-string-to-octets (content-disposition key val)) stream) (when (pathnamep val) (write-sequence (ascii-string-to-octets (format nil "Content-Type: ~A~C~C" (mimes:mime val) #\Return #\Newline)) stream)) (crlf) (typecase val (pathname (let ((buf (make-array 1024 :element-type '(unsigned-byte 8)))) (with-open-file (in val :element-type '(unsigned-byte 8)) (loop for n of-type fixnum = (read-sequence buf in) until (zerop n) do (write-sequence buf stream :end n))))) (string (write-sequence (babel:string-to-octets val) stream)) (otherwise (write-sequence (babel:string-to-octets (princ-to-string val)) stream))) (crlf) finally (boundary-line t))))) (defun decompress-body (content-encoding body) (unless content-encoding (return-from decompress-body body)) (cond ((string= content-encoding "gzip") (if (streamp body) (chipz:make-decompressing-stream :gzip body) (chipz:decompress nil (chipz:make-dstate :gzip) body))) ((string= content-encoding "deflate") (if (streamp body) (chipz:make-decompressing-stream :zlib body) (chipz:decompress nil (chipz:make-dstate :zlib) body))) (t body)))
4,455
Common Lisp
.lisp
102
30.068627
122
0.528749
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
85c48df59e6d2afed5b57de8e7d9d6c0622a589bdf1dd08c96d16c6944ecd23b
42,665
[ -1 ]
42,666
decoding-stream.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/decoding-stream.lisp
(in-package :cl-user) (defpackage dexador.decoding-stream (:use :cl) (:import-from :trivial-gray-streams :fundamental-character-input-stream :stream-read-char :stream-unread-char :stream-read-byte :stream-read-sequence) (:import-from :babel :*string-vector-mappings* :unicode-char) (:import-from :babel-encodings :*default-character-encoding* :get-character-encoding :code-point-counter :enc-max-units-per-char :lookup-mapping) (:export :make-decoding-stream :decoding-stream) (:documentation "Provides character decoding stream. Similar to flexi-input-stream, except this uses Babel for decoding.")) (in-package :dexador.decoding-stream) (declaim (type fixnum +buffer-size+)) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +buffer-size+ 128)) (defclass decoding-stream (fundamental-character-input-stream) ((stream :type stream :initarg :stream :initform (error ":stream is required") :accessor decoding-stream-stream) (encoding :initarg :encoding :initform (error ":encoding is required") :accessor decoding-stream-encoding) (buffer :type (simple-array (unsigned-byte 8) (#.+buffer-size+)) :initform (make-array +buffer-size+ :element-type '(unsigned-byte 8)) :accessor decoding-stream-buffer) (buffer-position :type fixnum :initform +buffer-size+ :accessor decoding-stream-buffer-position) (buffer-end-position :type fixnum :initform -1 :accessor decoding-stream-buffer-end-position) (last-char :type character :initform #\Nul :accessor decoding-stream-last-char) (last-char-size :type fixnum :initform 0 :accessor decoding-stream-last-char-size) (on-close :type (or null function) :initform nil :initarg :on-close))) (defmethod initialize-instance :after ((stream decoding-stream) &rest initargs) (declare (ignore initargs)) (with-slots (encoding) stream (when (keywordp encoding) (setf encoding (get-character-encoding encoding))))) (defun make-decoding-stream (stream &key (encoding babel-encodings:*default-character-encoding*) (on-close)) (let ((decoding-stream (make-instance 'decoding-stream :stream stream :encoding encoding :on-close on-close))) (fill-buffer decoding-stream) decoding-stream)) (defun fill-buffer (stream) (declare (optimize speed)) (with-slots (stream buffer buffer-position buffer-end-position) stream (declare (type (simple-array (unsigned-byte 8) (#.+buffer-size+)) buffer) (type fixnum buffer-position)) (let ((to-read (- +buffer-size+ buffer-position))) (declare (type fixnum to-read)) (replace buffer buffer :start1 0 :start2 buffer-position :end2 +buffer-size+) (setf buffer-position 0) (let ((n (read-sequence buffer stream :start to-read))) (declare (type fixnum n)) (unless (= n +buffer-size+) (setf buffer-end-position n)))))) (defun needs-to-fill-buffer-p (stream) (declare (optimize speed)) (when (/= -1 (the fixnum (decoding-stream-buffer-end-position stream))) (return-from needs-to-fill-buffer-p nil)) (with-slots (buffer-position encoding) stream (< (- +buffer-size+ (the fixnum buffer-position)) (the fixnum (enc-max-units-per-char encoding))))) (defmethod stream-read-char ((stream decoding-stream)) (declare (optimize speed)) (when (needs-to-fill-buffer-p stream) (fill-buffer stream)) (when (= (the fixnum (decoding-stream-buffer-end-position stream)) (the fixnum (decoding-stream-buffer-position stream))) (return-from stream-read-char :eof)) (with-slots (buffer buffer-position encoding last-char last-char-size) stream (declare (fixnum buffer-position)) (let* ((mapping (lookup-mapping *string-vector-mappings* encoding)) (counter (code-point-counter mapping))) (declare (type function counter)) (multiple-value-bind (chars new-end) (funcall counter buffer buffer-position +buffer-size+ 1) (declare (ignore chars) (fixnum new-end)) (let ((string (make-string 1 :element-type 'babel:unicode-char)) (size (the fixnum (- new-end buffer-position)))) (funcall (the function (babel-encodings:decoder mapping)) buffer buffer-position new-end string 0) (setf buffer-position new-end last-char (aref string 0) last-char-size size) (aref string 0)))))) (defmethod stream-unread-char ((stream decoding-stream) char) (let ((last-char (decoding-stream-last-char stream))) (when (char= last-char #\Nul) (error "No character to unread from this stream")) (unless (char= char last-char) (error "Last character read (~S) was different from ~S" last-char char)) (with-slots (buffer-position last-char-size) stream (decf buffer-position last-char-size)) (with-slots (last-char last-char-size) stream (setf last-char #\Nul last-char-size 0)) nil)) #+(or abcl clasp ecl) (defmethod stream-read-sequence ((stream decoding-stream) sequence start end &key) (loop for i from start to end for char = (stream-read-char stream) if (eq char :eof) do (return i) else do (setf (aref sequence i) char) finally (return end))) #+(or clasp ecl) (defmethod stream-read-byte ((stream decoding-stream)) (with-slots (last-char last-char-size) stream (setf last-char #\Nul last-char-size 0)) (read-byte (decoding-stream-stream stream) nil :eof)) (defmethod open-stream-p ((stream decoding-stream)) (open-stream-p (decoding-stream-stream stream))) (defmethod stream-element-type ((stream decoding-stream)) 'unicode-char) (defmethod close ((stream decoding-stream) &key abort) ;; TODO: modify me to return the connection to the connection pool (with-slots (stream) stream (when (open-stream-p stream) (close stream :abort abort))))
6,514
Common Lisp
.lisp
146
35.739726
96
0.635548
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
f92edd8e34124937252ee1cc0b828b52d5d6953570dc50cd5470444340d54ae8
42,666
[ -1 ]
42,667
keep-alive-stream.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/keep-alive-stream.lisp
(in-package :cl-user) (defpackage dexador.keep-alive-stream (:use :cl) (:import-from :trivial-gray-streams :fundamental-input-stream :stream-read-byte :stream-read-sequence :stream-element-type :open-stream-p) (:import-from :alexandria :xor) (:export :make-keep-alive-stream :keep-alive-stream :keep-alive-chunked-stream :keep-alive-stream-close-underlying-stream :keep-alive-stream-stream)) (in-package :dexador.keep-alive-stream) (defclass keep-alive-stream (fundamental-input-stream) ((stream :type (or null stream) :initarg :stream :initform (error ":stream is required") :accessor keep-alive-stream-stream :documentation "A stream; when we read END elements from it, we call CLOSE-ACTION on it and set this slot to nil.") (end :initarg :end :initform nil :accessor keep-alive-stream-end) (close-action :initarg :on-close-or-eof :reader close-action :documentation "A (lambda (stream abort)) which will be called with keep-alive-stream-stream when the stream is either closed or we hit end of file or we hit end"))) (defun keep-alive-stream-close-underlying-stream (underlying-stream abort) (when (and underlying-stream (open-stream-p underlying-stream)) (close underlying-stream :abort abort))) (defclass keep-alive-chunked-stream (keep-alive-stream) ((chunga-stream :initarg :chunga-stream :accessor chunga-stream))) (defun make-keep-alive-stream (stream &key end chunked-stream (on-close-or-eof #'keep-alive-stream-close-underlying-stream)) "ON-CLOSE-OR-EOF takes a single parameter, STREAM (the stream passed in here, not the keep-alive-stream), and should handle clean-up of it" (assert (xor end chunked-stream)) (if chunked-stream (make-instance 'keep-alive-chunked-stream :stream stream :chunga-stream chunked-stream :on-close-or-eof on-close-or-eof) (make-instance 'keep-alive-stream :stream stream :end end :on-close-or-eof on-close-or-eof))) (defun maybe-close (stream &optional (close-if nil)) "Will close the underlying stream if close-if is T (unless it is already closed). If the stream is already closed or we closed it returns :EOF otherwise NIL." (let ((underlying-stream (keep-alive-stream-stream stream))) (cond ((not underlying-stream) :eof) (close-if (funcall (close-action stream) underlying-stream nil) (setf (keep-alive-stream-stream stream) nil) :eof) (t nil)))) (defmethod stream-read-byte ((stream keep-alive-stream)) "Return :EOF or byte read. When we hit EOF or finish reading our allowed content, call the close-action on our underlying-stream and return EOF." (let ((byte :eof) (underlying-stream (keep-alive-stream-stream stream))) (or (maybe-close stream (<= (keep-alive-stream-end stream) 0)) (progn (setf byte (read-byte underlying-stream nil :eof)) (decf (keep-alive-stream-end stream) 1) (maybe-close stream (or (<= (keep-alive-stream-end stream) 0) (eql byte :eof))) byte)))) (defmethod stream-read-byte ((stream keep-alive-chunked-stream)) "Return :EOF or byte read. When we hit :EOF or finish reading our chunk, call the close-action on our underlying-stream and return :EOF" (or (maybe-close stream) (if (chunga:chunked-stream-input-chunking-p (chunga-stream stream)) (let ((byte (read-byte (chunga-stream stream) nil :eof))) (if (eql byte :eof) (prog1 byte (maybe-close stream t)) byte)) (or (maybe-close stream t) :eof)))) (defmethod stream-read-sequence ((stream keep-alive-stream) sequence start end &key) (declare (optimize speed)) (if (null (keep-alive-stream-stream stream)) ;; we already closed it start (let* ((to-read (min (- end start) (keep-alive-stream-end stream))) (n (read-sequence sequence (keep-alive-stream-stream stream) :start start :end (+ start to-read)))) (decf (keep-alive-stream-end stream) (- n start)) (maybe-close stream (<= (keep-alive-stream-end stream) 0)) n))) (defmethod stream-read-sequence ((stream keep-alive-chunked-stream) sequence start end &key) (declare (optimize speed)) (if (null (keep-alive-stream-stream stream)) ;; we already closed it start (if (chunga:chunked-stream-input-chunking-p (chunga-stream stream)) (prog1 (let ((num-read (read-sequence sequence (chunga-stream stream) :start start :end end))) num-read) (maybe-close stream (not (chunga:chunked-stream-input-chunking-p (chunga-stream stream))))) start))) (defmethod stream-element-type ((stream keep-alive-chunked-stream)) (stream-element-type (chunga-stream stream))) (defmethod stream-element-type ((stream keep-alive-stream)) '(unsigned-byte 8)) (defmethod open-stream-p ((stream keep-alive-stream)) (let ((underlying-stream (keep-alive-stream-stream stream))) (and underlying-stream (open-stream-p underlying-stream)))) (defmethod close ((stream keep-alive-stream) &key abort) (funcall (close-action stream) (keep-alive-stream-stream stream) abort))
5,415
Common Lisp
.lisp
107
43.009346
126
0.6678
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
51501b38019f018c26a8d8ae3d3ad4042a88407f3873f41555d896e2bd061a31
42,667
[ -1 ]
42,668
usocket.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/backend/usocket.lisp
(in-package :cl-user) (defpackage dexador.backend.usocket (:nicknames :dex.usocket) (:use :cl :dexador.encoding :dexador.util) (:import-from :dexador.connection-cache :steal-connection :push-connection) (:import-from :dexador.decoding-stream :make-decoding-stream) (:import-from :dexador.keep-alive-stream :make-keep-alive-stream) (:import-from :dexador.body :decompress-body :decode-body) (:import-from :dexador.error :http-request-failed :http-request-not-found :socks5-proxy-request-failed) (:import-from :usocket :socket-connect :socket-stream) (:import-from :fast-http :make-http-response :make-parser :http-status :http-headers) (:import-from :fast-io :make-output-buffer :finish-output-buffer :with-fast-output :fast-write-sequence :fast-write-byte) (:import-from :chunga :chunked-stream-input-chunking-p :chunked-stream-output-chunking-p :make-chunked-stream) (:import-from :trivial-mimes :mime) (:import-from :cl-cookie :merge-cookies :parse-set-cookie-header :cookie-jar-host-cookies :write-cookie-header) (:import-from :quri :uri-p :uri-host :uri-port :uri-path :uri-authority :uri-scheme :url-encode :url-encode-params :merge-uris) (:import-from :cl-base64 :string-to-base64-string) #-(or windows dexador-no-ssl) (:import-from :cl+ssl :with-global-context :make-context :make-ssl-client-stream :ensure-initialized :ssl-check-verify-p) (:import-from :alexandria :copy-stream :if-let :when-let :ensure-list :ends-with-subseq) (:import-from :uiop) (:export :request ;; Restarts :retry-request :ignore-and-continue)) (in-package :dexador.backend.usocket) (defparameter *ca-bundle* (uiop:native-namestring (asdf:system-relative-pathname :dexador #P"certs/cacert.pem"))) (defun-speedy read-until-crlf*2 (stream) (with-fast-output (buf) (tagbody read-cr (loop for byte of-type (or (unsigned-byte 8) null) = (read-byte stream nil nil) if byte do (fast-write-byte byte buf) else do (go eof) until (= byte (char-code #\Return))) read-lf (let ((next-byte (read-byte stream nil nil))) (unless next-byte (go eof)) (locally (declare (type (unsigned-byte 8) next-byte)) (cond ((= next-byte (char-code #\Newline)) (fast-write-byte next-byte buf) (go read-cr2)) ((= next-byte (char-code #\Return)) (fast-write-byte next-byte buf) (go read-lf)) (T (fast-write-byte next-byte buf) (go read-cr))))) read-cr2 (let ((next-byte (read-byte stream nil nil))) (unless next-byte (go eof)) (locally (declare (type (unsigned-byte 8) next-byte)) (cond ((= next-byte (char-code #\Return)) (fast-write-byte next-byte buf) (go read-lf2)) (T (fast-write-byte next-byte buf) (go read-cr))))) read-lf2 (let ((next-byte (read-byte stream nil nil))) (unless next-byte (go eof)) (locally (declare (type (unsigned-byte 8) next-byte)) (cond ((= next-byte (char-code #\Newline)) (fast-write-byte next-byte buf)) ((= next-byte (char-code #\Return)) (fast-write-byte next-byte buf) (go read-lf)) (T (fast-write-byte next-byte buf) (go read-cr))))) eof))) (defvar +empty-body+ (make-array 0 :element-type '(unsigned-byte 8))) (defun read-response (stream has-body collect-headers read-body) (let* ((http (make-http-response)) body body-data (headers-data (and collect-headers (make-output-buffer))) (header-finished-p nil) (finishedp nil) (content-length nil) (transfer-encoding-p) (parser (make-parser http :header-callback (lambda (headers) (setq header-finished-p t content-length (gethash "content-length" headers) transfer-encoding-p (gethash "transfer-encoding" headers)) (unless (and has-body (or content-length transfer-encoding-p)) (setq finishedp t))) :body-callback (lambda (data start end) (when body-data (fast-write-sequence data body-data start end))) :finish-callback (lambda () (setq finishedp t))))) (let ((buf (read-until-crlf*2 stream))) (declare (type octets buf)) (when collect-headers (fast-write-sequence buf headers-data)) (funcall parser buf)) (unless header-finished-p (error "maybe invalid header")) (cond ((not read-body) (setq body stream)) ((not has-body) (setq body +empty-body+)) ((and content-length (not transfer-encoding-p)) (let ((buf (make-array (etypecase content-length (integer content-length) (string (parse-integer content-length))) :element-type '(unsigned-byte 8)))) (read-sequence buf stream) (setq body buf))) ((let ((status (http-status http))) (or (= status 100) ;; Continue (= status 101) ;; Switching Protocols (= status 204) ;; No Content (= status 304))) ;; Not Modified (setq body +empty-body+)) (T (setq body-data (make-output-buffer)) (loop for buf of-type octets = (read-until-crlf*2 stream) do (funcall parser buf) until (or finishedp (zerop (length buf))) finally (setq body (finish-output-buffer body-data))))) (values http body (and collect-headers (finish-output-buffer headers-data)) transfer-encoding-p))) (defun print-verbose-data (direction &rest data) (flet ((boundary-line () (let ((char (ecase direction (:incoming #\<) (:outgoing #\>)))) (fresh-line) (dotimes (i 50) (write-char char)) (fresh-line)))) (boundary-line) (dolist (d data) (map nil (lambda (byte) (princ (code-char byte))) d)) (boundary-line))) (defun convert-body (body content-encoding content-type content-length chunkedp force-binary force-string keep-alive-p on-close) (when (streamp body) (cond ((and keep-alive-p chunkedp) (setf body (make-keep-alive-stream body :chunked-stream (let ((chunked-stream (chunga:make-chunked-stream body))) (setf (chunga:chunked-stream-input-chunking-p chunked-stream) t) chunked-stream) :on-close-or-eof on-close))) ((and keep-alive-p content-length) (setf body (make-keep-alive-stream body :end content-length :on-close-or-eof on-close))) (chunkedp (let ((chunked-stream (chunga:make-chunked-stream body))) (setf (chunga:chunked-stream-input-chunking-p chunked-stream) t) (setf body chunked-stream))))) (let ((body (decompress-body content-encoding body))) (if force-binary body (decode-body content-type body :default-charset (if force-string babel:*default-character-encoding* nil))))) (defun content-disposition (key val) (if (pathnamep val) (let* ((filename (file-namestring val)) (utf8-filename-p (find-if (lambda (char) (< 127 (char-code char))) filename))) (format nil "Content-Disposition: form-data; name=\"~A\"; ~:[filename=\"~A\"~;filename*=UTF-8''~A~]~C~C" key utf8-filename-p (if utf8-filename-p (url-encode filename :encoding :utf-8) filename) #\Return #\Newline)) (format nil "Content-Disposition: form-data; name=\"~A\"~C~C" key #\Return #\Newline))) (defun-speedy multipart-content-length (content boundary) (declare (type simple-string boundary)) (let ((boundary-length (length boundary))) (+ (loop for (key . val) in content sum (+ 2 boundary-length 2 (length (the simple-string (content-disposition key val))) (if (pathnamep val) (+ #.(length "Content-Type: ") (length (the simple-string (mimes:mime val))) 2) 0) 2 (typecase val (pathname (with-open-file (in val) (file-length in))) (string (length (the octets (babel:string-to-octets val)))) (symbol (length (the octets (babel:string-to-octets (princ-to-string val))))) (otherwise (length (princ-to-string val)))) 2)) 2 boundary-length 2 2))) (defun write-multipart-content (content boundary stream) (let ((boundary (ascii-string-to-octets boundary))) (labels ((boundary-line (&optional endp) (write-sequence (ascii-string-to-octets "--") stream) (write-sequence boundary stream) (when endp (write-sequence (ascii-string-to-octets "--") stream)) (crlf)) (crlf () (write-sequence +crlf+ stream))) (loop for (key . val) in content do (boundary-line) (write-sequence (ascii-string-to-octets (content-disposition key val)) stream) (when (pathnamep val) (write-sequence (ascii-string-to-octets (format nil "Content-Type: ~A~C~C" (mimes:mime val) #\Return #\Newline)) stream)) (crlf) (typecase val (pathname (let ((buf (make-array 1024 :element-type '(unsigned-byte 8)))) (with-open-file (in val :element-type '(unsigned-byte 8)) (loop for n of-type fixnum = (read-sequence buf in) until (zerop n) do (write-sequence buf stream :end n))))) (string (write-sequence (babel:string-to-octets val) stream)) (otherwise (write-sequence (babel:string-to-octets (princ-to-string val)) stream))) (crlf) finally (boundary-line t))))) (defun build-cookie-headers (uri cookie-jar) (with-header-output (buffer) (let ((cookies (cookie-jar-host-cookies cookie-jar (uri-host uri) (or (uri-path uri) "/") :securep (string= (uri-scheme uri) "https")))) (when cookies (fast-write-sequence (ascii-string-to-octets "Cookie: ") buffer) (fast-write-sequence (ascii-string-to-octets (write-cookie-header cookies)) buffer) (fast-write-sequence +crlf+ buffer))))) (defun make-connect-stream (uri version stream &optional proxy-auth) (let ((header (with-fast-output (buffer) (write-connect-header uri version buffer proxy-auth)))) (write-sequence header stream) (force-output stream) (read-until-crlf*2 stream) stream)) (defun make-proxy-authorization (uri) (let ((proxy-auth (quri:uri-userinfo uri))) (when proxy-auth (format nil "Basic ~A" (string-to-base64-string proxy-auth))))) (defconstant +socks5-version+ 5) (defconstant +socks5-reserved+ 0) (defconstant +socks5-no-auth+ 0) (defconstant +socks5-connect+ 1) (defconstant +socks5-domainname+ 3) (defconstant +socks5-succeeded+ 0) (defconstant +socks5-ipv4+ 1) (defconstant +socks5-ipv6+ 4) (defun ensure-socks5-connected (input output uri http-method) (labels ((fail (condition &key reason) (error (make-condition condition :body nil :status nil :headers nil :uri uri :method http-method :reason reason))) (exact (n reason) (unless (eql n (read-byte input nil 'eof)) (fail 'dexador.error:socks5-proxy-request-failed :reason reason))) (drop (n reason) (dotimes (i n) (when (eq (read-byte input nil 'eof) 'eof) (fail 'dexador.error:socks5-proxy-request-failed :reason reason))))) ;; Send Version + Auth Method ;; Currently, only supports no-auth method. (write-byte +socks5-version+ output) (write-byte 1 output) (write-byte +socks5-no-auth+ output) (finish-output output) ;; Receive Auth Method (exact +socks5-version+ "Unexpected version") (exact +socks5-no-auth+ "Unsupported auth method") ;; Send domainname Request (let* ((host (babel:string-to-octets (uri-host uri))) (hostlen (length host)) (port (uri-port uri))) (unless (<= 1 hostlen 255) (fail 'dexador.error:socks5-proxy-request-failed :reason "domainname too long")) (unless (<= 1 port 65535) (fail 'dexador.error:socks5-proxy-request-failed :reason "Invalid port")) (write-byte +socks5-version+ output) (write-byte +socks5-connect+ output) (write-byte +socks5-reserved+ output) (write-byte +socks5-domainname+ output) (write-byte hostlen output) (write-sequence host output) (write-byte (ldb (byte 8 8) port) output) (write-byte (ldb (byte 8 0) port) output) (finish-output output) ;; Receive reply (exact +socks5-version+ "Unexpected version") (exact +socks5-succeeded+ "Unexpected result code") (drop 1 "Should be reserved byte") (let ((atyp (read-byte input nil 'eof))) (cond ((eql atyp +socks5-ipv4+) (drop 6 "Should be IPv4 address and port")) ((eql atyp +socks5-ipv6+) (drop 18 "Should be IPv6 address and port")) ((eql atyp +socks5-domainname+) (let ((n (read-byte input nil 'eof))) (when (eq n 'eof) (fail 'dexador.error:socks5-proxy-request-failed :reason "Invalid domainname length")) (drop n "Should be domainname and port"))) (t (fail 'dexador.error:socks5-proxy-request-failed :reason "Unknown address"))))))) (defun make-ssl-stream (stream ca-path ssl-key-file ssl-cert-file ssl-key-password hostname insecure) #+(or windows dexador-no-ssl) (error "SSL not supported. Remove :dexador-no-ssl from *features* to enable SSL.") #-(or windows dexador-no-ssl) (progn (cl+ssl:ensure-initialized) (let ((ctx (cl+ssl:make-context :verify-mode (if insecure cl+ssl:+ssl-verify-none+ cl+ssl:+ssl-verify-peer+) :verify-location (cond (ca-path (uiop:native-namestring ca-path)) ((probe-file *ca-bundle*) *ca-bundle*) ;; In executable environment, perhaps *ca-bundle* doesn't exist. (t :default)))) (ssl-cert-pem-p (and ssl-cert-file (ends-with-subseq ".pem" ssl-cert-file)))) (cl+ssl:with-global-context (ctx :auto-free-p t) (when ssl-cert-pem-p (cl+ssl:use-certificate-chain-file ssl-cert-file)) (cl+ssl:make-ssl-client-stream stream :hostname hostname :verify (not insecure) :key ssl-key-file :certificate (and (not ssl-cert-pem-p) ssl-cert-file) :password ssl-key-password))))) (defstruct usocket-wrapped-stream stream) ;; Forward methods the user might want to use on this. ;; User is not meant to interact with this object except ;; potentially to close it when they decide they don't ;; need the :keep-alive connection anymore. (defmethod close ((u usocket-wrapped-stream) &key abort) (close (usocket-wrapped-stream-stream u) :abort abort)) (defmethod open-stream-p ((u usocket-wrapped-stream)) (open-stream-p (usocket-wrapped-stream-stream u))) (defun-careful request (uri &rest args &key (method :get) (version 1.1) content headers basic-auth cookie-jar (connect-timeout *default-connect-timeout*) (read-timeout *default-read-timeout*) (keep-alive t) (use-connection-pool t) (max-redirects 5) ssl-key-file ssl-cert-file ssl-key-password stream (verbose *verbose*) force-binary force-string want-stream (proxy *default-proxy*) (insecure *not-verify-ssl*) ca-path &aux (proxy-uri (and proxy (quri:uri proxy))) (original-user-supplied-stream stream) (user-supplied-stream (if (usocket-wrapped-stream-p stream) (usocket-wrapped-stream-stream stream) stream))) (declare (ignorable ssl-key-file ssl-cert-file ssl-key-password connect-timeout ca-path) (type real version) (type fixnum max-redirects)) (labels ((make-new-connection (uri) (restart-case (let* ((con-uri (quri:uri (or proxy uri))) (connection (usocket:socket-connect (uri-host con-uri) (uri-port con-uri) #-(or ecl clasp clisp allegro) :timeout #-(or ecl clasp clisp allegro) connect-timeout :element-type '(unsigned-byte 8))) (stream (usocket:socket-stream connection)) (scheme (uri-scheme uri))) (declare (type string scheme)) (when read-timeout (setf (usocket:socket-option connection :receive-timeout) read-timeout)) (when (socks5-proxy-p proxy-uri) (ensure-socks5-connected stream stream uri method)) (if (string= scheme "https") (make-ssl-stream (if (http-proxy-p proxy-uri) (make-connect-stream uri version stream (make-proxy-authorization con-uri)) stream) ca-path ssl-key-file ssl-cert-file ssl-key-password (uri-host uri) insecure) stream)) (retry-request () :report "Retry the same request." (return-from request (apply #'request uri :use-connection-pool nil args))) (retry-insecure () :report "Retry the same request without checking for SSL certificate validity." (return-from request (apply #'request uri :use-connection-pool nil :insecure t args))))) (http-proxy-p (uri) (and uri (let ((scheme (uri-scheme uri))) (and (stringp scheme) (or (string= scheme "http") (string= scheme "https")))))) (socks5-proxy-p (uri) (and uri (let ((scheme (uri-scheme uri))) (and (stringp scheme) (string= scheme "socks5"))))) (connection-keep-alive-p (connection-header) (and keep-alive (or (and (= (the real version) 1.0) (equalp connection-header "keep-alive")) (not (equalp connection-header "close"))))) (return-stream-to-pool (stream uri) (push-connection (format nil "~A://~A" (uri-scheme uri) (uri-authority uri)) stream #'close)) (return-stream-to-pool-or-close (stream connection-header uri) (if (and (not user-supplied-stream) use-connection-pool (connection-keep-alive-p connection-header)) (return-stream-to-pool stream uri) (when (open-stream-p stream) (close stream)))) (finalize-connection (stream connection-header uri) "If KEEP-ALIVE is in the connection-header and the user is not requesting a stream, we will push the connection to our connection pool if allowed, otherwise we return the stream back to the user who must close it." (unless want-stream (cond ((and use-connection-pool (connection-keep-alive-p connection-header) (not user-supplied-stream)) (return-stream-to-pool stream uri)) ((not (connection-keep-alive-p connection-header)) (when (open-stream-p stream) (close stream))))))) (let* ((uri (quri:uri uri)) (proxy (when (http-proxy-p proxy-uri) proxy)) (content-type (cdr (find :content-type headers :key #'car :test #'string-equal))) (multipart-p (or (string= content-type "multipart/form-data") (and (not content-type) (consp content) (find-if #'pathnamep content :key #'cdr)))) (form-urlencoded-p (or (string= content-type "application/x-www-form-urlencoded") (and (not content-type) (consp content) (not multipart-p)))) (boundary (and multipart-p (make-random-string 12))) (content (if (and form-urlencoded-p (not (stringp content))) ;; user can provide already encoded content, trust them. (quri:url-encode-params content) content)) (stream (or user-supplied-stream (and use-connection-pool (steal-connection (format nil "~A://~A" (uri-scheme uri) (uri-authority uri)))))) (reusing-stream-p (not (null stream))) ;; user provided or from connection-pool (stream (or stream (make-new-connection uri))) (content-length (assoc :content-length headers :test #'string-equal)) (transfer-encoding (assoc :transfer-encoding headers :test #'string-equal)) (chunkedp (or (and transfer-encoding (equalp (cdr transfer-encoding) "chunked")) (and content-length (null (cdr content-length))))) (first-line-data (with-fast-output (buffer) (write-first-line method uri version buffer))) (headers-data (flet ((write-header* (name value) (let ((header (assoc name headers :test #'string-equal))) (if header (when (cdr header) (write-header name (cdr header))) (write-header name value))) (values))) (with-header-output (buffer) (write-header* :user-agent #.*default-user-agent*) (write-header* :host (uri-authority uri)) (write-header* :accept "*/*") (cond ((and keep-alive (= (the real version) 1.0)) (write-header* :connection "keep-alive")) ((and (not keep-alive) (= (the real version) 1.1)) (write-header* :connection "close"))) (when basic-auth (write-header* :authorization (format nil "Basic ~A" (string-to-base64-string (format nil "~A:~A" (car basic-auth) (cdr basic-auth)))))) (when proxy (let ((scheme (quri:uri-scheme uri))) (when (string= scheme "http") (let* ((uri (quri:uri proxy)) (proxy-authorization (make-proxy-authorization uri))) (when proxy-authorization (write-header* :proxy-authorization proxy-authorization)))))) (cond (multipart-p (write-header :content-type (format nil "multipart/form-data; boundary=~A" boundary)) (unless chunkedp (write-header* :content-length (multipart-content-length content boundary)))) (form-urlencoded-p (write-header* :content-type "application/x-www-form-urlencoded") (unless chunkedp (write-header* :content-length (length (the string content))))) (t (etypecase content (null (unless chunkedp (write-header* :content-length 0))) (string (write-header* :content-type (or content-type "text/plain")) (unless chunkedp (write-header* :content-length (length (the (simple-array (unsigned-byte 8) *) (babel:string-to-octets content)))))) ((array (unsigned-byte 8) *) (write-header* :content-type (or content-type "text/plain")) (unless chunkedp (write-header* :content-length (length content)))) (pathname (write-header* :content-type (or content-type (mimes:mime content))) (unless chunkedp (if-let ((content-length (assoc :content-length headers :test #'string-equal))) (write-header :content-length (cdr content-length)) (with-open-file (in content) (write-header :content-length (file-length in))))))))) ;; Transfer-Encoding: chunked (when (and chunkedp (not transfer-encoding)) (write-header* :transfer-encoding "chunked")) ;; Custom headers (loop for (name . value) in headers unless (member name '(:user-agent :host :accept :connection :content-type :content-length) :test #'string-equal) do (write-header name value))))) (cookie-headers (and cookie-jar (build-cookie-headers uri cookie-jar)))) (macrolet ((maybe-try-again-without-reusing-stream (&optional (force nil)) `(progn ;; retrying by go retry avoids generating the header, parsing, etc. (when (open-stream-p stream) (close stream :abort t) (setf stream nil)) (when ,(or force 'reusing-stream-p) (setf reusing-stream-p nil user-supplied-stream nil stream (make-new-connection uri)) (go retry)))) (try-again-without-reusing-stream () `(maybe-try-again-without-reusing-stream t)) (with-retrying (&body body) `(restart-case (handler-bind (((and error ;; We should not retry errors received from the server. ;; Only technical errors such as disconnection or some ;; problems with the protocol should be retried automatically. ;; This solves https://github.com/fukamachi/dexador/issues/137 issue. (not http-request-failed)) (lambda (e) (declare (ignorable e)) (maybe-try-again-without-reusing-stream)))) ,@body) (retry-request () :report "Retry the same request." (return-from request (apply #'request uri args))) (ignore-and-continue () :report "Ignore the error and continue." (try-again-without-reusing-stream))))) (tagbody retry (unless (open-stream-p stream) (try-again-without-reusing-stream)) (with-retrying (write-sequence first-line-data stream) (write-sequence headers-data stream) (when cookie-headers (write-sequence cookie-headers stream)) (write-sequence +crlf+ stream) (force-output stream)) ;; Sending the content (when content (let ((stream (if chunkedp (chunga:make-chunked-stream stream) stream))) (when chunkedp (setf (chunga:chunked-stream-output-chunking-p stream) t)) (with-retrying (etypecase content (string (write-sequence (babel:string-to-octets content) stream)) ((array (unsigned-byte 8) *) (write-sequence content stream)) (pathname (with-open-file (in content :element-type '(unsigned-byte 8)) (copy-stream in stream))) (cons (write-multipart-content content boundary stream))) (when chunkedp (setf (chunga:chunked-stream-output-chunking-p stream) nil)) (finish-output stream)))) start-reading (multiple-value-bind (http body response-headers-data transfer-encoding-p) (with-retrying (read-response stream (not (eq method :head)) verbose (not want-stream))) (let* ((status (http-status http)) (response-headers (http-headers http)) (content-length (gethash "content-length" response-headers)) (content-length (etypecase content-length (null content-length) (string (parse-integer content-length)) (integer content-length)))) (when (= status 0) (with-retrying (http-request-failed status :body body :headers headers :uri uri :method method))) (when verbose (print-verbose-data :outgoing first-line-data headers-data cookie-headers +crlf+) (print-verbose-data :incoming response-headers-data)) (when cookie-jar (when-let (set-cookies (append (gethash "set-cookie" response-headers) (ensure-list (gethash "set-cookie2" response-headers)))) (merge-cookies cookie-jar (remove nil (mapcar (lambda (cookie) (declare (type string cookie)) (unless (= (length cookie) 0) (parse-set-cookie-header cookie (uri-host uri) (uri-path uri)))) set-cookies))))) (when (and (member status '(301 302 303 307) :test #'=) (gethash "location" response-headers) (/= max-redirects 0)) ;; Need to read the response body (when (and want-stream (not (eq method :head))) (cond ((integerp content-length) (dotimes (i content-length) (loop until (read-byte body nil nil)))) (transfer-encoding-p (read-until-crlf*2 body)))) (let* ((location-uri (quri:uri (gethash "location" response-headers))) (same-server-p (or (null (uri-host location-uri)) (and (string= (uri-scheme location-uri) (uri-scheme uri)) (string= (uri-host location-uri) (uri-host uri)) (eql (uri-port location-uri) (uri-port uri)))))) (if (and same-server-p (or (= status 307) (member method '(:get :head) :test #'eq))) (progn ;; redirection to the same host (setq uri (merge-uris location-uri uri)) (setq first-line-data (with-fast-output (buffer) (write-first-line method uri version buffer))) (when cookie-jar ;; Rebuild cookie-headers. (setq cookie-headers (build-cookie-headers uri cookie-jar))) (decf max-redirects) (if (equalp (gethash "connection" response-headers) "close") (try-again-without-reusing-stream) (progn (setq reusing-stream-p t) (go retry)))) (progn ;; this is a redirection to a different host (setf location-uri (quri:merge-uris location-uri uri)) ;; Close connection if it isn't from our connection pool or from the user and we aren't going to ;; pass it to our new call. (when (not same-server-p) (return-stream-to-pool-or-close stream (gethash "connection" response-headers) uri)) (setf (getf args :headers) (nconc `((:host . ,(uri-host location-uri))) headers)) (setf (getf args :max-redirects) (1- max-redirects)) ;; Redirect as GET if it's 301, 302, 303 (unless (or (= status 307) (member method '(:get :head) :test #'eq)) (setf (getf args :method) :get)) (return-from request (apply #'request location-uri (if same-server-p args (progn (remf args :stream) args)))))))) (unwind-protect (let* ((keep-connection-alive (connection-keep-alive-p (gethash "connection" response-headers))) (body (convert-body body (gethash "content-encoding" response-headers) (gethash "content-type" response-headers) content-length transfer-encoding-p force-binary force-string keep-connection-alive (if (and use-connection-pool keep-connection-alive (not user-supplied-stream) (streamp body)) (lambda (underlying-stream abort) (declare (ignore abort)) (when (open-stream-p underlying-stream) ;; read any left overs the user may have not read (in case of errors on user side?) (loop while (ignore-errors (listen underlying-stream)) ;; ssl streams may close do (read-byte underlying-stream nil nil)) (when (open-stream-p underlying-stream) (push-connection (format nil "~A://~A" (uri-scheme uri) (uri-authority uri)) underlying-stream #'close)))) #'dexador.keep-alive-stream:keep-alive-stream-close-underlying-stream)))) ;; Raise an error when the HTTP response status code is 4xx or 50x. (when (<= 400 status) (with-retrying (http-request-failed status :body body :headers response-headers :uri uri :method method))) ;; Have to be a little careful with the fifth value stream we return -- ;; the user may be not aware that keep-alive t without use-connection-pool can leak ;; sockets, so we wrap the returned last value so when it is garbage ;; collected it gets closed. If the user is getting a stream back as BODY, ;; then we instead add a finalizer to that stream to close it when garbage collected (return-from request (values body status response-headers uri (when (and keep-alive (not (equalp (gethash "connection" response-headers) "close")) (or (not use-connection-pool) user-supplied-stream)) (or (and original-user-supplied-stream ;; user provided a stream (if (usocket-wrapped-stream-p original-user-supplied-stream) ;; but, it came from us (eql (usocket-wrapped-stream-stream original-user-supplied-stream) stream) ;; and we used it (eql original-user-supplied-stream stream)) ;; user provided a bare stream original-user-supplied-stream) ;; return what the user sent without wrapping it (if want-stream ;; add a finalizer to the body to close the stream (progn (trivial-garbage:finalize body (lambda () (close stream))) stream) (let ((wrapped-stream (make-usocket-wrapped-stream :stream stream))) (trivial-garbage:finalize wrapped-stream (lambda () (close stream))) wrapped-stream))))))) (finalize-connection stream (gethash "connection" response-headers) uri)))))))))
43,220
Common Lisp
.lisp
824
31.947816
146
0.470327
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
6b520ded5bf0e302ea8b354a52d1af3b917241888e5f58b9c05504bd1aaf0c9d
42,668
[ -1 ]
42,669
winhttp.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/src/backend/winhttp.lisp
(defpackage #:dexador.backend.winhttp (:nicknames :dex.winhttp) (:use #:cl #:dexador.util #:winhttp) (:import-from #:dexador.body #:decode-body #:write-multipart-content #:decompress-body) (:import-from #:dexador.error #:http-request-failed) (:import-from #:winhttp #:set-ignore-certificates #:set-timeouts) (:import-from #:fast-io #:fast-output-stream #:with-fast-output #:fast-write-sequence #:finish-output-stream) (:import-from #:babel) (:import-from #:flexi-streams) (:import-from #:cl-cookie #:cookie-jar-host-cookies #:write-cookie-header #:parse-set-cookie-header #:merge-cookies) (:import-from #:alexandria #:read-file-into-byte-vector #:ensure-list #:when-let) (:import-from #:split-sequence #:split-sequence) (:export :request ;; Restarts :retry-request :ignore-and-continue)) (in-package #:dexador.backend.winhttp) (defconstant +WINHTTP_OPTION_DISABLE_FEATURE+ 63) (defconstant +WINHTTP_DISABLE_COOKIES+ #x00000001) (defconstant +WINHTTP_DISABLE_REDIRECTS+ #x00000002) (defconstant +WINHTTP_DISABLE_KEEP_ALIVE+ #x00000008) (defun set-option (req var value &optional (type :uint32)) (cffi:with-foreign-object (buf type) (setf (cffi:mem-aref buf type) value) (let ((ret (winhttp::%set-option req var buf (cffi:foreign-type-size type)))) (unless ret (winhttp::get-last-error))))) (defun query-headers* (req) (loop with hash = (make-hash-table :test 'equal) for (name-camelcased value) in (query-headers req) for name = (string-downcase name-camelcased) if (gethash name hash) do (setf (gethash name hash) (format nil "~A, ~A" (gethash name hash) value)) else do (setf (gethash name hash) value) finally (return hash))) (defun convert-content (content multipart-p form-urlencoded-p) (etypecase content (cons (cond (multipart-p (let ((boundary (make-random-string 12))) (values (let ((stream (make-instance 'fast-output-stream))) (write-multipart-content content boundary stream) (finish-output-stream stream)) (format nil "multipart/form-data; boundary=~A" boundary)))) (form-urlencoded-p (values (babel:string-to-octets (quri:url-encode-params content)) "application/x-www-form-urlencoded")))) (string (values (babel:string-to-octets content) "text/plain")) (pathname (values (read-file-into-byte-vector content) (mimes:mime content))) ((array (unsigned-byte 8) (*)) content) (null (make-array 0 :element-type '(unsigned-byte 8))))) ;; TODO: Try asynchronous (defun request (uri &rest args &key (method :get) (version 1.1) content headers basic-auth cookie-jar (connect-timeout *default-connect-timeout*) (read-timeout *default-read-timeout*) (keep-alive t) (use-connection-pool t) (max-redirects 5) ssl-key-file ssl-cert-file ssl-key-password stream (verbose *verbose*) force-binary force-string want-stream proxy (insecure *not-verify-ssl*) ca-path) (declare (ignore version use-connection-pool ssl-key-file ssl-cert-file ssl-key-password stream verbose proxy ca-path)) (let* ((uri (quri:uri uri)) (content-type (find :content-type headers :key #'car :test #'string-equal)) (multipart-p (or (string= (cdr content-type) "multipart/form-data") (and (null (cdr content-type)) (consp content) (find-if #'pathnamep content :key #'cdr)))) (form-urlencoded-p (or (string= (cdr content-type) "application/x-www-form-urlencoded") (and (null (cdr content-type)) (consp content) (not multipart-p)))) (user-agent (cdr (find :user-agent headers :key #'car :test #'string-equal)))) (multiple-value-bind (content detected-content-type) (convert-content content multipart-p form-urlencoded-p) (when detected-content-type (if content-type (setf (cdr (assoc :content-type headers :test #'string-equal)) detected-content-type) (setf headers (append `(("Content-Type" . ,detected-content-type)) headers)))) (when cookie-jar (let ((cookies (cookie-jar-host-cookies cookie-jar (quri:uri-host uri) (or (quri:uri-path uri) "/") :securep (string= (quri:uri-scheme uri) "https")))) (when cookies (setf headers (append headers `(("Cookie" . ,(write-cookie-header cookies)))))))) (with-http (session (or user-agent *default-user-agent*)) (with-connect (conn session (quri:uri-host uri) (quri:uri-port uri)) (with-request (req conn :verb method :url (format nil "~@[~A~]~@[?~A~]" (quri:uri-path uri) (quri:uri-query uri)) :https-p (equalp (quri:uri-scheme uri) "https")) (cond ((quri:uri-userinfo uri) (destructuring-bind (user pass) (split-sequence #\: (quri:uri-userinfo uri)) (set-credentials req user pass))) (basic-auth (set-credentials req (car basic-auth) (cdr basic-auth)))) ;; TODO: SSL arguments ;; TODO: proxy support (set-option req +WINHTTP_OPTION_DISABLE_FEATURE+ (logior +WINHTTP_DISABLE_COOKIES+ +WINHTTP_DISABLE_REDIRECTS+ (if keep-alive 0 +WINHTTP_DISABLE_KEEP_ALIVE+))) (dolist (header headers) (add-request-headers req (format nil "~:(~A~): ~A" (car header) (cdr header)))) (when (and (equalp (quri:uri-scheme uri) "https") insecure) (set-ignore-certificates req)) (when connect-timeout (set-timeouts req :connect (* 1000 connect-timeout) :recv (* 1000 read-timeout))) (send-request req content) (receive-response req) (let ((status (query-status-code req)) (response-headers (query-headers* req))) (when cookie-jar (when-let (set-cookies (append (ensure-list (gethash "set-cookie" response-headers)) (ensure-list (gethash "set-cookie2" response-headers)))) (merge-cookies cookie-jar (remove nil (mapcar (lambda (cookie) (declare (type string cookie)) (unless (= (length cookie) 0) (parse-set-cookie-header cookie (quri:uri-host uri) (quri:uri-path uri)))) set-cookies))))) ;; Redirect (when (and (member status '(301 302 303 307)) (gethash "location" response-headers) (/= max-redirects 0)) (let ((location-uri (quri:uri (gethash "location" response-headers)))) (let ((method (if (and (or (null (quri:uri-host location-uri)) (and (string= (quri:uri-scheme location-uri) (quri:uri-scheme uri)) (string= (quri:uri-host location-uri) (quri:uri-host uri)) (eql (quri:uri-port location-uri) (quri:uri-port uri)))) (or (= status 307) (member method '(:get :head) :test #'eq))) method :get))) ;; TODO: slurp the body (return-from request (apply #'request (quri:merge-uris location-uri uri) :max-redirects (1- max-redirects) :method method args))))) (let ((body (with-fast-output (body :vector) (loop with buffer = (make-array 1024 :element-type '(unsigned-byte 8)) for bytes = (read-data req buffer) until (zerop bytes) do (fast-write-sequence buffer body 0 bytes))))) (when (gethash "content-encoding" response-headers) (setf body (decompress-body (gethash "content-encoding" response-headers) body))) (let ((body (if force-binary body (decode-body (gethash "content-type" response-headers) body :default-charset (if force-string babel:*default-character-encoding* nil))))) ;; Raise an error when the HTTP response status is 4xx or 5xx. (when (<= 400 status) (restart-case (http-request-failed status :body body :headers response-headers :uri uri :method method) (retry-request () :report "Retry the same request." (apply #'request uri args)) (retry-insecure () :report "Retry the same request without checking for SSL certificate validity." (apply #'request uri :insecure t args)) (ignore-and-continue () :report "Ignore the error and continue."))) ;; TODO: This obviously isn't streaming. ;; Wrapping 'req' object by gray streams would be better, ;; but freeing it could be a problem for the next. (when want-stream (setf body (etypecase body (string (make-string-input-stream body)) (vector (flex:make-in-memory-input-stream body))))) (values body status response-headers uri))))))))))
12,362
Common Lisp
.lisp
240
30.225
109
0.450136
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
878703b732663754e4fdc1cbfb8e7c0140f109002e482d1159ca27410c15620d
42,669
[ 452879 ]
42,670
dexador.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/t/dexador.lisp
(in-package :cl-user) (defpackage dexador-test (:use :cl :rove) (:import-from :clack.test :*clack-test-port* :*clack-test-access-port* :port-available-p :localhost)) (in-package :dexador-test) (defun random-port () "Return a port number not in use from 50000 to 60000." (loop for port from (+ 50000 (random 1000)) upto 60000 if (clack.test::port-available-p port) return port)) (defmacro testing-app ((desc &key use-connection-pool) app &body body) `(let ((*clack-test-port* (random-port))) (clack.test:testing-app ,desc ,app ;; Clack's TESTING-APP sets dex:*use-connection-pool* to NIL, ;; but we need to change it in some tests (let ((dex:*use-connection-pool* ,use-connection-pool)) (dex:clear-connection-pool) ,@body)))) (deftest normal-case-tests (testing-app ("normal case") (lambda (env) `(200 (:content-length ,(length (getf env :request-uri))) (,(getf env :request-uri)))) (testing "GET" (multiple-value-bind (body code headers) (dex:get (localhost "/foo") :headers '((:x-foo . "ppp"))) (ok (eql code 200)) (ok (equal body "/foo")) (ok (equal (gethash "content-length" headers) "4")))) (testing "HEAD" (multiple-value-bind (body code) (dex:head (localhost "/foo")) (ok (eql code 200)) (ok (equal body "")))) (testing "PUT" (multiple-value-bind (body code) (dex:put (localhost "/foo")) (ok (eql code 200)) (ok (equal body "/foo")))) (testing "DELETE" (multiple-value-bind (body code) (dex:delete (localhost "/foo")) (ok (eql code 200)) (ok (equal body "/foo")))))) (deftest proxy-http-tests #+windows (skip "Skipped proxy tests on Windows") #-windows (testing-app ("proxy (http) case") ; proxy behavior is same as direct connection if http (lambda (env) (let ((body (format nil "~A~%~A" (gethash "host" (getf env :headers)) (getf env :request-uri)))) `(200 (:content-length ,(length body)) (,body)))) (testing "GET" (multiple-value-bind (body code) (dex:get "http://lisp.org/foo" :headers '((:x-foo . "ppp")) :proxy (localhost)) (ok (eql code 200)) (ok (equal body (format nil "lisp.org~%/foo"))))) (testing "HEAD" (multiple-value-bind (body code) (dex:head "http://lisp.org/foo" :proxy (localhost)) (ok (eql code 200)) (ok (equal body "")))) (testing "PUT" (multiple-value-bind (body code) (dex:put "http://lisp.org/foo" :proxy (localhost)) (ok (eql code 200)) (ok (equal body (format nil "lisp.org~%/foo"))))) (testing "DELETE" (multiple-value-bind (body code) (dex:delete "http://lisp.org/foo" :proxy (localhost)) (ok (eql code 200)) (ok (equal body (format nil "lisp.org~%/foo"))))))) (deftest proxy-socks5-tests #+windows (skip "SOCKS5 proxy tests are skipped") #-windows (testing-app ("proxy (socks5) case") (flet ((check (uri in out) (flexi-streams:with-input-from-sequence (in in) (equalp (flexi-streams:with-output-to-sequence (out :element-type '(unsigned-byte 8)) (dexador.backend.usocket::ensure-socks5-connected in out (quri:uri uri) :get)) out)))) (ok (check "http://example.com/" #(5 0 5 0 0 1 0 0 0 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 0 80))) (ok (check "https://example.com/" #(5 0 5 0 0 1 0 0 0 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 1 187))) (ok (check "http://example.com:8080/" #(5 0 5 0 0 1 0 0 0 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 31 144))) (ok (check "https://example.com:8080/" #(5 0 5 0 0 1 0 0 0 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 31 144))) (ok (check "http://example.com/" #(5 0 5 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 0 80))) (ok (check "http://example.com/" #(5 0 5 0 0 3 1 0 0 0) #(5 1 0 5 1 0 3 11 101 120 97 109 112 108 101 46 99 111 109 0 80))) (handler-case (check "http://example.com/" #(4) #()) (dex:socks5-proxy-request-failed () (ok t))) (handler-case (check "http://example.com/" #(5 255) #()) (dex:socks5-proxy-request-failed () (ok t)))) #+needs-Tor-running-on-localhost (let ((proxy "socks5://127.0.0.1:9150")) (testing "SOCKS5 GET" (multiple-value-bind (body code) (dex:get "http://duskgytldkxiuqc6.onion/" :proxy proxy) (declare (ignore body)) (ok (eql code 200)))) (testing "SOCKS5 GET with SSL" (multiple-value-bind (body code) (dex:get "https://www.facebookcorewwwi.onion/" :proxy proxy) (declare (ignore body)) (ok (eql code 200))))))) (deftest redirection-tests (testing-app ("redirection") (lambda (env) (let ((id (parse-integer (subseq (getf env :path-info) 1)))) (cond ((= id 3) '(200 (:content-length 2) ("OK"))) ((<= 300 id 399) `(,id (:location "/200") ())) ((= id 200) (let ((method (princ-to-string (getf env :request-method)))) `(200 (:content-length ,(length method)) (,method)))) (t `(302 (:location ,(format nil "/~D" (1+ id))) ()))))) (testing "redirect" (multiple-value-bind (body code headers) (dex:get (localhost "/1")) (ok (eql code 200)) (ok (equal body "OK")) (ok (equal (gethash "content-length" headers) (princ-to-string 2))))) (testing "not enough redirect" (multiple-value-bind (body code headers) (dex:get (localhost "/1") :max-redirects 0) (declare (ignore body)) (ok (eql code 302)) (ok (equal (gethash "location" headers) "/2")))) (testing "exceed max redirect" (multiple-value-bind (body code headers) (dex:get (localhost "/4") :max-redirects 7) (declare (ignore body)) (ok (eql code 302)) (ok (equal (gethash "location" headers) "/12")))) (testing "POST redirects as GET" (multiple-value-bind (body code headers uri) (dex:post (localhost "/301")) (declare (ignore headers)) (ok (eql code 200)) (ok (equal body "GET")) (ok (equal (quri:uri-path uri) "/200")))) (testing "POST redirects as POST for 307" (multiple-value-bind (body code headers uri) (dex:post (localhost "/307")) (declare (ignore headers)) (ok (eql code 200)) (ok (equal body "POST")) (ok (equal (quri:uri-path uri) "/200")))))) (deftest content-disposition-tests #+windows (skip "Content-Disposition tests are skipped") #-windows (testing "content-disposition" (ok (equal (dexador.backend.usocket::content-disposition "upload" #P"data/plain-file.txt") (format nil "Content-Disposition: form-data; name=\"upload\"; filename=\"plain-file.txt\"~C~C" #\Return #\Newline)) "ASCII file name") (ok (equal (dexador.backend.usocket::content-disposition "upload" #P"data/plain file.txt") (format nil "Content-Disposition: form-data; name=\"upload\"; filename=\"plain file.txt\"~C~C" #\Return #\Newline)) "ASCII file name with space") #+ecl (skip "Skipped because UTF-8 pathname is not allowed on ECL") #-ecl (ok (equal (dexador.backend.usocket::content-disposition "upload" #P"data/foo-あいうえお.txt") (format nil "Content-Disposition: form-data; name=\"upload\"; filename*=UTF-8''foo-%E3%81%82%E3%81%84%E3%81%86%E3%81%88%E3%81%8A.txt~C~C" #\Return #\Newline)) "UTF-8 file name") (ok (equal (dexador.backend.usocket::content-disposition "title" "ignore") (format nil "Content-Disposition: form-data; name=\"title\"~C~C" #\Return #\Newline)) "string value"))) ;; SBCL replaces LF with CRLF when reading from a stream on Windows (defun replace-crlf-to-lf (string) (ppcre:regex-replace-all (format nil "~C~C" #\Return #\Newline) string (format nil "~C" #\Newline))) (deftest post-request-tests (testing-app ("POST request") (lambda (env) (cond ((string= (getf env :path-info) "/upload") (let ((buf (make-array (getf env :content-length) :element-type '(unsigned-byte 8)))) (read-sequence buf (getf env :raw-body)) `(200 () (,(replace-crlf-to-lf (babel:octets-to-string buf)))))) (t (let ((req (lack.request:make-request env))) `(200 () (,(with-output-to-string (s) (loop for (k . v) in (lack.request:request-body-parameters req) do (format s "~&~A: ~A~%" k (cond ((and (consp v) (streamp (car v))) (let* ((buf (make-array 1024 :element-type '(unsigned-byte 8))) (n (read-sequence buf (car v)))) (replace-crlf-to-lf (babel:octets-to-string (subseq buf 0 n))))) ((consp v) (car v)) (t v))))))))))) (testing "content in alist" (multiple-value-bind (body code headers) (dex:post (localhost) :content '(("name" . "Eitaro") ("email" . "[email protected]"))) (declare (ignore headers)) (ok (eql code 200)) (ok (equal body (format nil "name: Eitaro~%email: [email protected]~%"))))) (testing "string content" (multiple-value-bind (body code headers) (dex:post (localhost "/upload") :content "this is string data") (declare (ignore headers)) (ok (eql code 200)) (ok (equal body "this is string data")))) (testing "octets content" (multiple-value-bind (body code headers) (dex:post (localhost "/upload") :content (babel:string-to-octets "this is octet data")) (declare (ignore headers)) (ok (eql code 200)) (ok (equal body "this is octet data")))) (testing "multipart" (multiple-value-bind (body code) (dex:post (localhost) :content `(("title" . "Road to Lisp") ("body" . ,(asdf:system-relative-pathname :dexador #P"t/data/quote.txt")))) (ok (eql code 200)) (ok (equal body (format nil "title: Road to Lisp~%body: \"Within a couple weeks of learning Lisp I found programming in any other language unbearably constraining.\" -- Paul Graham, Road to Lisp~2%"))))) (testing "upload" (multiple-value-bind (body code) (dex:post (localhost "/upload") :content (asdf:system-relative-pathname :dexador #P"t/data/quote.txt")) (ok (eql code 200)) (ok (equal body (format nil "\"Within a couple weeks of learning Lisp I found programming in any other language unbearably constraining.\" -- Paul Graham, Road to Lisp~%"))))))) (deftest http-request-failed-tests (testing-app ("HTTP request failed") (lambda (env) (if (string= (getf env :path-info) "/404") '(404 (:x-foo 0) ("Not Found")) '(500 (:x-bar 1) ("Internal Server Error")))) (handler-case (progn (dex:get (localhost)) (fail "Must raise an error DEX:HTTP-REQUEST-FAILED")) (dex:http-request-failed (e) (pass "Raise DEX:HTTP-REQUEST-FAILED error") (ok (eql (dex:response-status e) 500) "response status is 500") (ok (equal (dex:response-body e) "Internal Server Error") "response body is \"Internal Server Error\"") (ok (equal (gethash "x-bar" (dex:response-headers e)) "1")))) (handler-case (progn (dex:get (localhost "/404")) (fail "Must raise an error DEX:HTTP-REQUEST-NOT-FOUND")) (dex:http-request-not-found (e) (pass "Raise DEX:HTTP-REQUEST-FAILED error") (ok (eql (dex:response-status e) 404) "response status is 404") (ok (equal (dex:response-body e) "Not Found") "response body is \"Not Found\"") (ok (equal (gethash "x-foo" (dex:response-headers e)) "0")))))) (deftest using-cookies-tests (testing-app ("Using cookies") (lambda (env) (list (if (string= (getf env :path-info) "/302") 302 200) ;; mixi.jp '(:set-cookie "_auid=a8acafbaef245a806f6a308506dc95c8; domain=localhost; path=/; expires=Mon, 10-Jul-2017 12:32:47 GMT" ;; sourceforge :set-cookie2 "VISITOR=55a11217d3179d198af1d003; expires=\"Tue, 08-Jul-2025 12:54:47 GMT\"; httponly; Max-Age=315360000; Path=/") '("ok"))) (let ((cookie-jar (cl-cookie:make-cookie-jar))) (ok (eql (length (cl-cookie:cookie-jar-cookies cookie-jar)) 0) "0 cookies") (dex:head (localhost) :cookie-jar cookie-jar) (ok (eql (length (cl-cookie:cookie-jar-cookies cookie-jar)) 2) "2 cookies") (dex:head (localhost) :cookie-jar cookie-jar)) ;; 302 (let ((cookie-jar (cl-cookie:make-cookie-jar))) (ok (eql (length (cl-cookie:cookie-jar-cookies cookie-jar)) 0) "0 cookies") (dex:head (localhost "/302") :cookie-jar cookie-jar) (ok (eql (length (cl-cookie:cookie-jar-cookies cookie-jar)) 2) "2 cookies") (dex:head (localhost "/302") :cookie-jar cookie-jar)))) (deftest verbose-tests (testing-app ("verbose") (lambda (env) (declare (ignore env)) '(200 () ("ok"))) (ok (dex:get (localhost) :verbose t)))) (deftest want-stream-tests (testing-app ("want-stream") (lambda (env) (declare (ignore env)) '(200 (:content-type "text/plain") ("hi"))) ;; decoding stream (let ((body (dex:get (localhost) :want-stream t :keep-alive nil))) #+windows (ok (typep body 'stream)) #-windows (ok (typep body 'dexador.decoding-stream:decoding-stream) "body is a decoding stream") (ok (subtypep (stream-element-type body) 'babel:unicode-char) "body is a character stream") (let ((buf (make-string 2))) (read-sequence buf body) (ok (equal buf "hi")))) ;; binary stream (let ((body (dex:get (localhost) :want-stream t :force-binary t :keep-alive nil))) (ok (typep body 'stream) "body is a stream") (ok (open-stream-p body) "body is open") (ok (subtypep (stream-element-type body) '(unsigned-byte 8)) "body is a octets stream") (let ((buf (make-array 2 :element-type '(unsigned-byte 8)))) (read-sequence buf body) (ok (equal (babel:octets-to-string buf) "hi")))))) (deftest big-body-with-want-stream-tests (testing-app ("big body with want-stream") (lambda (env) (declare (ignore env)) `(200 (:content-type "application/json; charset=utf-8" :content-length 748) ("[{\"name\":\"allow-statement-in-has-a\",\"commit\":{\"sha\":\"d58b3c96503786c64eb2dba22980ebb14010bdbf\",\"url\":\"https://api.github.com/repos/fukamachi/datafly/commits/d58b3c96503786c64eb2dba22980ebb14010bdbf\"}},{\"name\":\"fix-has-a\",\"commit\":{\"sha\":\"4bcea61e84402317ab49605918972983a1511e6a\",\"url\":\"https://api.github.com/repos/fukamachi/datafly/commits/4bcea61e84402317ab49605918972983a1511e6a\"}},{\"name\":\"jojo\",\"commit\":{\"sha\":\"d2b753e7fdd0dbeada9721380cf410186a85535b\",\"url\":\"https://api.github.com/repos/fukamachi/datafly/commits/d2b753e7fdd0dbeada9721380cf410186a85535b\"}},{\"name\":\"master\",\"commit\":{\"sha\":\"d2b753e7fdd0dbeada9721380cf410186a85535b\",\"url\":\"https://api.github.com/repos/fukamachi/datafly/commits/d2b753e7fdd0dbeada9721380cf410186a85535b\"}}]"))) ;; decoding stream (let ((body (dex:get (localhost) :want-stream t))) #+windows (ok (typep body 'stream)) #-windows (ok (typep body 'dexador.decoding-stream:decoding-stream) "body is a decoding stream") (ok (subtypep (stream-element-type body) 'babel:unicode-char) "body is a character stream") (let ((buf (make-string 1024))) (ok (eql (read-sequence buf body) 748)))))) (deftest redirection-for-want-stream-tests (testing-app ("redirection for want-stream") (lambda (env) (if (string= (getf env :path-info) "/index.html") '(200 () ("ok")) '(307 (:location "/index.html" :transfer-encoding "chunked") ("")))) (let ((body (dex:get (localhost) :want-stream t))) (ok body)))) (deftest no-body-tests (testing-app ("no body") (lambda (env) (let ((path (getf env :path-info))) (if (string= path "/204") '(204 () ()) '(200 () ())))) ;; no Content-Length and no Transfer-Encoding (multiple-value-bind (body status headers) (dex:get (localhost)) (ok (equal body "")) (ok (eql status 200)) (ok (null (gethash "content-length" headers))) (ok (null (gethash "transfer-encoding" headers)))) ;; 204 No Content (multiple-value-bind (body status headers) (dex:get (localhost "/204")) (ok (eql status 204)) (ok (equal body "")) (ok (null (gethash "content-length" headers))) (ok (null (gethash "transfer-encoding" headers)))))) (defvar *json* "{\"name\":\"Eitaro Fukamachi\",\"name_ja\":\"深町英太郎\",\"login\":true}") (deftest json-tests (testing-app ("JSON") (lambda (env) (declare (ignore env)) `(200 (:content-type "application/json") (,*json*))) (multiple-value-bind (body status) (dex:get (localhost)) (ok (equal body *json*) "JSON is returned as a string") (ok (eql status 200))) (let ((babel:*default-character-encoding* :cp932)) ;; Test if the JSON encoding (multiple-value-bind (body status) (dex:get (localhost)) (ok (equal body *json*) "The default encoding is UTF-8 though babel:*default-character-encoding* is different") (ok (eql status 200)))))) (deftest keep-alive-tests (testing-app ("keep-alive") (lambda (env) (declare (ignore env)) '(200 () ("hi"))) (let ((headers (nth-value 2 (dex:get (localhost))))) (ok (or (null (gethash "connection" headers)) (string-equal (gethash "connection" headers) "keep-alive")))) (let ((headers (nth-value 2 (dex:get (localhost) :keep-alive nil)))) (ok (equalp (gethash "connection" headers) "close"))) (multiple-value-bind (b status response-headers uri opaque-socket-stream) (dex:get (localhost) :keep-alive t :use-connection-pool nil) (declare (ignorable b status response-headers uri opaque-socket-stream)) #+windows (ok (null opaque-socket-stream) "no socket stream") #-windows (ok (open-stream-p opaque-socket-stream) "stream is kept alive") (ok (= status 200) "success") #-windows (multiple-value-bind (b2 status2 response-headers2 uri2 opaque-socket-stream2) (dex:get (localhost) :keep-alive t :use-connection-pool nil :stream opaque-socket-stream) (declare (ignorable b2 response-headers2 uri2)) (ok (eql opaque-socket-stream opaque-socket-stream2) "stream is re-used") (ok (open-stream-p opaque-socket-stream2) "stream is kept alive") (ok (close opaque-socket-stream) "stream can be closed") (ok (= status2 200) "success") (multiple-value-bind (b3 status3 response-headers3 uri3 opaque-socket-stream3) (dex:get (localhost) :keep-alive t :use-connection-pool nil :stream opaque-socket-stream2) (declare (ignorable b3 uri3)) (member (gethash "connection" response-headers3) '(nil "keep-alive") :test #'equalp) (ok (= status3 200) "success") (ok (not (eql opaque-socket-stream3 opaque-socket-stream2)) "passing in closed stream works")))))) (defun assert-pool-items-count-is (expected-count) (let ((count (dexador.connection-cache::lru-pool-num-elts dexador:*connection-pool*))) (ok (= count expected-count) (format nil "Pool items count should be equal to ~A (real value is ~A)" expected-count count)))) (defun assert-connection-header-is (headers expected-value) (let ((value (gethash "connection" headers))) (ok (equalp value expected-value) (format nil "\"Connection\" header should be equal to ~S (real value is ~S)" expected-value value)))) (deftest connection-pool-and-errors ;; Here we are checking the situation when server returns 400 error and ;; in the second case also requests connection interruption. ;; Previously, this second case lead to an error when closed connection ;; was returned to the pool. #+windows (skip "Skipped because connection pool is not used on Windows.") #-windows (let ((success-count 0) (error-count 0) (error-and-close-count 0)) (flet ((assert-success-count (expected) (ok (= success-count expected) (format nil "Expected success-count to be ~S (real value is ~S)" expected success-count))) (assert-error-count (expected) (ok (= error-count expected) (format nil "Expected error-count to be ~S (real value is ~S)" expected error-count))) (assert-error-and-close-count (expected) (ok (= error-and-close-count expected) (format nil "Expected error-and-close-count to be ~S (real value is ~S)" expected error-and-close-count)))) (testing-app ("connection-pool-and-errors" :use-connection-pool t) (lambda (env) (let ((path (getf env :path-info))) (cond ((string= path "/error-and-close") (incf error-and-close-count) '(400 (:connection "close") (""))) ((string= path "/error") (incf error-count) '(400 nil (""))) (t (incf success-count) '(200 nil ("")))))) (testing "Initial pool state" (assert-pool-items-count-is 0)) (testing "Successful requests leave one connect in the pool" (loop repeat 10 do (dex:get (localhost "/"))) (assert-pool-items-count-is 1) (assert-success-count 10) (assert-error-count 0) (assert-error-and-close-count 0)) (testing "Repetitive success and error requests should not populate pool with connections" (loop repeat 10 do (dex:get (localhost "/")) (ok (rove:signals (dex:get (localhost "/error")) 'dex:http-request-bad-request))) (assert-success-count 20) (assert-error-count 10) (assert-error-and-close-count 0) ;; Previously, because of the bug, connections count was 8 (maximum) (assert-pool-items-count-is 1)) (testing "If server requests connection close on error, connection should not be returned to the pool." (loop repeat 10 do (dex:get (localhost "/")) ;; Previously, because of the another bug, other error was signaled, ;; because dexador retried and error with a new connection, ;; but closed it before the second attempt, because server response ;; has "Connection: close" header: (ok (rove:signals (dex:get (localhost "/error-and-close")) 'dex:http-request-bad-request))) (assert-success-count 30) (assert-error-count 10) (assert-error-and-close-count 10) (assert-pool-items-count-is 0)))))) (deftest deflate-compression-tests (testing-app ("deflate compression") (lambda (env) (declare (ignore env)) `(200 (:content-encoding "deflate" :content-type "text/plain") ,(asdf:system-relative-pathname :dexador #p"t/data/test.zlib"))) (let ((body (dex:get (localhost)))) (ok (equal body "Deflate test string."))))) (deftest gzip-compression-tests (testing-app ("gzip compression") (lambda (env) (declare (ignore env)) `(200 (:content-encoding "gzip" :content-type "text/plain") ,(asdf:system-relative-pathname :dexador #p"t/data/test.gz"))) (let ((body (dex:get (localhost)))) (ok (equal body "Gzip test string."))))) (deftest unread-character-tests (ok (eql #\u2602 (with-open-file (stream (asdf:system-relative-pathname :dexador #p"t/data/umb.bin") :element-type '(unsigned-byte 8)) (let ((decoding-stream (dexador.decoding-stream:make-decoding-stream stream))) (peek-char nil decoding-stream) (read-char decoding-stream)))))) (deftest keep-alive-stream/decoding-stream (with-open-file (stream0 (asdf:system-relative-pathname :dexador #p"t/data/bug139.txt") :element-type '(unsigned-byte 8)) (let* ((len (file-length stream0)) (stream1 (dexador.keep-alive-stream:make-keep-alive-stream stream0 :end len :chunked-stream nil)) (stream2 (dexador.decoding-stream:make-decoding-stream stream1))) (ok (= (length (loop for c = (read-char stream2 nil :eof) until (eq c :eof) collect c)) len))))) (deftest connection-cache-test (let ((dexador.connection-cache:*connection-pool* (dexador.connection-cache:make-connection-pool 2))) ;; Make sure empty cache works (ok (null (dexador.connection-cache:steal-connection "some-host"))) (dexador.connection-cache:clear-connection-pool) ;; Make sure push / steal works (dexador.connection-cache:push-connection "host1" "host1-socket") (ok (string= (dexador.connection-cache:steal-connection "host1") "host1-socket")) ;; Make sure steal actually removed the connection (ok (null (dexador.connection-cache:steal-connection "host1"))) ;; Check to make sure multiple elements with the same key work (dexador.connection-cache:push-connection "host1" "host1-socket1") (dexador.connection-cache:push-connection "host1" "host1-socket2") (let ((result1 (dexador.connection-cache:steal-connection "host1")) (result2 (dexador.connection-cache:steal-connection "host1"))) (ok (and (stringp result1) (stringp result2) (not (string= result1 result2))))) ;; make sure hash table stays clean (ok (zerop (hash-table-count (dexador.connection-cache::lru-pool-hash-table dexador.connection-cache::*connection-pool*)))) ;; make sure maximum connections is obeyed and least recently used element is evicted (dexador.connection-cache:push-connection "host1" "host1-socket1") (dexador.connection-cache:push-connection "host2" "host2-socket") (dexador.connection-cache:push-connection "host2" "host2-socket") (ok (null (dexador.connection-cache:steal-connection "host1"))) (ok (string= (dexador.connection-cache:steal-connection "host2") "host2-socket")) (ok (string= (dexador.connection-cache:steal-connection "host2") "host2-socket")) (ok (null (dexador.connection-cache:steal-connection "host2"))) ;; Make sure clear-connection-pool works and callbacks are called (let ((called nil)) (dexador.connection-cache:push-connection "host1" "host1-socket1" (lambda (s) (declare (ignore s)) (setf called t))) (dexador.connection-cache:clear-connection-pool) (ok called) (setf called nil) (dexador.connection-cache:push-connection "host1" "host1-socket" (lambda (s) (declare (ignore s)) (setf called "host1"))) (dexador.connection-cache:push-connection "host2" "host2-socket" (lambda (s) (declare (ignore s)) (setf called "host2"))) (dexador.connection-cache:push-connection "host3" "host3-socket" (lambda (s) (declare (ignore s)) (setf called "host3"))) (ok (string= called "host1")) (dexador.connection-cache:push-connection "host4" "host4-socket" (lambda (s) (declare (ignore s)) (setf called "host4"))) (ok (string= called "host2")))))
30,346
Common Lisp
.lisp
634
36.902208
824
0.568176
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
bc561376d96f5cc5d6f0316e87713ac3303e3fdd871fb981bbedc5f66259ccc2
42,670
[ -1 ]
42,671
benchmark.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/dexador-20221106-git/t/benchmark.lisp
(in-package :cl-user) (defpackage dexador-test.benchmark (:use :cl)) (in-package :dexador-test.benchmark) (defun run-benchmark () (clack:clackup (lambda (env) (declare (ignore env)) (list 200 ()))))
217
Common Lisp
.lisp
9
21.111111
36
0.676329
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
e04baa8b20aff884b8cade112d07ca2f7ada6d94e31c92b0dc39729646525e8e
42,671
[ 274237 ]
42,672
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/zpng-1.2.2/package.lisp
;;; ;;; Copyright (c) 2007 Zachary Beane, All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (defpackage #:zpng (:use #:cl #:salza2) (:export ;; generic #:width #:height #:rowstride #:color-type #:samples-per-pixel ;; in-memory pngs #:png #:copy-png #:png= #:image-data #:data-array #:write-png #:write-png-stream ;; row-at-a-time pngs #:streamed-png #:row-data #:start-png #:row-data #:write-row #:rows-written #:rows-left #:finish-png ;; pixel-at-a-time pngs #:pixel-streamed-png #:write-pixel #:pixels-left-in-row ;; conditions #:zpng-error #:invalid-size #:invalid-size-width #:invalid-size-height #:invalid-row-length #:insufficient-rows #:incomplete-row #:too-many-rows #:color-type-mismatch))
2,085
Common Lisp
.lisp
67
28.38806
70
0.708974
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
80d370c9be6da7bd7953ea3cb764e5362232291f4c25d219419f16fc07df8e92
42,672
[ 400099 ]
42,673
specials.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/zpng-1.2.2/specials.lisp
;;; ;;; Copyright (c) 2007 Zachary Beane, All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (in-package #:zpng) (defvar *color-types* '((:grayscale . 0) (:truecolor . 2) (:indexed-color . 3) (:grayscale-alpha . 4) (:truecolor-alpha . 6))) (defvar *png-signature* (make-array 8 :element-type '(unsigned-byte 8) :initial-contents '(137 80 78 71 13 10 26 10))) (defconstant +png-compression-method+ 0) (defconstant +png-filtering+ 0) (defconstant +png-interlace+ 0)
1,785
Common Lisp
.lisp
41
41.268293
70
0.725862
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
89b9ce19f525e3eafd5c21d81a9043e7aefa0264371f3baf4819b8161937f931
42,673
[ -1 ]
42,674
utils.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/zpng-1.2.2/utils.lisp
;;; ;;; Copyright (c) 2007 Zachary Beane, All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (in-package #:zpng) (defun write-uint32 (integer stream) (write-byte (ldb (byte 8 24) integer) stream) (write-byte (ldb (byte 8 16) integer) stream) (write-byte (ldb (byte 8 8) integer) stream) (write-byte (ldb (byte 8 0) integer) stream)) (defun checksum (data count) (let ((checksum (make-instance 'crc32-checksum))) (update checksum data 0 count) (result checksum)))
1,755
Common Lisp
.lisp
37
45.864865
70
0.741108
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
832055d00ea4f6f1cf25f54948b98a29f259fac626e127d46f30664c80ddb7ca
42,674
[ -1 ]
42,675
png.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/zpng-1.2.2/png.lisp
;;; ;;; Copyright (c) 2007 Zachary Beane, All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (in-package #:zpng) (defclass base-png () ((width :initarg :width :reader width) (height :initarg :height :reader height) (color-type :initform :truecolor :initarg :color-type :reader color-type) (bpp :initform 8 :initarg :bpp :reader bpp))) (defclass png (base-png) ((image-data :initarg :image-data :reader image-data :writer (setf %image-data)) (data-array :reader data-array :writer (setf %data-array)))) (defclass streamed-png (base-png) ((rows-written :initarg :rows-written :accessor rows-written) (row-data :initarg :row-data :accessor row-data) (compressor :initarg :compressor :accessor compressor) (output-stream :initarg :output-stream :accessor output-stream)) (:default-initargs :rows-written 0)) (defclass pixel-streamed-png (streamed-png) ((current-offset :initform 0 :accessor current-offset))) (defgeneric ihdr-color-type (png)) (defgeneric samples-per-pixel (png)) (defgeneric scanline-offset (png scanline)) (defgeneric rowstride (png)) (defgeneric write-png-header (png stream)) (defgeneric write-ihdr (png stream)) (defgeneric write-idat (png stream)) (defgeneric write-iend (png stream)) (defgeneric copy-png (png)) (defgeneric png= (png1 png2)) (defgeneric write-png-stream (png stream)) (defgeneric write-png (png pathname &key if-exists)) (defgeneric start-png (png stream)) (defgeneric write-row (row png &key start end)) (defgeneric finish-png (png)) (defgeneric rows-left (png)) (defgeneric reset-streamed-png (png)) (defgeneric write-pixel (pixel png)) (defgeneric pixels-left-in-row (png)) (defmethod slot-unbound (class (png png) (slot (eql 'data-array))) (let ((array (make-array (list (height png) (width png) (samples-per-pixel png)) :displaced-to (image-data png) :element-type '(unsigned-byte 8)))) (setf (%data-array png) array))) (defun check-size (png) (let ((width (width png)) (height (height png))) (unless (and (plusp width) (plusp height)) (error 'invalid-size :width width :height height)))) (defmethod initialize-instance :after ((png png) &rest args &key image-data) (declare (ignore args)) (check-size png) (unless (or image-data (slot-boundp png 'image-data)) (setf (%image-data png) (make-array (* (height png) (rowstride png)) :initial-element 0 :element-type '(unsigned-byte 8))))) (defmethod ihdr-color-type (png) (cdr (assoc (color-type png) *color-types*))) (defmethod samples-per-pixel (png) (ecase (color-type png) (:grayscale 1) (:truecolor 3) (:indexed-color 1) (:grayscale-alpha 2) (:truecolor-alpha 4))) (defmethod rowstride (png) (* (width png) (samples-per-pixel png))) (defmethod scanline-offset (png scanline) (* scanline (rowstride png))) (defmethod write-png-header (png stream) (write-sequence *png-signature* stream)) (defmethod write-ihdr (png stream) (let ((chunk (make-chunk 73 72 68 82 13))) (chunk-write-uint32 (width png) chunk) (chunk-write-uint32 (height png) chunk) (chunk-write-byte (bpp png) chunk) (chunk-write-byte (ihdr-color-type png) chunk) (chunk-write-byte +png-compression-method+ chunk) (chunk-write-byte +png-filtering+ chunk) (chunk-write-byte +png-interlace+ chunk) (write-chunk chunk stream))) (defun make-idat-callback (stream) (let* ((idat (make-chunk 73 68 65 84 16384)) (buffer (buffer idat))) (lambda (data end) (replace buffer data :start1 4 :end2 end) (setf (pos idat) (+ end 4)) (write-chunk idat stream)))) (defmethod write-idat (png stream) (let ((callback (make-idat-callback stream))) (with-compressor (compressor 'zlib-compressor :callback callback) (dotimes (i (height png)) (let* ((start-offset (scanline-offset png i)) (end-offset (+ start-offset (rowstride png)))) (compress-octet 0 compressor) (compress-octet-vector (image-data png) compressor :start start-offset :end end-offset)))))) (defmethod write-iend (png stream) (let ((chunk (make-chunk 73 69 78 68 0))) (write-chunk chunk stream))) (defmethod write-png-stream (png stream) (check-size png) (write-png-header png stream) (write-ihdr png stream) (write-idat png stream) (write-iend png stream)) (defmethod write-png (png file &key (if-exists :supersede)) (check-size png) (with-open-file (stream file :direction :output :if-exists if-exists :if-does-not-exist :create :element-type '(unsigned-byte 8)) (write-png-stream png stream) (truename file))) (defmethod copy-png (orig) (make-instance 'png :width (width orig) :height (height orig) :color-type (color-type orig) :bpp (bpp orig) :image-data (copy-seq (image-data orig)))) (defmethod png= (png1 png2) (or (eq png1 png2) (and (= (width png1) (width png2)) (= (height png1) (height png2)) (= (bpp png1) (bpp png2)) (eq (color-type png1) (color-type png2)) (let ((png1.data (image-data png1)) (png2.data (image-data png2))) (not (mismatch png1.data png2.data)))))) ;;; Streamed PNG methods (defmethod slot-unbound (class (png streamed-png) (slot (eql 'row-data))) (let ((data (make-array (rowstride png) :element-type '(unsigned-byte 8) :initial-element 0))) (setf (row-data png) data))) (defmethod start-png ((png streamed-png) stream) (setf (output-stream png) stream) (write-png-header png stream) (write-ihdr png stream) (setf (compressor png) (make-instance 'zlib-compressor :callback (make-idat-callback stream))) stream) (defmethod start-png ((png pixel-streamed-png) stream) (setf (current-offset png) 0) (call-next-method)) (defmethod write-row (row (png streamed-png) &key (start 0) end) (let ((rowstride (rowstride png))) (setf end (or end (+ start rowstride))) (let ((row-length (- end start))) (unless (= (- end start) (rowstride png)) (error 'invalid-row-length :expected-length rowstride :actual-length row-length)) (unless (< (rows-written png) (height png)) (error 'too-many-rows :count (height png))) (let ((compressor (compressor png))) (compress-octet 0 compressor) (compress-octet-vector row compressor :start start :end end) (incf (rows-written png)))))) (defmethod reset-streamed-png ((png streamed-png)) (setf (rows-written png) 0) (slot-makunbound png 'compressor) (slot-makunbound png 'output-stream) (fill (row-data png) 0)) (defmethod reset-streamed-png ((png pixel-streamed-png)) (setf (current-offset png) 0) (call-next-method)) (defmethod finish-png ((png streamed-png)) (when (/= (rows-written png) (height png)) (error 'insufficient-rows :written (rows-written png) :needed (height png))) (finish-compression (compressor png)) (write-iend png (output-stream png)) (reset-streamed-png png) png) (defmethod finish-png ((png pixel-streamed-png)) (let* ((color-channels (samples-per-pixel png)) (columns (/ (current-offset png) color-channels))) (unless (zerop columns) (error 'incomplete-row :written columns :needed (/ (length (row-data png)) color-channels)))) (call-next-method)) (defmethod rows-left ((png streamed-png)) (- (height png) (rows-written png))) (defmethod write-pixel (pixel (png pixel-streamed-png)) (let ((row-data (row-data png)) (samples-per-pixel (length pixel)) (samples-per-pixel-expected (samples-per-pixel png))) (unless (= samples-per-pixel samples-per-pixel-expected) (error 'color-type-mismatch :given samples-per-pixel :expected samples-per-pixel-expected)) (replace row-data pixel :start1 (current-offset png)) (when (= (incf (current-offset png) samples-per-pixel) (rowstride png)) (write-row row-data png) (setf (current-offset png) 0))) png) (defmethod pixels-left-in-row ((png pixel-streamed-png)) (/ (- (current-offset png) (rowstride png)) (samples-per-pixel png)))
9,964
Common Lisp
.lisp
248
34.157258
76
0.654431
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
f714b9263219e39a71c4507dc1b2c458d100b4e303dc6f020da9184bedd15e27
42,675
[ 114161 ]
42,676
conditions.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/zpng-1.2.2/conditions.lisp
;;; ;;; Copyright (c) 2008 Zachary Beane, All Rights Reserved ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;;; conditions.lisp (in-package #:zpng) (define-condition zpng-error (error) ()) (define-condition invalid-size (zpng-error) ((width :initarg :width :reader invalid-size-width) (height :initarg :height :reader invalid-size-height)) (:report (lambda (condition stream) (format stream "Invalid PNG size ~Ax~A; ~ both width and height must be positive" (invalid-size-width condition) (invalid-size-height condition))))) (define-condition invalid-row-length (zpng-error) ((expected-length :initarg :expected-length :accessor invalid-row-length-expected-length) (actual-length :initarg :actual-length :accessor invalid-row-length-actual-length)) (:report (lambda (condition stream) (format stream "Invalid row length ~A (expected ~A)" (invalid-row-length-actual-length condition) (invalid-row-length-expected-length condition))))) (define-condition insufficient-rows (zpng-error) ((written :initarg :written :accessor insufficient-rows-written) (needed :initarg :needed :accessor insufficient-rows-needed)) (:report (lambda (condition stream) (format stream "Insufficient rows written; need ~A, but only ~A ~ written" (insufficient-rows-needed condition) (insufficient-rows-written condition))))) (define-condition incomplete-row (zpng-error) ((written :initarg :written :accessor incomplete-row-written) (needed :initarg :needed :accessor incomplete-row-needed)) (:report (lambda (condition stream) (format stream "Incomplete row started; need ~A, but only ~A ~ written" (incomplete-row-needed condition) (incomplete-row-written condition))))) (define-condition too-many-rows (zpng-error) ((count :initarg :count :accessor too-many-rows-count)) (:report (lambda (condition stream) (format stream "Too many rows written for PNG; maximum row count ~ is ~A" (too-many-rows-count condition))))) (define-condition color-type-mismatch (zpng-error) ((given :initarg :given :accessor color-type-mismatch-given) (expected :initarg :expected :accessor color-type-mismatch-expected)) (:report (lambda (condition stream) (format stream "Wrong number of samples for PNG pixel; need ~A, ~ but only ~A written" (color-type-mismatch-expected condition) (color-type-mismatch-given condition)))))
4,091
Common Lisp
.lisp
97
35.463918
79
0.670848
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
d99f5302feb80e33122d6834f23eec5c8ea4029a03f4421b543b2b46c815c5b4
42,676
[ 134711 ]